Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name SemaOpenMP.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -relaxed-aliasing -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-9/lib/clang/9.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-9~svn360825/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-9~svn360825/tools/clang/include -I /build/llvm-toolchain-snapshot-9~svn360825/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-9~svn360825/build-llvm/include -I /build/llvm-toolchain-snapshot-9~svn360825/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/include/clang/9.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-9/lib/clang/9.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++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-9~svn360825/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-9~svn360825=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2019-05-16-032012-25149-1 -x c++ /build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp -faddrsig
1//===--- SemaOpenMP.cpp - Semantic Analysis for OpenMP constructs ---------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8/// \file
9/// This file implements semantic analysis for OpenMP directives and
10/// clauses.
11///
12//===----------------------------------------------------------------------===//
13
14#include "TreeTransform.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/ASTMutationListener.h"
17#include "clang/AST/CXXInheritance.h"
18#include "clang/AST/Decl.h"
19#include "clang/AST/DeclCXX.h"
20#include "clang/AST/DeclOpenMP.h"
21#include "clang/AST/StmtCXX.h"
22#include "clang/AST/StmtOpenMP.h"
23#include "clang/AST/StmtVisitor.h"
24#include "clang/AST/TypeOrdering.h"
25#include "clang/Basic/OpenMPKinds.h"
26#include "clang/Sema/Initialization.h"
27#include "clang/Sema/Lookup.h"
28#include "clang/Sema/Scope.h"
29#include "clang/Sema/ScopeInfo.h"
30#include "clang/Sema/SemaInternal.h"
31#include "llvm/ADT/PointerEmbeddedInt.h"
32using namespace clang;
33
34//===----------------------------------------------------------------------===//
35// Stack of data-sharing attributes for variables
36//===----------------------------------------------------------------------===//
37
38static const Expr *checkMapClauseExpressionBase(
39 Sema &SemaRef, Expr *E,
40 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
41 OpenMPClauseKind CKind, bool NoDiagnose);
42
43namespace {
44/// Default data sharing attributes, which can be applied to directive.
45enum DefaultDataSharingAttributes {
46 DSA_unspecified = 0, /// Data sharing attribute not specified.
47 DSA_none = 1 << 0, /// Default data sharing attribute 'none'.
48 DSA_shared = 1 << 1, /// Default data sharing attribute 'shared'.
49};
50
51/// Attributes of the defaultmap clause.
52enum DefaultMapAttributes {
53 DMA_unspecified, /// Default mapping is not specified.
54 DMA_tofrom_scalar, /// Default mapping is 'tofrom:scalar'.
55};
56
57/// Stack for tracking declarations used in OpenMP directives and
58/// clauses and their data-sharing attributes.
59class DSAStackTy {
60public:
61 struct DSAVarData {
62 OpenMPDirectiveKind DKind = OMPD_unknown;
63 OpenMPClauseKind CKind = OMPC_unknown;
64 const Expr *RefExpr = nullptr;
65 DeclRefExpr *PrivateCopy = nullptr;
66 SourceLocation ImplicitDSALoc;
67 DSAVarData() = default;
68 DSAVarData(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
69 const Expr *RefExpr, DeclRefExpr *PrivateCopy,
70 SourceLocation ImplicitDSALoc)
71 : DKind(DKind), CKind(CKind), RefExpr(RefExpr),
72 PrivateCopy(PrivateCopy), ImplicitDSALoc(ImplicitDSALoc) {}
73 };
74 using OperatorOffsetTy =
75 llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>;
76 using DoacrossDependMapTy =
77 llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>;
78
79private:
80 struct DSAInfo {
81 OpenMPClauseKind Attributes = OMPC_unknown;
82 /// Pointer to a reference expression and a flag which shows that the
83 /// variable is marked as lastprivate(true) or not (false).
84 llvm::PointerIntPair<const Expr *, 1, bool> RefExpr;
85 DeclRefExpr *PrivateCopy = nullptr;
86 };
87 using DeclSAMapTy = llvm::SmallDenseMap<const ValueDecl *, DSAInfo, 8>;
88 using AlignedMapTy = llvm::SmallDenseMap<const ValueDecl *, const Expr *, 8>;
89 using LCDeclInfo = std::pair<unsigned, VarDecl *>;
90 using LoopControlVariablesMapTy =
91 llvm::SmallDenseMap<const ValueDecl *, LCDeclInfo, 8>;
92 /// Struct that associates a component with the clause kind where they are
93 /// found.
94 struct MappedExprComponentTy {
95 OMPClauseMappableExprCommon::MappableExprComponentLists Components;
96 OpenMPClauseKind Kind = OMPC_unknown;
97 };
98 using MappedExprComponentsTy =
99 llvm::DenseMap<const ValueDecl *, MappedExprComponentTy>;
100 using CriticalsWithHintsTy =
101 llvm::StringMap<std::pair<const OMPCriticalDirective *, llvm::APSInt>>;
102 struct ReductionData {
103 using BOKPtrType = llvm::PointerEmbeddedInt<BinaryOperatorKind, 16>;
104 SourceRange ReductionRange;
105 llvm::PointerUnion<const Expr *, BOKPtrType> ReductionOp;
106 ReductionData() = default;
107 void set(BinaryOperatorKind BO, SourceRange RR) {
108 ReductionRange = RR;
109 ReductionOp = BO;
110 }
111 void set(const Expr *RefExpr, SourceRange RR) {
112 ReductionRange = RR;
113 ReductionOp = RefExpr;
114 }
115 };
116 using DeclReductionMapTy =
117 llvm::SmallDenseMap<const ValueDecl *, ReductionData, 4>;
118
119 struct SharingMapTy {
120 DeclSAMapTy SharingMap;
121 DeclReductionMapTy ReductionMap;
122 AlignedMapTy AlignedMap;
123 MappedExprComponentsTy MappedExprComponents;
124 LoopControlVariablesMapTy LCVMap;
125 DefaultDataSharingAttributes DefaultAttr = DSA_unspecified;
126 SourceLocation DefaultAttrLoc;
127 DefaultMapAttributes DefaultMapAttr = DMA_unspecified;
128 SourceLocation DefaultMapAttrLoc;
129 OpenMPDirectiveKind Directive = OMPD_unknown;
130 DeclarationNameInfo DirectiveName;
131 Scope *CurScope = nullptr;
132 SourceLocation ConstructLoc;
133 /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to
134 /// get the data (loop counters etc.) about enclosing loop-based construct.
135 /// This data is required during codegen.
136 DoacrossDependMapTy DoacrossDepends;
137 /// First argument (Expr *) contains optional argument of the
138 /// 'ordered' clause, the second one is true if the regions has 'ordered'
139 /// clause, false otherwise.
140 llvm::Optional<std::pair<const Expr *, OMPOrderedClause *>> OrderedRegion;
141 unsigned AssociatedLoops = 1;
142 const Decl *PossiblyLoopCounter = nullptr;
143 bool NowaitRegion = false;
144 bool CancelRegion = false;
145 bool LoopStart = false;
146 SourceLocation InnerTeamsRegionLoc;
147 /// Reference to the taskgroup task_reduction reference expression.
148 Expr *TaskgroupReductionRef = nullptr;
149 llvm::DenseSet<QualType> MappedClassesQualTypes;
150 /// List of globals marked as declare target link in this target region
151 /// (isOpenMPTargetExecutionDirective(Directive) == true).
152 llvm::SmallVector<DeclRefExpr *, 4> DeclareTargetLinkVarDecls;
153 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
154 Scope *CurScope, SourceLocation Loc)
155 : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
156 ConstructLoc(Loc) {}
157 SharingMapTy() = default;
158 };
159
160 using StackTy = SmallVector<SharingMapTy, 4>;
161
162 /// Stack of used declaration and their data-sharing attributes.
163 DeclSAMapTy Threadprivates;
164 const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr;
165 SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack;
166 /// true, if check for DSA must be from parent directive, false, if
167 /// from current directive.
168 OpenMPClauseKind ClauseKindMode = OMPC_unknown;
169 Sema &SemaRef;
170 bool ForceCapturing = false;
171 /// true if all the vaiables in the target executable directives must be
172 /// captured by reference.
173 bool ForceCaptureByReferenceInTargetExecutable = false;
174 CriticalsWithHintsTy Criticals;
175
176 using iterator = StackTy::const_reverse_iterator;
177
178 DSAVarData getDSA(iterator &Iter, ValueDecl *D) const;
179
180 /// Checks if the variable is a local for OpenMP region.
181 bool isOpenMPLocal(VarDecl *D, iterator Iter) const;
182
183 bool isStackEmpty() const {
184 return Stack.empty() ||
185 Stack.back().second != CurrentNonCapturingFunctionScope ||
186 Stack.back().first.empty();
187 }
188
189 /// Vector of previously declared requires directives
190 SmallVector<const OMPRequiresDecl *, 2> RequiresDecls;
191 /// omp_allocator_handle_t type.
192 QualType OMPAllocatorHandleT;
193 /// Expression for the predefined allocators.
194 Expr *OMPPredefinedAllocators[OMPAllocateDeclAttr::OMPUserDefinedMemAlloc] = {
195 nullptr};
196 /// Vector of previously encountered target directives
197 SmallVector<SourceLocation, 2> TargetLocations;
198
199public:
200 explicit DSAStackTy(Sema &S) : SemaRef(S) {}
201
202 /// Sets omp_allocator_handle_t type.
203 void setOMPAllocatorHandleT(QualType Ty) { OMPAllocatorHandleT = Ty; }
204 /// Gets omp_allocator_handle_t type.
205 QualType getOMPAllocatorHandleT() const { return OMPAllocatorHandleT; }
206 /// Sets the given default allocator.
207 void setAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
208 Expr *Allocator) {
209 OMPPredefinedAllocators[AllocatorKind] = Allocator;
210 }
211 /// Returns the specified default allocator.
212 Expr *getAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind) const {
213 return OMPPredefinedAllocators[AllocatorKind];
214 }
215
216 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
217 OpenMPClauseKind getClauseParsingMode() const {
218 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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 218, __PRETTY_FUNCTION__))
;
219 return ClauseKindMode;
220 }
221 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
222
223 bool isForceVarCapturing() const { return ForceCapturing; }
224 void setForceVarCapturing(bool V) { ForceCapturing = V; }
225
226 void setForceCaptureByReferenceInTargetExecutable(bool V) {
227 ForceCaptureByReferenceInTargetExecutable = V;
228 }
229 bool isForceCaptureByReferenceInTargetExecutable() const {
230 return ForceCaptureByReferenceInTargetExecutable;
231 }
232
233 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
234 Scope *CurScope, SourceLocation Loc) {
235 if (Stack.empty() ||
236 Stack.back().second != CurrentNonCapturingFunctionScope)
237 Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope);
238 Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc);
239 Stack.back().first.back().DefaultAttrLoc = Loc;
240 }
241
242 void pop() {
243 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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 244, __PRETTY_FUNCTION__))
244 "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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 244, __PRETTY_FUNCTION__))
;
245 Stack.back().first.pop_back();
246 }
247
248 /// Marks that we're started loop parsing.
249 void loopInit() {
250 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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 251, __PRETTY_FUNCTION__))
251 "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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 251, __PRETTY_FUNCTION__))
;
252 Stack.back().first.back().LoopStart = true;
253 }
254 /// Start capturing of the variables in the loop context.
255 void loopStart() {
256 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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 257, __PRETTY_FUNCTION__))
257 "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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 257, __PRETTY_FUNCTION__))
;
258 Stack.back().first.back().LoopStart = false;
259 }
260 /// true, if variables are captured, false otherwise.
261 bool isLoopStarted() const {
262 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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 263, __PRETTY_FUNCTION__))
263 "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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 263, __PRETTY_FUNCTION__))
;
264 return !Stack.back().first.back().LoopStart;
265 }
266 /// Marks (or clears) declaration as possibly loop counter.
267 void resetPossibleLoopCounter(const Decl *D = nullptr) {
268 Stack.back().first.back().PossiblyLoopCounter =
269 D ? D->getCanonicalDecl() : D;
270 }
271 /// Gets the possible loop counter decl.
272 const Decl *getPossiblyLoopCunter() const {
273 return Stack.back().first.back().PossiblyLoopCounter;
274 }
275 /// Start new OpenMP region stack in new non-capturing function.
276 void pushFunction() {
277 const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction();
278 assert(!isa<CapturingScopeInfo>(CurFnScope))((!isa<CapturingScopeInfo>(CurFnScope)) ? static_cast<
void> (0) : __assert_fail ("!isa<CapturingScopeInfo>(CurFnScope)"
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 278, __PRETTY_FUNCTION__))
;
279 CurrentNonCapturingFunctionScope = CurFnScope;
280 }
281 /// Pop region stack for non-capturing function.
282 void popFunction(const FunctionScopeInfo *OldFSI) {
283 if (!Stack.empty() && Stack.back().second == OldFSI) {
284 assert(Stack.back().first.empty())((Stack.back().first.empty()) ? static_cast<void> (0) :
__assert_fail ("Stack.back().first.empty()", "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 284, __PRETTY_FUNCTION__))
;
285 Stack.pop_back();
286 }
287 CurrentNonCapturingFunctionScope = nullptr;
288 for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) {
289 if (!isa<CapturingScopeInfo>(FSI)) {
290 CurrentNonCapturingFunctionScope = FSI;
291 break;
292 }
293 }
294 }
295
296 void addCriticalWithHint(const OMPCriticalDirective *D, llvm::APSInt Hint) {
297 Criticals.try_emplace(D->getDirectiveName().getAsString(), D, Hint);
298 }
299 const std::pair<const OMPCriticalDirective *, llvm::APSInt>
300 getCriticalWithHint(const DeclarationNameInfo &Name) const {
301 auto I = Criticals.find(Name.getAsString());
302 if (I != Criticals.end())
303 return I->second;
304 return std::make_pair(nullptr, llvm::APSInt());
305 }
306 /// If 'aligned' declaration for given variable \a D was not seen yet,
307 /// add it and return NULL; otherwise return previous occurrence's expression
308 /// for diagnostics.
309 const Expr *addUniqueAligned(const ValueDecl *D, const Expr *NewDE);
310
311 /// Register specified variable as loop control variable.
312 void addLoopControlVariable(const ValueDecl *D, VarDecl *Capture);
313 /// Check if the specified variable is a loop control variable for
314 /// current region.
315 /// \return The index of the loop control variable in the list of associated
316 /// for-loops (from outer to inner).
317 const LCDeclInfo isLoopControlVariable(const ValueDecl *D) const;
318 /// Check if the specified variable is a loop control variable for
319 /// parent region.
320 /// \return The index of the loop control variable in the list of associated
321 /// for-loops (from outer to inner).
322 const LCDeclInfo isParentLoopControlVariable(const ValueDecl *D) const;
323 /// Get the loop control variable for the I-th loop (or nullptr) in
324 /// parent directive.
325 const ValueDecl *getParentLoopControlVariable(unsigned I) const;
326
327 /// Adds explicit data sharing attribute to the specified declaration.
328 void addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
329 DeclRefExpr *PrivateCopy = nullptr);
330
331 /// Adds additional information for the reduction items with the reduction id
332 /// represented as an operator.
333 void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
334 BinaryOperatorKind BOK);
335 /// Adds additional information for the reduction items with the reduction id
336 /// represented as reduction identifier.
337 void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
338 const Expr *ReductionRef);
339 /// Returns the location and reduction operation from the innermost parent
340 /// region for the given \p D.
341 const DSAVarData
342 getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
343 BinaryOperatorKind &BOK,
344 Expr *&TaskgroupDescriptor) const;
345 /// Returns the location and reduction operation from the innermost parent
346 /// region for the given \p D.
347 const DSAVarData
348 getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
349 const Expr *&ReductionRef,
350 Expr *&TaskgroupDescriptor) const;
351 /// Return reduction reference expression for the current taskgroup.
352 Expr *getTaskgroupReductionRef() const {
353 assert(Stack.back().first.back().Directive == OMPD_taskgroup &&((Stack.back().first.back().Directive == OMPD_taskgroup &&
"taskgroup reference expression requested for non taskgroup "
"directive.") ? static_cast<void> (0) : __assert_fail (
"Stack.back().first.back().Directive == OMPD_taskgroup && \"taskgroup reference expression requested for non taskgroup \" \"directive.\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 355, __PRETTY_FUNCTION__))
354 "taskgroup reference expression requested for non taskgroup "((Stack.back().first.back().Directive == OMPD_taskgroup &&
"taskgroup reference expression requested for non taskgroup "
"directive.") ? static_cast<void> (0) : __assert_fail (
"Stack.back().first.back().Directive == OMPD_taskgroup && \"taskgroup reference expression requested for non taskgroup \" \"directive.\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 355, __PRETTY_FUNCTION__))
355 "directive.")((Stack.back().first.back().Directive == OMPD_taskgroup &&
"taskgroup reference expression requested for non taskgroup "
"directive.") ? static_cast<void> (0) : __assert_fail (
"Stack.back().first.back().Directive == OMPD_taskgroup && \"taskgroup reference expression requested for non taskgroup \" \"directive.\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 355, __PRETTY_FUNCTION__))
;
356 return Stack.back().first.back().TaskgroupReductionRef;
357 }
358 /// Checks if the given \p VD declaration is actually a taskgroup reduction
359 /// descriptor variable at the \p Level of OpenMP regions.
360 bool isTaskgroupReductionRef(const ValueDecl *VD, unsigned Level) const {
361 return Stack.back().first[Level].TaskgroupReductionRef &&
362 cast<DeclRefExpr>(Stack.back().first[Level].TaskgroupReductionRef)
363 ->getDecl() == VD;
364 }
365
366 /// Returns data sharing attributes from top of the stack for the
367 /// specified declaration.
368 const DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
369 /// Returns data-sharing attributes for the specified declaration.
370 const DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent) const;
371 /// Checks if the specified variables has data-sharing attributes which
372 /// match specified \a CPred predicate in any directive which matches \a DPred
373 /// predicate.
374 const DSAVarData
375 hasDSA(ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
376 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
377 bool FromParent) const;
378 /// Checks if the specified variables has data-sharing attributes which
379 /// match specified \a CPred predicate in any innermost directive which
380 /// matches \a DPred predicate.
381 const DSAVarData
382 hasInnermostDSA(ValueDecl *D,
383 const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
384 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
385 bool FromParent) const;
386 /// Checks if the specified variables has explicit data-sharing
387 /// attributes which match specified \a CPred predicate at the specified
388 /// OpenMP region.
389 bool hasExplicitDSA(const ValueDecl *D,
390 const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
391 unsigned Level, bool NotLastprivate = false) const;
392
393 /// Returns true if the directive at level \Level matches in the
394 /// specified \a DPred predicate.
395 bool hasExplicitDirective(
396 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
397 unsigned Level) const;
398
399 /// Finds a directive which matches specified \a DPred predicate.
400 bool hasDirective(
401 const llvm::function_ref<bool(
402 OpenMPDirectiveKind, const DeclarationNameInfo &, SourceLocation)>
403 DPred,
404 bool FromParent) const;
405
406 /// Returns currently analyzed directive.
407 OpenMPDirectiveKind getCurrentDirective() const {
408 return isStackEmpty() ? OMPD_unknown : Stack.back().first.back().Directive;
409 }
410 /// Returns directive kind at specified level.
411 OpenMPDirectiveKind getDirective(unsigned Level) const {
412 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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 412, __PRETTY_FUNCTION__))
;
413 return Stack.back().first[Level].Directive;
414 }
415 /// Returns parent directive.
416 OpenMPDirectiveKind getParentDirective() const {
417 if (isStackEmpty() || Stack.back().first.size() == 1)
418 return OMPD_unknown;
419 return std::next(Stack.back().first.rbegin())->Directive;
420 }
421
422 /// Add requires decl to internal vector
423 void addRequiresDecl(OMPRequiresDecl *RD) {
424 RequiresDecls.push_back(RD);
425 }
426
427 /// Checks if the defined 'requires' directive has specified type of clause.
428 template <typename ClauseType>
429 bool hasRequiresDeclWithClause() {
430 return llvm::any_of(RequiresDecls, [](const OMPRequiresDecl *D) {
431 return llvm::any_of(D->clauselists(), [](const OMPClause *C) {
432 return isa<ClauseType>(C);
433 });
434 });
435 }
436
437 /// Checks for a duplicate clause amongst previously declared requires
438 /// directives
439 bool hasDuplicateRequiresClause(ArrayRef<OMPClause *> ClauseList) const {
440 bool IsDuplicate = false;
441 for (OMPClause *CNew : ClauseList) {
442 for (const OMPRequiresDecl *D : RequiresDecls) {
443 for (const OMPClause *CPrev : D->clauselists()) {
444 if (CNew->getClauseKind() == CPrev->getClauseKind()) {
445 SemaRef.Diag(CNew->getBeginLoc(),
446 diag::err_omp_requires_clause_redeclaration)
447 << getOpenMPClauseName(CNew->getClauseKind());
448 SemaRef.Diag(CPrev->getBeginLoc(),
449 diag::note_omp_requires_previous_clause)
450 << getOpenMPClauseName(CPrev->getClauseKind());
451 IsDuplicate = true;
452 }
453 }
454 }
455 }
456 return IsDuplicate;
457 }
458
459 /// Add location of previously encountered target to internal vector
460 void addTargetDirLocation(SourceLocation LocStart) {
461 TargetLocations.push_back(LocStart);
462 }
463
464 // Return previously encountered target region locations.
465 ArrayRef<SourceLocation> getEncounteredTargetLocs() const {
466 return TargetLocations;
467 }
468
469 /// Set default data sharing attribute to none.
470 void setDefaultDSANone(SourceLocation Loc) {
471 assert(!isStackEmpty())((!isStackEmpty()) ? static_cast<void> (0) : __assert_fail
("!isStackEmpty()", "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 471, __PRETTY_FUNCTION__))
;
472 Stack.back().first.back().DefaultAttr = DSA_none;
473 Stack.back().first.back().DefaultAttrLoc = Loc;
474 }
475 /// Set default data sharing attribute to shared.
476 void setDefaultDSAShared(SourceLocation Loc) {
477 assert(!isStackEmpty())((!isStackEmpty()) ? static_cast<void> (0) : __assert_fail
("!isStackEmpty()", "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 477, __PRETTY_FUNCTION__))
;
478 Stack.back().first.back().DefaultAttr = DSA_shared;
479 Stack.back().first.back().DefaultAttrLoc = Loc;
480 }
481 /// Set default data mapping attribute to 'tofrom:scalar'.
482 void setDefaultDMAToFromScalar(SourceLocation Loc) {
483 assert(!isStackEmpty())((!isStackEmpty()) ? static_cast<void> (0) : __assert_fail
("!isStackEmpty()", "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 483, __PRETTY_FUNCTION__))
;
484 Stack.back().first.back().DefaultMapAttr = DMA_tofrom_scalar;
485 Stack.back().first.back().DefaultMapAttrLoc = Loc;
486 }
487
488 DefaultDataSharingAttributes getDefaultDSA() const {
489 return isStackEmpty() ? DSA_unspecified
490 : Stack.back().first.back().DefaultAttr;
491 }
492 SourceLocation getDefaultDSALocation() const {
493 return isStackEmpty() ? SourceLocation()
494 : Stack.back().first.back().DefaultAttrLoc;
495 }
496 DefaultMapAttributes getDefaultDMA() const {
497 return isStackEmpty() ? DMA_unspecified
498 : Stack.back().first.back().DefaultMapAttr;
499 }
500 DefaultMapAttributes getDefaultDMAAtLevel(unsigned Level) const {
501 return Stack.back().first[Level].DefaultMapAttr;
502 }
503 SourceLocation getDefaultDMALocation() const {
504 return isStackEmpty() ? SourceLocation()
505 : Stack.back().first.back().DefaultMapAttrLoc;
506 }
507
508 /// Checks if the specified variable is a threadprivate.
509 bool isThreadPrivate(VarDecl *D) {
510 const DSAVarData DVar = getTopDSA(D, false);
511 return isOpenMPThreadPrivate(DVar.CKind);
512 }
513
514 /// Marks current region as ordered (it has an 'ordered' clause).
515 void setOrderedRegion(bool IsOrdered, const Expr *Param,
516 OMPOrderedClause *Clause) {
517 assert(!isStackEmpty())((!isStackEmpty()) ? static_cast<void> (0) : __assert_fail
("!isStackEmpty()", "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 517, __PRETTY_FUNCTION__))
;
518 if (IsOrdered)
519 Stack.back().first.back().OrderedRegion.emplace(Param, Clause);
520 else
521 Stack.back().first.back().OrderedRegion.reset();
522 }
523 /// Returns true, if region is ordered (has associated 'ordered' clause),
524 /// false - otherwise.
525 bool isOrderedRegion() const {
526 if (isStackEmpty())
527 return false;
528 return Stack.back().first.rbegin()->OrderedRegion.hasValue();
529 }
530 /// Returns optional parameter for the ordered region.
531 std::pair<const Expr *, OMPOrderedClause *> getOrderedRegionParam() const {
532 if (isStackEmpty() ||
533 !Stack.back().first.rbegin()->OrderedRegion.hasValue())
534 return std::make_pair(nullptr, nullptr);
535 return Stack.back().first.rbegin()->OrderedRegion.getValue();
536 }
537 /// Returns true, if parent region is ordered (has associated
538 /// 'ordered' clause), false - otherwise.
539 bool isParentOrderedRegion() const {
540 if (isStackEmpty() || Stack.back().first.size() == 1)
541 return false;
542 return std::next(Stack.back().first.rbegin())->OrderedRegion.hasValue();
543 }
544 /// Returns optional parameter for the ordered region.
545 std::pair<const Expr *, OMPOrderedClause *>
546 getParentOrderedRegionParam() const {
547 if (isStackEmpty() || Stack.back().first.size() == 1 ||
548 !std::next(Stack.back().first.rbegin())->OrderedRegion.hasValue())
549 return std::make_pair(nullptr, nullptr);
550 return std::next(Stack.back().first.rbegin())->OrderedRegion.getValue();
551 }
552 /// Marks current region as nowait (it has a 'nowait' clause).
553 void setNowaitRegion(bool IsNowait = true) {
554 assert(!isStackEmpty())((!isStackEmpty()) ? static_cast<void> (0) : __assert_fail
("!isStackEmpty()", "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 554, __PRETTY_FUNCTION__))
;
555 Stack.back().first.back().NowaitRegion = IsNowait;
556 }
557 /// Returns true, if parent region is nowait (has associated
558 /// 'nowait' clause), false - otherwise.
559 bool isParentNowaitRegion() const {
560 if (isStackEmpty() || Stack.back().first.size() == 1)
561 return false;
562 return std::next(Stack.back().first.rbegin())->NowaitRegion;
563 }
564 /// Marks parent region as cancel region.
565 void setParentCancelRegion(bool Cancel = true) {
566 if (!isStackEmpty() && Stack.back().first.size() > 1) {
567 auto &StackElemRef = *std::next(Stack.back().first.rbegin());
568 StackElemRef.CancelRegion |= StackElemRef.CancelRegion || Cancel;
569 }
570 }
571 /// Return true if current region has inner cancel construct.
572 bool isCancelRegion() const {
573 return isStackEmpty() ? false : Stack.back().first.back().CancelRegion;
574 }
575
576 /// Set collapse value for the region.
577 void setAssociatedLoops(unsigned Val) {
578 assert(!isStackEmpty())((!isStackEmpty()) ? static_cast<void> (0) : __assert_fail
("!isStackEmpty()", "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 578, __PRETTY_FUNCTION__))
;
579 Stack.back().first.back().AssociatedLoops = Val;
580 }
581 /// Return collapse value for region.
582 unsigned getAssociatedLoops() const {
583 return isStackEmpty() ? 0 : Stack.back().first.back().AssociatedLoops;
584 }
585
586 /// Marks current target region as one with closely nested teams
587 /// region.
588 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
589 if (!isStackEmpty() && Stack.back().first.size() > 1) {
590 std::next(Stack.back().first.rbegin())->InnerTeamsRegionLoc =
591 TeamsRegionLoc;
592 }
593 }
594 /// Returns true, if current region has closely nested teams region.
595 bool hasInnerTeamsRegion() const {
596 return getInnerTeamsRegionLoc().isValid();
597 }
598 /// Returns location of the nested teams region (if any).
599 SourceLocation getInnerTeamsRegionLoc() const {
600 return isStackEmpty() ? SourceLocation()
601 : Stack.back().first.back().InnerTeamsRegionLoc;
602 }
603
604 Scope *getCurScope() const {
605 return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope;
606 }
607 SourceLocation getConstructLoc() const {
608 return isStackEmpty() ? SourceLocation()
609 : Stack.back().first.back().ConstructLoc;
610 }
611
612 /// Do the check specified in \a Check to all component lists and return true
613 /// if any issue is found.
614 bool checkMappableExprComponentListsForDecl(
615 const ValueDecl *VD, bool CurrentRegionOnly,
616 const llvm::function_ref<
617 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
618 OpenMPClauseKind)>
619 Check) const {
620 if (isStackEmpty())
621 return false;
622 auto SI = Stack.back().first.rbegin();
623 auto SE = Stack.back().first.rend();
624
625 if (SI == SE)
626 return false;
627
628 if (CurrentRegionOnly)
629 SE = std::next(SI);
630 else
631 std::advance(SI, 1);
632
633 for (; SI != SE; ++SI) {
634 auto MI = SI->MappedExprComponents.find(VD);
635 if (MI != SI->MappedExprComponents.end())
636 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
637 MI->second.Components)
638 if (Check(L, MI->second.Kind))
639 return true;
640 }
641 return false;
642 }
643
644 /// Do the check specified in \a Check to all component lists at a given level
645 /// and return true if any issue is found.
646 bool checkMappableExprComponentListsForDeclAtLevel(
647 const ValueDecl *VD, unsigned Level,
648 const llvm::function_ref<
649 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
650 OpenMPClauseKind)>
651 Check) const {
652 if (isStackEmpty())
653 return false;
654
655 auto StartI = Stack.back().first.begin();
656 auto EndI = Stack.back().first.end();
657 if (std::distance(StartI, EndI) <= (int)Level)
658 return false;
659 std::advance(StartI, Level);
660
661 auto MI = StartI->MappedExprComponents.find(VD);
662 if (MI != StartI->MappedExprComponents.end())
663 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
664 MI->second.Components)
665 if (Check(L, MI->second.Kind))
666 return true;
667 return false;
668 }
669
670 /// Create a new mappable expression component list associated with a given
671 /// declaration and initialize it with the provided list of components.
672 void addMappableExpressionComponents(
673 const ValueDecl *VD,
674 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
675 OpenMPClauseKind WhereFoundClauseKind) {
676 assert(!isStackEmpty() &&((!isStackEmpty() && "Not expecting to retrieve components from a empty stack!"
) ? static_cast<void> (0) : __assert_fail ("!isStackEmpty() && \"Not expecting to retrieve components from a empty stack!\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 677, __PRETTY_FUNCTION__))
677 "Not expecting to retrieve components from a empty stack!")((!isStackEmpty() && "Not expecting to retrieve components from a empty stack!"
) ? static_cast<void> (0) : __assert_fail ("!isStackEmpty() && \"Not expecting to retrieve components from a empty stack!\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 677, __PRETTY_FUNCTION__))
;
678 MappedExprComponentTy &MEC =
679 Stack.back().first.back().MappedExprComponents[VD];
680 // Create new entry and append the new components there.
681 MEC.Components.resize(MEC.Components.size() + 1);
682 MEC.Components.back().append(Components.begin(), Components.end());
683 MEC.Kind = WhereFoundClauseKind;
684 }
685
686 unsigned getNestingLevel() const {
687 assert(!isStackEmpty())((!isStackEmpty()) ? static_cast<void> (0) : __assert_fail
("!isStackEmpty()", "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 687, __PRETTY_FUNCTION__))
;
688 return Stack.back().first.size() - 1;
689 }
690 void addDoacrossDependClause(OMPDependClause *C,
691 const OperatorOffsetTy &OpsOffs) {
692 assert(!isStackEmpty() && Stack.back().first.size() > 1)((!isStackEmpty() && Stack.back().first.size() > 1
) ? static_cast<void> (0) : __assert_fail ("!isStackEmpty() && Stack.back().first.size() > 1"
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 692, __PRETTY_FUNCTION__))
;
693 SharingMapTy &StackElem = *std::next(Stack.back().first.rbegin());
694 assert(isOpenMPWorksharingDirective(StackElem.Directive))((isOpenMPWorksharingDirective(StackElem.Directive)) ? static_cast
<void> (0) : __assert_fail ("isOpenMPWorksharingDirective(StackElem.Directive)"
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 694, __PRETTY_FUNCTION__))
;
695 StackElem.DoacrossDepends.try_emplace(C, OpsOffs);
696 }
697 llvm::iterator_range<DoacrossDependMapTy::const_iterator>
698 getDoacrossDependClauses() const {
699 assert(!isStackEmpty())((!isStackEmpty()) ? static_cast<void> (0) : __assert_fail
("!isStackEmpty()", "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 699, __PRETTY_FUNCTION__))
;
700 const SharingMapTy &StackElem = Stack.back().first.back();
701 if (isOpenMPWorksharingDirective(StackElem.Directive)) {
702 const DoacrossDependMapTy &Ref = StackElem.DoacrossDepends;
703 return llvm::make_range(Ref.begin(), Ref.end());
704 }
705 return llvm::make_range(StackElem.DoacrossDepends.end(),
706 StackElem.DoacrossDepends.end());
707 }
708
709 // Store types of classes which have been explicitly mapped
710 void addMappedClassesQualTypes(QualType QT) {
711 SharingMapTy &StackElem = Stack.back().first.back();
712 StackElem.MappedClassesQualTypes.insert(QT);
713 }
714
715 // Return set of mapped classes types
716 bool isClassPreviouslyMapped(QualType QT) const {
717 const SharingMapTy &StackElem = Stack.back().first.back();
718 return StackElem.MappedClassesQualTypes.count(QT) != 0;
719 }
720
721 /// Adds global declare target to the parent target region.
722 void addToParentTargetRegionLinkGlobals(DeclRefExpr *E) {
723 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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 725, __PRETTY_FUNCTION__))
724 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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 725, __PRETTY_FUNCTION__))
725 "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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 725, __PRETTY_FUNCTION__))
;
726 if (isStackEmpty())
727 return;
728 auto It = Stack.back().first.rbegin();
729 while (It != Stack.back().first.rend() &&
730 !isOpenMPTargetExecutionDirective(It->Directive))
731 ++It;
732 if (It != Stack.back().first.rend()) {
733 assert(isOpenMPTargetExecutionDirective(It->Directive) &&((isOpenMPTargetExecutionDirective(It->Directive) &&
"Expected target executable directive.") ? static_cast<void
> (0) : __assert_fail ("isOpenMPTargetExecutionDirective(It->Directive) && \"Expected target executable directive.\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 734, __PRETTY_FUNCTION__))
734 "Expected target executable directive.")((isOpenMPTargetExecutionDirective(It->Directive) &&
"Expected target executable directive.") ? static_cast<void
> (0) : __assert_fail ("isOpenMPTargetExecutionDirective(It->Directive) && \"Expected target executable directive.\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 734, __PRETTY_FUNCTION__))
;
735 It->DeclareTargetLinkVarDecls.push_back(E);
736 }
737 }
738
739 /// Returns the list of globals with declare target link if current directive
740 /// is target.
741 ArrayRef<DeclRefExpr *> getLinkGlobals() const {
742 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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 743, __PRETTY_FUNCTION__))
743 "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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 743, __PRETTY_FUNCTION__))
;
744 return Stack.back().first.back().DeclareTargetLinkVarDecls;
745 }
746};
747
748bool isImplicitTaskingRegion(OpenMPDirectiveKind DKind) {
749 return isOpenMPParallelDirective(DKind) || isOpenMPTeamsDirective(DKind);
750}
751
752bool isImplicitOrExplicitTaskingRegion(OpenMPDirectiveKind DKind) {
753 return isImplicitTaskingRegion(DKind) || isOpenMPTaskingDirective(DKind) ||
754 DKind == OMPD_unknown;
755}
756
757} // namespace
758
759static const Expr *getExprAsWritten(const Expr *E) {
760 if (const auto *FE = dyn_cast<FullExpr>(E))
761 E = FE->getSubExpr();
762
763 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
764 E = MTE->GetTemporaryExpr();
765
766 while (const auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
767 E = Binder->getSubExpr();
768
769 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
770 E = ICE->getSubExprAsWritten();
771 return E->IgnoreParens();
772}
773
774static Expr *getExprAsWritten(Expr *E) {
775 return const_cast<Expr *>(getExprAsWritten(const_cast<const Expr *>(E)));
776}
777
778static const ValueDecl *getCanonicalDecl(const ValueDecl *D) {
779 if (const auto *CED = dyn_cast<OMPCapturedExprDecl>(D))
780 if (const auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
781 D = ME->getMemberDecl();
782 const auto *VD = dyn_cast<VarDecl>(D);
783 const auto *FD = dyn_cast<FieldDecl>(D);
784 if (VD != nullptr) {
785 VD = VD->getCanonicalDecl();
786 D = VD;
787 } else {
788 assert(FD)((FD) ? static_cast<void> (0) : __assert_fail ("FD", "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 788, __PRETTY_FUNCTION__))
;
789 FD = FD->getCanonicalDecl();
790 D = FD;
791 }
792 return D;
793}
794
795static ValueDecl *getCanonicalDecl(ValueDecl *D) {
796 return const_cast<ValueDecl *>(
797 getCanonicalDecl(const_cast<const ValueDecl *>(D)));
798}
799
800DSAStackTy::DSAVarData DSAStackTy::getDSA(iterator &Iter,
801 ValueDecl *D) const {
802 D = getCanonicalDecl(D);
803 auto *VD = dyn_cast<VarDecl>(D);
804 const auto *FD = dyn_cast<FieldDecl>(D);
805 DSAVarData DVar;
806 if (isStackEmpty() || Iter == Stack.back().first.rend()) {
807 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
808 // in a region but not in construct]
809 // File-scope or namespace-scope variables referenced in called routines
810 // in the region are shared unless they appear in a threadprivate
811 // directive.
812 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(VD))
813 DVar.CKind = OMPC_shared;
814
815 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
816 // in a region but not in construct]
817 // Variables with static storage duration that are declared in called
818 // routines in the region are shared.
819 if (VD && VD->hasGlobalStorage())
820 DVar.CKind = OMPC_shared;
821
822 // Non-static data members are shared by default.
823 if (FD)
824 DVar.CKind = OMPC_shared;
825
826 return DVar;
827 }
828
829 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
830 // in a Construct, C/C++, predetermined, p.1]
831 // Variables with automatic storage duration that are declared in a scope
832 // inside the construct are private.
833 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
834 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
835 DVar.CKind = OMPC_private;
836 return DVar;
837 }
838
839 DVar.DKind = Iter->Directive;
840 // Explicitly specified attributes and local variables with predetermined
841 // attributes.
842 if (Iter->SharingMap.count(D)) {
843 const DSAInfo &Data = Iter->SharingMap.lookup(D);
844 DVar.RefExpr = Data.RefExpr.getPointer();
845 DVar.PrivateCopy = Data.PrivateCopy;
846 DVar.CKind = Data.Attributes;
847 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
848 return DVar;
849 }
850
851 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
852 // in a Construct, C/C++, implicitly determined, p.1]
853 // In a parallel or task construct, the data-sharing attributes of these
854 // variables are determined by the default clause, if present.
855 switch (Iter->DefaultAttr) {
856 case DSA_shared:
857 DVar.CKind = OMPC_shared;
858 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
859 return DVar;
860 case DSA_none:
861 return DVar;
862 case DSA_unspecified:
863 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
864 // in a Construct, implicitly determined, p.2]
865 // In a parallel construct, if no default clause is present, these
866 // variables are shared.
867 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
868 if (isOpenMPParallelDirective(DVar.DKind) ||
869 isOpenMPTeamsDirective(DVar.DKind)) {
870 DVar.CKind = OMPC_shared;
871 return DVar;
872 }
873
874 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
875 // in a Construct, implicitly determined, p.4]
876 // In a task construct, if no default clause is present, a variable that in
877 // the enclosing context is determined to be shared by all implicit tasks
878 // bound to the current team is shared.
879 if (isOpenMPTaskingDirective(DVar.DKind)) {
880 DSAVarData DVarTemp;
881 iterator I = Iter, E = Stack.back().first.rend();
882 do {
883 ++I;
884 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
885 // Referenced in a Construct, implicitly determined, p.6]
886 // In a task construct, if no default clause is present, a variable
887 // whose data-sharing attribute is not determined by the rules above is
888 // firstprivate.
889 DVarTemp = getDSA(I, D);
890 if (DVarTemp.CKind != OMPC_shared) {
891 DVar.RefExpr = nullptr;
892 DVar.CKind = OMPC_firstprivate;
893 return DVar;
894 }
895 } while (I != E && !isImplicitTaskingRegion(I->Directive));
896 DVar.CKind =
897 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
898 return DVar;
899 }
900 }
901 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
902 // in a Construct, implicitly determined, p.3]
903 // For constructs other than task, if no default clause is present, these
904 // variables inherit their data-sharing attributes from the enclosing
905 // context.
906 return getDSA(++Iter, D);
907}
908
909const Expr *DSAStackTy::addUniqueAligned(const ValueDecl *D,
910 const Expr *NewDE) {
911 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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 911, __PRETTY_FUNCTION__))
;
912 D = getCanonicalDecl(D);
913 SharingMapTy &StackElem = Stack.back().first.back();
914 auto It = StackElem.AlignedMap.find(D);
915 if (It == StackElem.AlignedMap.end()) {
916 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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 916, __PRETTY_FUNCTION__))
;
917 StackElem.AlignedMap[D] = NewDE;
918 return nullptr;
919 }
920 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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 920, __PRETTY_FUNCTION__))
;
921 return It->second;
922}
923
924void DSAStackTy::addLoopControlVariable(const ValueDecl *D, VarDecl *Capture) {
925 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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 925, __PRETTY_FUNCTION__))
;
926 D = getCanonicalDecl(D);
927 SharingMapTy &StackElem = Stack.back().first.back();
928 StackElem.LCVMap.try_emplace(
929 D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture));
930}
931
932const DSAStackTy::LCDeclInfo
933DSAStackTy::isLoopControlVariable(const ValueDecl *D) const {
934 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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 934, __PRETTY_FUNCTION__))
;
935 D = getCanonicalDecl(D);
936 const SharingMapTy &StackElem = Stack.back().first.back();
937 auto It = StackElem.LCVMap.find(D);
938 if (It != StackElem.LCVMap.end())
939 return It->second;
940 return {0, nullptr};
941}
942
943const DSAStackTy::LCDeclInfo
944DSAStackTy::isParentLoopControlVariable(const ValueDecl *D) const {
945 assert(!isStackEmpty() && Stack.back().first.size() > 1 &&((!isStackEmpty() && Stack.back().first.size() > 1
&& "Data-sharing attributes stack is empty") ? static_cast
<void> (0) : __assert_fail ("!isStackEmpty() && Stack.back().first.size() > 1 && \"Data-sharing attributes stack is empty\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 946, __PRETTY_FUNCTION__))
946 "Data-sharing attributes stack is empty")((!isStackEmpty() && Stack.back().first.size() > 1
&& "Data-sharing attributes stack is empty") ? static_cast
<void> (0) : __assert_fail ("!isStackEmpty() && Stack.back().first.size() > 1 && \"Data-sharing attributes stack is empty\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 946, __PRETTY_FUNCTION__))
;
947 D = getCanonicalDecl(D);
948 const SharingMapTy &StackElem = *std::next(Stack.back().first.rbegin());
949 auto It = StackElem.LCVMap.find(D);
950 if (It != StackElem.LCVMap.end())
951 return It->second;
952 return {0, nullptr};
953}
954
955const ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) const {
956 assert(!isStackEmpty() && Stack.back().first.size() > 1 &&((!isStackEmpty() && Stack.back().first.size() > 1
&& "Data-sharing attributes stack is empty") ? static_cast
<void> (0) : __assert_fail ("!isStackEmpty() && Stack.back().first.size() > 1 && \"Data-sharing attributes stack is empty\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 957, __PRETTY_FUNCTION__))
957 "Data-sharing attributes stack is empty")((!isStackEmpty() && Stack.back().first.size() > 1
&& "Data-sharing attributes stack is empty") ? static_cast
<void> (0) : __assert_fail ("!isStackEmpty() && Stack.back().first.size() > 1 && \"Data-sharing attributes stack is empty\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 957, __PRETTY_FUNCTION__))
;
958 const SharingMapTy &StackElem = *std::next(Stack.back().first.rbegin());
959 if (StackElem.LCVMap.size() < I)
960 return nullptr;
961 for (const auto &Pair : StackElem.LCVMap)
962 if (Pair.second.first == I)
963 return Pair.first;
964 return nullptr;
965}
966
967void DSAStackTy::addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
968 DeclRefExpr *PrivateCopy) {
969 D = getCanonicalDecl(D);
970 if (A == OMPC_threadprivate) {
971 DSAInfo &Data = Threadprivates[D];
972 Data.Attributes = A;
973 Data.RefExpr.setPointer(E);
974 Data.PrivateCopy = nullptr;
975 } else {
976 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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 976, __PRETTY_FUNCTION__))
;
977 DSAInfo &Data = Stack.back().first.back().SharingMap[D];
978 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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 981, __PRETTY_FUNCTION__))
979 (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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 981, __PRETTY_FUNCTION__))
980 (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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 981, __PRETTY_FUNCTION__))
981 (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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 981, __PRETTY_FUNCTION__))
;
982 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
983 Data.RefExpr.setInt(/*IntVal=*/true);
984 return;
985 }
986 const bool IsLastprivate =
987 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
988 Data.Attributes = A;
989 Data.RefExpr.setPointerAndInt(E, IsLastprivate);
990 Data.PrivateCopy = PrivateCopy;
991 if (PrivateCopy) {
992 DSAInfo &Data =
993 Stack.back().first.back().SharingMap[PrivateCopy->getDecl()];
994 Data.Attributes = A;
995 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
996 Data.PrivateCopy = nullptr;
997 }
998 }
999}
1000
1001/// Build a variable declaration for OpenMP loop iteration variable.
1002static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
1003 StringRef Name, const AttrVec *Attrs = nullptr,
1004 DeclRefExpr *OrigRef = nullptr) {
1005 DeclContext *DC = SemaRef.CurContext;
1006 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1007 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
1008 auto *Decl =
1009 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
1010 if (Attrs) {
1011 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
1012 I != E; ++I)
1013 Decl->addAttr(*I);
1014 }
1015 Decl->setImplicit();
1016 if (OrigRef) {
1017 Decl->addAttr(
1018 OMPReferencedVarAttr::CreateImplicit(SemaRef.Context, OrigRef));
1019 }
1020 return Decl;
1021}
1022
1023static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
1024 SourceLocation Loc,
1025 bool RefersToCapture = false) {
1026 D->setReferenced();
1027 D->markUsed(S.Context);
1028 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
1029 SourceLocation(), D, RefersToCapture, Loc, Ty,
1030 VK_LValue);
1031}
1032
1033void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
1034 BinaryOperatorKind BOK) {
1035 D = getCanonicalDecl(D);
1036 assert(!isStackEmpty() && "Data-sharing attributes stack is empty")((!isStackEmpty() && "Data-sharing attributes stack is empty"
) ? static_cast<void> (0) : __assert_fail ("!isStackEmpty() && \"Data-sharing attributes stack is empty\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1036, __PRETTY_FUNCTION__))
;
1037 assert(((Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction
&& "Additional reduction info may be specified only for reduction items."
) ? static_cast<void> (0) : __assert_fail ("Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction && \"Additional reduction info may be specified only for reduction items.\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1039, __PRETTY_FUNCTION__))
1038 Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&((Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction
&& "Additional reduction info may be specified only for reduction items."
) ? static_cast<void> (0) : __assert_fail ("Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction && \"Additional reduction info may be specified only for reduction items.\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1039, __PRETTY_FUNCTION__))
1039 "Additional reduction info may be specified only for reduction items.")((Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction
&& "Additional reduction info may be specified only for reduction items."
) ? static_cast<void> (0) : __assert_fail ("Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction && \"Additional reduction info may be specified only for reduction items.\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1039, __PRETTY_FUNCTION__))
;
1040 ReductionData &ReductionData = Stack.back().first.back().ReductionMap[D];
1041 assert(ReductionData.ReductionRange.isInvalid() &&((ReductionData.ReductionRange.isInvalid() && Stack.back
().first.back().Directive == OMPD_taskgroup && "Additional reduction info may be specified only once for reduction "
"items.") ? static_cast<void> (0) : __assert_fail ("ReductionData.ReductionRange.isInvalid() && Stack.back().first.back().Directive == OMPD_taskgroup && \"Additional reduction info may be specified only once for reduction \" \"items.\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1044, __PRETTY_FUNCTION__))
1042 Stack.back().first.back().Directive == OMPD_taskgroup &&((ReductionData.ReductionRange.isInvalid() && Stack.back
().first.back().Directive == OMPD_taskgroup && "Additional reduction info may be specified only once for reduction "
"items.") ? static_cast<void> (0) : __assert_fail ("ReductionData.ReductionRange.isInvalid() && Stack.back().first.back().Directive == OMPD_taskgroup && \"Additional reduction info may be specified only once for reduction \" \"items.\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1044, __PRETTY_FUNCTION__))
1043 "Additional reduction info may be specified only once for reduction "((ReductionData.ReductionRange.isInvalid() && Stack.back
().first.back().Directive == OMPD_taskgroup && "Additional reduction info may be specified only once for reduction "
"items.") ? static_cast<void> (0) : __assert_fail ("ReductionData.ReductionRange.isInvalid() && Stack.back().first.back().Directive == OMPD_taskgroup && \"Additional reduction info may be specified only once for reduction \" \"items.\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1044, __PRETTY_FUNCTION__))
1044 "items.")((ReductionData.ReductionRange.isInvalid() && Stack.back
().first.back().Directive == OMPD_taskgroup && "Additional reduction info may be specified only once for reduction "
"items.") ? static_cast<void> (0) : __assert_fail ("ReductionData.ReductionRange.isInvalid() && Stack.back().first.back().Directive == OMPD_taskgroup && \"Additional reduction info may be specified only once for reduction \" \"items.\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1044, __PRETTY_FUNCTION__))
;
1045 ReductionData.set(BOK, SR);
1046 Expr *&TaskgroupReductionRef =
1047 Stack.back().first.back().TaskgroupReductionRef;
1048 if (!TaskgroupReductionRef) {
1049 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
1050 SemaRef.Context.VoidPtrTy, ".task_red.");
1051 TaskgroupReductionRef =
1052 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
1053 }
1054}
1055
1056void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
1057 const Expr *ReductionRef) {
1058 D = getCanonicalDecl(D);
1059 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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1059, __PRETTY_FUNCTION__))
;
1060 assert(((Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction
&& "Additional reduction info may be specified only for reduction items."
) ? static_cast<void> (0) : __assert_fail ("Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction && \"Additional reduction info may be specified only for reduction items.\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1062, __PRETTY_FUNCTION__))
1061 Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&((Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction
&& "Additional reduction info may be specified only for reduction items."
) ? static_cast<void> (0) : __assert_fail ("Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction && \"Additional reduction info may be specified only for reduction items.\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1062, __PRETTY_FUNCTION__))
1062 "Additional reduction info may be specified only for reduction items.")((Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction
&& "Additional reduction info may be specified only for reduction items."
) ? static_cast<void> (0) : __assert_fail ("Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction && \"Additional reduction info may be specified only for reduction items.\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1062, __PRETTY_FUNCTION__))
;
1063 ReductionData &ReductionData = Stack.back().first.back().ReductionMap[D];
1064 assert(ReductionData.ReductionRange.isInvalid() &&((ReductionData.ReductionRange.isInvalid() && Stack.back
().first.back().Directive == OMPD_taskgroup && "Additional reduction info may be specified only once for reduction "
"items.") ? static_cast<void> (0) : __assert_fail ("ReductionData.ReductionRange.isInvalid() && Stack.back().first.back().Directive == OMPD_taskgroup && \"Additional reduction info may be specified only once for reduction \" \"items.\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1067, __PRETTY_FUNCTION__))
1065 Stack.back().first.back().Directive == OMPD_taskgroup &&((ReductionData.ReductionRange.isInvalid() && Stack.back
().first.back().Directive == OMPD_taskgroup && "Additional reduction info may be specified only once for reduction "
"items.") ? static_cast<void> (0) : __assert_fail ("ReductionData.ReductionRange.isInvalid() && Stack.back().first.back().Directive == OMPD_taskgroup && \"Additional reduction info may be specified only once for reduction \" \"items.\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1067, __PRETTY_FUNCTION__))
1066 "Additional reduction info may be specified only once for reduction "((ReductionData.ReductionRange.isInvalid() && Stack.back
().first.back().Directive == OMPD_taskgroup && "Additional reduction info may be specified only once for reduction "
"items.") ? static_cast<void> (0) : __assert_fail ("ReductionData.ReductionRange.isInvalid() && Stack.back().first.back().Directive == OMPD_taskgroup && \"Additional reduction info may be specified only once for reduction \" \"items.\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1067, __PRETTY_FUNCTION__))
1067 "items.")((ReductionData.ReductionRange.isInvalid() && Stack.back
().first.back().Directive == OMPD_taskgroup && "Additional reduction info may be specified only once for reduction "
"items.") ? static_cast<void> (0) : __assert_fail ("ReductionData.ReductionRange.isInvalid() && Stack.back().first.back().Directive == OMPD_taskgroup && \"Additional reduction info may be specified only once for reduction \" \"items.\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1067, __PRETTY_FUNCTION__))
;
1068 ReductionData.set(ReductionRef, SR);
1069 Expr *&TaskgroupReductionRef =
1070 Stack.back().first.back().TaskgroupReductionRef;
1071 if (!TaskgroupReductionRef) {
1072 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
1073 SemaRef.Context.VoidPtrTy, ".task_red.");
1074 TaskgroupReductionRef =
1075 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
1076 }
1077}
1078
1079const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1080 const ValueDecl *D, SourceRange &SR, BinaryOperatorKind &BOK,
1081 Expr *&TaskgroupDescriptor) const {
1082 D = getCanonicalDecl(D);
1083 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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1083, __PRETTY_FUNCTION__))
;
1084 if (Stack.back().first.empty())
1085 return DSAVarData();
1086 for (iterator I = std::next(Stack.back().first.rbegin(), 1),
1087 E = Stack.back().first.rend();
1088 I != E; std::advance(I, 1)) {
1089 const DSAInfo &Data = I->SharingMap.lookup(D);
1090 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
1091 continue;
1092 const ReductionData &ReductionData = I->ReductionMap.lookup(D);
1093 if (!ReductionData.ReductionOp ||
1094 ReductionData.ReductionOp.is<const Expr *>())
1095 return DSAVarData();
1096 SR = ReductionData.ReductionRange;
1097 BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>();
1098 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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1100, __PRETTY_FUNCTION__))
1099 "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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1100, __PRETTY_FUNCTION__))
1100 "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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1100, __PRETTY_FUNCTION__))
;
1101 TaskgroupDescriptor = I->TaskgroupReductionRef;
1102 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
1103 Data.PrivateCopy, I->DefaultAttrLoc);
1104 }
1105 return DSAVarData();
1106}
1107
1108const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1109 const ValueDecl *D, SourceRange &SR, const Expr *&ReductionRef,
1110 Expr *&TaskgroupDescriptor) const {
1111 D = getCanonicalDecl(D);
1112 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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1112, __PRETTY_FUNCTION__))
;
1113 if (Stack.back().first.empty())
1114 return DSAVarData();
1115 for (iterator I = std::next(Stack.back().first.rbegin(), 1),
1116 E = Stack.back().first.rend();
1117 I != E; std::advance(I, 1)) {
1118 const DSAInfo &Data = I->SharingMap.lookup(D);
1119 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
1120 continue;
1121 const ReductionData &ReductionData = I->ReductionMap.lookup(D);
1122 if (!ReductionData.ReductionOp ||
1123 !ReductionData.ReductionOp.is<const Expr *>())
1124 return DSAVarData();
1125 SR = ReductionData.ReductionRange;
1126 ReductionRef = ReductionData.ReductionOp.get<const Expr *>();
1127 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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1129, __PRETTY_FUNCTION__))
1128 "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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1129, __PRETTY_FUNCTION__))
1129 "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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1129, __PRETTY_FUNCTION__))
;
1130 TaskgroupDescriptor = I->TaskgroupReductionRef;
1131 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
1132 Data.PrivateCopy, I->DefaultAttrLoc);
1133 }
1134 return DSAVarData();
1135}
1136
1137bool DSAStackTy::isOpenMPLocal(VarDecl *D, iterator Iter) const {
1138 D = D->getCanonicalDecl();
1139 if (!isStackEmpty()) {
1140 iterator I = Iter, E = Stack.back().first.rend();
1141 Scope *TopScope = nullptr;
1142 while (I != E && !isImplicitOrExplicitTaskingRegion(I->Directive) &&
1143 !isOpenMPTargetExecutionDirective(I->Directive))
1144 ++I;
1145 if (I == E)
1146 return false;
1147 TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
1148 Scope *CurScope = getCurScope();
1149 while (CurScope && CurScope != TopScope && !CurScope->isDeclScope(D))
1150 CurScope = CurScope->getParent();
1151 return CurScope != TopScope;
1152 }
1153 return false;
1154}
1155
1156static bool isConstNotMutableType(Sema &SemaRef, QualType Type,
1157 bool AcceptIfMutable = true,
1158 bool *IsClassType = nullptr) {
1159 ASTContext &Context = SemaRef.getASTContext();
1160 Type = Type.getNonReferenceType().getCanonicalType();
1161 bool IsConstant = Type.isConstant(Context);
1162 Type = Context.getBaseElementType(Type);
1163 const CXXRecordDecl *RD = AcceptIfMutable && SemaRef.getLangOpts().CPlusPlus
1164 ? Type->getAsCXXRecordDecl()
1165 : nullptr;
1166 if (const auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
1167 if (const ClassTemplateDecl *CTD = CTSD->getSpecializedTemplate())
1168 RD = CTD->getTemplatedDecl();
1169 if (IsClassType)
1170 *IsClassType = RD;
1171 return IsConstant && !(SemaRef.getLangOpts().CPlusPlus && RD &&
1172 RD->hasDefinition() && RD->hasMutableFields());
1173}
1174
1175static bool rejectConstNotMutableType(Sema &SemaRef, const ValueDecl *D,
1176 QualType Type, OpenMPClauseKind CKind,
1177 SourceLocation ELoc,
1178 bool AcceptIfMutable = true,
1179 bool ListItemNotVar = false) {
1180 ASTContext &Context = SemaRef.getASTContext();
1181 bool IsClassType;
1182 if (isConstNotMutableType(SemaRef, Type, AcceptIfMutable, &IsClassType)) {
1183 unsigned Diag = ListItemNotVar
1184 ? diag::err_omp_const_list_item
1185 : IsClassType ? diag::err_omp_const_not_mutable_variable
1186 : diag::err_omp_const_variable;
1187 SemaRef.Diag(ELoc, Diag) << getOpenMPClauseName(CKind);
1188 if (!ListItemNotVar && D) {
1189 const VarDecl *VD = dyn_cast<VarDecl>(D);
1190 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
1191 VarDecl::DeclarationOnly;
1192 SemaRef.Diag(D->getLocation(),
1193 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1194 << D;
1195 }
1196 return true;
1197 }
1198 return false;
1199}
1200
1201const DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D,
1202 bool FromParent) {
1203 D = getCanonicalDecl(D);
1204 DSAVarData DVar;
1205
1206 auto *VD = dyn_cast<VarDecl>(D);
1207 auto TI = Threadprivates.find(D);
1208 if (TI != Threadprivates.end()) {
1209 DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
1210 DVar.CKind = OMPC_threadprivate;
1211 return DVar;
1212 }
1213 if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
1214 DVar.RefExpr = buildDeclRefExpr(
1215 SemaRef, VD, D->getType().getNonReferenceType(),
1216 VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation());
1217 DVar.CKind = OMPC_threadprivate;
1218 addDSA(D, DVar.RefExpr, OMPC_threadprivate);
1219 return DVar;
1220 }
1221 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1222 // in a Construct, C/C++, predetermined, p.1]
1223 // Variables appearing in threadprivate directives are threadprivate.
1224 if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
1225 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1226 SemaRef.getLangOpts().OpenMPUseTLS &&
1227 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
1228 (VD && VD->getStorageClass() == SC_Register &&
1229 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
1230 DVar.RefExpr = buildDeclRefExpr(
1231 SemaRef, VD, D->getType().getNonReferenceType(), D->getLocation());
1232 DVar.CKind = OMPC_threadprivate;
1233 addDSA(D, DVar.RefExpr, OMPC_threadprivate);
1234 return DVar;
1235 }
1236 if (SemaRef.getLangOpts().OpenMPCUDAMode && VD &&
1237 VD->isLocalVarDeclOrParm() && !isStackEmpty() &&
1238 !isLoopControlVariable(D).first) {
1239 iterator IterTarget =
1240 std::find_if(Stack.back().first.rbegin(), Stack.back().first.rend(),
1241 [](const SharingMapTy &Data) {
1242 return isOpenMPTargetExecutionDirective(Data.Directive);
1243 });
1244 if (IterTarget != Stack.back().first.rend()) {
1245 iterator ParentIterTarget = std::next(IterTarget, 1);
1246 for (iterator Iter = Stack.back().first.rbegin();
1247 Iter != ParentIterTarget; std::advance(Iter, 1)) {
1248 if (isOpenMPLocal(VD, Iter)) {
1249 DVar.RefExpr =
1250 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1251 D->getLocation());
1252 DVar.CKind = OMPC_threadprivate;
1253 return DVar;
1254 }
1255 }
1256 if (!isClauseParsingMode() || IterTarget != Stack.back().first.rbegin()) {
1257 auto DSAIter = IterTarget->SharingMap.find(D);
1258 if (DSAIter != IterTarget->SharingMap.end() &&
1259 isOpenMPPrivate(DSAIter->getSecond().Attributes)) {
1260 DVar.RefExpr = DSAIter->getSecond().RefExpr.getPointer();
1261 DVar.CKind = OMPC_threadprivate;
1262 return DVar;
1263 }
1264 iterator End = Stack.back().first.rend();
1265 if (!SemaRef.isOpenMPCapturedByRef(
1266 D, std::distance(ParentIterTarget, End))) {
1267 DVar.RefExpr =
1268 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1269 IterTarget->ConstructLoc);
1270 DVar.CKind = OMPC_threadprivate;
1271 return DVar;
1272 }
1273 }
1274 }
1275 }
1276
1277 if (isStackEmpty())
1278 // Not in OpenMP execution region and top scope was already checked.
1279 return DVar;
1280
1281 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1282 // in a Construct, C/C++, predetermined, p.4]
1283 // Static data members are shared.
1284 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1285 // in a Construct, C/C++, predetermined, p.7]
1286 // Variables with static storage duration that are declared in a scope
1287 // inside the construct are shared.
1288 auto &&MatchesAlways = [](OpenMPDirectiveKind) { return true; };
1289 if (VD && VD->isStaticDataMember()) {
1290 DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent);
1291 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
1292 return DVar;
1293
1294 DVar.CKind = OMPC_shared;
1295 return DVar;
1296 }
1297
1298 // The predetermined shared attribute for const-qualified types having no
1299 // mutable members was removed after OpenMP 3.1.
1300 if (SemaRef.LangOpts.OpenMP <= 31) {
1301 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1302 // in a Construct, C/C++, predetermined, p.6]
1303 // Variables with const qualified type having no mutable member are
1304 // shared.
1305 if (isConstNotMutableType(SemaRef, D->getType())) {
1306 // Variables with const-qualified type having no mutable member may be
1307 // listed in a firstprivate clause, even if they are static data members.
1308 DSAVarData DVarTemp = hasInnermostDSA(
1309 D,
1310 [](OpenMPClauseKind C) {
1311 return C == OMPC_firstprivate || C == OMPC_shared;
1312 },
1313 MatchesAlways, FromParent);
1314 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
1315 return DVarTemp;
1316
1317 DVar.CKind = OMPC_shared;
1318 return DVar;
1319 }
1320 }
1321
1322 // Explicitly specified attributes and local variables with predetermined
1323 // attributes.
1324 iterator I = Stack.back().first.rbegin();
1325 iterator EndI = Stack.back().first.rend();
1326 if (FromParent && I != EndI)
1327 std::advance(I, 1);
1328 auto It = I->SharingMap.find(D);
1329 if (It != I->SharingMap.end()) {
1330 const DSAInfo &Data = It->getSecond();
1331 DVar.RefExpr = Data.RefExpr.getPointer();
1332 DVar.PrivateCopy = Data.PrivateCopy;
1333 DVar.CKind = Data.Attributes;
1334 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
1335 DVar.DKind = I->Directive;
1336 }
1337
1338 return DVar;
1339}
1340
1341const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
1342 bool FromParent) const {
1343 if (isStackEmpty()) {
1344 iterator I;
1345 return getDSA(I, D);
1346 }
1347 D = getCanonicalDecl(D);
1348 iterator StartI = Stack.back().first.rbegin();
1349 iterator EndI = Stack.back().first.rend();
1350 if (FromParent && StartI != EndI)
1351 std::advance(StartI, 1);
1352 return getDSA(StartI, D);
1353}
1354
1355const DSAStackTy::DSAVarData
1356DSAStackTy::hasDSA(ValueDecl *D,
1357 const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1358 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1359 bool FromParent) const {
1360 if (isStackEmpty())
1361 return {};
1362 D = getCanonicalDecl(D);
1363 iterator I = Stack.back().first.rbegin();
1364 iterator EndI = Stack.back().first.rend();
1365 if (FromParent && I != EndI)
1366 std::advance(I, 1);
1367 for (; I != EndI; std::advance(I, 1)) {
1368 if (!DPred(I->Directive) && !isImplicitOrExplicitTaskingRegion(I->Directive))
1369 continue;
1370 iterator NewI = I;
1371 DSAVarData DVar = getDSA(NewI, D);
1372 if (I == NewI && CPred(DVar.CKind))
1373 return DVar;
1374 }
1375 return {};
1376}
1377
1378const DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
1379 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1380 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1381 bool FromParent) const {
1382 if (isStackEmpty())
1383 return {};
1384 D = getCanonicalDecl(D);
1385 iterator StartI = Stack.back().first.rbegin();
1386 iterator EndI = Stack.back().first.rend();
1387 if (FromParent && StartI != EndI)
1388 std::advance(StartI, 1);
1389 if (StartI == EndI || !DPred(StartI->Directive))
1390 return {};
1391 iterator NewI = StartI;
1392 DSAVarData DVar = getDSA(NewI, D);
1393 return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData();
1394}
1395
1396bool DSAStackTy::hasExplicitDSA(
1397 const ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1398 unsigned Level, bool NotLastprivate) const {
1399 if (isStackEmpty())
1400 return false;
1401 D = getCanonicalDecl(D);
1402 auto StartI = Stack.back().first.begin();
1403 auto EndI = Stack.back().first.end();
1404 if (std::distance(StartI, EndI) <= (int)Level)
1405 return false;
1406 std::advance(StartI, Level);
1407 auto I = StartI->SharingMap.find(D);
1408 if ((I != StartI->SharingMap.end()) &&
1409 I->getSecond().RefExpr.getPointer() &&
1410 CPred(I->getSecond().Attributes) &&
1411 (!NotLastprivate || !I->getSecond().RefExpr.getInt()))
1412 return true;
1413 // Check predetermined rules for the loop control variables.
1414 auto LI = StartI->LCVMap.find(D);
1415 if (LI != StartI->LCVMap.end())
1416 return CPred(OMPC_private);
1417 return false;
1418}
1419
1420bool DSAStackTy::hasExplicitDirective(
1421 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1422 unsigned Level) const {
1423 if (isStackEmpty())
1424 return false;
1425 auto StartI = Stack.back().first.begin();
1426 auto EndI = Stack.back().first.end();
1427 if (std::distance(StartI, EndI) <= (int)Level)
1428 return false;
1429 std::advance(StartI, Level);
1430 return DPred(StartI->Directive);
1431}
1432
1433bool DSAStackTy::hasDirective(
1434 const llvm::function_ref<bool(OpenMPDirectiveKind,
1435 const DeclarationNameInfo &, SourceLocation)>
1436 DPred,
1437 bool FromParent) const {
1438 // We look only in the enclosing region.
1439 if (isStackEmpty())
1440 return false;
1441 auto StartI = std::next(Stack.back().first.rbegin());
1442 auto EndI = Stack.back().first.rend();
1443 if (FromParent && StartI != EndI)
1444 StartI = std::next(StartI);
1445 for (auto I = StartI, EE = EndI; I != EE; ++I) {
1446 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
1447 return true;
1448 }
1449 return false;
1450}
1451
1452void Sema::InitDataSharingAttributesStack() {
1453 VarDataSharingAttributesStack = new DSAStackTy(*this);
1454}
1455
1456#define DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
1457
1458void Sema::pushOpenMPFunctionRegion() {
1459 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->pushFunction();
1460}
1461
1462void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
1463 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->popFunction(OldFSI);
1464}
1465
1466static bool isOpenMPDeviceDelayedContext(Sema &S) {
1467 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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1468, __PRETTY_FUNCTION__))
1468 "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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1468, __PRETTY_FUNCTION__))
;
1469 return !S.isInOpenMPTargetExecutionDirective() &&
1470 !S.isInOpenMPDeclareTargetContext();
1471}
1472
1473/// Do we know that we will eventually codegen the given function?
1474static bool isKnownEmitted(Sema &S, FunctionDecl *FD) {
1475 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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1476, __PRETTY_FUNCTION__))
1476 "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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1476, __PRETTY_FUNCTION__))
;
1477 // Templates are emitted when they're instantiated.
1478 if (FD->isDependentContext())
1479 return false;
1480
1481 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
1482 FD->getCanonicalDecl()))
1483 return true;
1484
1485 // Otherwise, the function is known-emitted if it's in our set of
1486 // known-emitted functions.
1487 return S.DeviceKnownEmittedFns.count(FD) > 0;
1488}
1489
1490Sema::DeviceDiagBuilder Sema::diagIfOpenMPDeviceCode(SourceLocation Loc,
1491 unsigned DiagID) {
1492 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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1493, __PRETTY_FUNCTION__))
1493 "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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1493, __PRETTY_FUNCTION__))
;
1494 return DeviceDiagBuilder((isOpenMPDeviceDelayedContext(*this) &&
1495 !isKnownEmitted(*this, getCurFunctionDecl()))
1496 ? DeviceDiagBuilder::K_Deferred
1497 : DeviceDiagBuilder::K_Immediate,
1498 Loc, DiagID, getCurFunctionDecl(), *this);
1499}
1500
1501void Sema::checkOpenMPDeviceFunction(SourceLocation Loc, FunctionDecl *Callee) {
1502 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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1503, __PRETTY_FUNCTION__))
1503 "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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1503, __PRETTY_FUNCTION__))
;
1504 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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1504, __PRETTY_FUNCTION__))
;
1505 FunctionDecl *Caller = getCurFunctionDecl();
1506
1507 // If the caller is known-emitted, mark the callee as known-emitted.
1508 // Otherwise, mark the call in our call graph so we can traverse it later.
1509 if (!isOpenMPDeviceDelayedContext(*this) ||
1510 (Caller && isKnownEmitted(*this, Caller)))
1511 markKnownEmitted(*this, Caller, Callee, Loc, isKnownEmitted);
1512 else if (Caller)
1513 DeviceCallGraph[Caller].insert({Callee, Loc});
1514}
1515
1516void Sema::checkOpenMPDeviceExpr(const Expr *E) {
1517 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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1518, __PRETTY_FUNCTION__))
1518 "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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1518, __PRETTY_FUNCTION__))
;
1519 QualType Ty = E->getType();
1520 if ((Ty->isFloat16Type() && !Context.getTargetInfo().hasFloat16Type()) ||
1521 (Ty->isFloat128Type() && !Context.getTargetInfo().hasFloat128Type()) ||
1522 (Ty->isIntegerType() && Context.getTypeSize(Ty) == 128 &&
1523 !Context.getTargetInfo().hasInt128Type()))
1524 targetDiag(E->getExprLoc(), diag::err_type_unsupported)
1525 << Ty << E->getSourceRange();
1526}
1527
1528bool Sema::isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level) const {
1529 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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1529, __PRETTY_FUNCTION__))
;
1530
1531 ASTContext &Ctx = getASTContext();
1532 bool IsByRef = true;
1533
1534 // Find the directive that is associated with the provided scope.
1535 D = cast<ValueDecl>(D->getCanonicalDecl());
1536 QualType Ty = D->getType();
1537
1538 if (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
1539 // This table summarizes how a given variable should be passed to the device
1540 // given its type and the clauses where it appears. This table is based on
1541 // the description in OpenMP 4.5 [2.10.4, target Construct] and
1542 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
1543 //
1544 // =========================================================================
1545 // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
1546 // | |(tofrom:scalar)| | pvt | | | |
1547 // =========================================================================
1548 // | scl | | | | - | | bycopy|
1549 // | scl | | - | x | - | - | bycopy|
1550 // | scl | | x | - | - | - | null |
1551 // | scl | x | | | - | | byref |
1552 // | scl | x | - | x | - | - | bycopy|
1553 // | scl | x | x | - | - | - | null |
1554 // | scl | | - | - | - | x | byref |
1555 // | scl | x | - | - | - | x | byref |
1556 //
1557 // | agg | n.a. | | | - | | byref |
1558 // | agg | n.a. | - | x | - | - | byref |
1559 // | agg | n.a. | x | - | - | - | null |
1560 // | agg | n.a. | - | - | - | x | byref |
1561 // | agg | n.a. | - | - | - | x[] | byref |
1562 //
1563 // | ptr | n.a. | | | - | | bycopy|
1564 // | ptr | n.a. | - | x | - | - | bycopy|
1565 // | ptr | n.a. | x | - | - | - | null |
1566 // | ptr | n.a. | - | - | - | x | byref |
1567 // | ptr | n.a. | - | - | - | x[] | bycopy|
1568 // | ptr | n.a. | - | - | x | | bycopy|
1569 // | ptr | n.a. | - | - | x | x | bycopy|
1570 // | ptr | n.a. | - | - | x | x[] | bycopy|
1571 // =========================================================================
1572 // Legend:
1573 // scl - scalar
1574 // ptr - pointer
1575 // agg - aggregate
1576 // x - applies
1577 // - - invalid in this combination
1578 // [] - mapped with an array section
1579 // byref - should be mapped by reference
1580 // byval - should be mapped by value
1581 // null - initialize a local variable to null on the device
1582 //
1583 // Observations:
1584 // - All scalar declarations that show up in a map clause have to be passed
1585 // by reference, because they may have been mapped in the enclosing data
1586 // environment.
1587 // - If the scalar value does not fit the size of uintptr, it has to be
1588 // passed by reference, regardless the result in the table above.
1589 // - For pointers mapped by value that have either an implicit map or an
1590 // array section, the runtime library may pass the NULL value to the
1591 // device instead of the value passed to it by the compiler.
1592
1593 if (Ty->isReferenceType())
1594 Ty = Ty->castAs<ReferenceType>()->getPointeeType();
1595
1596 // Locate map clauses and see if the variable being captured is referred to
1597 // in any of those clauses. Here we only care about variables, not fields,
1598 // because fields are part of aggregates.
1599 bool IsVariableUsedInMapClause = false;
1600 bool IsVariableAssociatedWithSection = false;
1601
1602 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->checkMappableExprComponentListsForDeclAtLevel(
1603 D, Level,
1604 [&IsVariableUsedInMapClause, &IsVariableAssociatedWithSection, D](
1605 OMPClauseMappableExprCommon::MappableExprComponentListRef
1606 MapExprComponents,
1607 OpenMPClauseKind WhereFoundClauseKind) {
1608 // Only the map clause information influences how a variable is
1609 // captured. E.g. is_device_ptr does not require changing the default
1610 // behavior.
1611 if (WhereFoundClauseKind != OMPC_map)
1612 return false;
1613
1614 auto EI = MapExprComponents.rbegin();
1615 auto EE = MapExprComponents.rend();
1616
1617 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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1617, __PRETTY_FUNCTION__))
;
1618
1619 if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
1620 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
1621
1622 ++EI;
1623 if (EI == EE)
1624 return false;
1625
1626 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
1627 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
1628 isa<MemberExpr>(EI->getAssociatedExpression())) {
1629 IsVariableAssociatedWithSection = true;
1630 // There is nothing more we need to know about this variable.
1631 return true;
1632 }
1633
1634 // Keep looking for more map info.
1635 return false;
1636 });
1637
1638 if (IsVariableUsedInMapClause) {
1639 // If variable is identified in a map clause it is always captured by
1640 // reference except if it is a pointer that is dereferenced somehow.
1641 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
1642 } else {
1643 // By default, all the data that has a scalar type is mapped by copy
1644 // (except for reduction variables).
1645 IsByRef =
1646 (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isForceCaptureByReferenceInTargetExecutable() &&
1647 !Ty->isAnyPointerType()) ||
1648 !Ty->isScalarType() ||
1649 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getDefaultDMAAtLevel(Level) == DMA_tofrom_scalar ||
1650 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasExplicitDSA(
1651 D, [](OpenMPClauseKind K) { return K == OMPC_reduction; }, Level);
1652 }
1653 }
1654
1655 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
1656 IsByRef =
1657 ((DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isForceCaptureByReferenceInTargetExecutable() &&
1658 !Ty->isAnyPointerType()) ||
1659 !DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasExplicitDSA(
1660 D,
1661 [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
1662 Level, /*NotLastprivate=*/true)) &&
1663 // If the variable is artificial and must be captured by value - try to
1664 // capture by value.
1665 !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() &&
1666 !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue());
1667 }
1668
1669 // When passing data by copy, we need to make sure it fits the uintptr size
1670 // and alignment, because the runtime library only deals with uintptr types.
1671 // If it does not fit the uintptr size, we need to pass the data by reference
1672 // instead.
1673 if (!IsByRef &&
1674 (Ctx.getTypeSizeInChars(Ty) >
1675 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
1676 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
1677 IsByRef = true;
1678 }
1679
1680 return IsByRef;
1681}
1682
1683unsigned Sema::getOpenMPNestingLevel() const {
1684 assert(getLangOpts().OpenMP)((getLangOpts().OpenMP) ? static_cast<void> (0) : __assert_fail
("getLangOpts().OpenMP", "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1684, __PRETTY_FUNCTION__))
;
1685 return DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getNestingLevel();
1686}
1687
1688bool Sema::isInOpenMPTargetExecutionDirective() const {
1689 return (isOpenMPTargetExecutionDirective(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective()) &&
1690 !DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isClauseParsingMode()) ||
1691 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasDirective(
1692 [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
1693 SourceLocation) -> bool {
1694 return isOpenMPTargetExecutionDirective(K);
1695 },
1696 false);
1697}
1698
1699VarDecl *Sema::isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo,
1700 unsigned StopAt) {
1701 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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1701, __PRETTY_FUNCTION__))
;
1702 D = getCanonicalDecl(D);
1703
1704 // If we are attempting to capture a global variable in a directive with
1705 // 'target' we return true so that this global is also mapped to the device.
1706 //
1707 auto *VD = dyn_cast<VarDecl>(D);
1708 if (VD && !VD->hasLocalStorage()) {
1709 if (isInOpenMPDeclareTargetContext() &&
1710 (getCurCapturedRegion() || getCurBlock() || getCurLambda())) {
1711 // Try to mark variable as declare target if it is used in capturing
1712 // regions.
1713 if (!OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
1714 checkDeclIsAllowedInOpenMPTarget(nullptr, VD);
1715 return nullptr;
1716 } else if (isInOpenMPTargetExecutionDirective()) {
1717 // If the declaration is enclosed in a 'declare target' directive,
1718 // then it should not be captured.
1719 //
1720 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
1721 return nullptr;
1722 return VD;
1723 }
1724 }
1725 // Capture variables captured by reference in lambdas for target-based
1726 // directives.
1727 if (VD && !DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isClauseParsingMode()) {
1728 if (const auto *RD = VD->getType()
1729 .getCanonicalType()
1730 .getNonReferenceType()
1731 ->getAsCXXRecordDecl()) {
1732 bool SavedForceCaptureByReferenceInTargetExecutable =
1733 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isForceCaptureByReferenceInTargetExecutable();
1734 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->setForceCaptureByReferenceInTargetExecutable(/*V=*/true);
1735 if (RD->isLambda()) {
1736 llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
1737 FieldDecl *ThisCapture;
1738 RD->getCaptureFields(Captures, ThisCapture);
1739 for (const LambdaCapture &LC : RD->captures()) {
1740 if (LC.getCaptureKind() == LCK_ByRef) {
1741 VarDecl *VD = LC.getCapturedVar();
1742 DeclContext *VDC = VD->getDeclContext();
1743 if (!VDC->Encloses(CurContext))
1744 continue;
1745 DSAStackTy::DSAVarData DVarPrivate =
1746 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getTopDSA(VD, /*FromParent=*/false);
1747 // Do not capture already captured variables.
1748 if (!OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) &&
1749 DVarPrivate.CKind == OMPC_unknown &&
1750 !DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->checkMappableExprComponentListsForDecl(
1751 D, /*CurrentRegionOnly=*/true,
1752 [](OMPClauseMappableExprCommon::
1753 MappableExprComponentListRef,
1754 OpenMPClauseKind) { return true; }))
1755 MarkVariableReferenced(LC.getLocation(), LC.getCapturedVar());
1756 } else if (LC.getCaptureKind() == LCK_This) {
1757 QualType ThisTy = getCurrentThisType();
1758 if (!ThisTy.isNull() &&
1759 Context.typesAreCompatible(ThisTy, ThisCapture->getType()))
1760 CheckCXXThisCapture(LC.getLocation());
1761 }
1762 }
1763 }
1764 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->setForceCaptureByReferenceInTargetExecutable(
1765 SavedForceCaptureByReferenceInTargetExecutable);
1766 }
1767 }
1768
1769 if (CheckScopeInfo) {
1770 bool OpenMPFound = false;
1771 for (unsigned I = StopAt + 1; I > 0; --I) {
1772 FunctionScopeInfo *FSI = FunctionScopes[I - 1];
1773 if(!isa<CapturingScopeInfo>(FSI))
1774 return nullptr;
1775 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(FSI))
1776 if (RSI->CapRegionKind == CR_OpenMP) {
1777 OpenMPFound = true;
1778 break;
1779 }
1780 }
1781 if (!OpenMPFound)
1782 return nullptr;
1783 }
1784
1785 if (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective() != OMPD_unknown &&
1786 (!DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isClauseParsingMode() ||
1787 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getParentDirective() != OMPD_unknown)) {
1788 auto &&Info = DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isLoopControlVariable(D);
1789 if (Info.first ||
1790 (VD && VD->hasLocalStorage() &&
1791 isImplicitOrExplicitTaskingRegion(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective())) ||
1792 (VD && DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isForceVarCapturing()))
1793 return VD ? VD : Info.second;
1794 DSAStackTy::DSAVarData DVarPrivate =
1795 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getTopDSA(D, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isClauseParsingMode());
1796 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
1797 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
1798 DVarPrivate = DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasDSA(D, isOpenMPPrivate,
1799 [](OpenMPDirectiveKind) { return true; },
1800 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isClauseParsingMode());
1801 // The variable is not private or it is the variable in the directive with
1802 // default(none) clause and not used in any clause.
1803 if (DVarPrivate.CKind != OMPC_unknown ||
1804 (VD && DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getDefaultDSA() == DSA_none))
1805 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
1806 }
1807 return nullptr;
1808}
1809
1810void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
1811 unsigned Level) const {
1812 SmallVector<OpenMPDirectiveKind, 4> Regions;
1813 getOpenMPCaptureRegions(Regions, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getDirective(Level));
1814 FunctionScopesIndex -= Regions.size();
1815}
1816
1817void Sema::startOpenMPLoop() {
1818 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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1818, __PRETTY_FUNCTION__))
;
1819 if (isOpenMPLoopDirective(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective()))
1820 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->loopInit();
1821}
1822
1823bool Sema::isOpenMPPrivateDecl(const ValueDecl *D, unsigned Level) const {
1824 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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1824, __PRETTY_FUNCTION__))
;
1825 if (isOpenMPLoopDirective(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective())) {
1826 if (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getAssociatedLoops() > 0 &&
1827 !DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isLoopStarted()) {
1828 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->resetPossibleLoopCounter(D);
1829 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->loopStart();
1830 return true;
1831 }
1832 if ((DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getPossiblyLoopCunter() == D->getCanonicalDecl() ||
1833 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isLoopControlVariable(D).first) &&
1834 !DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasExplicitDSA(
1835 D, [](OpenMPClauseKind K) { return K != OMPC_private; }, Level) &&
1836 !isOpenMPSimdDirective(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective()))
1837 return true;
1838 }
1839 return DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasExplicitDSA(
1840 D, [](OpenMPClauseKind K) { return K == OMPC_private; }, Level) ||
1841 (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isClauseParsingMode() &&
1842 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getClauseParsingMode() == OMPC_private) ||
1843 // Consider taskgroup reduction descriptor variable a private to avoid
1844 // possible capture in the region.
1845 (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasExplicitDirective(
1846 [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; },
1847 Level) &&
1848 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isTaskgroupReductionRef(D, Level));
1849}
1850
1851void Sema::setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D,
1852 unsigned Level) {
1853 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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1853, __PRETTY_FUNCTION__))
;
1854 D = getCanonicalDecl(D);
1855 OpenMPClauseKind OMPC = OMPC_unknown;
1856 for (unsigned I = DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getNestingLevel() + 1; I > Level; --I) {
1857 const unsigned NewLevel = I - 1;
1858 if (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasExplicitDSA(D,
1859 [&OMPC](const OpenMPClauseKind K) {
1860 if (isOpenMPPrivate(K)) {
1861 OMPC = K;
1862 return true;
1863 }
1864 return false;
1865 },
1866 NewLevel))
1867 break;
1868 if (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->checkMappableExprComponentListsForDeclAtLevel(
1869 D, NewLevel,
1870 [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
1871 OpenMPClauseKind) { return true; })) {
1872 OMPC = OMPC_map;
1873 break;
1874 }
1875 if (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1876 NewLevel)) {
1877 OMPC = OMPC_map;
1878 if (D->getType()->isScalarType() &&
1879 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getDefaultDMAAtLevel(NewLevel) !=
1880 DefaultMapAttributes::DMA_tofrom_scalar)
1881 OMPC = OMPC_firstprivate;
1882 break;
1883 }
1884 }
1885 if (OMPC != OMPC_unknown)
1886 FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, OMPC));
1887}
1888
1889bool Sema::isOpenMPTargetCapturedDecl(const ValueDecl *D,
1890 unsigned Level) const {
1891 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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1891, __PRETTY_FUNCTION__))
;
1892 // Return true if the current level is no longer enclosed in a target region.
1893
1894 const auto *VD = dyn_cast<VarDecl>(D);
1895 return VD && !VD->hasLocalStorage() &&
1896 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1897 Level);
1898}
1899
1900void Sema::DestroyDataSharingAttributesStack() { delete DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
; }
1901
1902void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
1903 const DeclarationNameInfo &DirName,
1904 Scope *CurScope, SourceLocation Loc) {
1905 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->push(DKind, DirName, CurScope, Loc);
1906 PushExpressionEvaluationContext(
1907 ExpressionEvaluationContext::PotentiallyEvaluated);
1908}
1909
1910void Sema::StartOpenMPClause(OpenMPClauseKind K) {
1911 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->setClauseParsingMode(K);
1912}
1913
1914void Sema::EndOpenMPClause() {
1915 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->setClauseParsingMode(/*K=*/OMPC_unknown);
1916}
1917
1918static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
1919 ArrayRef<OMPClause *> Clauses);
1920
1921void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
1922 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
1923 // A variable of class type (or array thereof) that appears in a lastprivate
1924 // clause requires an accessible, unambiguous default constructor for the
1925 // class type, unless the list item is also specified in a firstprivate
1926 // clause.
1927 if (const auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
1928 for (OMPClause *C : D->clauses()) {
1929 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
1930 SmallVector<Expr *, 8> PrivateCopies;
1931 for (Expr *DE : Clause->varlists()) {
1932 if (DE->isValueDependent() || DE->isTypeDependent()) {
1933 PrivateCopies.push_back(nullptr);
1934 continue;
1935 }
1936 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
1937 auto *VD = cast<VarDecl>(DRE->getDecl());
1938 QualType Type = VD->getType().getNonReferenceType();
1939 const DSAStackTy::DSAVarData DVar =
1940 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getTopDSA(VD, /*FromParent=*/false);
1941 if (DVar.CKind == OMPC_lastprivate) {
1942 // Generate helper private variable and initialize it with the
1943 // default value. The address of the original variable is replaced
1944 // by the address of the new private variable in CodeGen. This new
1945 // variable is not added to IdResolver, so the code in the OpenMP
1946 // region uses original variable for proper diagnostics.
1947 VarDecl *VDPrivate = buildVarDecl(
1948 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
1949 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE);
1950 ActOnUninitializedDecl(VDPrivate);
1951 if (VDPrivate->isInvalidDecl()) {
1952 PrivateCopies.push_back(nullptr);
1953 continue;
1954 }
1955 PrivateCopies.push_back(buildDeclRefExpr(
1956 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
1957 } else {
1958 // The variable is also a firstprivate, so initialization sequence
1959 // for private copy is generated already.
1960 PrivateCopies.push_back(nullptr);
1961 }
1962 }
1963 Clause->setPrivateCopies(PrivateCopies);
1964 }
1965 }
1966 // Check allocate clauses.
1967 if (!CurContext->isDependentContext())
1968 checkAllocateClauses(*this, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, D->clauses());
1969 }
1970
1971 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->pop();
1972 DiscardCleanupsInEvaluationContext();
1973 PopExpressionEvaluationContext();
1974}
1975
1976static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
1977 Expr *NumIterations, Sema &SemaRef,
1978 Scope *S, DSAStackTy *Stack);
1979
1980namespace {
1981
1982class VarDeclFilterCCC final : public CorrectionCandidateCallback {
1983private:
1984 Sema &SemaRef;
1985
1986public:
1987 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
1988 bool ValidateCandidate(const TypoCorrection &Candidate) override {
1989 NamedDecl *ND = Candidate.getCorrectionDecl();
1990 if (const auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
1991 return VD->hasGlobalStorage() &&
1992 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1993 SemaRef.getCurScope());
1994 }
1995 return false;
1996 }
1997
1998 std::unique_ptr<CorrectionCandidateCallback> clone() override {
1999 return llvm::make_unique<VarDeclFilterCCC>(*this);
2000 }
2001
2002};
2003
2004class VarOrFuncDeclFilterCCC final : public CorrectionCandidateCallback {
2005private:
2006 Sema &SemaRef;
2007
2008public:
2009 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
2010 bool ValidateCandidate(const TypoCorrection &Candidate) override {
2011 NamedDecl *ND = Candidate.getCorrectionDecl();
2012 if (ND && ((isa<VarDecl>(ND) && ND->getKind() == Decl::Var) ||
2013 isa<FunctionDecl>(ND))) {
2014 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
2015 SemaRef.getCurScope());
2016 }
2017 return false;
2018 }
2019
2020 std::unique_ptr<CorrectionCandidateCallback> clone() override {
2021 return llvm::make_unique<VarOrFuncDeclFilterCCC>(*this);
2022 }
2023};
2024
2025} // namespace
2026
2027ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
2028 CXXScopeSpec &ScopeSpec,
2029 const DeclarationNameInfo &Id,
2030 OpenMPDirectiveKind Kind) {
2031 LookupResult Lookup(*this, Id, LookupOrdinaryName);
2032 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
2033
2034 if (Lookup.isAmbiguous())
2035 return ExprError();
2036
2037 VarDecl *VD;
2038 if (!Lookup.isSingleResult()) {
2039 VarDeclFilterCCC CCC(*this);
2040 if (TypoCorrection Corrected =
2041 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
2042 CTK_ErrorRecovery)) {
2043 diagnoseTypo(Corrected,
2044 PDiag(Lookup.empty()
2045 ? diag::err_undeclared_var_use_suggest
2046 : diag::err_omp_expected_var_arg_suggest)
2047 << Id.getName());
2048 VD = Corrected.getCorrectionDeclAs<VarDecl>();
2049 } else {
2050 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
2051 : diag::err_omp_expected_var_arg)
2052 << Id.getName();
2053 return ExprError();
2054 }
2055 } else if (!(VD = Lookup.getAsSingle<VarDecl>())) {
2056 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
2057 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
2058 return ExprError();
2059 }
2060 Lookup.suppressDiagnostics();
2061
2062 // OpenMP [2.9.2, Syntax, C/C++]
2063 // Variables must be file-scope, namespace-scope, or static block-scope.
2064 if (Kind == OMPD_threadprivate && !VD->hasGlobalStorage()) {
2065 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
2066 << getOpenMPDirectiveName(Kind) << !VD->isStaticLocal();
2067 bool IsDecl =
2068 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2069 Diag(VD->getLocation(),
2070 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2071 << VD;
2072 return ExprError();
2073 }
2074
2075 VarDecl *CanonicalVD = VD->getCanonicalDecl();
2076 NamedDecl *ND = CanonicalVD;
2077 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
2078 // A threadprivate directive for file-scope variables must appear outside
2079 // any definition or declaration.
2080 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
2081 !getCurLexicalContext()->isTranslationUnit()) {
2082 Diag(Id.getLoc(), diag::err_omp_var_scope)
2083 << getOpenMPDirectiveName(Kind) << VD;
2084 bool IsDecl =
2085 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2086 Diag(VD->getLocation(),
2087 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2088 << VD;
2089 return ExprError();
2090 }
2091 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
2092 // A threadprivate directive for static class member variables must appear
2093 // in the class definition, in the same scope in which the member
2094 // variables are declared.
2095 if (CanonicalVD->isStaticDataMember() &&
2096 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
2097 Diag(Id.getLoc(), diag::err_omp_var_scope)
2098 << getOpenMPDirectiveName(Kind) << VD;
2099 bool IsDecl =
2100 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2101 Diag(VD->getLocation(),
2102 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2103 << VD;
2104 return ExprError();
2105 }
2106 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
2107 // A threadprivate directive for namespace-scope variables must appear
2108 // outside any definition or declaration other than the namespace
2109 // definition itself.
2110 if (CanonicalVD->getDeclContext()->isNamespace() &&
2111 (!getCurLexicalContext()->isFileContext() ||
2112 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
2113 Diag(Id.getLoc(), diag::err_omp_var_scope)
2114 << getOpenMPDirectiveName(Kind) << VD;
2115 bool IsDecl =
2116 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2117 Diag(VD->getLocation(),
2118 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2119 << VD;
2120 return ExprError();
2121 }
2122 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
2123 // A threadprivate directive for static block-scope variables must appear
2124 // in the scope of the variable and not in a nested scope.
2125 if (CanonicalVD->isLocalVarDecl() && CurScope &&
2126 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
2127 Diag(Id.getLoc(), diag::err_omp_var_scope)
2128 << getOpenMPDirectiveName(Kind) << VD;
2129 bool IsDecl =
2130 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2131 Diag(VD->getLocation(),
2132 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2133 << VD;
2134 return ExprError();
2135 }
2136
2137 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
2138 // A threadprivate directive must lexically precede all references to any
2139 // of the variables in its list.
2140 if (Kind == OMPD_threadprivate && VD->isUsed() &&
2141 !DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isThreadPrivate(VD)) {
2142 Diag(Id.getLoc(), diag::err_omp_var_used)
2143 << getOpenMPDirectiveName(Kind) << VD;
2144 return ExprError();
2145 }
2146
2147 QualType ExprType = VD->getType().getNonReferenceType();
2148 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
2149 SourceLocation(), VD,
2150 /*RefersToEnclosingVariableOrCapture=*/false,
2151 Id.getLoc(), ExprType, VK_LValue);
2152}
2153
2154Sema::DeclGroupPtrTy
2155Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
2156 ArrayRef<Expr *> VarList) {
2157 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
2158 CurContext->addDecl(D);
2159 return DeclGroupPtrTy::make(DeclGroupRef(D));
2160 }
2161 return nullptr;
2162}
2163
2164namespace {
2165class LocalVarRefChecker final
2166 : public ConstStmtVisitor<LocalVarRefChecker, bool> {
2167 Sema &SemaRef;
2168
2169public:
2170 bool VisitDeclRefExpr(const DeclRefExpr *E) {
2171 if (const auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
2172 if (VD->hasLocalStorage()) {
2173 SemaRef.Diag(E->getBeginLoc(),
2174 diag::err_omp_local_var_in_threadprivate_init)
2175 << E->getSourceRange();
2176 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
2177 << VD << VD->getSourceRange();
2178 return true;
2179 }
2180 }
2181 return false;
2182 }
2183 bool VisitStmt(const Stmt *S) {
2184 for (const Stmt *Child : S->children()) {
2185 if (Child && Visit(Child))
2186 return true;
2187 }
2188 return false;
2189 }
2190 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
2191};
2192} // namespace
2193
2194OMPThreadPrivateDecl *
2195Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
2196 SmallVector<Expr *, 8> Vars;
2197 for (Expr *RefExpr : VarList) {
2198 auto *DE = cast<DeclRefExpr>(RefExpr);
2199 auto *VD = cast<VarDecl>(DE->getDecl());
2200 SourceLocation ILoc = DE->getExprLoc();
2201
2202 // Mark variable as used.
2203 VD->setReferenced();
2204 VD->markUsed(Context);
2205
2206 QualType QType = VD->getType();
2207 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
2208 // It will be analyzed later.
2209 Vars.push_back(DE);
2210 continue;
2211 }
2212
2213 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2214 // A threadprivate variable must not have an incomplete type.
2215 if (RequireCompleteType(ILoc, VD->getType(),
2216 diag::err_omp_threadprivate_incomplete_type)) {
2217 continue;
2218 }
2219
2220 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2221 // A threadprivate variable must not have a reference type.
2222 if (VD->getType()->isReferenceType()) {
2223 Diag(ILoc, diag::err_omp_ref_type_arg)
2224 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
2225 bool IsDecl =
2226 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2227 Diag(VD->getLocation(),
2228 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2229 << VD;
2230 continue;
2231 }
2232
2233 // Check if this is a TLS variable. If TLS is not being supported, produce
2234 // the corresponding diagnostic.
2235 if ((VD->getTLSKind() != VarDecl::TLS_None &&
2236 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
2237 getLangOpts().OpenMPUseTLS &&
2238 getASTContext().getTargetInfo().isTLSSupported())) ||
2239 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
2240 !VD->isLocalVarDecl())) {
2241 Diag(ILoc, diag::err_omp_var_thread_local)
2242 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
2243 bool IsDecl =
2244 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2245 Diag(VD->getLocation(),
2246 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2247 << VD;
2248 continue;
2249 }
2250
2251 // Check if initial value of threadprivate variable reference variable with
2252 // local storage (it is not supported by runtime).
2253 if (const Expr *Init = VD->getAnyInitializer()) {
2254 LocalVarRefChecker Checker(*this);
2255 if (Checker.Visit(Init))
2256 continue;
2257 }
2258
2259 Vars.push_back(RefExpr);
2260 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->addDSA(VD, DE, OMPC_threadprivate);
2261 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
2262 Context, SourceRange(Loc, Loc)));
2263 if (ASTMutationListener *ML = Context.getASTMutationListener())
2264 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
2265 }
2266 OMPThreadPrivateDecl *D = nullptr;
2267 if (!Vars.empty()) {
2268 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
2269 Vars);
2270 D->setAccess(AS_public);
2271 }
2272 return D;
2273}
2274
2275static OMPAllocateDeclAttr::AllocatorTypeTy
2276getAllocatorKind(Sema &S, DSAStackTy *Stack, Expr *Allocator) {
2277 if (!Allocator)
2278 return OMPAllocateDeclAttr::OMPDefaultMemAlloc;
2279 if (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
2280 Allocator->isInstantiationDependent() ||
2281 Allocator->containsUnexpandedParameterPack())
2282 return OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
2283 auto AllocatorKindRes = OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
2284 const Expr *AE = Allocator->IgnoreParenImpCasts();
2285 for (int I = OMPAllocateDeclAttr::OMPDefaultMemAlloc;
2286 I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
2287 auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
2288 const Expr *DefAllocator = Stack->getAllocator(AllocatorKind);
2289 llvm::FoldingSetNodeID AEId, DAEId;
2290 AE->Profile(AEId, S.getASTContext(), /*Canonical=*/true);
2291 DefAllocator->Profile(DAEId, S.getASTContext(), /*Canonical=*/true);
2292 if (AEId == DAEId) {
2293 AllocatorKindRes = AllocatorKind;
2294 break;
2295 }
2296 }
2297 return AllocatorKindRes;
2298}
2299
2300static bool checkPreviousOMPAllocateAttribute(
2301 Sema &S, DSAStackTy *Stack, Expr *RefExpr, VarDecl *VD,
2302 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind, Expr *Allocator) {
2303 if (!VD->hasAttr<OMPAllocateDeclAttr>())
2304 return false;
2305 const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
2306 Expr *PrevAllocator = A->getAllocator();
2307 OMPAllocateDeclAttr::AllocatorTypeTy PrevAllocatorKind =
2308 getAllocatorKind(S, Stack, PrevAllocator);
2309 bool AllocatorsMatch = AllocatorKind == PrevAllocatorKind;
2310 if (AllocatorsMatch &&
2311 AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc &&
2312 Allocator && PrevAllocator) {
2313 const Expr *AE = Allocator->IgnoreParenImpCasts();
2314 const Expr *PAE = PrevAllocator->IgnoreParenImpCasts();
2315 llvm::FoldingSetNodeID AEId, PAEId;
2316 AE->Profile(AEId, S.Context, /*Canonical=*/true);
2317 PAE->Profile(PAEId, S.Context, /*Canonical=*/true);
2318 AllocatorsMatch = AEId == PAEId;
2319 }
2320 if (!AllocatorsMatch) {
2321 SmallString<256> AllocatorBuffer;
2322 llvm::raw_svector_ostream AllocatorStream(AllocatorBuffer);
2323 if (Allocator)
2324 Allocator->printPretty(AllocatorStream, nullptr, S.getPrintingPolicy());
2325 SmallString<256> PrevAllocatorBuffer;
2326 llvm::raw_svector_ostream PrevAllocatorStream(PrevAllocatorBuffer);
2327 if (PrevAllocator)
2328 PrevAllocator->printPretty(PrevAllocatorStream, nullptr,
2329 S.getPrintingPolicy());
2330
2331 SourceLocation AllocatorLoc =
2332 Allocator ? Allocator->getExprLoc() : RefExpr->getExprLoc();
2333 SourceRange AllocatorRange =
2334 Allocator ? Allocator->getSourceRange() : RefExpr->getSourceRange();
2335 SourceLocation PrevAllocatorLoc =
2336 PrevAllocator ? PrevAllocator->getExprLoc() : A->getLocation();
2337 SourceRange PrevAllocatorRange =
2338 PrevAllocator ? PrevAllocator->getSourceRange() : A->getRange();
2339 S.Diag(AllocatorLoc, diag::warn_omp_used_different_allocator)
2340 << (Allocator ? 1 : 0) << AllocatorStream.str()
2341 << (PrevAllocator ? 1 : 0) << PrevAllocatorStream.str()
2342 << AllocatorRange;
2343 S.Diag(PrevAllocatorLoc, diag::note_omp_previous_allocator)
2344 << PrevAllocatorRange;
2345 return true;
2346 }
2347 return false;
2348}
2349
2350static void
2351applyOMPAllocateAttribute(Sema &S, VarDecl *VD,
2352 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
2353 Expr *Allocator, SourceRange SR) {
2354 if (VD->hasAttr<OMPAllocateDeclAttr>())
2355 return;
2356 if (Allocator &&
2357 (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
2358 Allocator->isInstantiationDependent() ||
2359 Allocator->containsUnexpandedParameterPack()))
2360 return;
2361 auto *A = OMPAllocateDeclAttr::CreateImplicit(S.Context, AllocatorKind,
2362 Allocator, SR);
2363 VD->addAttr(A);
2364 if (ASTMutationListener *ML = S.Context.getASTMutationListener())
2365 ML->DeclarationMarkedOpenMPAllocate(VD, A);
2366}
2367
2368Sema::DeclGroupPtrTy Sema::ActOnOpenMPAllocateDirective(
2369 SourceLocation Loc, ArrayRef<Expr *> VarList,
2370 ArrayRef<OMPClause *> Clauses, DeclContext *Owner) {
2371 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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 2371, __PRETTY_FUNCTION__))
;
2372 Expr *Allocator = nullptr;
2373 if (Clauses.empty()) {
2374 // OpenMP 5.0, 2.11.3 allocate Directive, Restrictions.
2375 // allocate directives that appear in a target region must specify an
2376 // allocator clause unless a requires directive with the dynamic_allocators
2377 // clause is present in the same compilation unit.
2378 if (LangOpts.OpenMPIsDevice &&
2379 !DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
2380 targetDiag(Loc, diag::err_expected_allocator_clause);
2381 } else {
2382 Allocator = cast<OMPAllocatorClause>(Clauses.back())->getAllocator();
2383 }
2384 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
2385 getAllocatorKind(*this, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, Allocator);
2386 SmallVector<Expr *, 8> Vars;
2387 for (Expr *RefExpr : VarList) {
2388 auto *DE = cast<DeclRefExpr>(RefExpr);
2389 auto *VD = cast<VarDecl>(DE->getDecl());
2390
2391 // Check if this is a TLS variable or global register.
2392 if (VD->getTLSKind() != VarDecl::TLS_None ||
2393 VD->hasAttr<OMPThreadPrivateDeclAttr>() ||
2394 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
2395 !VD->isLocalVarDecl()))
2396 continue;
2397
2398 // If the used several times in the allocate directive, the same allocator
2399 // must be used.
2400 if (checkPreviousOMPAllocateAttribute(*this, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, RefExpr, VD,
2401 AllocatorKind, Allocator))
2402 continue;
2403
2404 // OpenMP, 2.11.3 allocate Directive, Restrictions, C / C++
2405 // If a list item has a static storage type, the allocator expression in the
2406 // allocator clause must be a constant expression that evaluates to one of
2407 // the predefined memory allocator values.
2408 if (Allocator && VD->hasGlobalStorage()) {
2409 if (AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc) {
2410 Diag(Allocator->getExprLoc(),
2411 diag::err_omp_expected_predefined_allocator)
2412 << Allocator->getSourceRange();
2413 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
2414 VarDecl::DeclarationOnly;
2415 Diag(VD->getLocation(),
2416 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2417 << VD;
2418 continue;
2419 }
2420 }
2421
2422 Vars.push_back(RefExpr);
2423 applyOMPAllocateAttribute(*this, VD, AllocatorKind, Allocator,
2424 DE->getSourceRange());
2425 }
2426 if (Vars.empty())
2427 return nullptr;
2428 if (!Owner)
2429 Owner = getCurLexicalContext();
2430 auto *D = OMPAllocateDecl::Create(Context, Owner, Loc, Vars, Clauses);
2431 D->setAccess(AS_public);
2432 Owner->addDecl(D);
2433 return DeclGroupPtrTy::make(DeclGroupRef(D));
2434}
2435
2436Sema::DeclGroupPtrTy
2437Sema::ActOnOpenMPRequiresDirective(SourceLocation Loc,
2438 ArrayRef<OMPClause *> ClauseList) {
2439 OMPRequiresDecl *D = nullptr;
2440 if (!CurContext->isFileContext()) {
2441 Diag(Loc, diag::err_omp_invalid_scope) << "requires";
2442 } else {
2443 D = CheckOMPRequiresDecl(Loc, ClauseList);
2444 if (D) {
2445 CurContext->addDecl(D);
2446 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->addRequiresDecl(D);
2447 }
2448 }
2449 return DeclGroupPtrTy::make(DeclGroupRef(D));
2450}
2451
2452OMPRequiresDecl *Sema::CheckOMPRequiresDecl(SourceLocation Loc,
2453 ArrayRef<OMPClause *> ClauseList) {
2454 /// For target specific clauses, the requires directive cannot be
2455 /// specified after the handling of any of the target regions in the
2456 /// current compilation unit.
2457 ArrayRef<SourceLocation> TargetLocations =
2458 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getEncounteredTargetLocs();
2459 if (!TargetLocations.empty()) {
2460 for (const OMPClause *CNew : ClauseList) {
2461 // Check if any of the requires clauses affect target regions.
2462 if (isa<OMPUnifiedSharedMemoryClause>(CNew) ||
2463 isa<OMPUnifiedAddressClause>(CNew) ||
2464 isa<OMPReverseOffloadClause>(CNew) ||
2465 isa<OMPDynamicAllocatorsClause>(CNew)) {
2466 Diag(Loc, diag::err_omp_target_before_requires)
2467 << getOpenMPClauseName(CNew->getClauseKind());
2468 for (SourceLocation TargetLoc : TargetLocations) {
2469 Diag(TargetLoc, diag::note_omp_requires_encountered_target);
2470 }
2471 }
2472 }
2473 }
2474
2475 if (!DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasDuplicateRequiresClause(ClauseList))
2476 return OMPRequiresDecl::Create(Context, getCurLexicalContext(), Loc,
2477 ClauseList);
2478 return nullptr;
2479}
2480
2481static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
2482 const ValueDecl *D,
2483 const DSAStackTy::DSAVarData &DVar,
2484 bool IsLoopIterVar = false) {
2485 if (DVar.RefExpr) {
2486 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
2487 << getOpenMPClauseName(DVar.CKind);
2488 return;
2489 }
2490 enum {
2491 PDSA_StaticMemberShared,
2492 PDSA_StaticLocalVarShared,
2493 PDSA_LoopIterVarPrivate,
2494 PDSA_LoopIterVarLinear,
2495 PDSA_LoopIterVarLastprivate,
2496 PDSA_ConstVarShared,
2497 PDSA_GlobalVarShared,
2498 PDSA_TaskVarFirstprivate,
2499 PDSA_LocalVarPrivate,
2500 PDSA_Implicit
2501 } Reason = PDSA_Implicit;
2502 bool ReportHint = false;
2503 auto ReportLoc = D->getLocation();
2504 auto *VD = dyn_cast<VarDecl>(D);
2505 if (IsLoopIterVar) {
2506 if (DVar.CKind == OMPC_private)
2507 Reason = PDSA_LoopIterVarPrivate;
2508 else if (DVar.CKind == OMPC_lastprivate)
2509 Reason = PDSA_LoopIterVarLastprivate;
2510 else
2511 Reason = PDSA_LoopIterVarLinear;
2512 } else if (isOpenMPTaskingDirective(DVar.DKind) &&
2513 DVar.CKind == OMPC_firstprivate) {
2514 Reason = PDSA_TaskVarFirstprivate;
2515 ReportLoc = DVar.ImplicitDSALoc;
2516 } else if (VD && VD->isStaticLocal())
2517 Reason = PDSA_StaticLocalVarShared;
2518 else if (VD && VD->isStaticDataMember())
2519 Reason = PDSA_StaticMemberShared;
2520 else if (VD && VD->isFileVarDecl())
2521 Reason = PDSA_GlobalVarShared;
2522 else if (D->getType().isConstant(SemaRef.getASTContext()))
2523 Reason = PDSA_ConstVarShared;
2524 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
2525 ReportHint = true;
2526 Reason = PDSA_LocalVarPrivate;
2527 }
2528 if (Reason != PDSA_Implicit) {
2529 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
2530 << Reason << ReportHint
2531 << getOpenMPDirectiveName(Stack->getCurrentDirective());
2532 } else if (DVar.ImplicitDSALoc.isValid()) {
2533 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
2534 << getOpenMPClauseName(DVar.CKind);
2535 }
2536}
2537
2538namespace {
2539class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> {
2540 DSAStackTy *Stack;
2541 Sema &SemaRef;
2542 bool ErrorFound = false;
2543 CapturedStmt *CS = nullptr;
2544 llvm::SmallVector<Expr *, 4> ImplicitFirstprivate;
2545 llvm::SmallVector<Expr *, 4> ImplicitMap;
2546 Sema::VarsWithInheritedDSAType VarsWithInheritedDSA;
2547 llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations;
2548
2549 void VisitSubCaptures(OMPExecutableDirective *S) {
2550 // Check implicitly captured variables.
2551 if (!S->hasAssociatedStmt() || !S->getAssociatedStmt())
2552 return;
2553 for (const CapturedStmt::Capture &Cap :
2554 S->getInnermostCapturedStmt()->captures()) {
2555 if (!Cap.capturesVariable())
2556 continue;
2557 VarDecl *VD = Cap.getCapturedVar();
2558 // Do not try to map the variable if it or its sub-component was mapped
2559 // already.
2560 if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
2561 Stack->checkMappableExprComponentListsForDecl(
2562 VD, /*CurrentRegionOnly=*/true,
2563 [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
2564 OpenMPClauseKind) { return true; }))
2565 continue;
2566 DeclRefExpr *DRE = buildDeclRefExpr(
2567 SemaRef, VD, VD->getType().getNonLValueExprType(SemaRef.Context),
2568 Cap.getLocation(), /*RefersToCapture=*/true);
2569 Visit(DRE);
2570 }
2571 }
2572
2573public:
2574 void VisitDeclRefExpr(DeclRefExpr *E) {
2575 if (E->isTypeDependent() || E->isValueDependent() ||
2576 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
2577 return;
2578 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
2579 // Check the datasharing rules for the expressions in the clauses.
2580 if (!CS) {
2581 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD))
2582 if (!CED->hasAttr<OMPCaptureNoInitAttr>()) {
2583 Visit(CED->getInit());
2584 return;
2585 }
2586 }
2587 VD = VD->getCanonicalDecl();
2588 // Skip internally declared variables.
2589 if (VD->hasLocalStorage() && CS && !CS->capturesVariable(VD))
2590 return;
2591
2592 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
2593 // Check if the variable has explicit DSA set and stop analysis if it so.
2594 if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
2595 return;
2596
2597 // Skip internally declared static variables.
2598 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
2599 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
2600 if (VD->hasGlobalStorage() && CS && !CS->capturesVariable(VD) &&
2601 (!Res || *Res != OMPDeclareTargetDeclAttr::MT_Link))
2602 return;
2603
2604 SourceLocation ELoc = E->getExprLoc();
2605 OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
2606 // The default(none) clause requires that each variable that is referenced
2607 // in the construct, and does not have a predetermined data-sharing
2608 // attribute, must have its data-sharing attribute explicitly determined
2609 // by being listed in a data-sharing attribute clause.
2610 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
2611 isImplicitOrExplicitTaskingRegion(DKind) &&
2612 VarsWithInheritedDSA.count(VD) == 0) {
2613 VarsWithInheritedDSA[VD] = E;
2614 return;
2615 }
2616
2617 if (isOpenMPTargetExecutionDirective(DKind) &&
2618 !Stack->isLoopControlVariable(VD).first) {
2619 if (!Stack->checkMappableExprComponentListsForDecl(
2620 VD, /*CurrentRegionOnly=*/true,
2621 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
2622 StackComponents,
2623 OpenMPClauseKind) {
2624 // Variable is used if it has been marked as an array, array
2625 // section or the variable iself.
2626 return StackComponents.size() == 1 ||
2627 std::all_of(
2628 std::next(StackComponents.rbegin()),
2629 StackComponents.rend(),
2630 [](const OMPClauseMappableExprCommon::
2631 MappableComponent &MC) {
2632 return MC.getAssociatedDeclaration() ==
2633 nullptr &&
2634 (isa<OMPArraySectionExpr>(
2635 MC.getAssociatedExpression()) ||
2636 isa<ArraySubscriptExpr>(
2637 MC.getAssociatedExpression()));
2638 });
2639 })) {
2640 bool IsFirstprivate = false;
2641 // By default lambdas are captured as firstprivates.
2642 if (const auto *RD =
2643 VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
2644 IsFirstprivate = RD->isLambda();
2645 IsFirstprivate =
2646 IsFirstprivate ||
2647 (VD->getType().getNonReferenceType()->isScalarType() &&
2648 Stack->getDefaultDMA() != DMA_tofrom_scalar && !Res);
2649 if (IsFirstprivate)
2650 ImplicitFirstprivate.emplace_back(E);
2651 else
2652 ImplicitMap.emplace_back(E);
2653 return;
2654 }
2655 }
2656
2657 // OpenMP [2.9.3.6, Restrictions, p.2]
2658 // A list item that appears in a reduction clause of the innermost
2659 // enclosing worksharing or parallel construct may not be accessed in an
2660 // explicit task.
2661 DVar = Stack->hasInnermostDSA(
2662 VD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
2663 [](OpenMPDirectiveKind K) {
2664 return isOpenMPParallelDirective(K) ||
2665 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
2666 },
2667 /*FromParent=*/true);
2668 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
2669 ErrorFound = true;
2670 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
2671 reportOriginalDsa(SemaRef, Stack, VD, DVar);
2672 return;
2673 }
2674
2675 // Define implicit data-sharing attributes for task.
2676 DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false);
2677 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
2678 !Stack->isLoopControlVariable(VD).first) {
2679 ImplicitFirstprivate.push_back(E);
2680 return;
2681 }
2682
2683 // Store implicitly used globals with declare target link for parent
2684 // target.
2685 if (!isOpenMPTargetExecutionDirective(DKind) && Res &&
2686 *Res == OMPDeclareTargetDeclAttr::MT_Link) {
2687 Stack->addToParentTargetRegionLinkGlobals(E);
2688 return;
2689 }
2690 }
2691 }
2692 void VisitMemberExpr(MemberExpr *E) {
2693 if (E->isTypeDependent() || E->isValueDependent() ||
2694 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
2695 return;
2696 auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
2697 OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
2698 if (auto *TE = dyn_cast<CXXThisExpr>(E->getBase()->IgnoreParens())) {
2699 if (!FD)
2700 return;
2701 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false);
2702 // Check if the variable has explicit DSA set and stop analysis if it
2703 // so.
2704 if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
2705 return;
2706
2707 if (isOpenMPTargetExecutionDirective(DKind) &&
2708 !Stack->isLoopControlVariable(FD).first &&
2709 !Stack->checkMappableExprComponentListsForDecl(
2710 FD, /*CurrentRegionOnly=*/true,
2711 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
2712 StackComponents,
2713 OpenMPClauseKind) {
2714 return isa<CXXThisExpr>(
2715 cast<MemberExpr>(
2716 StackComponents.back().getAssociatedExpression())
2717 ->getBase()
2718 ->IgnoreParens());
2719 })) {
2720 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
2721 // A bit-field cannot appear in a map clause.
2722 //
2723 if (FD->isBitField())
2724 return;
2725
2726 // Check to see if the member expression is referencing a class that
2727 // has already been explicitly mapped
2728 if (Stack->isClassPreviouslyMapped(TE->getType()))
2729 return;
2730
2731 ImplicitMap.emplace_back(E);
2732 return;
2733 }
2734
2735 SourceLocation ELoc = E->getExprLoc();
2736 // OpenMP [2.9.3.6, Restrictions, p.2]
2737 // A list item that appears in a reduction clause of the innermost
2738 // enclosing worksharing or parallel construct may not be accessed in
2739 // an explicit task.
2740 DVar = Stack->hasInnermostDSA(
2741 FD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
2742 [](OpenMPDirectiveKind K) {
2743 return isOpenMPParallelDirective(K) ||
2744 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
2745 },
2746 /*FromParent=*/true);
2747 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
2748 ErrorFound = true;
2749 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
2750 reportOriginalDsa(SemaRef, Stack, FD, DVar);
2751 return;
2752 }
2753
2754 // Define implicit data-sharing attributes for task.
2755 DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false);
2756 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
2757 !Stack->isLoopControlVariable(FD).first) {
2758 // Check if there is a captured expression for the current field in the
2759 // region. Do not mark it as firstprivate unless there is no captured
2760 // expression.
2761 // TODO: try to make it firstprivate.
2762 if (DVar.CKind != OMPC_unknown)
2763 ImplicitFirstprivate.push_back(E);
2764 }
2765 return;
2766 }
2767 if (isOpenMPTargetExecutionDirective(DKind)) {
2768 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
2769 if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map,
2770 /*NoDiagnose=*/true))
2771 return;
2772 const auto *VD = cast<ValueDecl>(
2773 CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
2774 if (!Stack->checkMappableExprComponentListsForDecl(
2775 VD, /*CurrentRegionOnly=*/true,
2776 [&CurComponents](
2777 OMPClauseMappableExprCommon::MappableExprComponentListRef
2778 StackComponents,
2779 OpenMPClauseKind) {
2780 auto CCI = CurComponents.rbegin();
2781 auto CCE = CurComponents.rend();
2782 for (const auto &SC : llvm::reverse(StackComponents)) {
2783 // Do both expressions have the same kind?
2784 if (CCI->getAssociatedExpression()->getStmtClass() !=
2785 SC.getAssociatedExpression()->getStmtClass())
2786 if (!(isa<OMPArraySectionExpr>(
2787 SC.getAssociatedExpression()) &&
2788 isa<ArraySubscriptExpr>(
2789 CCI->getAssociatedExpression())))
2790 return false;
2791
2792 const Decl *CCD = CCI->getAssociatedDeclaration();
2793 const Decl *SCD = SC.getAssociatedDeclaration();
2794 CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
2795 SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
2796 if (SCD != CCD)
2797 return false;
2798 std::advance(CCI, 1);
2799 if (CCI == CCE)
2800 break;
2801 }
2802 return true;
2803 })) {
2804 Visit(E->getBase());
2805 }
2806 } else {
2807 Visit(E->getBase());
2808 }
2809 }
2810 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
2811 for (OMPClause *C : S->clauses()) {
2812 // Skip analysis of arguments of implicitly defined firstprivate clause
2813 // for task|target directives.
2814 // Skip analysis of arguments of implicitly defined map clause for target
2815 // directives.
2816 if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
2817 C->isImplicit())) {
2818 for (Stmt *CC : C->children()) {
2819 if (CC)
2820 Visit(CC);
2821 }
2822 }
2823 }
2824 // Check implicitly captured variables.
2825 VisitSubCaptures(S);
2826 }
2827 void VisitStmt(Stmt *S) {
2828 for (Stmt *C : S->children()) {
2829 if (C) {
2830 // Check implicitly captured variables in the task-based directives to
2831 // check if they must be firstprivatized.
2832 Visit(C);
2833 }
2834 }
2835 }
2836
2837 bool isErrorFound() const { return ErrorFound; }
2838 ArrayRef<Expr *> getImplicitFirstprivate() const {
2839 return ImplicitFirstprivate;
2840 }
2841 ArrayRef<Expr *> getImplicitMap() const { return ImplicitMap; }
2842 const Sema::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const {
2843 return VarsWithInheritedDSA;
2844 }
2845
2846 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
2847 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {
2848 // Process declare target link variables for the target directives.
2849 if (isOpenMPTargetExecutionDirective(S->getCurrentDirective())) {
2850 for (DeclRefExpr *E : Stack->getLinkGlobals())
2851 Visit(E);
2852 }
2853 }
2854};
2855} // namespace
2856
2857void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
2858 switch (DKind) {
2859 case OMPD_parallel:
2860 case OMPD_parallel_for:
2861 case OMPD_parallel_for_simd:
2862 case OMPD_parallel_sections:
2863 case OMPD_teams:
2864 case OMPD_teams_distribute:
2865 case OMPD_teams_distribute_simd: {
2866 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2867 QualType KmpInt32PtrTy =
2868 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2869 Sema::CapturedParamNameType Params[] = {
2870 std::make_pair(".global_tid.", KmpInt32PtrTy),
2871 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2872 std::make_pair(StringRef(), QualType()) // __context with shared vars
2873 };
2874 ActOnCapturedRegionStart(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc(), CurScope, CR_OpenMP,
2875 Params);
2876 break;
2877 }
2878 case OMPD_target_teams:
2879 case OMPD_target_parallel:
2880 case OMPD_target_parallel_for:
2881 case OMPD_target_parallel_for_simd:
2882 case OMPD_target_teams_distribute:
2883 case OMPD_target_teams_distribute_simd: {
2884 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2885 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2886 QualType KmpInt32PtrTy =
2887 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2888 QualType Args[] = {VoidPtrTy};
2889 FunctionProtoType::ExtProtoInfo EPI;
2890 EPI.Variadic = true;
2891 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2892 Sema::CapturedParamNameType Params[] = {
2893 std::make_pair(".global_tid.", KmpInt32Ty),
2894 std::make_pair(".part_id.", KmpInt32PtrTy),
2895 std::make_pair(".privates.", VoidPtrTy),
2896 std::make_pair(
2897 ".copy_fn.",
2898 Context.getPointerType(CopyFnType).withConst().withRestrict()),
2899 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2900 std::make_pair(StringRef(), QualType()) // __context with shared vars
2901 };
2902 ActOnCapturedRegionStart(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc(), CurScope, CR_OpenMP,
2903 Params);
2904 // Mark this captured region as inlined, because we don't use outlined
2905 // function directly.
2906 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2907 AlwaysInlineAttr::CreateImplicit(
2908 Context, AlwaysInlineAttr::Keyword_forceinline));
2909 Sema::CapturedParamNameType ParamsTarget[] = {
2910 std::make_pair(StringRef(), QualType()) // __context with shared vars
2911 };
2912 // Start a captured region for 'target' with no implicit parameters.
2913 ActOnCapturedRegionStart(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc(), CurScope, CR_OpenMP,
2914 ParamsTarget);
2915 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
2916 std::make_pair(".global_tid.", KmpInt32PtrTy),
2917 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2918 std::make_pair(StringRef(), QualType()) // __context with shared vars
2919 };
2920 // Start a captured region for 'teams' or 'parallel'. Both regions have
2921 // the same implicit parameters.
2922 ActOnCapturedRegionStart(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc(), CurScope, CR_OpenMP,
2923 ParamsTeamsOrParallel);
2924 break;
2925 }
2926 case OMPD_target:
2927 case OMPD_target_simd: {
2928 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2929 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2930 QualType KmpInt32PtrTy =
2931 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2932 QualType Args[] = {VoidPtrTy};
2933 FunctionProtoType::ExtProtoInfo EPI;
2934 EPI.Variadic = true;
2935 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2936 Sema::CapturedParamNameType Params[] = {
2937 std::make_pair(".global_tid.", KmpInt32Ty),
2938 std::make_pair(".part_id.", KmpInt32PtrTy),
2939 std::make_pair(".privates.", VoidPtrTy),
2940 std::make_pair(
2941 ".copy_fn.",
2942 Context.getPointerType(CopyFnType).withConst().withRestrict()),
2943 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2944 std::make_pair(StringRef(), QualType()) // __context with shared vars
2945 };
2946 ActOnCapturedRegionStart(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc(), CurScope, CR_OpenMP,
2947 Params);
2948 // Mark this captured region as inlined, because we don't use outlined
2949 // function directly.
2950 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2951 AlwaysInlineAttr::CreateImplicit(
2952 Context, AlwaysInlineAttr::Keyword_forceinline));
2953 ActOnCapturedRegionStart(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc(), CurScope, CR_OpenMP,
2954 std::make_pair(StringRef(), QualType()));
2955 break;
2956 }
2957 case OMPD_simd:
2958 case OMPD_for:
2959 case OMPD_for_simd:
2960 case OMPD_sections:
2961 case OMPD_section:
2962 case OMPD_single:
2963 case OMPD_master:
2964 case OMPD_critical:
2965 case OMPD_taskgroup:
2966 case OMPD_distribute:
2967 case OMPD_distribute_simd:
2968 case OMPD_ordered:
2969 case OMPD_atomic:
2970 case OMPD_target_data: {
2971 Sema::CapturedParamNameType Params[] = {
2972 std::make_pair(StringRef(), QualType()) // __context with shared vars
2973 };
2974 ActOnCapturedRegionStart(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc(), CurScope, CR_OpenMP,
2975 Params);
2976 break;
2977 }
2978 case OMPD_task: {
2979 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2980 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2981 QualType KmpInt32PtrTy =
2982 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2983 QualType Args[] = {VoidPtrTy};
2984 FunctionProtoType::ExtProtoInfo EPI;
2985 EPI.Variadic = true;
2986 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2987 Sema::CapturedParamNameType Params[] = {
2988 std::make_pair(".global_tid.", KmpInt32Ty),
2989 std::make_pair(".part_id.", KmpInt32PtrTy),
2990 std::make_pair(".privates.", VoidPtrTy),
2991 std::make_pair(
2992 ".copy_fn.",
2993 Context.getPointerType(CopyFnType).withConst().withRestrict()),
2994 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2995 std::make_pair(StringRef(), QualType()) // __context with shared vars
2996 };
2997 ActOnCapturedRegionStart(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc(), CurScope, CR_OpenMP,
2998 Params);
2999 // Mark this captured region as inlined, because we don't use outlined
3000 // function directly.
3001 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3002 AlwaysInlineAttr::CreateImplicit(
3003 Context, AlwaysInlineAttr::Keyword_forceinline));
3004 break;
3005 }
3006 case OMPD_taskloop:
3007 case OMPD_taskloop_simd: {
3008 QualType KmpInt32Ty =
3009 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
3010 .withConst();
3011 QualType KmpUInt64Ty =
3012 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
3013 .withConst();
3014 QualType KmpInt64Ty =
3015 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
3016 .withConst();
3017 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3018 QualType KmpInt32PtrTy =
3019 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3020 QualType Args[] = {VoidPtrTy};
3021 FunctionProtoType::ExtProtoInfo EPI;
3022 EPI.Variadic = true;
3023 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3024 Sema::CapturedParamNameType Params[] = {
3025 std::make_pair(".global_tid.", KmpInt32Ty),
3026 std::make_pair(".part_id.", KmpInt32PtrTy),
3027 std::make_pair(".privates.", VoidPtrTy),
3028 std::make_pair(
3029 ".copy_fn.",
3030 Context.getPointerType(CopyFnType).withConst().withRestrict()),
3031 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3032 std::make_pair(".lb.", KmpUInt64Ty),
3033 std::make_pair(".ub.", KmpUInt64Ty),
3034 std::make_pair(".st.", KmpInt64Ty),
3035 std::make_pair(".liter.", KmpInt32Ty),
3036 std::make_pair(".reductions.", VoidPtrTy),
3037 std::make_pair(StringRef(), QualType()) // __context with shared vars
3038 };
3039 ActOnCapturedRegionStart(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc(), CurScope, CR_OpenMP,
3040 Params);
3041 // Mark this captured region as inlined, because we don't use outlined
3042 // function directly.
3043 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3044 AlwaysInlineAttr::CreateImplicit(
3045 Context, AlwaysInlineAttr::Keyword_forceinline));
3046 break;
3047 }
3048 case OMPD_distribute_parallel_for_simd:
3049 case OMPD_distribute_parallel_for: {
3050 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3051 QualType KmpInt32PtrTy =
3052 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3053 Sema::CapturedParamNameType Params[] = {
3054 std::make_pair(".global_tid.", KmpInt32PtrTy),
3055 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3056 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
3057 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
3058 std::make_pair(StringRef(), QualType()) // __context with shared vars
3059 };
3060 ActOnCapturedRegionStart(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc(), CurScope, CR_OpenMP,
3061 Params);
3062 break;
3063 }
3064 case OMPD_target_teams_distribute_parallel_for:
3065 case OMPD_target_teams_distribute_parallel_for_simd: {
3066 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3067 QualType KmpInt32PtrTy =
3068 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3069 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3070
3071 QualType Args[] = {VoidPtrTy};
3072 FunctionProtoType::ExtProtoInfo EPI;
3073 EPI.Variadic = true;
3074 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3075 Sema::CapturedParamNameType Params[] = {
3076 std::make_pair(".global_tid.", KmpInt32Ty),
3077 std::make_pair(".part_id.", KmpInt32PtrTy),
3078 std::make_pair(".privates.", VoidPtrTy),
3079 std::make_pair(
3080 ".copy_fn.",
3081 Context.getPointerType(CopyFnType).withConst().withRestrict()),
3082 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3083 std::make_pair(StringRef(), QualType()) // __context with shared vars
3084 };
3085 ActOnCapturedRegionStart(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc(), CurScope, CR_OpenMP,
3086 Params);
3087 // Mark this captured region as inlined, because we don't use outlined
3088 // function directly.
3089 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3090 AlwaysInlineAttr::CreateImplicit(
3091 Context, AlwaysInlineAttr::Keyword_forceinline));
3092 Sema::CapturedParamNameType ParamsTarget[] = {
3093 std::make_pair(StringRef(), QualType()) // __context with shared vars
3094 };
3095 // Start a captured region for 'target' with no implicit parameters.
3096 ActOnCapturedRegionStart(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc(), CurScope, CR_OpenMP,
3097 ParamsTarget);
3098
3099 Sema::CapturedParamNameType ParamsTeams[] = {
3100 std::make_pair(".global_tid.", KmpInt32PtrTy),
3101 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3102 std::make_pair(StringRef(), QualType()) // __context with shared vars
3103 };
3104 // Start a captured region for 'target' with no implicit parameters.
3105 ActOnCapturedRegionStart(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc(), CurScope, CR_OpenMP,
3106 ParamsTeams);
3107
3108 Sema::CapturedParamNameType ParamsParallel[] = {
3109 std::make_pair(".global_tid.", KmpInt32PtrTy),
3110 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3111 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
3112 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
3113 std::make_pair(StringRef(), QualType()) // __context with shared vars
3114 };
3115 // Start a captured region for 'teams' or 'parallel'. Both regions have
3116 // the same implicit parameters.
3117 ActOnCapturedRegionStart(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc(), CurScope, CR_OpenMP,
3118 ParamsParallel);
3119 break;
3120 }
3121
3122 case OMPD_teams_distribute_parallel_for:
3123 case OMPD_teams_distribute_parallel_for_simd: {
3124 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3125 QualType KmpInt32PtrTy =
3126 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3127
3128 Sema::CapturedParamNameType ParamsTeams[] = {
3129 std::make_pair(".global_tid.", KmpInt32PtrTy),
3130 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3131 std::make_pair(StringRef(), QualType()) // __context with shared vars
3132 };
3133 // Start a captured region for 'target' with no implicit parameters.
3134 ActOnCapturedRegionStart(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc(), CurScope, CR_OpenMP,
3135 ParamsTeams);
3136
3137 Sema::CapturedParamNameType ParamsParallel[] = {
3138 std::make_pair(".global_tid.", KmpInt32PtrTy),
3139 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3140 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
3141 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
3142 std::make_pair(StringRef(), QualType()) // __context with shared vars
3143 };
3144 // Start a captured region for 'teams' or 'parallel'. Both regions have
3145 // the same implicit parameters.
3146 ActOnCapturedRegionStart(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc(), CurScope, CR_OpenMP,
3147 ParamsParallel);
3148 break;
3149 }
3150 case OMPD_target_update:
3151 case OMPD_target_enter_data:
3152 case OMPD_target_exit_data: {
3153 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3154 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3155 QualType KmpInt32PtrTy =
3156 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3157 QualType Args[] = {VoidPtrTy};
3158 FunctionProtoType::ExtProtoInfo EPI;
3159 EPI.Variadic = true;
3160 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3161 Sema::CapturedParamNameType Params[] = {
3162 std::make_pair(".global_tid.", KmpInt32Ty),
3163 std::make_pair(".part_id.", KmpInt32PtrTy),
3164 std::make_pair(".privates.", VoidPtrTy),
3165 std::make_pair(
3166 ".copy_fn.",
3167 Context.getPointerType(CopyFnType).withConst().withRestrict()),
3168 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3169 std::make_pair(StringRef(), QualType()) // __context with shared vars
3170 };
3171 ActOnCapturedRegionStart(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc(), CurScope, CR_OpenMP,
3172 Params);
3173 // Mark this captured region as inlined, because we don't use outlined
3174 // function directly.
3175 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3176 AlwaysInlineAttr::CreateImplicit(
3177 Context, AlwaysInlineAttr::Keyword_forceinline));
3178 break;
3179 }
3180 case OMPD_threadprivate:
3181 case OMPD_allocate:
3182 case OMPD_taskyield:
3183 case OMPD_barrier:
3184 case OMPD_taskwait:
3185 case OMPD_cancellation_point:
3186 case OMPD_cancel:
3187 case OMPD_flush:
3188 case OMPD_declare_reduction:
3189 case OMPD_declare_mapper:
3190 case OMPD_declare_simd:
3191 case OMPD_declare_target:
3192 case OMPD_end_declare_target:
3193 case OMPD_requires:
3194 llvm_unreachable("OpenMP Directive is not allowed")::llvm::llvm_unreachable_internal("OpenMP Directive is not allowed"
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 3194)
;
3195 case OMPD_unknown:
3196 llvm_unreachable("Unknown OpenMP directive")::llvm::llvm_unreachable_internal("Unknown OpenMP directive",
"/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 3196)
;
3197 }
3198}
3199
3200int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
3201 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
3202 getOpenMPCaptureRegions(CaptureRegions, DKind);
3203 return CaptureRegions.size();
3204}
3205
3206static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
3207 Expr *CaptureExpr, bool WithInit,
3208 bool AsExpression) {
3209 assert(CaptureExpr)((CaptureExpr) ? static_cast<void> (0) : __assert_fail (
"CaptureExpr", "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 3209, __PRETTY_FUNCTION__))
;
3210 ASTContext &C = S.getASTContext();
3211 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
3212 QualType Ty = Init->getType();
3213 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
3214 if (S.getLangOpts().CPlusPlus) {
3215 Ty = C.getLValueReferenceType(Ty);
3216 } else {
3217 Ty = C.getPointerType(Ty);
3218 ExprResult Res =
3219 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
3220 if (!Res.isUsable())
3221 return nullptr;
3222 Init = Res.get();
3223 }
3224 WithInit = true;
3225 }
3226 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
3227 CaptureExpr->getBeginLoc());
3228 if (!WithInit)
3229 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C));
3230 S.CurContext->addHiddenDecl(CED);
3231 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
3232 return CED;
3233}
3234
3235static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
3236 bool WithInit) {
3237 OMPCapturedExprDecl *CD;
3238 if (VarDecl *VD = S.isOpenMPCapturedDecl(D))
3239 CD = cast<OMPCapturedExprDecl>(VD);
3240 else
3241 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
3242 /*AsExpression=*/false);
3243 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
3244 CaptureExpr->getExprLoc());
3245}
3246
3247static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
3248 CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get();
3249 if (!Ref) {
3250 OMPCapturedExprDecl *CD = buildCaptureDecl(
3251 S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr,
3252 /*WithInit=*/true, /*AsExpression=*/true);
3253 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
3254 CaptureExpr->getExprLoc());
3255 }
3256 ExprResult Res = Ref;
3257 if (!S.getLangOpts().CPlusPlus &&
3258 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
3259 Ref->getType()->isPointerType()) {
3260 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
3261 if (!Res.isUsable())
3262 return ExprError();
3263 }
3264 return S.DefaultLvalueConversion(Res.get());
3265}
3266
3267namespace {
3268// OpenMP directives parsed in this section are represented as a
3269// CapturedStatement with an associated statement. If a syntax error
3270// is detected during the parsing of the associated statement, the
3271// compiler must abort processing and close the CapturedStatement.
3272//
3273// Combined directives such as 'target parallel' have more than one
3274// nested CapturedStatements. This RAII ensures that we unwind out
3275// of all the nested CapturedStatements when an error is found.
3276class CaptureRegionUnwinderRAII {
3277private:
3278 Sema &S;
3279 bool &ErrorFound;
3280 OpenMPDirectiveKind DKind = OMPD_unknown;
3281
3282public:
3283 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
3284 OpenMPDirectiveKind DKind)
3285 : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
3286 ~CaptureRegionUnwinderRAII() {
3287 if (ErrorFound) {
3288 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
3289 while (--ThisCaptureLevel >= 0)
3290 S.ActOnCapturedRegionError();
3291 }
3292 }
3293};
3294} // namespace
3295
3296StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
3297 ArrayRef<OMPClause *> Clauses) {
3298 bool ErrorFound = false;
3299 CaptureRegionUnwinderRAII CaptureRegionUnwinder(
3300 *this, ErrorFound, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective());
3301 if (!S.isUsable()) {
3302 ErrorFound = true;
3303 return StmtError();
3304 }
3305
3306 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
3307 getOpenMPCaptureRegions(CaptureRegions, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective());
3308 OMPOrderedClause *OC = nullptr;
3309 OMPScheduleClause *SC = nullptr;
3310 SmallVector<const OMPLinearClause *, 4> LCs;
3311 SmallVector<const OMPClauseWithPreInit *, 4> PICs;
3312 // This is required for proper codegen.
3313 for (OMPClause *Clause : Clauses) {
3314 if (isOpenMPTaskingDirective(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective()) &&
3315 Clause->getClauseKind() == OMPC_in_reduction) {
3316 // Capture taskgroup task_reduction descriptors inside the tasking regions
3317 // with the corresponding in_reduction items.
3318 auto *IRC = cast<OMPInReductionClause>(Clause);
3319 for (Expr *E : IRC->taskgroup_descriptors())
3320 if (E)
3321 MarkDeclarationsReferencedInExpr(E);
3322 }
3323 if (isOpenMPPrivate(Clause->getClauseKind()) ||
3324 Clause->getClauseKind() == OMPC_copyprivate ||
3325 (getLangOpts().OpenMPUseTLS &&
3326 getASTContext().getTargetInfo().isTLSSupported() &&
3327 Clause->getClauseKind() == OMPC_copyin)) {
3328 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
3329 // Mark all variables in private list clauses as used in inner region.
3330 for (Stmt *VarRef : Clause->children()) {
3331 if (auto *E = cast_or_null<Expr>(VarRef)) {
3332 MarkDeclarationsReferencedInExpr(E);
3333 }
3334 }
3335 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->setForceVarCapturing(/*V=*/false);
3336 } else if (CaptureRegions.size() > 1 ||
3337 CaptureRegions.back() != OMPD_unknown) {
3338 if (auto *C = OMPClauseWithPreInit::get(Clause))
3339 PICs.push_back(C);
3340 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
3341 if (Expr *E = C->getPostUpdateExpr())
3342 MarkDeclarationsReferencedInExpr(E);
3343 }
3344 }
3345 if (Clause->getClauseKind() == OMPC_schedule)
3346 SC = cast<OMPScheduleClause>(Clause);
3347 else if (Clause->getClauseKind() == OMPC_ordered)
3348 OC = cast<OMPOrderedClause>(Clause);
3349 else if (Clause->getClauseKind() == OMPC_linear)
3350 LCs.push_back(cast<OMPLinearClause>(Clause));
3351 }
3352 // OpenMP, 2.7.1 Loop Construct, Restrictions
3353 // The nonmonotonic modifier cannot be specified if an ordered clause is
3354 // specified.
3355 if (SC &&
3356 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
3357 SC->getSecondScheduleModifier() ==
3358 OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
3359 OC) {
3360 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
3361 ? SC->getFirstScheduleModifierLoc()
3362 : SC->getSecondScheduleModifierLoc(),
3363 diag::err_omp_schedule_nonmonotonic_ordered)
3364 << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
3365 ErrorFound = true;
3366 }
3367 if (!LCs.empty() && OC && OC->getNumForLoops()) {
3368 for (const OMPLinearClause *C : LCs) {
3369 Diag(C->getBeginLoc(), diag::err_omp_linear_ordered)
3370 << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
3371 }
3372 ErrorFound = true;
3373 }
3374 if (isOpenMPWorksharingDirective(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective()) &&
3375 isOpenMPSimdDirective(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective()) && OC &&
3376 OC->getNumForLoops()) {
3377 Diag(OC->getBeginLoc(), diag::err_omp_ordered_simd)
3378 << getOpenMPDirectiveName(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective());
3379 ErrorFound = true;
3380 }
3381 if (ErrorFound) {
3382 return StmtError();
3383 }
3384 StmtResult SR = S;
3385 for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
3386 // Mark all variables in private list clauses as used in inner region.
3387 // Required for proper codegen of combined directives.
3388 // TODO: add processing for other clauses.
3389 if (ThisCaptureRegion != OMPD_unknown) {
3390 for (const clang::OMPClauseWithPreInit *C : PICs) {
3391 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
3392 // Find the particular capture region for the clause if the
3393 // directive is a combined one with multiple capture regions.
3394 // If the directive is not a combined one, the capture region
3395 // associated with the clause is OMPD_unknown and is generated
3396 // only once.
3397 if (CaptureRegion == ThisCaptureRegion ||
3398 CaptureRegion == OMPD_unknown) {
3399 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
3400 for (Decl *D : DS->decls())
3401 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
3402 }
3403 }
3404 }
3405 }
3406 SR = ActOnCapturedRegionEnd(SR.get());
3407 }
3408 return SR;
3409}
3410
3411static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
3412 OpenMPDirectiveKind CancelRegion,
3413 SourceLocation StartLoc) {
3414 // CancelRegion is only needed for cancel and cancellation_point.
3415 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
3416 return false;
3417
3418 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
3419 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
3420 return false;
3421
3422 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
3423 << getOpenMPDirectiveName(CancelRegion);
3424 return true;
3425}
3426
3427static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack,
3428 OpenMPDirectiveKind CurrentRegion,
3429 const DeclarationNameInfo &CurrentName,
3430 OpenMPDirectiveKind CancelRegion,
3431 SourceLocation StartLoc) {
3432 if (Stack->getCurScope()) {
3433 OpenMPDirectiveKind ParentRegion = Stack->getParentDirective();
3434 OpenMPDirectiveKind OffendingRegion = ParentRegion;
3435 bool NestingProhibited = false;
3436 bool CloseNesting = true;
3437 bool OrphanSeen = false;
3438 enum {
3439 NoRecommend,
3440 ShouldBeInParallelRegion,
3441 ShouldBeInOrderedRegion,
3442 ShouldBeInTargetRegion,
3443 ShouldBeInTeamsRegion
3444 } Recommend = NoRecommend;
3445 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
3446 // OpenMP [2.16, Nesting of Regions]
3447 // OpenMP constructs may not be nested inside a simd region.
3448 // OpenMP [2.8.1,simd Construct, Restrictions]
3449 // An ordered construct with the simd clause is the only OpenMP
3450 // construct that can appear in the simd region.
3451 // Allowing a SIMD construct nested in another SIMD construct is an
3452 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
3453 // message.
3454 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
3455 ? diag::err_omp_prohibited_region_simd
3456 : diag::warn_omp_nesting_simd);
3457 return CurrentRegion != OMPD_simd;
3458 }
3459 if (ParentRegion == OMPD_atomic) {
3460 // OpenMP [2.16, Nesting of Regions]
3461 // OpenMP constructs may not be nested inside an atomic region.
3462 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
3463 return true;
3464 }
3465 if (CurrentRegion == OMPD_section) {
3466 // OpenMP [2.7.2, sections Construct, Restrictions]
3467 // Orphaned section directives are prohibited. That is, the section
3468 // directives must appear within the sections construct and must not be
3469 // encountered elsewhere in the sections region.
3470 if (ParentRegion != OMPD_sections &&
3471 ParentRegion != OMPD_parallel_sections) {
3472 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
3473 << (ParentRegion != OMPD_unknown)
3474 << getOpenMPDirectiveName(ParentRegion);
3475 return true;
3476 }
3477 return false;
3478 }
3479 // Allow some constructs (except teams and cancellation constructs) to be
3480 // orphaned (they could be used in functions, called from OpenMP regions
3481 // with the required preconditions).
3482 if (ParentRegion == OMPD_unknown &&
3483 !isOpenMPNestingTeamsDirective(CurrentRegion) &&
3484 CurrentRegion != OMPD_cancellation_point &&
3485 CurrentRegion != OMPD_cancel)
3486 return false;
3487 if (CurrentRegion == OMPD_cancellation_point ||
3488 CurrentRegion == OMPD_cancel) {
3489 // OpenMP [2.16, Nesting of Regions]
3490 // A cancellation point construct for which construct-type-clause is
3491 // taskgroup must be nested inside a task construct. A cancellation
3492 // point construct for which construct-type-clause is not taskgroup must
3493 // be closely nested inside an OpenMP construct that matches the type
3494 // specified in construct-type-clause.
3495 // A cancel construct for which construct-type-clause is taskgroup must be
3496 // nested inside a task construct. A cancel construct for which
3497 // construct-type-clause is not taskgroup must be closely nested inside an
3498 // OpenMP construct that matches the type specified in
3499 // construct-type-clause.
3500 NestingProhibited =
3501 !((CancelRegion == OMPD_parallel &&
3502 (ParentRegion == OMPD_parallel ||
3503 ParentRegion == OMPD_target_parallel)) ||
3504 (CancelRegion == OMPD_for &&
3505 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
3506 ParentRegion == OMPD_target_parallel_for ||
3507 ParentRegion == OMPD_distribute_parallel_for ||
3508 ParentRegion == OMPD_teams_distribute_parallel_for ||
3509 ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
3510 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
3511 (CancelRegion == OMPD_sections &&
3512 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
3513 ParentRegion == OMPD_parallel_sections)));
3514 OrphanSeen = ParentRegion == OMPD_unknown;
3515 } else if (CurrentRegion == OMPD_master) {
3516 // OpenMP [2.16, Nesting of Regions]
3517 // A master region may not be closely nested inside a worksharing,
3518 // atomic, or explicit task region.
3519 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
3520 isOpenMPTaskingDirective(ParentRegion);
3521 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
3522 // OpenMP [2.16, Nesting of Regions]
3523 // A critical region may not be nested (closely or otherwise) inside a
3524 // critical region with the same name. Note that this restriction is not
3525 // sufficient to prevent deadlock.
3526 SourceLocation PreviousCriticalLoc;
3527 bool DeadLock = Stack->hasDirective(
3528 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
3529 const DeclarationNameInfo &DNI,
3530 SourceLocation Loc) {
3531 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
3532 PreviousCriticalLoc = Loc;
3533 return true;
3534 }
3535 return false;
3536 },
3537 false /* skip top directive */);
3538 if (DeadLock) {
3539 SemaRef.Diag(StartLoc,
3540 diag::err_omp_prohibited_region_critical_same_name)
3541 << CurrentName.getName();
3542 if (PreviousCriticalLoc.isValid())
3543 SemaRef.Diag(PreviousCriticalLoc,
3544 diag::note_omp_previous_critical_region);
3545 return true;
3546 }
3547 } else if (CurrentRegion == OMPD_barrier) {
3548 // OpenMP [2.16, Nesting of Regions]
3549 // A barrier region may not be closely nested inside a worksharing,
3550 // explicit task, critical, ordered, atomic, or master region.
3551 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
3552 isOpenMPTaskingDirective(ParentRegion) ||
3553 ParentRegion == OMPD_master ||
3554 ParentRegion == OMPD_critical ||
3555 ParentRegion == OMPD_ordered;
3556 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
3557 !isOpenMPParallelDirective(CurrentRegion) &&
3558 !isOpenMPTeamsDirective(CurrentRegion)) {
3559 // OpenMP [2.16, Nesting of Regions]
3560 // A worksharing region may not be closely nested inside a worksharing,
3561 // explicit task, critical, ordered, atomic, or master region.
3562 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
3563 isOpenMPTaskingDirective(ParentRegion) ||
3564 ParentRegion == OMPD_master ||
3565 ParentRegion == OMPD_critical ||
3566 ParentRegion == OMPD_ordered;
3567 Recommend = ShouldBeInParallelRegion;
3568 } else if (CurrentRegion == OMPD_ordered) {
3569 // OpenMP [2.16, Nesting of Regions]
3570 // An ordered region may not be closely nested inside a critical,
3571 // atomic, or explicit task region.
3572 // An ordered region must be closely nested inside a loop region (or
3573 // parallel loop region) with an ordered clause.
3574 // OpenMP [2.8.1,simd Construct, Restrictions]
3575 // An ordered construct with the simd clause is the only OpenMP construct
3576 // that can appear in the simd region.
3577 NestingProhibited = ParentRegion == OMPD_critical ||
3578 isOpenMPTaskingDirective(ParentRegion) ||
3579 !(isOpenMPSimdDirective(ParentRegion) ||
3580 Stack->isParentOrderedRegion());
3581 Recommend = ShouldBeInOrderedRegion;
3582 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
3583 // OpenMP [2.16, Nesting of Regions]
3584 // If specified, a teams construct must be contained within a target
3585 // construct.
3586 NestingProhibited = ParentRegion != OMPD_target;
3587 OrphanSeen = ParentRegion == OMPD_unknown;
3588 Recommend = ShouldBeInTargetRegion;
3589 }
3590 if (!NestingProhibited &&
3591 !isOpenMPTargetExecutionDirective(CurrentRegion) &&
3592 !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
3593 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
3594 // OpenMP [2.16, Nesting of Regions]
3595 // distribute, parallel, parallel sections, parallel workshare, and the
3596 // parallel loop and parallel loop SIMD constructs are the only OpenMP
3597 // constructs that can be closely nested in the teams region.
3598 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
3599 !isOpenMPDistributeDirective(CurrentRegion);
3600 Recommend = ShouldBeInParallelRegion;
3601 }
3602 if (!NestingProhibited &&
3603 isOpenMPNestingDistributeDirective(CurrentRegion)) {
3604 // OpenMP 4.5 [2.17 Nesting of Regions]
3605 // The region associated with the distribute construct must be strictly
3606 // nested inside a teams region
3607 NestingProhibited =
3608 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
3609 Recommend = ShouldBeInTeamsRegion;
3610 }
3611 if (!NestingProhibited &&
3612 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
3613 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
3614 // OpenMP 4.5 [2.17 Nesting of Regions]
3615 // If a target, target update, target data, target enter data, or
3616 // target exit data construct is encountered during execution of a
3617 // target region, the behavior is unspecified.
3618 NestingProhibited = Stack->hasDirective(
3619 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
3620 SourceLocation) {
3621 if (isOpenMPTargetExecutionDirective(K)) {
3622 OffendingRegion = K;
3623 return true;
3624 }
3625 return false;
3626 },
3627 false /* don't skip top directive */);
3628 CloseNesting = false;
3629 }
3630 if (NestingProhibited) {
3631 if (OrphanSeen) {
3632 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
3633 << getOpenMPDirectiveName(CurrentRegion) << Recommend;
3634 } else {
3635 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
3636 << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
3637 << Recommend << getOpenMPDirectiveName(CurrentRegion);
3638 }
3639 return true;
3640 }
3641 }
3642 return false;
3643}
3644
3645static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
3646 ArrayRef<OMPClause *> Clauses,
3647 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
3648 bool ErrorFound = false;
3649 unsigned NamedModifiersNumber = 0;
3650 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
3651 OMPD_unknown + 1);
3652 SmallVector<SourceLocation, 4> NameModifierLoc;
3653 for (const OMPClause *C : Clauses) {
3654 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
3655 // At most one if clause without a directive-name-modifier can appear on
3656 // the directive.
3657 OpenMPDirectiveKind CurNM = IC->getNameModifier();
3658 if (FoundNameModifiers[CurNM]) {
3659 S.Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
3660 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
3661 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
3662 ErrorFound = true;
3663 } else if (CurNM != OMPD_unknown) {
3664 NameModifierLoc.push_back(IC->getNameModifierLoc());
3665 ++NamedModifiersNumber;
3666 }
3667 FoundNameModifiers[CurNM] = IC;
3668 if (CurNM == OMPD_unknown)
3669 continue;
3670 // Check if the specified name modifier is allowed for the current
3671 // directive.
3672 // At most one if clause with the particular directive-name-modifier can
3673 // appear on the directive.
3674 bool MatchFound = false;
3675 for (auto NM : AllowedNameModifiers) {
3676 if (CurNM == NM) {
3677 MatchFound = true;
3678 break;
3679 }
3680 }
3681 if (!MatchFound) {
3682 S.Diag(IC->getNameModifierLoc(),
3683 diag::err_omp_wrong_if_directive_name_modifier)
3684 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
3685 ErrorFound = true;
3686 }
3687 }
3688 }
3689 // If any if clause on the directive includes a directive-name-modifier then
3690 // all if clauses on the directive must include a directive-name-modifier.
3691 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
3692 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
3693 S.Diag(FoundNameModifiers[OMPD_unknown]->getBeginLoc(),
3694 diag::err_omp_no_more_if_clause);
3695 } else {
3696 std::string Values;
3697 std::string Sep(", ");
3698 unsigned AllowedCnt = 0;
3699 unsigned TotalAllowedNum =
3700 AllowedNameModifiers.size() - NamedModifiersNumber;
3701 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
3702 ++Cnt) {
3703 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
3704 if (!FoundNameModifiers[NM]) {
3705 Values += "'";
3706 Values += getOpenMPDirectiveName(NM);
3707 Values += "'";
3708 if (AllowedCnt + 2 == TotalAllowedNum)
3709 Values += " or ";
3710 else if (AllowedCnt + 1 != TotalAllowedNum)
3711 Values += Sep;
3712 ++AllowedCnt;
3713 }
3714 }
3715 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getBeginLoc(),
3716 diag::err_omp_unnamed_if_clause)
3717 << (TotalAllowedNum > 1) << Values;
3718 }
3719 for (SourceLocation Loc : NameModifierLoc) {
3720 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
3721 }
3722 ErrorFound = true;
3723 }
3724 return ErrorFound;
3725}
3726
3727static std::pair<ValueDecl *, bool>
3728getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
3729 SourceRange &ERange, bool AllowArraySection = false) {
3730 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
3731 RefExpr->containsUnexpandedParameterPack())
3732 return std::make_pair(nullptr, true);
3733
3734 // OpenMP [3.1, C/C++]
3735 // A list item is a variable name.
3736 // OpenMP [2.9.3.3, Restrictions, p.1]
3737 // A variable that is part of another variable (as an array or
3738 // structure element) cannot appear in a private clause.
3739 RefExpr = RefExpr->IgnoreParens();
3740 enum {
3741 NoArrayExpr = -1,
3742 ArraySubscript = 0,
3743 OMPArraySection = 1
3744 } IsArrayExpr = NoArrayExpr;
3745 if (AllowArraySection) {
3746 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
3747 Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
3748 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
3749 Base = TempASE->getBase()->IgnoreParenImpCasts();
3750 RefExpr = Base;
3751 IsArrayExpr = ArraySubscript;
3752 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
3753 Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
3754 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
3755 Base = TempOASE->getBase()->IgnoreParenImpCasts();
3756 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
3757 Base = TempASE->getBase()->IgnoreParenImpCasts();
3758 RefExpr = Base;
3759 IsArrayExpr = OMPArraySection;
3760 }
3761 }
3762 ELoc = RefExpr->getExprLoc();
3763 ERange = RefExpr->getSourceRange();
3764 RefExpr = RefExpr->IgnoreParenImpCasts();
3765 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
3766 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
3767 if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
3768 (S.getCurrentThisType().isNull() || !ME ||
3769 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
3770 !isa<FieldDecl>(ME->getMemberDecl()))) {
3771 if (IsArrayExpr != NoArrayExpr) {
3772 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
3773 << ERange;
3774 } else {
3775 S.Diag(ELoc,
3776 AllowArraySection
3777 ? diag::err_omp_expected_var_name_member_expr_or_array_item
3778 : diag::err_omp_expected_var_name_member_expr)
3779 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
3780 }
3781 return std::make_pair(nullptr, false);
3782 }
3783 return std::make_pair(
3784 getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
3785}
3786
3787static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
3788 ArrayRef<OMPClause *> Clauses) {
3789 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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 3790, __PRETTY_FUNCTION__))
3790 "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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 3790, __PRETTY_FUNCTION__))
;
3791 auto AllocateRange =
3792 llvm::make_filter_range(Clauses, OMPAllocateClause::classof);
3793 llvm::DenseMap<CanonicalDeclPtr<Decl>, CanonicalDeclPtr<VarDecl>>
3794 DeclToCopy;
3795 auto PrivateRange = llvm::make_filter_range(Clauses, [](const OMPClause *C) {
3796 return isOpenMPPrivate(C->getClauseKind());
3797 });
3798 for (OMPClause *Cl : PrivateRange) {
3799 MutableArrayRef<Expr *>::iterator I, It, Et;
3800 if (Cl->getClauseKind() == OMPC_private) {
3801 auto *PC = cast<OMPPrivateClause>(Cl);
3802 I = PC->private_copies().begin();
3803 It = PC->varlist_begin();
3804 Et = PC->varlist_end();
3805 } else if (Cl->getClauseKind() == OMPC_firstprivate) {
3806 auto *PC = cast<OMPFirstprivateClause>(Cl);
3807 I = PC->private_copies().begin();
3808 It = PC->varlist_begin();
3809 Et = PC->varlist_end();
3810 } else if (Cl->getClauseKind() == OMPC_lastprivate) {
3811 auto *PC = cast<OMPLastprivateClause>(Cl);
3812 I = PC->private_copies().begin();
3813 It = PC->varlist_begin();
3814 Et = PC->varlist_end();
3815 } else if (Cl->getClauseKind() == OMPC_linear) {
3816 auto *PC = cast<OMPLinearClause>(Cl);
3817 I = PC->privates().begin();
3818 It = PC->varlist_begin();
3819 Et = PC->varlist_end();
3820 } else if (Cl->getClauseKind() == OMPC_reduction) {
3821 auto *PC = cast<OMPReductionClause>(Cl);
3822 I = PC->privates().begin();
3823 It = PC->varlist_begin();
3824 Et = PC->varlist_end();
3825 } else if (Cl->getClauseKind() == OMPC_task_reduction) {
3826 auto *PC = cast<OMPTaskReductionClause>(Cl);
3827 I = PC->privates().begin();
3828 It = PC->varlist_begin();
3829 Et = PC->varlist_end();
3830 } else if (Cl->getClauseKind() == OMPC_in_reduction) {
3831 auto *PC = cast<OMPInReductionClause>(Cl);
3832 I = PC->privates().begin();
3833 It = PC->varlist_begin();
3834 Et = PC->varlist_end();
3835 } else {
3836 llvm_unreachable("Expected private clause.")::llvm::llvm_unreachable_internal("Expected private clause.",
"/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 3836)
;
3837 }
3838 for (Expr *E : llvm::make_range(It, Et)) {
3839 if (!*I) {
3840 ++I;
3841 continue;
3842 }
3843 SourceLocation ELoc;
3844 SourceRange ERange;
3845 Expr *SimpleRefExpr = E;
3846 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
3847 /*AllowArraySection=*/true);
3848 DeclToCopy.try_emplace(Res.first,
3849 cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()));
3850 ++I;
3851 }
3852 }
3853 for (OMPClause *C : AllocateRange) {
3854 auto *AC = cast<OMPAllocateClause>(C);
3855 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
3856 getAllocatorKind(S, Stack, AC->getAllocator());
3857 // OpenMP, 2.11.4 allocate Clause, Restrictions.
3858 // For task, taskloop or target directives, allocation requests to memory
3859 // allocators with the trait access set to thread result in unspecified
3860 // behavior.
3861 if (AllocatorKind == OMPAllocateDeclAttr::OMPThreadMemAlloc &&
3862 (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
3863 isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()))) {
3864 S.Diag(AC->getAllocator()->getExprLoc(),
3865 diag::warn_omp_allocate_thread_on_task_target_directive)
3866 << getOpenMPDirectiveName(Stack->getCurrentDirective());
3867 }
3868 for (Expr *E : AC->varlists()) {
3869 SourceLocation ELoc;
3870 SourceRange ERange;
3871 Expr *SimpleRefExpr = E;
3872 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange);
3873 ValueDecl *VD = Res.first;
3874 DSAStackTy::DSAVarData Data = Stack->getTopDSA(VD, /*FromParent=*/false);
3875 if (!isOpenMPPrivate(Data.CKind)) {
3876 S.Diag(E->getExprLoc(),
3877 diag::err_omp_expected_private_copy_for_allocate);
3878 continue;
3879 }
3880 VarDecl *PrivateVD = DeclToCopy[VD];
3881 if (checkPreviousOMPAllocateAttribute(S, Stack, E, PrivateVD,
3882 AllocatorKind, AC->getAllocator()))
3883 continue;
3884 applyOMPAllocateAttribute(S, PrivateVD, AllocatorKind, AC->getAllocator(),
3885 E->getSourceRange());
3886 }
3887 }
3888}
3889
3890StmtResult Sema::ActOnOpenMPExecutableDirective(
3891 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
3892 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
3893 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
3894 StmtResult Res = StmtError();
3895 // First check CancelRegion which is then used in checkNestingOfRegions.
3896 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
3897 checkNestingOfRegions(*this, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, Kind, DirName, CancelRegion,
3898 StartLoc))
3899 return StmtError();
3900
3901 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
3902 VarsWithInheritedDSAType VarsWithInheritedDSA;
3903 bool ErrorFound = false;
3904 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
3905 if (AStmt && !CurContext->isDependentContext()) {
3906 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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 3906, __PRETTY_FUNCTION__))
;
3907
3908 // Check default data sharing attributes for referenced variables.
3909 DSAAttrChecker DSAChecker(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, *this, cast<CapturedStmt>(AStmt));
3910 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
3911 Stmt *S = AStmt;
3912 while (--ThisCaptureLevel >= 0)
3913 S = cast<CapturedStmt>(S)->getCapturedStmt();
3914 DSAChecker.Visit(S);
3915 if (DSAChecker.isErrorFound())
3916 return StmtError();
3917 // Generate list of implicitly defined firstprivate variables.
3918 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
3919
3920 SmallVector<Expr *, 4> ImplicitFirstprivates(
3921 DSAChecker.getImplicitFirstprivate().begin(),
3922 DSAChecker.getImplicitFirstprivate().end());
3923 SmallVector<Expr *, 4> ImplicitMaps(DSAChecker.getImplicitMap().begin(),
3924 DSAChecker.getImplicitMap().end());
3925 // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
3926 for (OMPClause *C : Clauses) {
3927 if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
3928 for (Expr *E : IRC->taskgroup_descriptors())
3929 if (E)
3930 ImplicitFirstprivates.emplace_back(E);
3931 }
3932 }
3933 if (!ImplicitFirstprivates.empty()) {
3934 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
3935 ImplicitFirstprivates, SourceLocation(), SourceLocation(),
3936 SourceLocation())) {
3937 ClausesWithImplicit.push_back(Implicit);
3938 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
3939 ImplicitFirstprivates.size();
3940 } else {
3941 ErrorFound = true;
3942 }
3943 }
3944 if (!ImplicitMaps.empty()) {
3945 CXXScopeSpec MapperIdScopeSpec;
3946 DeclarationNameInfo MapperId;
3947 if (OMPClause *Implicit = ActOnOpenMPMapClause(
3948 llvm::None, llvm::None, MapperIdScopeSpec, MapperId,
3949 OMPC_MAP_tofrom, /*IsMapTypeImplicit=*/true, SourceLocation(),
3950 SourceLocation(), ImplicitMaps, OMPVarListLocTy())) {
3951 ClausesWithImplicit.emplace_back(Implicit);
3952 ErrorFound |=
3953 cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMaps.size();
3954 } else {
3955 ErrorFound = true;
3956 }
3957 }
3958 }
3959
3960 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
3961 switch (Kind) {
3962 case OMPD_parallel:
3963 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
3964 EndLoc);
3965 AllowedNameModifiers.push_back(OMPD_parallel);
3966 break;
3967 case OMPD_simd:
3968 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
3969 VarsWithInheritedDSA);
3970 break;
3971 case OMPD_for:
3972 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
3973 VarsWithInheritedDSA);
3974 break;
3975 case OMPD_for_simd:
3976 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3977 EndLoc, VarsWithInheritedDSA);
3978 break;
3979 case OMPD_sections:
3980 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
3981 EndLoc);
3982 break;
3983 case OMPD_section:
3984 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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 3985, __PRETTY_FUNCTION__))
3985 "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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 3985, __PRETTY_FUNCTION__))
;
3986 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
3987 break;
3988 case OMPD_single:
3989 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
3990 EndLoc);
3991 break;
3992 case OMPD_master:
3993 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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 3994, __PRETTY_FUNCTION__))
3994 "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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 3994, __PRETTY_FUNCTION__))
;
3995 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
3996 break;
3997 case OMPD_critical:
3998 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
3999 StartLoc, EndLoc);
4000 break;
4001 case OMPD_parallel_for:
4002 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
4003 EndLoc, VarsWithInheritedDSA);
4004 AllowedNameModifiers.push_back(OMPD_parallel);
4005 break;
4006 case OMPD_parallel_for_simd:
4007 Res = ActOnOpenMPParallelForSimdDirective(
4008 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4009 AllowedNameModifiers.push_back(OMPD_parallel);
4010 break;
4011 case OMPD_parallel_sections:
4012 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
4013 StartLoc, EndLoc);
4014 AllowedNameModifiers.push_back(OMPD_parallel);
4015 break;
4016 case OMPD_task:
4017 Res =
4018 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
4019 AllowedNameModifiers.push_back(OMPD_task);
4020 break;
4021 case OMPD_taskyield:
4022 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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4023, __PRETTY_FUNCTION__))
4023 "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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4023, __PRETTY_FUNCTION__))
;
4024 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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4025, __PRETTY_FUNCTION__))
4025 "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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4025, __PRETTY_FUNCTION__))
;
4026 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
4027 break;
4028 case OMPD_barrier:
4029 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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4030, __PRETTY_FUNCTION__))
4030 "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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4030, __PRETTY_FUNCTION__))
;
4031 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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4032, __PRETTY_FUNCTION__))
4032 "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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4032, __PRETTY_FUNCTION__))
;
4033 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
4034 break;
4035 case OMPD_taskwait:
4036 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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4037, __PRETTY_FUNCTION__))
4037 "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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4037, __PRETTY_FUNCTION__))
;
4038 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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4039, __PRETTY_FUNCTION__))
4039 "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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4039, __PRETTY_FUNCTION__))
;
4040 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
4041 break;
4042 case OMPD_taskgroup:
4043 Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
4044 EndLoc);
4045 break;
4046 case OMPD_flush:
4047 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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4048, __PRETTY_FUNCTION__))
4048 "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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4048, __PRETTY_FUNCTION__))
;
4049 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
4050 break;
4051 case OMPD_ordered:
4052 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
4053 EndLoc);
4054 break;
4055 case OMPD_atomic:
4056 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
4057 EndLoc);
4058 break;
4059 case OMPD_teams:
4060 Res =
4061 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
4062 break;
4063 case OMPD_target:
4064 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
4065 EndLoc);
4066 AllowedNameModifiers.push_back(OMPD_target);
4067 break;
4068 case OMPD_target_parallel:
4069 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
4070 StartLoc, EndLoc);
4071 AllowedNameModifiers.push_back(OMPD_target);
4072 AllowedNameModifiers.push_back(OMPD_parallel);
4073 break;
4074 case OMPD_target_parallel_for:
4075 Res = ActOnOpenMPTargetParallelForDirective(
4076 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4077 AllowedNameModifiers.push_back(OMPD_target);
4078 AllowedNameModifiers.push_back(OMPD_parallel);
4079 break;
4080 case OMPD_cancellation_point:
4081 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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4082, __PRETTY_FUNCTION__))
4082 "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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4082, __PRETTY_FUNCTION__))
;
4083 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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4084, __PRETTY_FUNCTION__))
4084 "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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4084, __PRETTY_FUNCTION__))
;
4085 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
4086 break;
4087 case OMPD_cancel:
4088 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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4089, __PRETTY_FUNCTION__))
4089 "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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4089, __PRETTY_FUNCTION__))
;
4090 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
4091 CancelRegion);
4092 AllowedNameModifiers.push_back(OMPD_cancel);
4093 break;
4094 case OMPD_target_data:
4095 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
4096 EndLoc);
4097 AllowedNameModifiers.push_back(OMPD_target_data);
4098 break;
4099 case OMPD_target_enter_data:
4100 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
4101 EndLoc, AStmt);
4102 AllowedNameModifiers.push_back(OMPD_target_enter_data);
4103 break;
4104 case OMPD_target_exit_data:
4105 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
4106 EndLoc, AStmt);
4107 AllowedNameModifiers.push_back(OMPD_target_exit_data);
4108 break;
4109 case OMPD_taskloop:
4110 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
4111 EndLoc, VarsWithInheritedDSA);
4112 AllowedNameModifiers.push_back(OMPD_taskloop);
4113 break;
4114 case OMPD_taskloop_simd:
4115 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
4116 EndLoc, VarsWithInheritedDSA);
4117 AllowedNameModifiers.push_back(OMPD_taskloop);
4118 break;
4119 case OMPD_distribute:
4120 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
4121 EndLoc, VarsWithInheritedDSA);
4122 break;
4123 case OMPD_target_update:
4124 Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
4125 EndLoc, AStmt);
4126 AllowedNameModifiers.push_back(OMPD_target_update);
4127 break;
4128 case OMPD_distribute_parallel_for:
4129 Res = ActOnOpenMPDistributeParallelForDirective(
4130 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4131 AllowedNameModifiers.push_back(OMPD_parallel);
4132 break;
4133 case OMPD_distribute_parallel_for_simd:
4134 Res = ActOnOpenMPDistributeParallelForSimdDirective(
4135 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4136 AllowedNameModifiers.push_back(OMPD_parallel);
4137 break;
4138 case OMPD_distribute_simd:
4139 Res = ActOnOpenMPDistributeSimdDirective(
4140 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4141 break;
4142 case OMPD_target_parallel_for_simd:
4143 Res = ActOnOpenMPTargetParallelForSimdDirective(
4144 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4145 AllowedNameModifiers.push_back(OMPD_target);
4146 AllowedNameModifiers.push_back(OMPD_parallel);
4147 break;
4148 case OMPD_target_simd:
4149 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
4150 EndLoc, VarsWithInheritedDSA);
4151 AllowedNameModifiers.push_back(OMPD_target);
4152 break;
4153 case OMPD_teams_distribute:
4154 Res = ActOnOpenMPTeamsDistributeDirective(
4155 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4156 break;
4157 case OMPD_teams_distribute_simd:
4158 Res = ActOnOpenMPTeamsDistributeSimdDirective(
4159 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4160 break;
4161 case OMPD_teams_distribute_parallel_for_simd:
4162 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
4163 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4164 AllowedNameModifiers.push_back(OMPD_parallel);
4165 break;
4166 case OMPD_teams_distribute_parallel_for:
4167 Res = ActOnOpenMPTeamsDistributeParallelForDirective(
4168 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4169 AllowedNameModifiers.push_back(OMPD_parallel);
4170 break;
4171 case OMPD_target_teams:
4172 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
4173 EndLoc);
4174 AllowedNameModifiers.push_back(OMPD_target);
4175 break;
4176 case OMPD_target_teams_distribute:
4177 Res = ActOnOpenMPTargetTeamsDistributeDirective(
4178 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4179 AllowedNameModifiers.push_back(OMPD_target);
4180 break;
4181 case OMPD_target_teams_distribute_parallel_for:
4182 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
4183 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4184 AllowedNameModifiers.push_back(OMPD_target);
4185 AllowedNameModifiers.push_back(OMPD_parallel);
4186 break;
4187 case OMPD_target_teams_distribute_parallel_for_simd:
4188 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
4189 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4190 AllowedNameModifiers.push_back(OMPD_target);
4191 AllowedNameModifiers.push_back(OMPD_parallel);
4192 break;
4193 case OMPD_target_teams_distribute_simd:
4194 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
4195 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4196 AllowedNameModifiers.push_back(OMPD_target);
4197 break;
4198 case OMPD_declare_target:
4199 case OMPD_end_declare_target:
4200 case OMPD_threadprivate:
4201 case OMPD_allocate:
4202 case OMPD_declare_reduction:
4203 case OMPD_declare_mapper:
4204 case OMPD_declare_simd:
4205 case OMPD_requires:
4206 llvm_unreachable("OpenMP Directive is not allowed")::llvm::llvm_unreachable_internal("OpenMP Directive is not allowed"
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4206)
;
4207 case OMPD_unknown:
4208 llvm_unreachable("Unknown OpenMP directive")::llvm::llvm_unreachable_internal("Unknown OpenMP directive",
"/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4208)
;
4209 }
4210
4211 ErrorFound = Res.isInvalid() || ErrorFound;
4212
4213 // Check variables in the clauses if default(none) was specified.
4214 if (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getDefaultDSA() == DSA_none) {
4215 DSAAttrChecker DSAChecker(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, *this, nullptr);
4216 for (OMPClause *C : Clauses) {
4217 switch (C->getClauseKind()) {
4218 case OMPC_num_threads:
4219 case OMPC_dist_schedule:
4220 // Do not analyse if no parent teams directive.
4221 if (isOpenMPTeamsDirective(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective()))
4222 break;
4223 continue;
4224 case OMPC_if:
4225 if (isOpenMPTeamsDirective(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective()) &&
4226 cast<OMPIfClause>(C)->getNameModifier() != OMPD_target)
4227 break;
4228 continue;
4229 case OMPC_schedule:
4230 break;
4231 case OMPC_ordered:
4232 case OMPC_device:
4233 case OMPC_num_teams:
4234 case OMPC_thread_limit:
4235 case OMPC_priority:
4236 case OMPC_grainsize:
4237 case OMPC_num_tasks:
4238 case OMPC_hint:
4239 case OMPC_collapse:
4240 case OMPC_safelen:
4241 case OMPC_simdlen:
4242 case OMPC_final:
4243 case OMPC_default:
4244 case OMPC_proc_bind:
4245 case OMPC_private:
4246 case OMPC_firstprivate:
4247 case OMPC_lastprivate:
4248 case OMPC_shared:
4249 case OMPC_reduction:
4250 case OMPC_task_reduction:
4251 case OMPC_in_reduction:
4252 case OMPC_linear:
4253 case OMPC_aligned:
4254 case OMPC_copyin:
4255 case OMPC_copyprivate:
4256 case OMPC_nowait:
4257 case OMPC_untied:
4258 case OMPC_mergeable:
4259 case OMPC_allocate:
4260 case OMPC_read:
4261 case OMPC_write:
4262 case OMPC_update:
4263 case OMPC_capture:
4264 case OMPC_seq_cst:
4265 case OMPC_depend:
4266 case OMPC_threads:
4267 case OMPC_simd:
4268 case OMPC_map:
4269 case OMPC_nogroup:
4270 case OMPC_defaultmap:
4271 case OMPC_to:
4272 case OMPC_from:
4273 case OMPC_use_device_ptr:
4274 case OMPC_is_device_ptr:
4275 continue;
4276 case OMPC_allocator:
4277 case OMPC_flush:
4278 case OMPC_threadprivate:
4279 case OMPC_uniform:
4280 case OMPC_unknown:
4281 case OMPC_unified_address:
4282 case OMPC_unified_shared_memory:
4283 case OMPC_reverse_offload:
4284 case OMPC_dynamic_allocators:
4285 case OMPC_atomic_default_mem_order:
4286 llvm_unreachable("Unexpected clause")::llvm::llvm_unreachable_internal("Unexpected clause", "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4286)
;
4287 }
4288 for (Stmt *CC : C->children()) {
4289 if (CC)
4290 DSAChecker.Visit(CC);
4291 }
4292 }
4293 for (auto &P : DSAChecker.getVarsWithInheritedDSA())
4294 VarsWithInheritedDSA[P.getFirst()] = P.getSecond();
4295 }
4296 for (const auto &P : VarsWithInheritedDSA) {
4297 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
4298 << P.first << P.second->getSourceRange();
4299 Diag(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getDefaultDSALocation(), diag::note_omp_default_dsa_none);
4300 }
4301 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
4302
4303 if (!AllowedNameModifiers.empty())
4304 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
4305 ErrorFound;
4306
4307 if (ErrorFound)
4308 return StmtError();
4309
4310 if (!(Res.getAs<OMPExecutableDirective>()->isStandaloneDirective())) {
4311 Res.getAs<OMPExecutableDirective>()
4312 ->getStructuredBlock()
4313 ->setIsOMPStructuredBlock(true);
4314 }
4315
4316 if (!CurContext->isDependentContext() &&
4317 isOpenMPTargetExecutionDirective(Kind) &&
4318 !(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
4319 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasRequiresDeclWithClause<OMPUnifiedAddressClause>() ||
4320 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasRequiresDeclWithClause<OMPReverseOffloadClause>() ||
4321 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())) {
4322 // Register target to DSA Stack.
4323 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->addTargetDirLocation(StartLoc);
4324 }
4325
4326 return Res;
4327}
4328
4329Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
4330 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
4331 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
4332 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
4333 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
4334 assert(Aligneds.size() == Alignments.size())((Aligneds.size() == Alignments.size()) ? static_cast<void
> (0) : __assert_fail ("Aligneds.size() == Alignments.size()"
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4334, __PRETTY_FUNCTION__))
;
4335 assert(Linears.size() == LinModifiers.size())((Linears.size() == LinModifiers.size()) ? static_cast<void
> (0) : __assert_fail ("Linears.size() == LinModifiers.size()"
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4335, __PRETTY_FUNCTION__))
;
4336 assert(Linears.size() == Steps.size())((Linears.size() == Steps.size()) ? static_cast<void> (
0) : __assert_fail ("Linears.size() == Steps.size()", "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4336, __PRETTY_FUNCTION__))
;
4337 if (!DG || DG.get().isNull())
4338 return DeclGroupPtrTy();
4339
4340 if (!DG.get().isSingleDecl()) {
4341 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
4342 return DG;
4343 }
4344 Decl *ADecl = DG.get().getSingleDecl();
4345 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
4346 ADecl = FTD->getTemplatedDecl();
4347
4348 auto *FD = dyn_cast<FunctionDecl>(ADecl);
4349 if (!FD) {
4350 Diag(ADecl->getLocation(), diag::err_omp_function_expected);
4351 return DeclGroupPtrTy();
4352 }
4353
4354 // OpenMP [2.8.2, declare simd construct, Description]
4355 // The parameter of the simdlen clause must be a constant positive integer
4356 // expression.
4357 ExprResult SL;
4358 if (Simdlen)
4359 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
4360 // OpenMP [2.8.2, declare simd construct, Description]
4361 // The special this pointer can be used as if was one of the arguments to the
4362 // function in any of the linear, aligned, or uniform clauses.
4363 // The uniform clause declares one or more arguments to have an invariant
4364 // value for all concurrent invocations of the function in the execution of a
4365 // single SIMD loop.
4366 llvm::DenseMap<const Decl *, const Expr *> UniformedArgs;
4367 const Expr *UniformedLinearThis = nullptr;
4368 for (const Expr *E : Uniforms) {
4369 E = E->IgnoreParenImpCasts();
4370 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
4371 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
4372 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
4373 FD->getParamDecl(PVD->getFunctionScopeIndex())
4374 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
4375 UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E);
4376 continue;
4377 }
4378 if (isa<CXXThisExpr>(E)) {
4379 UniformedLinearThis = E;
4380 continue;
4381 }
4382 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
4383 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
4384 }
4385 // OpenMP [2.8.2, declare simd construct, Description]
4386 // The aligned clause declares that the object to which each list item points
4387 // is aligned to the number of bytes expressed in the optional parameter of
4388 // the aligned clause.
4389 // The special this pointer can be used as if was one of the arguments to the
4390 // function in any of the linear, aligned, or uniform clauses.
4391 // The type of list items appearing in the aligned clause must be array,
4392 // pointer, reference to array, or reference to pointer.
4393 llvm::DenseMap<const Decl *, const Expr *> AlignedArgs;
4394 const Expr *AlignedThis = nullptr;
4395 for (const Expr *E : Aligneds) {
4396 E = E->IgnoreParenImpCasts();
4397 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
4398 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
4399 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
4400 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
4401 FD->getParamDecl(PVD->getFunctionScopeIndex())
4402 ->getCanonicalDecl() == CanonPVD) {
4403 // OpenMP [2.8.1, simd construct, Restrictions]
4404 // A list-item cannot appear in more than one aligned clause.
4405 if (AlignedArgs.count(CanonPVD) > 0) {
4406 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
4407 << 1 << E->getSourceRange();
4408 Diag(AlignedArgs[CanonPVD]->getExprLoc(),
4409 diag::note_omp_explicit_dsa)
4410 << getOpenMPClauseName(OMPC_aligned);
4411 continue;
4412 }
4413 AlignedArgs[CanonPVD] = E;
4414 QualType QTy = PVD->getType()
4415 .getNonReferenceType()
4416 .getUnqualifiedType()
4417 .getCanonicalType();
4418 const Type *Ty = QTy.getTypePtrOrNull();
4419 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
4420 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
4421 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
4422 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
4423 }
4424 continue;
4425 }
4426 }
4427 if (isa<CXXThisExpr>(E)) {
4428 if (AlignedThis) {
4429 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
4430 << 2 << E->getSourceRange();
4431 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
4432 << getOpenMPClauseName(OMPC_aligned);
4433 }
4434 AlignedThis = E;
4435 continue;
4436 }
4437 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
4438 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
4439 }
4440 // The optional parameter of the aligned clause, alignment, must be a constant
4441 // positive integer expression. If no optional parameter is specified,
4442 // implementation-defined default alignments for SIMD instructions on the
4443 // target platforms are assumed.
4444 SmallVector<const Expr *, 4> NewAligns;
4445 for (Expr *E : Alignments) {
4446 ExprResult Align;
4447 if (E)
4448 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
4449 NewAligns.push_back(Align.get());
4450 }
4451 // OpenMP [2.8.2, declare simd construct, Description]
4452 // The linear clause declares one or more list items to be private to a SIMD
4453 // lane and to have a linear relationship with respect to the iteration space
4454 // of a loop.
4455 // The special this pointer can be used as if was one of the arguments to the
4456 // function in any of the linear, aligned, or uniform clauses.
4457 // When a linear-step expression is specified in a linear clause it must be
4458 // either a constant integer expression or an integer-typed parameter that is
4459 // specified in a uniform clause on the directive.
4460 llvm::DenseMap<const Decl *, const Expr *> LinearArgs;
4461 const bool IsUniformedThis = UniformedLinearThis != nullptr;
4462 auto MI = LinModifiers.begin();
4463 for (const Expr *E : Linears) {
4464 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
4465 ++MI;
4466 E = E->IgnoreParenImpCasts();
4467 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
4468 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
4469 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
4470 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
4471 FD->getParamDecl(PVD->getFunctionScopeIndex())
4472 ->getCanonicalDecl() == CanonPVD) {
4473 // OpenMP [2.15.3.7, linear Clause, Restrictions]
4474 // A list-item cannot appear in more than one linear clause.
4475 if (LinearArgs.count(CanonPVD) > 0) {
4476 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
4477 << getOpenMPClauseName(OMPC_linear)
4478 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
4479 Diag(LinearArgs[CanonPVD]->getExprLoc(),
4480 diag::note_omp_explicit_dsa)
4481 << getOpenMPClauseName(OMPC_linear);
4482 continue;
4483 }
4484 // Each argument can appear in at most one uniform or linear clause.
4485 if (UniformedArgs.count(CanonPVD) > 0) {
4486 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
4487 << getOpenMPClauseName(OMPC_linear)
4488 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
4489 Diag(UniformedArgs[CanonPVD]->getExprLoc(),
4490 diag::note_omp_explicit_dsa)
4491 << getOpenMPClauseName(OMPC_uniform);
4492 continue;
4493 }
4494 LinearArgs[CanonPVD] = E;
4495 if (E->isValueDependent() || E->isTypeDependent() ||
4496 E->isInstantiationDependent() ||
4497 E->containsUnexpandedParameterPack())
4498 continue;
4499 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
4500 PVD->getOriginalType());
4501 continue;
4502 }
4503 }
4504 if (isa<CXXThisExpr>(E)) {
4505 if (UniformedLinearThis) {
4506 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
4507 << getOpenMPClauseName(OMPC_linear)
4508 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
4509 << E->getSourceRange();
4510 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
4511 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
4512 : OMPC_linear);
4513 continue;
4514 }
4515 UniformedLinearThis = E;
4516 if (E->isValueDependent() || E->isTypeDependent() ||
4517 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
4518 continue;
4519 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
4520 E->getType());
4521 continue;
4522 }
4523 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
4524 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
4525 }
4526 Expr *Step = nullptr;
4527 Expr *NewStep = nullptr;
4528 SmallVector<Expr *, 4> NewSteps;
4529 for (Expr *E : Steps) {
4530 // Skip the same step expression, it was checked already.
4531 if (Step == E || !E) {
4532 NewSteps.push_back(E ? NewStep : nullptr);
4533 continue;
4534 }
4535 Step = E;
4536 if (const auto *DRE = dyn_cast<DeclRefExpr>(Step))
4537 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
4538 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
4539 if (UniformedArgs.count(CanonPVD) == 0) {
4540 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
4541 << Step->getSourceRange();
4542 } else if (E->isValueDependent() || E->isTypeDependent() ||
4543 E->isInstantiationDependent() ||
4544 E->containsUnexpandedParameterPack() ||
4545 CanonPVD->getType()->hasIntegerRepresentation()) {
4546 NewSteps.push_back(Step);
4547 } else {
4548 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
4549 << Step->getSourceRange();
4550 }
4551 continue;
4552 }
4553 NewStep = Step;
4554 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
4555 !Step->isInstantiationDependent() &&
4556 !Step->containsUnexpandedParameterPack()) {
4557 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
4558 .get();
4559 if (NewStep)
4560 NewStep = VerifyIntegerConstantExpression(NewStep).get();
4561 }
4562 NewSteps.push_back(NewStep);
4563 }
4564 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
4565 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
4566 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
4567 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
4568 const_cast<Expr **>(Linears.data()), Linears.size(),
4569 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
4570 NewSteps.data(), NewSteps.size(), SR);
4571 ADecl->addAttr(NewAttr);
4572 return ConvertDeclToDeclGroup(ADecl);
4573}
4574
4575StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
4576 Stmt *AStmt,
4577 SourceLocation StartLoc,
4578 SourceLocation EndLoc) {
4579 if (!AStmt)
4580 return StmtError();
4581
4582 auto *CS = cast<CapturedStmt>(AStmt);
4583 // 1.2.2 OpenMP Language Terminology
4584 // Structured block - An executable statement with a single entry at the
4585 // top and a single exit at the bottom.
4586 // The point of exit cannot be a branch out of the structured block.
4587 // longjmp() and throw() must not violate the entry/exit criteria.
4588 CS->getCapturedDecl()->setNothrow();
4589
4590 setFunctionHasBranchProtectedScope();
4591
4592 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4593 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isCancelRegion());
4594}
4595
4596namespace {
4597/// Helper class for checking canonical form of the OpenMP loops and
4598/// extracting iteration space of each loop in the loop nest, that will be used
4599/// for IR generation.
4600class OpenMPIterationSpaceChecker {
4601 /// Reference to Sema.
4602 Sema &SemaRef;
4603 /// Data-sharing stack.
4604 DSAStackTy &Stack;
4605 /// A location for diagnostics (when there is no some better location).
4606 SourceLocation DefaultLoc;
4607 /// A location for diagnostics (when increment is not compatible).
4608 SourceLocation ConditionLoc;
4609 /// A source location for referring to loop init later.
4610 SourceRange InitSrcRange;
4611 /// A source location for referring to condition later.
4612 SourceRange ConditionSrcRange;
4613 /// A source location for referring to increment later.
4614 SourceRange IncrementSrcRange;
4615 /// Loop variable.
4616 ValueDecl *LCDecl = nullptr;
4617 /// Reference to loop variable.
4618 Expr *LCRef = nullptr;
4619 /// Lower bound (initializer for the var).
4620 Expr *LB = nullptr;
4621 /// Upper bound.
4622 Expr *UB = nullptr;
4623 /// Loop step (increment).
4624 Expr *Step = nullptr;
4625 /// This flag is true when condition is one of:
4626 /// Var < UB
4627 /// Var <= UB
4628 /// UB > Var
4629 /// UB >= Var
4630 /// This will have no value when the condition is !=
4631 llvm::Optional<bool> TestIsLessOp;
4632 /// This flag is true when condition is strict ( < or > ).
4633 bool TestIsStrictOp = false;
4634 /// This flag is true when step is subtracted on each iteration.
4635 bool SubtractStep = false;
4636 /// The outer loop counter this loop depends on (if any).
4637 const ValueDecl *DepDecl = nullptr;
4638 /// Contains number of loop (starts from 1) on which loop counter init
4639 /// expression of this loop depends on.
4640 Optional<unsigned> InitDependOnLC;
4641 /// Contains number of loop (starts from 1) on which loop counter condition
4642 /// expression of this loop depends on.
4643 Optional<unsigned> CondDependOnLC;
4644 /// Checks if the provide statement depends on the loop counter.
4645 Optional<unsigned> doesDependOnLoopCounter(const Stmt *S, bool IsInitializer);
4646
4647public:
4648 OpenMPIterationSpaceChecker(Sema &SemaRef, DSAStackTy &Stack,
4649 SourceLocation DefaultLoc)
4650 : SemaRef(SemaRef), Stack(Stack), DefaultLoc(DefaultLoc),
4651 ConditionLoc(DefaultLoc) {}
4652 /// Check init-expr for canonical loop form and save loop counter
4653 /// variable - #Var and its initialization value - #LB.
4654 bool checkAndSetInit(Stmt *S, bool EmitDiags = true);
4655 /// Check test-expr for canonical form, save upper-bound (#UB), flags
4656 /// for less/greater and for strict/non-strict comparison.
4657 bool checkAndSetCond(Expr *S);
4658 /// Check incr-expr for canonical loop form and return true if it
4659 /// does not conform, otherwise save loop step (#Step).
4660 bool checkAndSetInc(Expr *S);
4661 /// Return the loop counter variable.
4662 ValueDecl *getLoopDecl() const { return LCDecl; }
4663 /// Return the reference expression to loop counter variable.
4664 Expr *getLoopDeclRefExpr() const { return LCRef; }
4665 /// Source range of the loop init.
4666 SourceRange getInitSrcRange() const { return InitSrcRange; }
4667 /// Source range of the loop condition.
4668 SourceRange getConditionSrcRange() const { return ConditionSrcRange; }
4669 /// Source range of the loop increment.
4670 SourceRange getIncrementSrcRange() const { return IncrementSrcRange; }
4671 /// True if the step should be subtracted.
4672 bool shouldSubtractStep() const { return SubtractStep; }
4673 /// True, if the compare operator is strict (<, > or !=).
4674 bool isStrictTestOp() const { return TestIsStrictOp; }
4675 /// Build the expression to calculate the number of iterations.
4676 Expr *buildNumIterations(
4677 Scope *S, const bool LimitedType,
4678 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
4679 /// Build the precondition expression for the loops.
4680 Expr *
4681 buildPreCond(Scope *S, Expr *Cond,
4682 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
4683 /// Build reference expression to the counter be used for codegen.
4684 DeclRefExpr *
4685 buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
4686 DSAStackTy &DSA) const;
4687 /// Build reference expression to the private counter be used for
4688 /// codegen.
4689 Expr *buildPrivateCounterVar() const;
4690 /// Build initialization of the counter be used for codegen.
4691 Expr *buildCounterInit() const;
4692 /// Build step of the counter be used for codegen.
4693 Expr *buildCounterStep() const;
4694 /// Build loop data with counter value for depend clauses in ordered
4695 /// directives.
4696 Expr *
4697 buildOrderedLoopData(Scope *S, Expr *Counter,
4698 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
4699 SourceLocation Loc, Expr *Inc = nullptr,
4700 OverloadedOperatorKind OOK = OO_Amp);
4701 /// Return true if any expression is dependent.
4702 bool dependent() const;
4703
4704private:
4705 /// Check the right-hand side of an assignment in the increment
4706 /// expression.
4707 bool checkAndSetIncRHS(Expr *RHS);
4708 /// Helper to set loop counter variable and its initializer.
4709 bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB,
4710 bool EmitDiags);
4711 /// Helper to set upper bound.
4712 bool setUB(Expr *NewUB, llvm::Optional<bool> LessOp, bool StrictOp,
4713 SourceRange SR, SourceLocation SL);
4714 /// Helper to set loop increment.
4715 bool setStep(Expr *NewStep, bool Subtract);
4716};
4717
4718bool OpenMPIterationSpaceChecker::dependent() const {
4719 if (!LCDecl) {
4720 assert(!LB && !UB && !Step)((!LB && !UB && !Step) ? static_cast<void>
(0) : __assert_fail ("!LB && !UB && !Step", "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4720, __PRETTY_FUNCTION__))
;
4721 return false;
4722 }
4723 return LCDecl->getType()->isDependentType() ||
4724 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
4725 (Step && Step->isValueDependent());
4726}
4727
4728bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl,
4729 Expr *NewLCRefExpr,
4730 Expr *NewLB, bool EmitDiags) {
4731 // State consistency checking to ensure correct usage.
4732 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&((LCDecl == nullptr && LB == nullptr && LCRef
== nullptr && UB == nullptr && Step == nullptr
&& !TestIsLessOp && !TestIsStrictOp) ? static_cast
<void> (0) : __assert_fail ("LCDecl == nullptr && LB == nullptr && LCRef == nullptr && UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp"
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4733, __PRETTY_FUNCTION__))
4733 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp)((LCDecl == nullptr && LB == nullptr && LCRef
== nullptr && UB == nullptr && Step == nullptr
&& !TestIsLessOp && !TestIsStrictOp) ? static_cast
<void> (0) : __assert_fail ("LCDecl == nullptr && LB == nullptr && LCRef == nullptr && UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp"
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4733, __PRETTY_FUNCTION__))
;
4734 if (!NewLCDecl || !NewLB)
4735 return true;
4736 LCDecl = getCanonicalDecl(NewLCDecl);
4737 LCRef = NewLCRefExpr;
4738 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
4739 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
4740 if ((Ctor->isCopyOrMoveConstructor() ||
4741 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
4742 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
4743 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
4744 LB = NewLB;
4745 if (EmitDiags)
4746 InitDependOnLC = doesDependOnLoopCounter(LB, /*IsInitializer=*/true);
4747 return false;
4748}
4749
4750bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB,
4751 llvm::Optional<bool> LessOp,
4752 bool StrictOp, SourceRange SR,
4753 SourceLocation SL) {
4754 // State consistency checking to ensure correct usage.
4755 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&((LCDecl != nullptr && LB != nullptr && UB ==
nullptr && Step == nullptr && !TestIsLessOp &&
!TestIsStrictOp) ? static_cast<void> (0) : __assert_fail
("LCDecl != nullptr && LB != nullptr && UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp"
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4756, __PRETTY_FUNCTION__))
4756 Step == nullptr && !TestIsLessOp && !TestIsStrictOp)((LCDecl != nullptr && LB != nullptr && UB ==
nullptr && Step == nullptr && !TestIsLessOp &&
!TestIsStrictOp) ? static_cast<void> (0) : __assert_fail
("LCDecl != nullptr && LB != nullptr && UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp"
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4756, __PRETTY_FUNCTION__))
;
4757 if (!NewUB)
4758 return true;
4759 UB = NewUB;
4760 if (LessOp)
4761 TestIsLessOp = LessOp;
4762 TestIsStrictOp = StrictOp;
4763 ConditionSrcRange = SR;
4764 ConditionLoc = SL;
4765 CondDependOnLC = doesDependOnLoopCounter(UB, /*IsInitializer=*/false);
4766 return false;
4767}
4768
4769bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) {
4770 // State consistency checking to ensure correct usage.
4771 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr)((LCDecl != nullptr && LB != nullptr && Step ==
nullptr) ? static_cast<void> (0) : __assert_fail ("LCDecl != nullptr && LB != nullptr && Step == nullptr"
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4771, __PRETTY_FUNCTION__))
;
4772 if (!NewStep)
4773 return true;
4774 if (!NewStep->isValueDependent()) {
4775 // Check that the step is integer expression.
4776 SourceLocation StepLoc = NewStep->getBeginLoc();
4777 ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
4778 StepLoc, getExprAsWritten(NewStep));
4779 if (Val.isInvalid())
4780 return true;
4781 NewStep = Val.get();
4782
4783 // OpenMP [2.6, Canonical Loop Form, Restrictions]
4784 // If test-expr is of form var relational-op b and relational-op is < or
4785 // <= then incr-expr must cause var to increase on each iteration of the
4786 // loop. If test-expr is of form var relational-op b and relational-op is
4787 // > or >= then incr-expr must cause var to decrease on each iteration of
4788 // the loop.
4789 // If test-expr is of form b relational-op var and relational-op is < or
4790 // <= then incr-expr must cause var to decrease on each iteration of the
4791 // loop. If test-expr is of form b relational-op var and relational-op is
4792 // > or >= then incr-expr must cause var to increase on each iteration of
4793 // the loop.
4794 llvm::APSInt Result;
4795 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
4796 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
4797 bool IsConstNeg =
4798 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
4799 bool IsConstPos =
4800 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
4801 bool IsConstZero = IsConstant && !Result.getBoolValue();
4802
4803 // != with increment is treated as <; != with decrement is treated as >
4804 if (!TestIsLessOp.hasValue())
4805 TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract);
4806 if (UB && (IsConstZero ||
4807 (TestIsLessOp.getValue() ?
4808 (IsConstNeg || (IsUnsigned && Subtract)) :
4809 (IsConstPos || (IsUnsigned && !Subtract))))) {
4810 SemaRef.Diag(NewStep->getExprLoc(),
4811 diag::err_omp_loop_incr_not_compatible)
4812 << LCDecl << TestIsLessOp.getValue() << NewStep->getSourceRange();
4813 SemaRef.Diag(ConditionLoc,
4814 diag::note_omp_loop_cond_requres_compatible_incr)
4815 << TestIsLessOp.getValue() << ConditionSrcRange;
4816 return true;
4817 }
4818 if (TestIsLessOp.getValue() == Subtract) {
4819 NewStep =
4820 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
4821 .get();
4822 Subtract = !Subtract;
4823 }
4824 }
4825
4826 Step = NewStep;
4827 SubtractStep = Subtract;
4828 return false;
4829}
4830
4831namespace {
4832/// Checker for the non-rectangular loops. Checks if the initializer or
4833/// condition expression references loop counter variable.
4834class LoopCounterRefChecker final
4835 : public ConstStmtVisitor<LoopCounterRefChecker, bool> {
4836 Sema &SemaRef;
4837 DSAStackTy &Stack;
4838 const ValueDecl *CurLCDecl = nullptr;
4839 const ValueDecl *DepDecl = nullptr;
4840 const ValueDecl *PrevDepDecl = nullptr;
4841 bool IsInitializer = true;
4842 unsigned BaseLoopId = 0;
4843 bool checkDecl(const Expr *E, const ValueDecl *VD) {
4844 if (getCanonicalDecl(VD) == getCanonicalDecl(CurLCDecl)) {
4845 SemaRef.Diag(E->getExprLoc(), diag::err_omp_stmt_depends_on_loop_counter)
4846 << (IsInitializer ? 0 : 1);
4847 return false;
4848 }
4849 const auto &&Data = Stack.isLoopControlVariable(VD);
4850 // OpenMP, 2.9.1 Canonical Loop Form, Restrictions.
4851 // The type of the loop iterator on which we depend may not have a random
4852 // access iterator type.
4853 if (Data.first && VD->getType()->isRecordType()) {
4854 SmallString<128> Name;
4855 llvm::raw_svector_ostream OS(Name);
4856 VD->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
4857 /*Qualified=*/true);
4858 SemaRef.Diag(E->getExprLoc(),
4859 diag::err_omp_wrong_dependency_iterator_type)
4860 << OS.str();
4861 SemaRef.Diag(VD->getLocation(), diag::note_previous_decl) << VD;
4862 return false;
4863 }
4864 if (Data.first &&
4865 (DepDecl || (PrevDepDecl &&
4866 getCanonicalDecl(VD) != getCanonicalDecl(PrevDepDecl)))) {
4867 if (!DepDecl && PrevDepDecl)
4868 DepDecl = PrevDepDecl;
4869 SmallString<128> Name;
4870 llvm::raw_svector_ostream OS(Name);
4871 DepDecl->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
4872 /*Qualified=*/true);
4873 SemaRef.Diag(E->getExprLoc(),
4874 diag::err_omp_invariant_or_linear_dependency)
4875 << OS.str();
4876 return false;
4877 }
4878 if (Data.first) {
4879 DepDecl = VD;
4880 BaseLoopId = Data.first;
4881 }
4882 return Data.first;
4883 }
4884
4885public:
4886 bool VisitDeclRefExpr(const DeclRefExpr *E) {
4887 const ValueDecl *VD = E->getDecl();
4888 if (isa<VarDecl>(VD))
4889 return checkDecl(E, VD);
4890 return false;
4891 }
4892 bool VisitMemberExpr(const MemberExpr *E) {
4893 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
4894 const ValueDecl *VD = E->getMemberDecl();
4895 return checkDecl(E, VD);
4896 }
4897 return false;
4898 }
4899 bool VisitStmt(const Stmt *S) {
4900 bool Res = true;
4901 for (const Stmt *Child : S->children())
4902 Res = Child && Visit(Child) && Res;
4903 return Res;
4904 }
4905 explicit LoopCounterRefChecker(Sema &SemaRef, DSAStackTy &Stack,
4906 const ValueDecl *CurLCDecl, bool IsInitializer,
4907 const ValueDecl *PrevDepDecl = nullptr)
4908 : SemaRef(SemaRef), Stack(Stack), CurLCDecl(CurLCDecl),
4909 PrevDepDecl(PrevDepDecl), IsInitializer(IsInitializer) {}
4910 unsigned getBaseLoopId() const {
4911 assert(CurLCDecl && "Expected loop dependency.")((CurLCDecl && "Expected loop dependency.") ? static_cast
<void> (0) : __assert_fail ("CurLCDecl && \"Expected loop dependency.\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4911, __PRETTY_FUNCTION__))
;
4912 return BaseLoopId;
4913 }
4914 const ValueDecl *getDepDecl() const {
4915 assert(CurLCDecl && "Expected loop dependency.")((CurLCDecl && "Expected loop dependency.") ? static_cast
<void> (0) : __assert_fail ("CurLCDecl && \"Expected loop dependency.\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4915, __PRETTY_FUNCTION__))
;
4916 return DepDecl;
4917 }
4918};
4919} // namespace
4920
4921Optional<unsigned>
4922OpenMPIterationSpaceChecker::doesDependOnLoopCounter(const Stmt *S,
4923 bool IsInitializer) {
4924 // Check for the non-rectangular loops.
4925 LoopCounterRefChecker LoopStmtChecker(SemaRef, Stack, LCDecl, IsInitializer,
4926 DepDecl);
4927 if (LoopStmtChecker.Visit(S)) {
4928 DepDecl = LoopStmtChecker.getDepDecl();
4929 return LoopStmtChecker.getBaseLoopId();
4930 }
4931 return llvm::None;
4932}
4933
4934bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) {
4935 // Check init-expr for canonical loop form and save loop counter
4936 // variable - #Var and its initialization value - #LB.
4937 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
4938 // var = lb
4939 // integer-type var = lb
4940 // random-access-iterator-type var = lb
4941 // pointer-type var = lb
4942 //
4943 if (!S) {
4944 if (EmitDiags) {
4945 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
4946 }
4947 return true;
4948 }
4949 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
4950 if (!ExprTemp->cleanupsHaveSideEffects())
4951 S = ExprTemp->getSubExpr();
4952
4953 InitSrcRange = S->getSourceRange();
4954 if (Expr *E = dyn_cast<Expr>(S))
4955 S = E->IgnoreParens();
4956 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
4957 if (BO->getOpcode() == BO_Assign) {
4958 Expr *LHS = BO->getLHS()->IgnoreParens();
4959 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
4960 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
4961 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
4962 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
4963 EmitDiags);
4964 return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS(), EmitDiags);
4965 }
4966 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
4967 if (ME->isArrow() &&
4968 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
4969 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
4970 EmitDiags);
4971 }
4972 }
4973 } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
4974 if (DS->isSingleDecl()) {
4975 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
4976 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
4977 // Accept non-canonical init form here but emit ext. warning.
4978 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
4979 SemaRef.Diag(S->getBeginLoc(),
4980 diag::ext_omp_loop_not_canonical_init)
4981 << S->getSourceRange();
4982 return setLCDeclAndLB(
4983 Var,
4984 buildDeclRefExpr(SemaRef, Var,
4985 Var->getType().getNonReferenceType(),
4986 DS->getBeginLoc()),
4987 Var->getInit(), EmitDiags);
4988 }
4989 }
4990 }
4991 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
4992 if (CE->getOperator() == OO_Equal) {
4993 Expr *LHS = CE->getArg(0);
4994 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
4995 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
4996 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
4997 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
4998 EmitDiags);
4999 return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1), EmitDiags);
5000 }
5001 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
5002 if (ME->isArrow() &&
5003 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
5004 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
5005 EmitDiags);
5006 }
5007 }
5008 }
5009
5010 if (dependent() || SemaRef.CurContext->isDependentContext())
5011 return false;
5012 if (EmitDiags) {
5013 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init)
5014 << S->getSourceRange();
5015 }
5016 return true;
5017}
5018
5019/// Ignore parenthesizes, implicit casts, copy constructor and return the
5020/// variable (which may be the loop variable) if possible.
5021static const ValueDecl *getInitLCDecl(const Expr *E) {
5022 if (!E)
5023 return nullptr;
5024 E = getExprAsWritten(E);
5025 if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
5026 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
5027 if ((Ctor->isCopyOrMoveConstructor() ||
5028 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
5029 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
5030 E = CE->getArg(0)->IgnoreParenImpCasts();
5031 if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
5032 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
5033 return getCanonicalDecl(VD);
5034 }
5035 if (const auto *ME = dyn_cast_or_null<MemberExpr>(E))
5036 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
5037 return getCanonicalDecl(ME->getMemberDecl());
5038 return nullptr;
5039}
5040
5041bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) {
5042 // Check test-expr for canonical form, save upper-bound UB, flags for
5043 // less/greater and for strict/non-strict comparison.
5044 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
5045 // var relational-op b
5046 // b relational-op var
5047 //
5048 if (!S) {
5049 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
5050 return true;
5051 }
5052 S = getExprAsWritten(S);
5053 SourceLocation CondLoc = S->getBeginLoc();
5054 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
5055 if (BO->isRelationalOp()) {
5056 if (getInitLCDecl(BO->getLHS()) == LCDecl)
5057 return setUB(BO->getRHS(),
5058 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
5059 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
5060 BO->getSourceRange(), BO->getOperatorLoc());
5061 if (getInitLCDecl(BO->getRHS()) == LCDecl)
5062 return setUB(BO->getLHS(),
5063 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
5064 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
5065 BO->getSourceRange(), BO->getOperatorLoc());
5066 } else if (BO->getOpcode() == BO_NE)
5067 return setUB(getInitLCDecl(BO->getLHS()) == LCDecl ?
5068 BO->getRHS() : BO->getLHS(),
5069 /*LessOp=*/llvm::None,
5070 /*StrictOp=*/true,
5071 BO->getSourceRange(), BO->getOperatorLoc());
5072 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
5073 if (CE->getNumArgs() == 2) {
5074 auto Op = CE->getOperator();
5075 switch (Op) {
5076 case OO_Greater:
5077 case OO_GreaterEqual:
5078 case OO_Less:
5079 case OO_LessEqual:
5080 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
5081 return setUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
5082 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
5083 CE->getOperatorLoc());
5084 if (getInitLCDecl(CE->getArg(1)) == LCDecl)
5085 return setUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
5086 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
5087 CE->getOperatorLoc());
5088 break;
5089 case OO_ExclaimEqual:
5090 return setUB(getInitLCDecl(CE->getArg(0)) == LCDecl ?
5091 CE->getArg(1) : CE->getArg(0),
5092 /*LessOp=*/llvm::None,
5093 /*StrictOp=*/true,
5094 CE->getSourceRange(),
5095 CE->getOperatorLoc());
5096 break;
5097 default:
5098 break;
5099 }
5100 }
5101 }
5102 if (dependent() || SemaRef.CurContext->isDependentContext())
5103 return false;
5104 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
5105 << S->getSourceRange() << LCDecl;
5106 return true;
5107}
5108
5109bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) {
5110 // RHS of canonical loop form increment can be:
5111 // var + incr
5112 // incr + var
5113 // var - incr
5114 //
5115 RHS = RHS->IgnoreParenImpCasts();
5116 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
5117 if (BO->isAdditiveOp()) {
5118 bool IsAdd = BO->getOpcode() == BO_Add;
5119 if (getInitLCDecl(BO->getLHS()) == LCDecl)
5120 return setStep(BO->getRHS(), !IsAdd);
5121 if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl)
5122 return setStep(BO->getLHS(), /*Subtract=*/false);
5123 }
5124 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
5125 bool IsAdd = CE->getOperator() == OO_Plus;
5126 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
5127 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
5128 return setStep(CE->getArg(1), !IsAdd);
5129 if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl)
5130 return setStep(CE->getArg(0), /*Subtract=*/false);
5131 }
5132 }
5133 if (dependent() || SemaRef.CurContext->isDependentContext())
5134 return false;
5135 SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
5136 << RHS->getSourceRange() << LCDecl;
5137 return true;
5138}
5139
5140bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) {
5141 // Check incr-expr for canonical loop form and return true if it
5142 // does not conform.
5143 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
5144 // ++var
5145 // var++
5146 // --var
5147 // var--
5148 // var += incr
5149 // var -= incr
5150 // var = var + incr
5151 // var = incr + var
5152 // var = var - incr
5153 //
5154 if (!S) {
5155 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
5156 return true;
5157 }
5158 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
5159 if (!ExprTemp->cleanupsHaveSideEffects())
5160 S = ExprTemp->getSubExpr();
5161
5162 IncrementSrcRange = S->getSourceRange();
5163 S = S->IgnoreParens();
5164 if (auto *UO = dyn_cast<UnaryOperator>(S)) {
5165 if (UO->isIncrementDecrementOp() &&
5166 getInitLCDecl(UO->getSubExpr()) == LCDecl)
5167 return setStep(SemaRef
5168 .ActOnIntegerConstant(UO->getBeginLoc(),
5169 (UO->isDecrementOp() ? -1 : 1))
5170 .get(),
5171 /*Subtract=*/false);
5172 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
5173 switch (BO->getOpcode()) {
5174 case BO_AddAssign:
5175 case BO_SubAssign:
5176 if (getInitLCDecl(BO->getLHS()) == LCDecl)
5177 return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
5178 break;
5179 case BO_Assign:
5180 if (getInitLCDecl(BO->getLHS()) == LCDecl)
5181 return checkAndSetIncRHS(BO->getRHS());
5182 break;
5183 default:
5184 break;
5185 }
5186 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
5187 switch (CE->getOperator()) {
5188 case OO_PlusPlus:
5189 case OO_MinusMinus:
5190 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
5191 return setStep(SemaRef
5192 .ActOnIntegerConstant(
5193 CE->getBeginLoc(),
5194 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
5195 .get(),
5196 /*Subtract=*/false);
5197 break;
5198 case OO_PlusEqual:
5199 case OO_MinusEqual:
5200 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
5201 return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
5202 break;
5203 case OO_Equal:
5204 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
5205 return checkAndSetIncRHS(CE->getArg(1));
5206 break;
5207 default:
5208 break;
5209 }
5210 }
5211 if (dependent() || SemaRef.CurContext->isDependentContext())
5212 return false;
5213 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
5214 << S->getSourceRange() << LCDecl;
5215 return true;
5216}
5217
5218static ExprResult
5219tryBuildCapture(Sema &SemaRef, Expr *Capture,
5220 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
5221 if (SemaRef.CurContext->isDependentContext())
5222 return ExprResult(Capture);
5223 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
5224 return SemaRef.PerformImplicitConversion(
5225 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
5226 /*AllowExplicit=*/true);
5227 auto I = Captures.find(Capture);
5228 if (I != Captures.end())
5229 return buildCapture(SemaRef, Capture, I->second);
5230 DeclRefExpr *Ref = nullptr;
5231 ExprResult Res = buildCapture(SemaRef, Capture, Ref);
5232 Captures[Capture] = Ref;
5233 return Res;
5234}
5235
5236/// Build the expression to calculate the number of iterations.
5237Expr *OpenMPIterationSpaceChecker::buildNumIterations(
5238 Scope *S, const bool LimitedType,
5239 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
5240 ExprResult Diff;
5241 QualType VarType = LCDecl->getType().getNonReferenceType();
5242 if (VarType->isIntegerType() || VarType->isPointerType() ||
5243 SemaRef.getLangOpts().CPlusPlus) {
5244 // Upper - Lower
5245 Expr *UBExpr = TestIsLessOp.getValue() ? UB : LB;
5246 Expr *LBExpr = TestIsLessOp.getValue() ? LB : UB;
5247 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
5248 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
5249 if (!Upper || !Lower)
5250 return nullptr;
5251
5252 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
5253
5254 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
5255 // BuildBinOp already emitted error, this one is to point user to upper
5256 // and lower bound, and to tell what is passed to 'operator-'.
5257 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
5258 << Upper->getSourceRange() << Lower->getSourceRange();
5259 return nullptr;
5260 }
5261 }
5262
5263 if (!Diff.isUsable())
5264 return nullptr;
5265
5266 // Upper - Lower [- 1]
5267 if (TestIsStrictOp)
5268 Diff = SemaRef.BuildBinOp(
5269 S, DefaultLoc, BO_Sub, Diff.get(),
5270 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
5271 if (!Diff.isUsable())
5272 return nullptr;
5273
5274 // Upper - Lower [- 1] + Step
5275 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
5276 if (!NewStep.isUsable())
5277 return nullptr;
5278 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
5279 if (!Diff.isUsable())
5280 return nullptr;
5281
5282 // Parentheses (for dumping/debugging purposes only).
5283 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
5284 if (!Diff.isUsable())
5285 return nullptr;
5286
5287 // (Upper - Lower [- 1] + Step) / Step
5288 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
5289 if (!Diff.isUsable())
5290 return nullptr;
5291
5292 // OpenMP runtime requires 32-bit or 64-bit loop variables.
5293 QualType Type = Diff.get()->getType();
5294 ASTContext &C = SemaRef.Context;
5295 bool UseVarType = VarType->hasIntegerRepresentation() &&
5296 C.getTypeSize(Type) > C.getTypeSize(VarType);
5297 if (!Type->isIntegerType() || UseVarType) {
5298 unsigned NewSize =
5299 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
5300 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
5301 : Type->hasSignedIntegerRepresentation();
5302 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
5303 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
5304 Diff = SemaRef.PerformImplicitConversion(
5305 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
5306 if (!Diff.isUsable())
5307 return nullptr;
5308 }
5309 }
5310 if (LimitedType) {
5311 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
5312 if (NewSize != C.getTypeSize(Type)) {
5313 if (NewSize < C.getTypeSize(Type)) {
5314 assert(NewSize == 64 && "incorrect loop var size")((NewSize == 64 && "incorrect loop var size") ? static_cast
<void> (0) : __assert_fail ("NewSize == 64 && \"incorrect loop var size\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 5314, __PRETTY_FUNCTION__))
;
5315 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
5316 << InitSrcRange << ConditionSrcRange;
5317 }
5318 QualType NewType = C.getIntTypeForBitwidth(
5319 NewSize, Type->hasSignedIntegerRepresentation() ||
5320 C.getTypeSize(Type) < NewSize);
5321 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
5322 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
5323 Sema::AA_Converting, true);
5324 if (!Diff.isUsable())
5325 return nullptr;
5326 }
5327 }
5328 }
5329
5330 return Diff.get();
5331}
5332
5333Expr *OpenMPIterationSpaceChecker::buildPreCond(
5334 Scope *S, Expr *Cond,
5335 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
5336 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
5337 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
5338 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
5339
5340 ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures);
5341 ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures);
5342 if (!NewLB.isUsable() || !NewUB.isUsable())
5343 return nullptr;
5344
5345 ExprResult CondExpr =
5346 SemaRef.BuildBinOp(S, DefaultLoc,
5347 TestIsLessOp.getValue() ?
5348 (TestIsStrictOp ? BO_LT : BO_LE) :
5349 (TestIsStrictOp ? BO_GT : BO_GE),
5350 NewLB.get(), NewUB.get());
5351 if (CondExpr.isUsable()) {
5352 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
5353 SemaRef.Context.BoolTy))
5354 CondExpr = SemaRef.PerformImplicitConversion(
5355 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
5356 /*AllowExplicit=*/true);
5357 }
5358 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
5359 // Otherwise use original loop condition and evaluate it in runtime.
5360 return CondExpr.isUsable() ? CondExpr.get() : Cond;
5361}
5362
5363/// Build reference expression to the counter be used for codegen.
5364DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar(
5365 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
5366 DSAStackTy &DSA) const {
5367 auto *VD = dyn_cast<VarDecl>(LCDecl);
5368 if (!VD) {
5369 VD = SemaRef.isOpenMPCapturedDecl(LCDecl);
5370 DeclRefExpr *Ref = buildDeclRefExpr(
5371 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
5372 const DSAStackTy::DSAVarData Data =
5373 DSA.getTopDSA(LCDecl, /*FromParent=*/false);
5374 // If the loop control decl is explicitly marked as private, do not mark it
5375 // as captured again.
5376 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
5377 Captures.insert(std::make_pair(LCRef, Ref));
5378 return Ref;
5379 }
5380 return cast<DeclRefExpr>(LCRef);
5381}
5382
5383Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const {
5384 if (LCDecl && !LCDecl->isInvalidDecl()) {
5385 QualType Type = LCDecl->getType().getNonReferenceType();
5386 VarDecl *PrivateVar = buildVarDecl(
5387 SemaRef, DefaultLoc, Type, LCDecl->getName(),
5388 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr,
5389 isa<VarDecl>(LCDecl)
5390 ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc)
5391 : nullptr);
5392 if (PrivateVar->isInvalidDecl())
5393 return nullptr;
5394 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
5395 }
5396 return nullptr;
5397}
5398
5399/// Build initialization of the counter to be used for codegen.
5400Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; }
5401
5402/// Build step of the counter be used for codegen.
5403Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; }
5404
5405Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData(
5406 Scope *S, Expr *Counter,
5407 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc,
5408 Expr *Inc, OverloadedOperatorKind OOK) {
5409 Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get();
5410 if (!Cnt)
5411 return nullptr;
5412 if (Inc) {
5413 assert((OOK == OO_Plus || OOK == OO_Minus) &&(((OOK == OO_Plus || OOK == OO_Minus) && "Expected only + or - operations for depend clauses."
) ? static_cast<void> (0) : __assert_fail ("(OOK == OO_Plus || OOK == OO_Minus) && \"Expected only + or - operations for depend clauses.\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 5414, __PRETTY_FUNCTION__))
5414 "Expected only + or - operations for depend clauses.")(((OOK == OO_Plus || OOK == OO_Minus) && "Expected only + or - operations for depend clauses."
) ? static_cast<void> (0) : __assert_fail ("(OOK == OO_Plus || OOK == OO_Minus) && \"Expected only + or - operations for depend clauses.\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 5414, __PRETTY_FUNCTION__))
;
5415 BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub;
5416 Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get();
5417 if (!Cnt)
5418 return nullptr;
5419 }
5420 ExprResult Diff;
5421 QualType VarType = LCDecl->getType().getNonReferenceType();
5422 if (VarType->isIntegerType() || VarType->isPointerType() ||
5423 SemaRef.getLangOpts().CPlusPlus) {
5424 // Upper - Lower
5425 Expr *Upper = TestIsLessOp.getValue()
5426 ? Cnt
5427 : tryBuildCapture(SemaRef, UB, Captures).get();
5428 Expr *Lower = TestIsLessOp.getValue()
5429 ? tryBuildCapture(SemaRef, LB, Captures).get()
5430 : Cnt;
5431 if (!Upper || !Lower)
5432 return nullptr;
5433
5434 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
5435
5436 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
5437 // BuildBinOp already emitted error, this one is to point user to upper
5438 // and lower bound, and to tell what is passed to 'operator-'.
5439 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
5440 << Upper->getSourceRange() << Lower->getSourceRange();
5441 return nullptr;
5442 }
5443 }
5444
5445 if (!Diff.isUsable())
5446 return nullptr;
5447
5448 // Parentheses (for dumping/debugging purposes only).
5449 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
5450 if (!Diff.isUsable())
5451 return nullptr;
5452
5453 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
5454 if (!NewStep.isUsable())
5455 return nullptr;
5456 // (Upper - Lower) / Step
5457 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
5458 if (!Diff.isUsable())
5459 return nullptr;
5460
5461 return Diff.get();
5462}
5463
5464/// Iteration space of a single for loop.
5465struct LoopIterationSpace final {
5466 /// True if the condition operator is the strict compare operator (<, > or
5467 /// !=).
5468 bool IsStrictCompare = false;
5469 /// Condition of the loop.
5470 Expr *PreCond = nullptr;
5471 /// This expression calculates the number of iterations in the loop.
5472 /// It is always possible to calculate it before starting the loop.
5473 Expr *NumIterations = nullptr;
5474 /// The loop counter variable.
5475 Expr *CounterVar = nullptr;
5476 /// Private loop counter variable.
5477 Expr *PrivateCounterVar = nullptr;
5478 /// This is initializer for the initial value of #CounterVar.
5479 Expr *CounterInit = nullptr;
5480 /// This is step for the #CounterVar used to generate its update:
5481 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
5482 Expr *CounterStep = nullptr;
5483 /// Should step be subtracted?
5484 bool Subtract = false;
5485 /// Source range of the loop init.
5486 SourceRange InitSrcRange;
5487 /// Source range of the loop condition.
5488 SourceRange CondSrcRange;
5489 /// Source range of the loop increment.
5490 SourceRange IncSrcRange;
5491};
5492
5493} // namespace
5494
5495void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
5496 assert(getLangOpts().OpenMP && "OpenMP is not active.")((getLangOpts().OpenMP && "OpenMP is not active.") ? static_cast
<void> (0) : __assert_fail ("getLangOpts().OpenMP && \"OpenMP is not active.\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 5496, __PRETTY_FUNCTION__))
;
5497 assert(Init && "Expected loop in canonical form.")((Init && "Expected loop in canonical form.") ? static_cast
<void> (0) : __assert_fail ("Init && \"Expected loop in canonical form.\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 5497, __PRETTY_FUNCTION__))
;
5498 unsigned AssociatedLoops = DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getAssociatedLoops();
5499 if (AssociatedLoops > 0 &&
5500 isOpenMPLoopDirective(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective())) {
5501 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->loopStart();
5502 OpenMPIterationSpaceChecker ISC(*this, *DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, ForLoc);
5503 if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) {
5504 if (ValueDecl *D = ISC.getLoopDecl()) {
5505 auto *VD = dyn_cast<VarDecl>(D);
5506 if (!VD) {
5507 if (VarDecl *Private = isOpenMPCapturedDecl(D)) {
5508 VD = Private;
5509 } else {
5510 DeclRefExpr *Ref = buildCapture(*this, D, ISC.getLoopDeclRefExpr(),
5511 /*WithInit=*/false);
5512 VD = cast<VarDecl>(Ref->getDecl());
5513 }
5514 }
5515 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->addLoopControlVariable(D, VD);
5516 const Decl *LD = DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getPossiblyLoopCunter();
5517 if (LD != D->getCanonicalDecl()) {
5518 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->resetPossibleLoopCounter();
5519 if (auto *Var = dyn_cast_or_null<VarDecl>(LD))
5520 MarkDeclarationsReferencedInExpr(
5521 buildDeclRefExpr(*this, const_cast<VarDecl *>(Var),
5522 Var->getType().getNonLValueExprType(Context),
5523 ForLoc, /*RefersToCapture=*/true));
5524 }
5525 }
5526 }
5527 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->setAssociatedLoops(AssociatedLoops - 1);
5528 }
5529}
5530
5531/// Called on a for stmt to check and extract its iteration space
5532/// for further processing (such as collapsing).
5533static bool checkOpenMPIterationSpace(
5534 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
5535 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
5536 unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr,
5537 Expr *OrderedLoopCountExpr,
5538 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
5539 LoopIterationSpace &ResultIterSpace,
5540 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
5541 // OpenMP [2.6, Canonical Loop Form]
5542 // for (init-expr; test-expr; incr-expr) structured-block
5543 auto *For = dyn_cast_or_null<ForStmt>(S);
5544 if (!For) {
5545 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for)
5546 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
5547 << getOpenMPDirectiveName(DKind) << TotalNestedLoopCount
5548 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
5549 if (TotalNestedLoopCount > 1) {
5550 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
5551 SemaRef.Diag(DSA.getConstructLoc(),
5552 diag::note_omp_collapse_ordered_expr)
5553 << 2 << CollapseLoopCountExpr->getSourceRange()
5554 << OrderedLoopCountExpr->getSourceRange();
5555 else if (CollapseLoopCountExpr)
5556 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
5557 diag::note_omp_collapse_ordered_expr)
5558 << 0 << CollapseLoopCountExpr->getSourceRange();
5559 else
5560 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
5561 diag::note_omp_collapse_ordered_expr)
5562 << 1 << OrderedLoopCountExpr->getSourceRange();
5563 }
5564 return true;
5565 }
5566 assert(For->getBody())((For->getBody()) ? static_cast<void> (0) : __assert_fail
("For->getBody()", "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 5566, __PRETTY_FUNCTION__))
;
5567
5568 OpenMPIterationSpaceChecker ISC(SemaRef, DSA, For->getForLoc());
5569
5570 // Check init.
5571 Stmt *Init = For->getInit();
5572 if (ISC.checkAndSetInit(Init))
5573 return true;
5574
5575 bool HasErrors = false;
5576
5577 // Check loop variable's type.
5578 if (ValueDecl *LCDecl = ISC.getLoopDecl()) {
5579 Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr();
5580
5581 // OpenMP [2.6, Canonical Loop Form]
5582 // Var is one of the following:
5583 // A variable of signed or unsigned integer type.
5584 // For C++, a variable of a random access iterator type.
5585 // For C, a variable of a pointer type.
5586 QualType VarType = LCDecl->getType().getNonReferenceType();
5587 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
5588 !VarType->isPointerType() &&
5589 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
5590 SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type)
5591 << SemaRef.getLangOpts().CPlusPlus;
5592 HasErrors = true;
5593 }
5594
5595 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
5596 // a Construct
5597 // The loop iteration variable(s) in the associated for-loop(s) of a for or
5598 // parallel for construct is (are) private.
5599 // The loop iteration variable in the associated for-loop of a simd
5600 // construct with just one associated for-loop is linear with a
5601 // constant-linear-step that is the increment of the associated for-loop.
5602 // Exclude loop var from the list of variables with implicitly defined data
5603 // sharing attributes.
5604 VarsWithImplicitDSA.erase(LCDecl);
5605
5606 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
5607 // in a Construct, C/C++].
5608 // The loop iteration variable in the associated for-loop of a simd
5609 // construct with just one associated for-loop may be listed in a linear
5610 // clause with a constant-linear-step that is the increment of the
5611 // associated for-loop.
5612 // The loop iteration variable(s) in the associated for-loop(s) of a for or
5613 // parallel for construct may be listed in a private or lastprivate clause.
5614 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
5615 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
5616 // declared in the loop and it is predetermined as a private.
5617 OpenMPClauseKind PredeterminedCKind =
5618 isOpenMPSimdDirective(DKind)
5619 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
5620 : OMPC_private;
5621 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
5622 DVar.CKind != PredeterminedCKind) ||
5623 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
5624 isOpenMPDistributeDirective(DKind)) &&
5625 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
5626 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
5627 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
5628 SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa)
5629 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
5630 << getOpenMPClauseName(PredeterminedCKind);
5631 if (DVar.RefExpr == nullptr)
5632 DVar.CKind = PredeterminedCKind;
5633 reportOriginalDsa(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
5634 HasErrors = true;
5635 } else if (LoopDeclRefExpr != nullptr) {
5636 // Make the loop iteration variable private (for worksharing constructs),
5637 // linear (for simd directives with the only one associated loop) or
5638 // lastprivate (for simd directives with several collapsed or ordered
5639 // loops).
5640 if (DVar.CKind == OMPC_unknown)
5641 DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
5642 }
5643
5644 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars")((isOpenMPLoopDirective(DKind) && "DSA for non-loop vars"
) ? static_cast<void> (0) : __assert_fail ("isOpenMPLoopDirective(DKind) && \"DSA for non-loop vars\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 5644, __PRETTY_FUNCTION__))
;
5645
5646 // Check test-expr.
5647 HasErrors |= ISC.checkAndSetCond(For->getCond());
5648
5649 // Check incr-expr.
5650 HasErrors |= ISC.checkAndSetInc(For->getInc());
5651 }
5652
5653 if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
5654 return HasErrors;
5655
5656 // Build the loop's iteration space representation.
5657 ResultIterSpace.PreCond =
5658 ISC.buildPreCond(DSA.getCurScope(), For->getCond(), Captures);
5659 ResultIterSpace.NumIterations = ISC.buildNumIterations(
5660 DSA.getCurScope(),
5661 (isOpenMPWorksharingDirective(DKind) ||
5662 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
5663 Captures);
5664 ResultIterSpace.CounterVar = ISC.buildCounterVar(Captures, DSA);
5665 ResultIterSpace.PrivateCounterVar = ISC.buildPrivateCounterVar();
5666 ResultIterSpace.CounterInit = ISC.buildCounterInit();
5667 ResultIterSpace.CounterStep = ISC.buildCounterStep();
5668 ResultIterSpace.InitSrcRange = ISC.getInitSrcRange();
5669 ResultIterSpace.CondSrcRange = ISC.getConditionSrcRange();
5670 ResultIterSpace.IncSrcRange = ISC.getIncrementSrcRange();
5671 ResultIterSpace.Subtract = ISC.shouldSubtractStep();
5672 ResultIterSpace.IsStrictCompare = ISC.isStrictTestOp();
5673
5674 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
5675 ResultIterSpace.NumIterations == nullptr ||
5676 ResultIterSpace.CounterVar == nullptr ||
5677 ResultIterSpace.PrivateCounterVar == nullptr ||
5678 ResultIterSpace.CounterInit == nullptr ||
5679 ResultIterSpace.CounterStep == nullptr);
5680 if (!HasErrors && DSA.isOrderedRegion()) {
5681 if (DSA.getOrderedRegionParam().second->getNumForLoops()) {
5682 if (CurrentNestedLoopCount <
5683 DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) {
5684 DSA.getOrderedRegionParam().second->setLoopNumIterations(
5685 CurrentNestedLoopCount, ResultIterSpace.NumIterations);
5686 DSA.getOrderedRegionParam().second->setLoopCounter(
5687 CurrentNestedLoopCount, ResultIterSpace.CounterVar);
5688 }
5689 }
5690 for (auto &Pair : DSA.getDoacrossDependClauses()) {
5691 if (CurrentNestedLoopCount >= Pair.first->getNumLoops()) {
5692 // Erroneous case - clause has some problems.
5693 continue;
5694 }
5695 if (Pair.first->getDependencyKind() == OMPC_DEPEND_sink &&
5696 Pair.second.size() <= CurrentNestedLoopCount) {
5697 // Erroneous case - clause has some problems.
5698 Pair.first->setLoopData(CurrentNestedLoopCount, nullptr);
5699 continue;
5700 }
5701 Expr *CntValue;
5702 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
5703 CntValue = ISC.buildOrderedLoopData(
5704 DSA.getCurScope(), ResultIterSpace.CounterVar, Captures,
5705 Pair.first->getDependencyLoc());
5706 else
5707 CntValue = ISC.buildOrderedLoopData(
5708 DSA.getCurScope(), ResultIterSpace.CounterVar, Captures,
5709 Pair.first->getDependencyLoc(),
5710 Pair.second[CurrentNestedLoopCount].first,
5711 Pair.second[CurrentNestedLoopCount].second);
5712 Pair.first->setLoopData(CurrentNestedLoopCount, CntValue);
5713 }
5714 }
5715
5716 return HasErrors;
5717}
5718
5719/// Build 'VarRef = Start.
5720static ExprResult
5721buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
5722 ExprResult Start,
5723 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
5724 // Build 'VarRef = Start.
5725 ExprResult NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
5726 if (!NewStart.isUsable())
5727 return ExprError();
5728 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
5729 VarRef.get()->getType())) {
5730 NewStart = SemaRef.PerformImplicitConversion(
5731 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
5732 /*AllowExplicit=*/true);
5733 if (!NewStart.isUsable())
5734 return ExprError();
5735 }
5736
5737 ExprResult Init =
5738 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
5739 return Init;
5740}
5741
5742/// Build 'VarRef = Start + Iter * Step'.
5743static ExprResult buildCounterUpdate(
5744 Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
5745 ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract,
5746 llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) {
5747 // Add parentheses (for debugging purposes only).
5748 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
5749 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
5750 !Step.isUsable())
5751 return ExprError();
5752
5753 ExprResult NewStep = Step;
5754 if (Captures)
5755 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
5756 if (NewStep.isInvalid())
5757 return ExprError();
5758 ExprResult Update =
5759 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
5760 if (!Update.isUsable())
5761 return ExprError();
5762
5763 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
5764 // 'VarRef = Start (+|-) Iter * Step'.
5765 ExprResult NewStart = Start;
5766 if (Captures)
5767 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
5768 if (NewStart.isInvalid())
5769 return ExprError();
5770
5771 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
5772 ExprResult SavedUpdate = Update;
5773 ExprResult UpdateVal;
5774 if (VarRef.get()->getType()->isOverloadableType() ||
5775 NewStart.get()->getType()->isOverloadableType() ||
5776 Update.get()->getType()->isOverloadableType()) {
5777 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
5778 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
5779 Update =
5780 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
5781 if (Update.isUsable()) {
5782 UpdateVal =
5783 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
5784 VarRef.get(), SavedUpdate.get());
5785 if (UpdateVal.isUsable()) {
5786 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
5787 UpdateVal.get());
5788 }
5789 }
5790 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
5791 }
5792
5793 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
5794 if (!Update.isUsable() || !UpdateVal.isUsable()) {
5795 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
5796 NewStart.get(), SavedUpdate.get());
5797 if (!Update.isUsable())
5798 return ExprError();
5799
5800 if (!SemaRef.Context.hasSameType(Update.get()->getType(),
5801 VarRef.get()->getType())) {
5802 Update = SemaRef.PerformImplicitConversion(
5803 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
5804 if (!Update.isUsable())
5805 return ExprError();
5806 }
5807
5808 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
5809 }
5810 return Update;
5811}
5812
5813/// Convert integer expression \a E to make it have at least \a Bits
5814/// bits.
5815static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
5816 if (E == nullptr)
5817 return ExprError();
5818 ASTContext &C = SemaRef.Context;
5819 QualType OldType = E->getType();
5820 unsigned HasBits = C.getTypeSize(OldType);
5821 if (HasBits >= Bits)
5822 return ExprResult(E);
5823 // OK to convert to signed, because new type has more bits than old.
5824 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
5825 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
5826 true);
5827}
5828
5829/// Check if the given expression \a E is a constant integer that fits
5830/// into \a Bits bits.
5831static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) {
5832 if (E == nullptr)
5833 return false;
5834 llvm::APSInt Result;
5835 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
5836 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
5837 return false;
5838}
5839
5840/// Build preinits statement for the given declarations.
5841static Stmt *buildPreInits(ASTContext &Context,
5842 MutableArrayRef<Decl *> PreInits) {
5843 if (!PreInits.empty()) {
5844 return new (Context) DeclStmt(
5845 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
5846 SourceLocation(), SourceLocation());
5847 }
5848 return nullptr;
5849}
5850
5851/// Build preinits statement for the given declarations.
5852static Stmt *
5853buildPreInits(ASTContext &Context,
5854 const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
5855 if (!Captures.empty()) {
5856 SmallVector<Decl *, 16> PreInits;
5857 for (const auto &Pair : Captures)
5858 PreInits.push_back(Pair.second->getDecl());
5859 return buildPreInits(Context, PreInits);
5860 }
5861 return nullptr;
5862}
5863
5864/// Build postupdate expression for the given list of postupdates expressions.
5865static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
5866 Expr *PostUpdate = nullptr;
5867 if (!PostUpdates.empty()) {
5868 for (Expr *E : PostUpdates) {
5869 Expr *ConvE = S.BuildCStyleCastExpr(
5870 E->getExprLoc(),
5871 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
5872 E->getExprLoc(), E)
5873 .get();
5874 PostUpdate = PostUpdate
5875 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
5876 PostUpdate, ConvE)
5877 .get()
5878 : ConvE;
5879 }
5880 }
5881 return PostUpdate;
5882}
5883
5884/// Called on a for stmt to check itself and nested loops (if any).
5885/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
5886/// number of collapsed loops otherwise.
5887static unsigned
5888checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
5889 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
5890 DSAStackTy &DSA,
5891 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
5892 OMPLoopDirective::HelperExprs &Built) {
5893 unsigned NestedLoopCount = 1;
5894 if (CollapseLoopCountExpr) {
1
Assuming 'CollapseLoopCountExpr' is null
2
Taking false branch
5895 // Found 'collapse' clause - calculate collapse number.
5896 Expr::EvalResult Result;
5897 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
5898 NestedLoopCount = Result.Val.getInt().getLimitedValue();
5899 }
5900 unsigned OrderedLoopCount = 1;
5901 if (OrderedLoopCountExpr) {
3
Assuming 'OrderedLoopCountExpr' is non-null
4
Taking true branch
5902 // Found 'ordered' clause - calculate collapse number.
5903 Expr::EvalResult EVResult;
5904 if (OrderedLoopCountExpr->EvaluateAsInt(EVResult, SemaRef.getASTContext())) {
5
Assuming the condition is true
6
Taking true branch
5905 llvm::APSInt Result = EVResult.Val.getInt();
5906 if (Result.getLimitedValue() < NestedLoopCount) {
7
Assuming the condition is true
8
Taking true branch
5907 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
5908 diag::err_omp_wrong_ordered_loop_count)
5909 << OrderedLoopCountExpr->getSourceRange();
5910 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
9
Called C++ object pointer is null
5911 diag::note_collapse_loop_count)
5912 << CollapseLoopCountExpr->getSourceRange();
5913 }
5914 OrderedLoopCount = Result.getLimitedValue();
5915 }
5916 }
5917 // This is helper routine for loop directives (e.g., 'for', 'simd',
5918 // 'for simd', etc.).
5919 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
5920 SmallVector<LoopIterationSpace, 4> IterSpaces(
5921 std::max(OrderedLoopCount, NestedLoopCount));
5922 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
5923 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
5924 if (checkOpenMPIterationSpace(
5925 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
5926 std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
5927 OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces[Cnt],
5928 Captures))
5929 return 0;
5930 // Move on to the next nested for loop, or to the loop body.
5931 // OpenMP [2.8.1, simd construct, Restrictions]
5932 // All loops associated with the construct must be perfectly nested; that
5933 // is, there must be no intervening code nor any OpenMP directive between
5934 // any two loops.
5935 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
5936 }
5937 for (unsigned Cnt = NestedLoopCount; Cnt < OrderedLoopCount; ++Cnt) {
5938 if (checkOpenMPIterationSpace(
5939 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
5940 std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
5941 OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces[Cnt],
5942 Captures))
5943 return 0;
5944 if (Cnt > 0 && IterSpaces[Cnt].CounterVar) {
5945 // Handle initialization of captured loop iterator variables.
5946 auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar);
5947 if (isa<OMPCapturedExprDecl>(DRE->getDecl())) {
5948 Captures[DRE] = DRE;
5949 }
5950 }
5951 // Move on to the next nested for loop, or to the loop body.
5952 // OpenMP [2.8.1, simd construct, Restrictions]
5953 // All loops associated with the construct must be perfectly nested; that
5954 // is, there must be no intervening code nor any OpenMP directive between
5955 // any two loops.
5956 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
5957 }
5958
5959 Built.clear(/* size */ NestedLoopCount);
5960
5961 if (SemaRef.CurContext->isDependentContext())
5962 return NestedLoopCount;
5963
5964 // An example of what is generated for the following code:
5965 //
5966 // #pragma omp simd collapse(2) ordered(2)
5967 // for (i = 0; i < NI; ++i)
5968 // for (k = 0; k < NK; ++k)
5969 // for (j = J0; j < NJ; j+=2) {
5970 // <loop body>
5971 // }
5972 //
5973 // We generate the code below.
5974 // Note: the loop body may be outlined in CodeGen.
5975 // Note: some counters may be C++ classes, operator- is used to find number of
5976 // iterations and operator+= to calculate counter value.
5977 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
5978 // or i64 is currently supported).
5979 //
5980 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
5981 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
5982 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
5983 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
5984 // // similar updates for vars in clauses (e.g. 'linear')
5985 // <loop body (using local i and j)>
5986 // }
5987 // i = NI; // assign final values of counters
5988 // j = NJ;
5989 //
5990
5991 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
5992 // the iteration counts of the collapsed for loops.
5993 // Precondition tests if there is at least one iteration (all conditions are
5994 // true).
5995 auto PreCond = ExprResult(IterSpaces[0].PreCond);
5996 Expr *N0 = IterSpaces[0].NumIterations;
5997 ExprResult LastIteration32 =
5998 widenIterationCount(/*Bits=*/32,
5999 SemaRef
6000 .PerformImplicitConversion(
6001 N0->IgnoreImpCasts(), N0->getType(),
6002 Sema::AA_Converting, /*AllowExplicit=*/true)
6003 .get(),
6004 SemaRef);
6005 ExprResult LastIteration64 = widenIterationCount(
6006 /*Bits=*/64,
6007 SemaRef
6008 .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(),
6009 Sema::AA_Converting,
6010 /*AllowExplicit=*/true)
6011 .get(),
6012 SemaRef);
6013
6014 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
6015 return NestedLoopCount;
6016
6017 ASTContext &C = SemaRef.Context;
6018 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
6019
6020 Scope *CurScope = DSA.getCurScope();
6021 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
6022 if (PreCond.isUsable()) {
6023 PreCond =
6024 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
6025 PreCond.get(), IterSpaces[Cnt].PreCond);
6026 }
6027 Expr *N = IterSpaces[Cnt].NumIterations;
6028 SourceLocation Loc = N->getExprLoc();
6029 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
6030 if (LastIteration32.isUsable())
6031 LastIteration32 = SemaRef.BuildBinOp(
6032 CurScope, Loc, BO_Mul, LastIteration32.get(),
6033 SemaRef
6034 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
6035 Sema::AA_Converting,
6036 /*AllowExplicit=*/true)
6037 .get());
6038 if (LastIteration64.isUsable())
6039 LastIteration64 = SemaRef.BuildBinOp(
6040 CurScope, Loc, BO_Mul, LastIteration64.get(),
6041 SemaRef
6042 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
6043 Sema::AA_Converting,
6044 /*AllowExplicit=*/true)
6045 .get());
6046 }
6047
6048 // Choose either the 32-bit or 64-bit version.
6049 ExprResult LastIteration = LastIteration64;
6050 if (SemaRef.getLangOpts().OpenMPOptimisticCollapse ||
6051 (LastIteration32.isUsable() &&
6052 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
6053 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
6054 fitsInto(
6055 /*Bits=*/32,
6056 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
6057 LastIteration64.get(), SemaRef))))
6058 LastIteration = LastIteration32;
6059 QualType VType = LastIteration.get()->getType();
6060 QualType RealVType = VType;
6061 QualType StrideVType = VType;
6062 if (isOpenMPTaskLoopDirective(DKind)) {
6063 VType =
6064 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
6065 StrideVType =
6066 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
6067 }
6068
6069 if (!LastIteration.isUsable())
6070 return 0;
6071
6072 // Save the number of iterations.
6073 ExprResult NumIterations = LastIteration;
6074 {
6075 LastIteration = SemaRef.BuildBinOp(
6076 CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
6077 LastIteration.get(),
6078 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
6079 if (!LastIteration.isUsable())
6080 return 0;
6081 }
6082
6083 // Calculate the last iteration number beforehand instead of doing this on
6084 // each iteration. Do not do this if the number of iterations may be kfold-ed.
6085 llvm::APSInt Result;
6086 bool IsConstant =
6087 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
6088 ExprResult CalcLastIteration;
6089 if (!IsConstant) {
6090 ExprResult SaveRef =
6091 tryBuildCapture(SemaRef, LastIteration.get(), Captures);
6092 LastIteration = SaveRef;
6093
6094 // Prepare SaveRef + 1.
6095 NumIterations = SemaRef.BuildBinOp(
6096 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
6097 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
6098 if (!NumIterations.isUsable())
6099 return 0;
6100 }
6101
6102 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
6103
6104 // Build variables passed into runtime, necessary for worksharing directives.
6105 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
6106 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
6107 isOpenMPDistributeDirective(DKind)) {
6108 // Lower bound variable, initialized with zero.
6109 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
6110 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
6111 SemaRef.AddInitializerToDecl(LBDecl,
6112 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
6113 /*DirectInit*/ false);
6114
6115 // Upper bound variable, initialized with last iteration number.
6116 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
6117 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
6118 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
6119 /*DirectInit*/ false);
6120
6121 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
6122 // This will be used to implement clause 'lastprivate'.
6123 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
6124 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
6125 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
6126 SemaRef.AddInitializerToDecl(ILDecl,
6127 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
6128 /*DirectInit*/ false);
6129
6130 // Stride variable returned by runtime (we initialize it to 1 by default).
6131 VarDecl *STDecl =
6132 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
6133 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
6134 SemaRef.AddInitializerToDecl(STDecl,
6135 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
6136 /*DirectInit*/ false);
6137
6138 // Build expression: UB = min(UB, LastIteration)
6139 // It is necessary for CodeGen of directives with static scheduling.
6140 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
6141 UB.get(), LastIteration.get());
6142 ExprResult CondOp = SemaRef.ActOnConditionalOp(
6143 LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(),
6144 LastIteration.get(), UB.get());
6145 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
6146 CondOp.get());
6147 EUB = SemaRef.ActOnFinishFullExpr(EUB.get(), /*DiscardedValue*/ false);
6148
6149 // If we have a combined directive that combines 'distribute', 'for' or
6150 // 'simd' we need to be able to access the bounds of the schedule of the
6151 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
6152 // by scheduling 'distribute' have to be passed to the schedule of 'for'.
6153 if (isOpenMPLoopBoundSharingDirective(DKind)) {
6154 // Lower bound variable, initialized with zero.
6155 VarDecl *CombLBDecl =
6156 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
6157 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
6158 SemaRef.AddInitializerToDecl(
6159 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
6160 /*DirectInit*/ false);
6161
6162 // Upper bound variable, initialized with last iteration number.
6163 VarDecl *CombUBDecl =
6164 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
6165 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
6166 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
6167 /*DirectInit*/ false);
6168
6169 ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
6170 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
6171 ExprResult CombCondOp =
6172 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
6173 LastIteration.get(), CombUB.get());
6174 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
6175 CombCondOp.get());
6176 CombEUB =
6177 SemaRef.ActOnFinishFullExpr(CombEUB.get(), /*DiscardedValue*/ false);
6178
6179 const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
6180 // We expect to have at least 2 more parameters than the 'parallel'
6181 // directive does - the lower and upper bounds of the previous schedule.
6182 assert(CD->getNumParams() >= 4 &&((CD->getNumParams() >= 4 && "Unexpected number of parameters in loop combined directive"
) ? static_cast<void> (0) : __assert_fail ("CD->getNumParams() >= 4 && \"Unexpected number of parameters in loop combined directive\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 6183, __PRETTY_FUNCTION__))
6183 "Unexpected number of parameters in loop combined directive")((CD->getNumParams() >= 4 && "Unexpected number of parameters in loop combined directive"
) ? static_cast<void> (0) : __assert_fail ("CD->getNumParams() >= 4 && \"Unexpected number of parameters in loop combined directive\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 6183, __PRETTY_FUNCTION__))
;
6184
6185 // Set the proper type for the bounds given what we learned from the
6186 // enclosed loops.
6187 ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
6188 ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
6189
6190 // Previous lower and upper bounds are obtained from the region
6191 // parameters.
6192 PrevLB =
6193 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
6194 PrevUB =
6195 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
6196 }
6197 }
6198
6199 // Build the iteration variable and its initialization before loop.
6200 ExprResult IV;
6201 ExprResult Init, CombInit;
6202 {
6203 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
6204 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
6205 Expr *RHS =
6206 (isOpenMPWorksharingDirective(DKind) ||
6207 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
6208 ? LB.get()
6209 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
6210 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
6211 Init = SemaRef.ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
6212
6213 if (isOpenMPLoopBoundSharingDirective(DKind)) {
6214 Expr *CombRHS =
6215 (isOpenMPWorksharingDirective(DKind) ||
6216 isOpenMPTaskLoopDirective(DKind) ||
6217 isOpenMPDistributeDirective(DKind))
6218 ? CombLB.get()
6219 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
6220 CombInit =
6221 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
6222 CombInit =
6223 SemaRef.ActOnFinishFullExpr(CombInit.get(), /*DiscardedValue*/ false);
6224 }
6225 }
6226
6227 bool UseStrictCompare =
6228 RealVType->hasUnsignedIntegerRepresentation() &&
6229 llvm::all_of(IterSpaces, [](const LoopIterationSpace &LIS) {
6230 return LIS.IsStrictCompare;
6231 });
6232 // Loop condition (IV < NumIterations) or (IV <= UB or IV < UB + 1 (for
6233 // unsigned IV)) for worksharing loops.
6234 SourceLocation CondLoc = AStmt->getBeginLoc();
6235 Expr *BoundUB = UB.get();
6236 if (UseStrictCompare) {
6237 BoundUB =
6238 SemaRef
6239 .BuildBinOp(CurScope, CondLoc, BO_Add, BoundUB,
6240 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
6241 .get();
6242 BoundUB =
6243 SemaRef.ActOnFinishFullExpr(BoundUB, /*DiscardedValue*/ false).get();
6244 }
6245 ExprResult Cond =
6246 (isOpenMPWorksharingDirective(DKind) ||
6247 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
6248 ? SemaRef.BuildBinOp(CurScope, CondLoc,
6249 UseStrictCompare ? BO_LT : BO_LE, IV.get(),
6250 BoundUB)
6251 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
6252 NumIterations.get());
6253 ExprResult CombDistCond;
6254 if (isOpenMPLoopBoundSharingDirective(DKind)) {
6255 CombDistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
6256 NumIterations.get());
6257 }
6258
6259 ExprResult CombCond;
6260 if (isOpenMPLoopBoundSharingDirective(DKind)) {
6261 Expr *BoundCombUB = CombUB.get();
6262 if (UseStrictCompare) {
6263 BoundCombUB =
6264 SemaRef
6265 .BuildBinOp(
6266 CurScope, CondLoc, BO_Add, BoundCombUB,
6267 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
6268 .get();
6269 BoundCombUB =
6270 SemaRef.ActOnFinishFullExpr(BoundCombUB, /*DiscardedValue*/ false)
6271 .get();
6272 }
6273 CombCond =
6274 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
6275 IV.get(), BoundCombUB);
6276 }
6277 // Loop increment (IV = IV + 1)
6278 SourceLocation IncLoc = AStmt->getBeginLoc();
6279 ExprResult Inc =
6280 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
6281 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
6282 if (!Inc.isUsable())
6283 return 0;
6284 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
6285 Inc = SemaRef.ActOnFinishFullExpr(Inc.get(), /*DiscardedValue*/ false);
6286 if (!Inc.isUsable())
6287 return 0;
6288
6289 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
6290 // Used for directives with static scheduling.
6291 // In combined construct, add combined version that use CombLB and CombUB
6292 // base variables for the update
6293 ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
6294 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
6295 isOpenMPDistributeDirective(DKind)) {
6296 // LB + ST
6297 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
6298 if (!NextLB.isUsable())
6299 return 0;
6300 // LB = LB + ST
6301 NextLB =
6302 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
6303 NextLB =
6304 SemaRef.ActOnFinishFullExpr(NextLB.get(), /*DiscardedValue*/ false);
6305 if (!NextLB.isUsable())
6306 return 0;
6307 // UB + ST
6308 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
6309 if (!NextUB.isUsable())
6310 return 0;
6311 // UB = UB + ST
6312 NextUB =
6313 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
6314 NextUB =
6315 SemaRef.ActOnFinishFullExpr(NextUB.get(), /*DiscardedValue*/ false);
6316 if (!NextUB.isUsable())
6317 return 0;
6318 if (isOpenMPLoopBoundSharingDirective(DKind)) {
6319 CombNextLB =
6320 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
6321 if (!NextLB.isUsable())
6322 return 0;
6323 // LB = LB + ST
6324 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
6325 CombNextLB.get());
6326 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get(),
6327 /*DiscardedValue*/ false);
6328 if (!CombNextLB.isUsable())
6329 return 0;
6330 // UB + ST
6331 CombNextUB =
6332 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
6333 if (!CombNextUB.isUsable())
6334 return 0;
6335 // UB = UB + ST
6336 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
6337 CombNextUB.get());
6338 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get(),
6339 /*DiscardedValue*/ false);
6340 if (!CombNextUB.isUsable())
6341 return 0;
6342 }
6343 }
6344
6345 // Create increment expression for distribute loop when combined in a same
6346 // directive with for as IV = IV + ST; ensure upper bound expression based
6347 // on PrevUB instead of NumIterations - used to implement 'for' when found
6348 // in combination with 'distribute', like in 'distribute parallel for'
6349 SourceLocation DistIncLoc = AStmt->getBeginLoc();
6350 ExprResult DistCond, DistInc, PrevEUB, ParForInDistCond;
6351 if (isOpenMPLoopBoundSharingDirective(DKind)) {
6352 DistCond = SemaRef.BuildBinOp(
6353 CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, IV.get(), BoundUB);
6354 assert(DistCond.isUsable() && "distribute cond expr was not built")((DistCond.isUsable() && "distribute cond expr was not built"
) ? static_cast<void> (0) : __assert_fail ("DistCond.isUsable() && \"distribute cond expr was not built\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 6354, __PRETTY_FUNCTION__))
;
6355
6356 DistInc =
6357 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
6358 assert(DistInc.isUsable() && "distribute inc expr was not built")((DistInc.isUsable() && "distribute inc expr was not built"
) ? static_cast<void> (0) : __assert_fail ("DistInc.isUsable() && \"distribute inc expr was not built\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 6358, __PRETTY_FUNCTION__))
;
6359 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
6360 DistInc.get());
6361 DistInc =
6362 SemaRef.ActOnFinishFullExpr(DistInc.get(), /*DiscardedValue*/ false);
6363 assert(DistInc.isUsable() && "distribute inc expr was not built")((DistInc.isUsable() && "distribute inc expr was not built"
) ? static_cast<void> (0) : __assert_fail ("DistInc.isUsable() && \"distribute inc expr was not built\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 6363, __PRETTY_FUNCTION__))
;
6364
6365 // Build expression: UB = min(UB, prevUB) for #for in composite or combined
6366 // construct
6367 SourceLocation DistEUBLoc = AStmt->getBeginLoc();
6368 ExprResult IsUBGreater =
6369 SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
6370 ExprResult CondOp = SemaRef.ActOnConditionalOp(
6371 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
6372 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
6373 CondOp.get());
6374 PrevEUB =
6375 SemaRef.ActOnFinishFullExpr(PrevEUB.get(), /*DiscardedValue*/ false);
6376
6377 // Build IV <= PrevUB or IV < PrevUB + 1 for unsigned IV to be used in
6378 // parallel for is in combination with a distribute directive with
6379 // schedule(static, 1)
6380 Expr *BoundPrevUB = PrevUB.get();
6381 if (UseStrictCompare) {
6382 BoundPrevUB =
6383 SemaRef
6384 .BuildBinOp(
6385 CurScope, CondLoc, BO_Add, BoundPrevUB,
6386 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
6387 .get();
6388 BoundPrevUB =
6389 SemaRef.ActOnFinishFullExpr(BoundPrevUB, /*DiscardedValue*/ false)
6390 .get();
6391 }
6392 ParForInDistCond =
6393 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
6394 IV.get(), BoundPrevUB);
6395 }
6396
6397 // Build updates and final values of the loop counters.
6398 bool HasErrors = false;
6399 Built.Counters.resize(NestedLoopCount);
6400 Built.Inits.resize(NestedLoopCount);
6401 Built.Updates.resize(NestedLoopCount);
6402 Built.Finals.resize(NestedLoopCount);
6403 {
6404 // We implement the following algorithm for obtaining the
6405 // original loop iteration variable values based on the
6406 // value of the collapsed loop iteration variable IV.
6407 //
6408 // Let n+1 be the number of collapsed loops in the nest.
6409 // Iteration variables (I0, I1, .... In)
6410 // Iteration counts (N0, N1, ... Nn)
6411 //
6412 // Acc = IV;
6413 //
6414 // To compute Ik for loop k, 0 <= k <= n, generate:
6415 // Prod = N(k+1) * N(k+2) * ... * Nn;
6416 // Ik = Acc / Prod;
6417 // Acc -= Ik * Prod;
6418 //
6419 ExprResult Acc = IV;
6420 for (unsigned int Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
6421 LoopIterationSpace &IS = IterSpaces[Cnt];
6422 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
6423 ExprResult Iter;
6424
6425 // Compute prod
6426 ExprResult Prod =
6427 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
6428 for (unsigned int K = Cnt+1; K < NestedLoopCount; ++K)
6429 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Prod.get(),
6430 IterSpaces[K].NumIterations);
6431
6432 // Iter = Acc / Prod
6433 // If there is at least one more inner loop to avoid
6434 // multiplication by 1.
6435 if (Cnt + 1 < NestedLoopCount)
6436 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div,
6437 Acc.get(), Prod.get());
6438 else
6439 Iter = Acc;
6440 if (!Iter.isUsable()) {
6441 HasErrors = true;
6442 break;
6443 }
6444
6445 // Update Acc:
6446 // Acc -= Iter * Prod
6447 // Check if there is at least one more inner loop to avoid
6448 // multiplication by 1.
6449 if (Cnt + 1 < NestedLoopCount)
6450 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul,
6451 Iter.get(), Prod.get());
6452 else
6453 Prod = Iter;
6454 Acc = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Sub,
6455 Acc.get(), Prod.get());
6456
6457 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
6458 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
6459 DeclRefExpr *CounterVar = buildDeclRefExpr(
6460 SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
6461 /*RefersToCapture=*/true);
6462 ExprResult Init = buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
6463 IS.CounterInit, Captures);
6464 if (!Init.isUsable()) {
6465 HasErrors = true;
6466 break;
6467 }
6468 ExprResult Update = buildCounterUpdate(
6469 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
6470 IS.CounterStep, IS.Subtract, &Captures);
6471 if (!Update.isUsable()) {
6472 HasErrors = true;
6473 break;
6474 }
6475
6476 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
6477 ExprResult Final = buildCounterUpdate(
6478 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
6479 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
6480 if (!Final.isUsable()) {
6481 HasErrors = true;
6482 break;
6483 }
6484
6485 if (!Update.isUsable() || !Final.isUsable()) {
6486 HasErrors = true;
6487 break;
6488 }
6489 // Save results
6490 Built.Counters[Cnt] = IS.CounterVar;
6491 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
6492 Built.Inits[Cnt] = Init.get();
6493 Built.Updates[Cnt] = Update.get();
6494 Built.Finals[Cnt] = Final.get();
6495 }
6496 }
6497
6498 if (HasErrors)
6499 return 0;
6500
6501 // Save results
6502 Built.IterationVarRef = IV.get();
6503 Built.LastIteration = LastIteration.get();
6504 Built.NumIterations = NumIterations.get();
6505 Built.CalcLastIteration = SemaRef
6506 .ActOnFinishFullExpr(CalcLastIteration.get(),
6507 /*DiscardedValue*/ false)
6508 .get();
6509 Built.PreCond = PreCond.get();
6510 Built.PreInits = buildPreInits(C, Captures);
6511 Built.Cond = Cond.get();
6512 Built.Init = Init.get();
6513 Built.Inc = Inc.get();
6514 Built.LB = LB.get();
6515 Built.UB = UB.get();
6516 Built.IL = IL.get();
6517 Built.ST = ST.get();
6518 Built.EUB = EUB.get();
6519 Built.NLB = NextLB.get();
6520 Built.NUB = NextUB.get();
6521 Built.PrevLB = PrevLB.get();
6522 Built.PrevUB = PrevUB.get();
6523 Built.DistInc = DistInc.get();
6524 Built.PrevEUB = PrevEUB.get();
6525 Built.DistCombinedFields.LB = CombLB.get();
6526 Built.DistCombinedFields.UB = CombUB.get();
6527 Built.DistCombinedFields.EUB = CombEUB.get();
6528 Built.DistCombinedFields.Init = CombInit.get();
6529 Built.DistCombinedFields.Cond = CombCond.get();
6530 Built.DistCombinedFields.NLB = CombNextLB.get();
6531 Built.DistCombinedFields.NUB = CombNextUB.get();
6532 Built.DistCombinedFields.DistCond = CombDistCond.get();
6533 Built.DistCombinedFields.ParForInDistCond = ParForInDistCond.get();
6534
6535 return NestedLoopCount;
6536}
6537
6538static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
6539 auto CollapseClauses =
6540 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
6541 if (CollapseClauses.begin() != CollapseClauses.end())
6542 return (*CollapseClauses.begin())->getNumForLoops();
6543 return nullptr;
6544}
6545
6546static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
6547 auto OrderedClauses =
6548 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
6549 if (OrderedClauses.begin() != OrderedClauses.end())
6550 return (*OrderedClauses.begin())->getNumForLoops();
6551 return nullptr;
6552}
6553
6554static bool checkSimdlenSafelenSpecified(Sema &S,
6555 const ArrayRef<OMPClause *> Clauses) {
6556 const OMPSafelenClause *Safelen = nullptr;
6557 const OMPSimdlenClause *Simdlen = nullptr;
6558
6559 for (const OMPClause *Clause : Clauses) {
6560 if (Clause->getClauseKind() == OMPC_safelen)
6561 Safelen = cast<OMPSafelenClause>(Clause);
6562 else if (Clause->getClauseKind() == OMPC_simdlen)
6563 Simdlen = cast<OMPSimdlenClause>(Clause);
6564 if (Safelen && Simdlen)
6565 break;
6566 }
6567
6568 if (Simdlen && Safelen) {
6569 const Expr *SimdlenLength = Simdlen->getSimdlen();
6570 const Expr *SafelenLength = Safelen->getSafelen();
6571 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
6572 SimdlenLength->isInstantiationDependent() ||
6573 SimdlenLength->containsUnexpandedParameterPack())
6574 return false;
6575 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
6576 SafelenLength->isInstantiationDependent() ||
6577 SafelenLength->containsUnexpandedParameterPack())
6578 return false;
6579 Expr::EvalResult SimdlenResult, SafelenResult;
6580 SimdlenLength->EvaluateAsInt(SimdlenResult, S.Context);
6581 SafelenLength->EvaluateAsInt(SafelenResult, S.Context);
6582 llvm::APSInt SimdlenRes = SimdlenResult.Val.getInt();
6583 llvm::APSInt SafelenRes = SafelenResult.Val.getInt();
6584 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
6585 // If both simdlen and safelen clauses are specified, the value of the
6586 // simdlen parameter must be less than or equal to the value of the safelen
6587 // parameter.
6588 if (SimdlenRes > SafelenRes) {
6589 S.Diag(SimdlenLength->getExprLoc(),
6590 diag::err_omp_wrong_simdlen_safelen_values)
6591 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
6592 return true;
6593 }
6594 }
6595 return false;
6596}
6597
6598StmtResult
6599Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
6600 SourceLocation StartLoc, SourceLocation EndLoc,
6601 VarsWithInheritedDSAType &VarsWithImplicitDSA) {
6602 if (!AStmt)
6603 return StmtError();
6604
6605 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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 6605, __PRETTY_FUNCTION__))
;
6606 OMPLoopDirective::HelperExprs B;
6607 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6608 // define the nested loops number.
6609 unsigned NestedLoopCount = checkOpenMPLoop(
6610 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
6611 AStmt, *this, *DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, VarsWithImplicitDSA, B);
6612 if (NestedLoopCount == 0)
6613 return StmtError();
6614
6615 assert((CurContext->isDependentContext() || B.builtAll()) &&(((CurContext->isDependentContext() || B.builtAll()) &&
"omp simd loop exprs were not built") ? static_cast<void>
(0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp simd loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 6616, __PRETTY_FUNCTION__))
6616 "omp simd loop exprs were not built")(((CurContext->isDependentContext() || B.builtAll()) &&
"omp simd loop exprs were not built") ? static_cast<void>
(0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp simd loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 6616, __PRETTY_FUNCTION__))
;
6617
6618 if (!CurContext->isDependentContext()) {
6619 // Finalize the clauses that need pre-built expressions for CodeGen.
6620 for (OMPClause *C : Clauses) {
6621 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6622 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6623 B.NumIterations, *this, CurScope,
6624 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
))
6625 return StmtError();
6626 }
6627 }
6628
6629 if (checkSimdlenSafelenSpecified(*this, Clauses))
6630 return StmtError();
6631
6632 setFunctionHasBranchProtectedScope();
6633 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
6634 Clauses, AStmt, B);
6635}
6636
6637StmtResult
6638Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
6639 SourceLocation StartLoc, SourceLocation EndLoc,
6640 VarsWithInheritedDSAType &VarsWithImplicitDSA) {
6641 if (!AStmt)
6642 return StmtError();
6643
6644 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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 6644, __PRETTY_FUNCTION__))
;
6645 OMPLoopDirective::HelperExprs B;
6646 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6647 // define the nested loops number.
6648 unsigned NestedLoopCount = checkOpenMPLoop(
6649 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
6650 AStmt, *this, *DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, VarsWithImplicitDSA, B);
6651 if (NestedLoopCount == 0)
6652 return StmtError();
6653
6654 assert((CurContext->isDependentContext() || B.builtAll()) &&(((CurContext->isDependentContext() || B.builtAll()) &&
"omp for loop exprs were not built") ? static_cast<void>
(0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp for loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 6655, __PRETTY_FUNCTION__))
6655 "omp for loop exprs were not built")(((CurContext->isDependentContext() || B.builtAll()) &&
"omp for loop exprs were not built") ? static_cast<void>
(0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp for loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 6655, __PRETTY_FUNCTION__))
;
6656
6657 if (!CurContext->isDependentContext()) {
6658 // Finalize the clauses that need pre-built expressions for CodeGen.
6659 for (OMPClause *C : Clauses) {
6660 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6661 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6662 B.NumIterations, *this, CurScope,
6663 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
))
6664 return StmtError();
6665 }
6666 }
6667
6668 setFunctionHasBranchProtectedScope();
6669 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
6670 Clauses, AStmt, B, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isCancelRegion());
6671}
6672
6673StmtResult Sema::ActOnOpenMPForSimdDirective(
6674 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6675 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
6676 if (!AStmt)
6677 return StmtError();
6678
6679 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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 6679, __PRETTY_FUNCTION__))
;
6680 OMPLoopDirective::HelperExprs B;
6681 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6682 // define the nested loops number.
6683 unsigned NestedLoopCount =
6684 checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
6685 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
,
6686 VarsWithImplicitDSA, B);
6687 if (NestedLoopCount == 0)
6688 return StmtError();
6689
6690 assert((CurContext->isDependentContext() || B.builtAll()) &&(((CurContext->isDependentContext() || B.builtAll()) &&
"omp for simd loop exprs were not built") ? static_cast<void
> (0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp for simd loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 6691, __PRETTY_FUNCTION__))
6691 "omp for simd loop exprs were not built")(((CurContext->isDependentContext() || B.builtAll()) &&
"omp for simd loop exprs were not built") ? static_cast<void
> (0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp for simd loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 6691, __PRETTY_FUNCTION__))
;
6692
6693 if (!CurContext->isDependentContext()) {
6694 // Finalize the clauses that need pre-built expressions for CodeGen.
6695 for (OMPClause *C : Clauses) {
6696 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6697 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6698 B.NumIterations, *this, CurScope,
6699 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
))
6700 return StmtError();
6701 }
6702 }
6703
6704 if (checkSimdlenSafelenSpecified(*this, Clauses))
6705 return StmtError();
6706
6707 setFunctionHasBranchProtectedScope();
6708 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
6709 Clauses, AStmt, B);
6710}
6711
6712StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
6713 Stmt *AStmt,
6714 SourceLocation StartLoc,
6715 SourceLocation EndLoc) {
6716 if (!AStmt)
6717 return StmtError();
6718
6719 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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 6719, __PRETTY_FUNCTION__))
;
6720 auto BaseStmt = AStmt;
6721 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
6722 BaseStmt = CS->getCapturedStmt();
6723 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
6724 auto S = C->children();
6725 if (S.begin() == S.end())
6726 return StmtError();
6727 // All associated statements must be '#pragma omp section' except for
6728 // the first one.
6729 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
6730 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
6731 if (SectionStmt)
6732 Diag(SectionStmt->getBeginLoc(),
6733 diag::err_omp_sections_substmt_not_section);
6734 return StmtError();
6735 }
6736 cast<OMPSectionDirective>(SectionStmt)
6737 ->setHasCancel(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isCancelRegion());
6738 }
6739 } else {
6740 Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt);
6741 return StmtError();
6742 }
6743
6744 setFunctionHasBranchProtectedScope();
6745
6746 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
6747 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isCancelRegion());
6748}
6749
6750StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
6751 SourceLocation StartLoc,
6752 SourceLocation EndLoc) {
6753 if (!AStmt)
6754 return StmtError();
6755
6756 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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 6756, __PRETTY_FUNCTION__))
;
6757
6758 setFunctionHasBranchProtectedScope();
6759 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->setParentCancelRegion(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isCancelRegion());
6760
6761 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
6762 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isCancelRegion());
6763}
6764
6765StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
6766 Stmt *AStmt,
6767 SourceLocation StartLoc,
6768 SourceLocation EndLoc) {
6769 if (!AStmt)
6770 return StmtError();
6771
6772 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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 6772, __PRETTY_FUNCTION__))
;
6773
6774 setFunctionHasBranchProtectedScope();
6775
6776 // OpenMP [2.7.3, single Construct, Restrictions]
6777 // The copyprivate clause must not be used with the nowait clause.
6778 const OMPClause *Nowait = nullptr;
6779 const OMPClause *Copyprivate = nullptr;
6780 for (const OMPClause *Clause : Clauses) {
6781 if (Clause->getClauseKind() == OMPC_nowait)
6782 Nowait = Clause;
6783 else if (Clause->getClauseKind() == OMPC_copyprivate)
6784 Copyprivate = Clause;
6785 if (Copyprivate && Nowait) {
6786 Diag(Copyprivate->getBeginLoc(),
6787 diag::err_omp_single_copyprivate_with_nowait);
6788 Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here);
6789 return StmtError();
6790 }
6791 }
6792
6793 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6794}
6795
6796StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
6797 SourceLocation StartLoc,
6798 SourceLocation EndLoc) {
6799 if (!AStmt)
6800 return StmtError();
6801
6802 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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 6802, __PRETTY_FUNCTION__))
;
6803
6804 setFunctionHasBranchProtectedScope();
6805
6806 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
6807}
6808
6809StmtResult Sema::ActOnOpenMPCriticalDirective(
6810 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
6811 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
6812 if (!AStmt)
6813 return StmtError();
6814
6815 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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 6815, __PRETTY_FUNCTION__))
;
6816
6817 bool ErrorFound = false;
6818 llvm::APSInt Hint;
6819 SourceLocation HintLoc;
6820 bool DependentHint = false;
6821 for (const OMPClause *C : Clauses) {
6822 if (C->getClauseKind() == OMPC_hint) {
6823 if (!DirName.getName()) {
6824 Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name);
6825 ErrorFound = true;
6826 }
6827 Expr *E = cast<OMPHintClause>(C)->getHint();
6828 if (E->isTypeDependent() || E->isValueDependent() ||
6829 E->isInstantiationDependent()) {
6830 DependentHint = true;
6831 } else {
6832 Hint = E->EvaluateKnownConstInt(Context);
6833 HintLoc = C->getBeginLoc();
6834 }
6835 }
6836 }
6837 if (ErrorFound)
6838 return StmtError();
6839 const auto Pair = DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCriticalWithHint(DirName);
6840 if (Pair.first && DirName.getName() && !DependentHint) {
6841 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
6842 Diag(StartLoc, diag::err_omp_critical_with_hint);
6843 if (HintLoc.isValid())
6844 Diag(HintLoc, diag::note_omp_critical_hint_here)
6845 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
6846 else
6847 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
6848 if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
6849 Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here)
6850 << 1
6851 << C->getHint()->EvaluateKnownConstInt(Context).toString(
6852 /*Radix=*/10, /*Signed=*/false);
6853 } else {
6854 Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1;
6855 }
6856 }
6857 }
6858
6859 setFunctionHasBranchProtectedScope();
6860
6861 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
6862 Clauses, AStmt);
6863 if (!Pair.first && DirName.getName() && !DependentHint)
6864 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->addCriticalWithHint(Dir, Hint);
6865 return Dir;
6866}
6867
6868StmtResult Sema::ActOnOpenMPParallelForDirective(
6869 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6870 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
6871 if (!AStmt)
6872 return StmtError();
6873
6874 auto *CS = cast<CapturedStmt>(AStmt);
6875 // 1.2.2 OpenMP Language Terminology
6876 // Structured block - An executable statement with a single entry at the
6877 // top and a single exit at the bottom.
6878 // The point of exit cannot be a branch out of the structured block.
6879 // longjmp() and throw() must not violate the entry/exit criteria.
6880 CS->getCapturedDecl()->setNothrow();
6881
6882 OMPLoopDirective::HelperExprs B;
6883 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6884 // define the nested loops number.
6885 unsigned NestedLoopCount =
6886 checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
6887 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
,
6888 VarsWithImplicitDSA, B);
6889 if (NestedLoopCount == 0)
6890 return StmtError();
6891
6892 assert((CurContext->isDependentContext() || B.builtAll()) &&(((CurContext->isDependentContext() || B.builtAll()) &&
"omp parallel for loop exprs were not built") ? static_cast<
void> (0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp parallel for loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 6893, __PRETTY_FUNCTION__))
6893 "omp parallel for loop exprs were not built")(((CurContext->isDependentContext() || B.builtAll()) &&
"omp parallel for loop exprs were not built") ? static_cast<
void> (0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp parallel for loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 6893, __PRETTY_FUNCTION__))
;
6894
6895 if (!CurContext->isDependentContext()) {
6896 // Finalize the clauses that need pre-built expressions for CodeGen.
6897 for (OMPClause *C : Clauses) {
6898 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6899 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6900 B.NumIterations, *this, CurScope,
6901 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
))
6902 return StmtError();
6903 }
6904 }
6905
6906 setFunctionHasBranchProtectedScope();
6907 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
6908 NestedLoopCount, Clauses, AStmt, B,
6909 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isCancelRegion());
6910}
6911
6912StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
6913 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6914 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
6915 if (!AStmt)
6916 return StmtError();
6917
6918 auto *CS = cast<CapturedStmt>(AStmt);
6919 // 1.2.2 OpenMP Language Terminology
6920 // Structured block - An executable statement with a single entry at the
6921 // top and a single exit at the bottom.
6922 // The point of exit cannot be a branch out of the structured block.
6923 // longjmp() and throw() must not violate the entry/exit criteria.
6924 CS->getCapturedDecl()->setNothrow();
6925
6926 OMPLoopDirective::HelperExprs B;
6927 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6928 // define the nested loops number.
6929 unsigned NestedLoopCount =
6930 checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
6931 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
,
6932 VarsWithImplicitDSA, B);
6933 if (NestedLoopCount == 0)
6934 return StmtError();
6935
6936 if (!CurContext->isDependentContext()) {
6937 // Finalize the clauses that need pre-built expressions for CodeGen.
6938 for (OMPClause *C : Clauses) {
6939 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6940 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6941 B.NumIterations, *this, CurScope,
6942 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
))
6943 return StmtError();
6944 }
6945 }
6946
6947 if (checkSimdlenSafelenSpecified(*this, Clauses))
6948 return StmtError();
6949
6950 setFunctionHasBranchProtectedScope();
6951 return OMPParallelForSimdDirective::Create(
6952 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6953}
6954
6955StmtResult
6956Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
6957 Stmt *AStmt, SourceLocation StartLoc,
6958 SourceLocation EndLoc) {
6959 if (!AStmt)
6960 return StmtError();
6961
6962 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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 6962, __PRETTY_FUNCTION__))
;
6963 auto BaseStmt = AStmt;
6964 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
6965 BaseStmt = CS->getCapturedStmt();
6966 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
6967 auto S = C->children();
6968 if (S.begin() == S.end())
6969 return StmtError();
6970 // All associated statements must be '#pragma omp section' except for
6971 // the first one.
6972 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
6973 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
6974 if (SectionStmt)
6975 Diag(SectionStmt->getBeginLoc(),
6976 diag::err_omp_parallel_sections_substmt_not_section);
6977 return StmtError();
6978 }
6979 cast<OMPSectionDirective>(SectionStmt)
6980 ->setHasCancel(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isCancelRegion());
6981 }
6982 } else {
6983 Diag(AStmt->getBeginLoc(),
6984 diag::err_omp_parallel_sections_not_compound_stmt);
6985 return StmtError();
6986 }
6987
6988 setFunctionHasBranchProtectedScope();
6989
6990 return OMPParallelSectionsDirective::Create(
6991 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isCancelRegion());
6992}
6993
6994StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
6995 Stmt *AStmt, SourceLocation StartLoc,
6996 SourceLocation EndLoc) {
6997 if (!AStmt)
6998 return StmtError();
6999
7000 auto *CS = cast<CapturedStmt>(AStmt);
7001 // 1.2.2 OpenMP Language Terminology
7002 // Structured block - An executable statement with a single entry at the
7003 // top and a single exit at the bottom.
7004 // The point of exit cannot be a branch out of the structured block.
7005 // longjmp() and throw() must not violate the entry/exit criteria.
7006 CS->getCapturedDecl()->setNothrow();
7007
7008 setFunctionHasBranchProtectedScope();
7009
7010 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
7011 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isCancelRegion());
7012}
7013
7014StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
7015 SourceLocation EndLoc) {
7016 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
7017}
7018
7019StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
7020 SourceLocation EndLoc) {
7021 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
7022}
7023
7024StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
7025 SourceLocation EndLoc) {
7026 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
7027}
7028
7029StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
7030 Stmt *AStmt,
7031 SourceLocation StartLoc,
7032 SourceLocation EndLoc) {
7033 if (!AStmt)
7034 return StmtError();
7035
7036 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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 7036, __PRETTY_FUNCTION__))
;
7037
7038 setFunctionHasBranchProtectedScope();
7039
7040 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
7041 AStmt,
7042 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getTaskgroupReductionRef());
7043}
7044
7045StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
7046 SourceLocation StartLoc,
7047 SourceLocation EndLoc) {
7048 assert(Clauses.size() <= 1 && "Extra clauses in flush directive")((Clauses.size() <= 1 && "Extra clauses in flush directive"
) ? static_cast<void> (0) : __assert_fail ("Clauses.size() <= 1 && \"Extra clauses in flush directive\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 7048, __PRETTY_FUNCTION__))
;
7049 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
7050}
7051
7052StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
7053 Stmt *AStmt,
7054 SourceLocation StartLoc,
7055 SourceLocation EndLoc) {
7056 const OMPClause *DependFound = nullptr;
7057 const OMPClause *DependSourceClause = nullptr;
7058 const OMPClause *DependSinkClause = nullptr;
7059 bool ErrorFound = false;
7060 const OMPThreadsClause *TC = nullptr;
7061 const OMPSIMDClause *SC = nullptr;
7062 for (const OMPClause *C : Clauses) {
7063 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
7064 DependFound = C;
7065 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
7066 if (DependSourceClause) {
7067 Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
7068 << getOpenMPDirectiveName(OMPD_ordered)
7069 << getOpenMPClauseName(OMPC_depend) << 2;
7070 ErrorFound = true;
7071 } else {
7072 DependSourceClause = C;
7073 }
7074 if (DependSinkClause) {
7075 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
7076 << 0;
7077 ErrorFound = true;
7078 }
7079 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
7080 if (DependSourceClause) {
7081 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
7082 << 1;
7083 ErrorFound = true;
7084 }
7085 DependSinkClause = C;
7086 }
7087 } else if (C->getClauseKind() == OMPC_threads) {
7088 TC = cast<OMPThreadsClause>(C);
7089 } else if (C->getClauseKind() == OMPC_simd) {
7090 SC = cast<OMPSIMDClause>(C);
7091 }
7092 }
7093 if (!ErrorFound && !SC &&
7094 isOpenMPSimdDirective(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getParentDirective())) {
7095 // OpenMP [2.8.1,simd Construct, Restrictions]
7096 // An ordered construct with the simd clause is the only OpenMP construct
7097 // that can appear in the simd region.
7098 Diag(StartLoc, diag::err_omp_prohibited_region_simd);
7099 ErrorFound = true;
7100 } else if (DependFound && (TC || SC)) {
7101 Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd)
7102 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
7103 ErrorFound = true;
7104 } else if (DependFound && !DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getParentOrderedRegionParam().first) {
7105 Diag(DependFound->getBeginLoc(),
7106 diag::err_omp_ordered_directive_without_param);
7107 ErrorFound = true;
7108 } else if (TC || Clauses.empty()) {
7109 if (const Expr *Param = DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getParentOrderedRegionParam().first) {
7110 SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc;
7111 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
7112 << (TC != nullptr);
7113 Diag(Param->getBeginLoc(), diag::note_omp_ordered_param);
7114 ErrorFound = true;
7115 }
7116 }
7117 if ((!AStmt && !DependFound) || ErrorFound)
7118 return StmtError();
7119
7120 if (AStmt) {
7121 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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 7121, __PRETTY_FUNCTION__))
;
7122
7123 setFunctionHasBranchProtectedScope();
7124 }
7125
7126 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
7127}
7128
7129namespace {
7130/// Helper class for checking expression in 'omp atomic [update]'
7131/// construct.
7132class OpenMPAtomicUpdateChecker {
7133 /// Error results for atomic update expressions.
7134 enum ExprAnalysisErrorCode {
7135 /// A statement is not an expression statement.
7136 NotAnExpression,
7137 /// Expression is not builtin binary or unary operation.
7138 NotABinaryOrUnaryExpression,
7139 /// Unary operation is not post-/pre- increment/decrement operation.
7140 NotAnUnaryIncDecExpression,
7141 /// An expression is not of scalar type.
7142 NotAScalarType,
7143 /// A binary operation is not an assignment operation.
7144 NotAnAssignmentOp,
7145 /// RHS part of the binary operation is not a binary expression.
7146 NotABinaryExpression,
7147 /// RHS part is not additive/multiplicative/shift/biwise binary
7148 /// expression.
7149 NotABinaryOperator,
7150 /// RHS binary operation does not have reference to the updated LHS
7151 /// part.
7152 NotAnUpdateExpression,
7153 /// No errors is found.
7154 NoError
7155 };
7156 /// Reference to Sema.
7157 Sema &SemaRef;
7158 /// A location for note diagnostics (when error is found).
7159 SourceLocation NoteLoc;
7160 /// 'x' lvalue part of the source atomic expression.
7161 Expr *X;
7162 /// 'expr' rvalue part of the source atomic expression.
7163 Expr *E;
7164 /// Helper expression of the form
7165 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
7166 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
7167 Expr *UpdateExpr;
7168 /// Is 'x' a LHS in a RHS part of full update expression. It is
7169 /// important for non-associative operations.
7170 bool IsXLHSInRHSPart;
7171 BinaryOperatorKind Op;
7172 SourceLocation OpLoc;
7173 /// true if the source expression is a postfix unary operation, false
7174 /// if it is a prefix unary operation.
7175 bool IsPostfixUpdate;
7176
7177public:
7178 OpenMPAtomicUpdateChecker(Sema &SemaRef)
7179 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
7180 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
7181 /// Check specified statement that it is suitable for 'atomic update'
7182 /// constructs and extract 'x', 'expr' and Operation from the original
7183 /// expression. If DiagId and NoteId == 0, then only check is performed
7184 /// without error notification.
7185 /// \param DiagId Diagnostic which should be emitted if error is found.
7186 /// \param NoteId Diagnostic note for the main error message.
7187 /// \return true if statement is not an update expression, false otherwise.
7188 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
7189 /// Return the 'x' lvalue part of the source atomic expression.
7190 Expr *getX() const { return X; }
7191 /// Return the 'expr' rvalue part of the source atomic expression.
7192 Expr *getExpr() const { return E; }
7193 /// Return the update expression used in calculation of the updated
7194 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
7195 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
7196 Expr *getUpdateExpr() const { return UpdateExpr; }
7197 /// Return true if 'x' is LHS in RHS part of full update expression,
7198 /// false otherwise.
7199 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
7200
7201 /// true if the source expression is a postfix unary operation, false
7202 /// if it is a prefix unary operation.
7203 bool isPostfixUpdate() const { return IsPostfixUpdate; }
7204
7205private:
7206 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
7207 unsigned NoteId = 0);
7208};
7209} // namespace
7210
7211bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
7212 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
7213 ExprAnalysisErrorCode ErrorFound = NoError;
7214 SourceLocation ErrorLoc, NoteLoc;
7215 SourceRange ErrorRange, NoteRange;
7216 // Allowed constructs are:
7217 // x = x binop expr;
7218 // x = expr binop x;
7219 if (AtomicBinOp->getOpcode() == BO_Assign) {
7220 X = AtomicBinOp->getLHS();
7221 if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
7222 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
7223 if (AtomicInnerBinOp->isMultiplicativeOp() ||
7224 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
7225 AtomicInnerBinOp->isBitwiseOp()) {
7226 Op = AtomicInnerBinOp->getOpcode();
7227 OpLoc = AtomicInnerBinOp->getOperatorLoc();
7228 Expr *LHS = AtomicInnerBinOp->getLHS();
7229 Expr *RHS = AtomicInnerBinOp->getRHS();
7230 llvm::FoldingSetNodeID XId, LHSId, RHSId;
7231 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
7232 /*Canonical=*/true);
7233 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
7234 /*Canonical=*/true);
7235 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
7236 /*Canonical=*/true);
7237 if (XId == LHSId) {
7238 E = RHS;
7239 IsXLHSInRHSPart = true;
7240 } else if (XId == RHSId) {
7241 E = LHS;
7242 IsXLHSInRHSPart = false;
7243 } else {
7244 ErrorLoc = AtomicInnerBinOp->getExprLoc();
7245 ErrorRange = AtomicInnerBinOp->getSourceRange();
7246 NoteLoc = X->getExprLoc();
7247 NoteRange = X->getSourceRange();
7248 ErrorFound = NotAnUpdateExpression;
7249 }
7250 } else {
7251 ErrorLoc = AtomicInnerBinOp->getExprLoc();
7252 ErrorRange = AtomicInnerBinOp->getSourceRange();
7253 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
7254 NoteRange = SourceRange(NoteLoc, NoteLoc);
7255 ErrorFound = NotABinaryOperator;
7256 }
7257 } else {
7258 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
7259 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
7260 ErrorFound = NotABinaryExpression;
7261 }
7262 } else {
7263 ErrorLoc = AtomicBinOp->getExprLoc();
7264 ErrorRange = AtomicBinOp->getSourceRange();
7265 NoteLoc = AtomicBinOp->getOperatorLoc();
7266 NoteRange = SourceRange(NoteLoc, NoteLoc);
7267 ErrorFound = NotAnAssignmentOp;
7268 }
7269 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
7270 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
7271 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
7272 return true;
7273 }
7274 if (SemaRef.CurContext->isDependentContext())
7275 E = X = UpdateExpr = nullptr;
7276 return ErrorFound != NoError;
7277}
7278
7279bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
7280 unsigned NoteId) {
7281 ExprAnalysisErrorCode ErrorFound = NoError;
7282 SourceLocation ErrorLoc, NoteLoc;
7283 SourceRange ErrorRange, NoteRange;
7284 // Allowed constructs are:
7285 // x++;
7286 // x--;
7287 // ++x;
7288 // --x;
7289 // x binop= expr;
7290 // x = x binop expr;
7291 // x = expr binop x;
7292 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
7293 AtomicBody = AtomicBody->IgnoreParenImpCasts();
7294 if (AtomicBody->getType()->isScalarType() ||
7295 AtomicBody->isInstantiationDependent()) {
7296 if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
7297 AtomicBody->IgnoreParenImpCasts())) {
7298 // Check for Compound Assignment Operation
7299 Op = BinaryOperator::getOpForCompoundAssignment(
7300 AtomicCompAssignOp->getOpcode());
7301 OpLoc = AtomicCompAssignOp->getOperatorLoc();
7302 E = AtomicCompAssignOp->getRHS();
7303 X = AtomicCompAssignOp->getLHS()->IgnoreParens();
7304 IsXLHSInRHSPart = true;
7305 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
7306 AtomicBody->IgnoreParenImpCasts())) {
7307 // Check for Binary Operation
7308 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
7309 return true;
7310 } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
7311 AtomicBody->IgnoreParenImpCasts())) {
7312 // Check for Unary Operation
7313 if (AtomicUnaryOp->isIncrementDecrementOp()) {
7314 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
7315 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
7316 OpLoc = AtomicUnaryOp->getOperatorLoc();
7317 X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
7318 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
7319 IsXLHSInRHSPart = true;
7320 } else {
7321 ErrorFound = NotAnUnaryIncDecExpression;
7322 ErrorLoc = AtomicUnaryOp->getExprLoc();
7323 ErrorRange = AtomicUnaryOp->getSourceRange();
7324 NoteLoc = AtomicUnaryOp->getOperatorLoc();
7325 NoteRange = SourceRange(NoteLoc, NoteLoc);
7326 }
7327 } else if (!AtomicBody->isInstantiationDependent()) {
7328 ErrorFound = NotABinaryOrUnaryExpression;
7329 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
7330 NoteRange = ErrorRange = AtomicBody->getSourceRange();
7331 }
7332 } else {
7333 ErrorFound = NotAScalarType;
7334 NoteLoc = ErrorLoc = AtomicBody->getBeginLoc();
7335 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
7336 }
7337 } else {
7338 ErrorFound = NotAnExpression;
7339 NoteLoc = ErrorLoc = S->getBeginLoc();
7340 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
7341 }
7342 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
7343 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
7344 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
7345 return true;
7346 }
7347 if (SemaRef.CurContext->isDependentContext())
7348 E = X = UpdateExpr = nullptr;
7349 if (ErrorFound == NoError && E && X) {
7350 // Build an update expression of form 'OpaqueValueExpr(x) binop
7351 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
7352 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
7353 auto *OVEX = new (SemaRef.getASTContext())
7354 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
7355 auto *OVEExpr = new (SemaRef.getASTContext())
7356 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
7357 ExprResult Update =
7358 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
7359 IsXLHSInRHSPart ? OVEExpr : OVEX);
7360 if (Update.isInvalid())
7361 return true;
7362 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
7363 Sema::AA_Casting);
7364 if (Update.isInvalid())
7365 return true;
7366 UpdateExpr = Update.get();
7367 }
7368 return ErrorFound != NoError;
7369}
7370
7371StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
7372 Stmt *AStmt,
7373 SourceLocation StartLoc,
7374 SourceLocation EndLoc) {
7375 if (!AStmt)
7376 return StmtError();
7377
7378 auto *CS = cast<CapturedStmt>(AStmt);
7379 // 1.2.2 OpenMP Language Terminology
7380 // Structured block - An executable statement with a single entry at the
7381 // top and a single exit at the bottom.
7382 // The point of exit cannot be a branch out of the structured block.
7383 // longjmp() and throw() must not violate the entry/exit criteria.
7384 OpenMPClauseKind AtomicKind = OMPC_unknown;
7385 SourceLocation AtomicKindLoc;
7386 for (const OMPClause *C : Clauses) {
7387 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
7388 C->getClauseKind() == OMPC_update ||
7389 C->getClauseKind() == OMPC_capture) {
7390 if (AtomicKind != OMPC_unknown) {
7391 Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses)
7392 << SourceRange(C->getBeginLoc(), C->getEndLoc());
7393 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
7394 << getOpenMPClauseName(AtomicKind);
7395 } else {
7396 AtomicKind = C->getClauseKind();
7397 AtomicKindLoc = C->getBeginLoc();
7398 }
7399 }
7400 }
7401
7402 Stmt *Body = CS->getCapturedStmt();
7403 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
7404 Body = EWC->getSubExpr();
7405
7406 Expr *X = nullptr;
7407 Expr *V = nullptr;
7408 Expr *E = nullptr;
7409 Expr *UE = nullptr;
7410 bool IsXLHSInRHSPart = false;
7411 bool IsPostfixUpdate = false;
7412 // OpenMP [2.12.6, atomic Construct]
7413 // In the next expressions:
7414 // * x and v (as applicable) are both l-value expressions with scalar type.
7415 // * During the execution of an atomic region, multiple syntactic
7416 // occurrences of x must designate the same storage location.
7417 // * Neither of v and expr (as applicable) may access the storage location
7418 // designated by x.
7419 // * Neither of x and expr (as applicable) may access the storage location
7420 // designated by v.
7421 // * expr is an expression with scalar type.
7422 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
7423 // * binop, binop=, ++, and -- are not overloaded operators.
7424 // * The expression x binop expr must be numerically equivalent to x binop
7425 // (expr). This requirement is satisfied if the operators in expr have
7426 // precedence greater than binop, or by using parentheses around expr or
7427 // subexpressions of expr.
7428 // * The expression expr binop x must be numerically equivalent to (expr)
7429 // binop x. This requirement is satisfied if the operators in expr have
7430 // precedence equal to or greater than binop, or by using parentheses around
7431 // expr or subexpressions of expr.
7432 // * For forms that allow multiple occurrences of x, the number of times
7433 // that x is evaluated is unspecified.
7434 if (AtomicKind == OMPC_read) {
7435 enum {
7436 NotAnExpression,
7437 NotAnAssignmentOp,
7438 NotAScalarType,
7439 NotAnLValue,
7440 NoError
7441 } ErrorFound = NoError;
7442 SourceLocation ErrorLoc, NoteLoc;
7443 SourceRange ErrorRange, NoteRange;
7444 // If clause is read:
7445 // v = x;
7446 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
7447 const auto *AtomicBinOp =
7448 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
7449 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
7450 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
7451 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
7452 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
7453 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
7454 if (!X->isLValue() || !V->isLValue()) {
7455 const Expr *NotLValueExpr = X->isLValue() ? V : X;
7456 ErrorFound = NotAnLValue;
7457 ErrorLoc = AtomicBinOp->getExprLoc();
7458 ErrorRange = AtomicBinOp->getSourceRange();
7459 NoteLoc = NotLValueExpr->getExprLoc();
7460 NoteRange = NotLValueExpr->getSourceRange();
7461 }
7462 } else if (!X->isInstantiationDependent() ||
7463 !V->isInstantiationDependent()) {
7464 const Expr *NotScalarExpr =
7465 (X->isInstantiationDependent() || X->getType()->isScalarType())
7466 ? V
7467 : X;
7468 ErrorFound = NotAScalarType;
7469 ErrorLoc = AtomicBinOp->getExprLoc();
7470 ErrorRange = AtomicBinOp->getSourceRange();
7471 NoteLoc = NotScalarExpr->getExprLoc();
7472 NoteRange = NotScalarExpr->getSourceRange();
7473 }
7474 } else if (!AtomicBody->isInstantiationDependent()) {
7475 ErrorFound = NotAnAssignmentOp;
7476 ErrorLoc = AtomicBody->getExprLoc();
7477 ErrorRange = AtomicBody->getSourceRange();
7478 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
7479 : AtomicBody->getExprLoc();
7480 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
7481 : AtomicBody->getSourceRange();
7482 }
7483 } else {
7484 ErrorFound = NotAnExpression;
7485 NoteLoc = ErrorLoc = Body->getBeginLoc();
7486 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
7487 }
7488 if (ErrorFound != NoError) {
7489 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
7490 << ErrorRange;
7491 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
7492 << NoteRange;
7493 return StmtError();
7494 }
7495 if (CurContext->isDependentContext())
7496 V = X = nullptr;
7497 } else if (AtomicKind == OMPC_write) {
7498 enum {
7499 NotAnExpression,
7500 NotAnAssignmentOp,
7501 NotAScalarType,
7502 NotAnLValue,
7503 NoError
7504 } ErrorFound = NoError;
7505 SourceLocation ErrorLoc, NoteLoc;
7506 SourceRange ErrorRange, NoteRange;
7507 // If clause is write:
7508 // x = expr;
7509 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
7510 const auto *AtomicBinOp =
7511 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
7512 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
7513 X = AtomicBinOp->getLHS();
7514 E = AtomicBinOp->getRHS();
7515 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
7516 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
7517 if (!X->isLValue()) {
7518 ErrorFound = NotAnLValue;
7519 ErrorLoc = AtomicBinOp->getExprLoc();
7520 ErrorRange = AtomicBinOp->getSourceRange();
7521 NoteLoc = X->getExprLoc();
7522 NoteRange = X->getSourceRange();
7523 }
7524 } else if (!X->isInstantiationDependent() ||
7525 !E->isInstantiationDependent()) {
7526 const Expr *NotScalarExpr =
7527 (X->isInstantiationDependent() || X->getType()->isScalarType())
7528 ? E
7529 : X;
7530 ErrorFound = NotAScalarType;
7531 ErrorLoc = AtomicBinOp->getExprLoc();
7532 ErrorRange = AtomicBinOp->getSourceRange();
7533 NoteLoc = NotScalarExpr->getExprLoc();
7534 NoteRange = NotScalarExpr->getSourceRange();
7535 }
7536 } else if (!AtomicBody->isInstantiationDependent()) {
7537 ErrorFound = NotAnAssignmentOp;
7538 ErrorLoc = AtomicBody->getExprLoc();
7539 ErrorRange = AtomicBody->getSourceRange();
7540 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
7541 : AtomicBody->getExprLoc();
7542 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
7543 : AtomicBody->getSourceRange();
7544 }
7545 } else {
7546 ErrorFound = NotAnExpression;
7547 NoteLoc = ErrorLoc = Body->getBeginLoc();
7548 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
7549 }
7550 if (ErrorFound != NoError) {
7551 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
7552 << ErrorRange;
7553 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
7554 << NoteRange;
7555 return StmtError();
7556 }
7557 if (CurContext->isDependentContext())
7558 E = X = nullptr;
7559 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
7560 // If clause is update:
7561 // x++;
7562 // x--;
7563 // ++x;
7564 // --x;
7565 // x binop= expr;
7566 // x = x binop expr;
7567 // x = expr binop x;
7568 OpenMPAtomicUpdateChecker Checker(*this);
7569 if (Checker.checkStatement(
7570 Body, (AtomicKind == OMPC_update)
7571 ? diag::err_omp_atomic_update_not_expression_statement
7572 : diag::err_omp_atomic_not_expression_statement,
7573 diag::note_omp_atomic_update))
7574 return StmtError();
7575 if (!CurContext->isDependentContext()) {
7576 E = Checker.getExpr();
7577 X = Checker.getX();
7578 UE = Checker.getUpdateExpr();
7579 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
7580 }
7581 } else if (AtomicKind == OMPC_capture) {
7582 enum {
7583 NotAnAssignmentOp,
7584 NotACompoundStatement,
7585 NotTwoSubstatements,
7586 NotASpecificExpression,
7587 NoError
7588 } ErrorFound = NoError;
7589 SourceLocation ErrorLoc, NoteLoc;
7590 SourceRange ErrorRange, NoteRange;
7591 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
7592 // If clause is a capture:
7593 // v = x++;
7594 // v = x--;
7595 // v = ++x;
7596 // v = --x;
7597 // v = x binop= expr;
7598 // v = x = x binop expr;
7599 // v = x = expr binop x;
7600 const auto *AtomicBinOp =
7601 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
7602 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
7603 V = AtomicBinOp->getLHS();
7604 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
7605 OpenMPAtomicUpdateChecker Checker(*this);
7606 if (Checker.checkStatement(
7607 Body, diag::err_omp_atomic_capture_not_expression_statement,
7608 diag::note_omp_atomic_update))
7609 return StmtError();
7610 E = Checker.getExpr();
7611 X = Checker.getX();
7612 UE = Checker.getUpdateExpr();
7613 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
7614 IsPostfixUpdate = Checker.isPostfixUpdate();
7615 } else if (!AtomicBody->isInstantiationDependent()) {
7616 ErrorLoc = AtomicBody->getExprLoc();
7617 ErrorRange = AtomicBody->getSourceRange();
7618 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
7619 : AtomicBody->getExprLoc();
7620 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
7621 : AtomicBody->getSourceRange();
7622 ErrorFound = NotAnAssignmentOp;
7623 }
7624 if (ErrorFound != NoError) {
7625 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
7626 << ErrorRange;
7627 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
7628 return StmtError();
7629 }
7630 if (CurContext->isDependentContext())
7631 UE = V = E = X = nullptr;
7632 } else {
7633 // If clause is a capture:
7634 // { v = x; x = expr; }
7635 // { v = x; x++; }
7636 // { v = x; x--; }
7637 // { v = x; ++x; }
7638 // { v = x; --x; }
7639 // { v = x; x binop= expr; }
7640 // { v = x; x = x binop expr; }
7641 // { v = x; x = expr binop x; }
7642 // { x++; v = x; }
7643 // { x--; v = x; }
7644 // { ++x; v = x; }
7645 // { --x; v = x; }
7646 // { x binop= expr; v = x; }
7647 // { x = x binop expr; v = x; }
7648 // { x = expr binop x; v = x; }
7649 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
7650 // Check that this is { expr1; expr2; }
7651 if (CS->size() == 2) {
7652 Stmt *First = CS->body_front();
7653 Stmt *Second = CS->body_back();
7654 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
7655 First = EWC->getSubExpr()->IgnoreParenImpCasts();
7656 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
7657 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
7658 // Need to find what subexpression is 'v' and what is 'x'.
7659 OpenMPAtomicUpdateChecker Checker(*this);
7660 bool IsUpdateExprFound = !Checker.checkStatement(Second);
7661 BinaryOperator *BinOp = nullptr;
7662 if (IsUpdateExprFound) {
7663 BinOp = dyn_cast<BinaryOperator>(First);
7664 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
7665 }
7666 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
7667 // { v = x; x++; }
7668 // { v = x; x--; }
7669 // { v = x; ++x; }
7670 // { v = x; --x; }
7671 // { v = x; x binop= expr; }
7672 // { v = x; x = x binop expr; }
7673 // { v = x; x = expr binop x; }
7674 // Check that the first expression has form v = x.
7675 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
7676 llvm::FoldingSetNodeID XId, PossibleXId;
7677 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
7678 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
7679 IsUpdateExprFound = XId == PossibleXId;
7680 if (IsUpdateExprFound) {
7681 V = BinOp->getLHS();
7682 X = Checker.getX();
7683 E = Checker.getExpr();
7684 UE = Checker.getUpdateExpr();
7685 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
7686 IsPostfixUpdate = true;
7687 }
7688 }
7689 if (!IsUpdateExprFound) {
7690 IsUpdateExprFound = !Checker.checkStatement(First);
7691 BinOp = nullptr;
7692 if (IsUpdateExprFound) {
7693 BinOp = dyn_cast<BinaryOperator>(Second);
7694 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
7695 }
7696 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
7697 // { x++; v = x; }
7698 // { x--; v = x; }
7699 // { ++x; v = x; }
7700 // { --x; v = x; }
7701 // { x binop= expr; v = x; }
7702 // { x = x binop expr; v = x; }
7703 // { x = expr binop x; v = x; }
7704 // Check that the second expression has form v = x.
7705 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
7706 llvm::FoldingSetNodeID XId, PossibleXId;
7707 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
7708 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
7709 IsUpdateExprFound = XId == PossibleXId;
7710 if (IsUpdateExprFound) {
7711 V = BinOp->getLHS();
7712 X = Checker.getX();
7713 E = Checker.getExpr();
7714 UE = Checker.getUpdateExpr();
7715 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
7716 IsPostfixUpdate = false;
7717 }
7718 }
7719 }
7720 if (!IsUpdateExprFound) {
7721 // { v = x; x = expr; }
7722 auto *FirstExpr = dyn_cast<Expr>(First);
7723 auto *SecondExpr = dyn_cast<Expr>(Second);
7724 if (!FirstExpr || !SecondExpr ||
7725 !(FirstExpr->isInstantiationDependent() ||
7726 SecondExpr->isInstantiationDependent())) {
7727 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
7728 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
7729 ErrorFound = NotAnAssignmentOp;
7730 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
7731 : First->getBeginLoc();
7732 NoteRange = ErrorRange = FirstBinOp
7733 ? FirstBinOp->getSourceRange()
7734 : SourceRange(ErrorLoc, ErrorLoc);
7735 } else {
7736 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
7737 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
7738 ErrorFound = NotAnAssignmentOp;
7739 NoteLoc = ErrorLoc = SecondBinOp
7740 ? SecondBinOp->getOperatorLoc()
7741 : Second->getBeginLoc();
7742 NoteRange = ErrorRange =
7743 SecondBinOp ? SecondBinOp->getSourceRange()
7744 : SourceRange(ErrorLoc, ErrorLoc);
7745 } else {
7746 Expr *PossibleXRHSInFirst =
7747 FirstBinOp->getRHS()->IgnoreParenImpCasts();
7748 Expr *PossibleXLHSInSecond =
7749 SecondBinOp->getLHS()->IgnoreParenImpCasts();
7750 llvm::FoldingSetNodeID X1Id, X2Id;
7751 PossibleXRHSInFirst->Profile(X1Id, Context,
7752 /*Canonical=*/true);
7753 PossibleXLHSInSecond->Profile(X2Id, Context,
7754 /*Canonical=*/true);
7755 IsUpdateExprFound = X1Id == X2Id;
7756 if (IsUpdateExprFound) {
7757 V = FirstBinOp->getLHS();
7758 X = SecondBinOp->getLHS();
7759 E = SecondBinOp->getRHS();
7760 UE = nullptr;
7761 IsXLHSInRHSPart = false;
7762 IsPostfixUpdate = true;
7763 } else {
7764 ErrorFound = NotASpecificExpression;
7765 ErrorLoc = FirstBinOp->getExprLoc();
7766 ErrorRange = FirstBinOp->getSourceRange();
7767 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
7768 NoteRange = SecondBinOp->getRHS()->getSourceRange();
7769 }
7770 }
7771 }
7772 }
7773 }
7774 } else {
7775 NoteLoc = ErrorLoc = Body->getBeginLoc();
7776 NoteRange = ErrorRange =
7777 SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
7778 ErrorFound = NotTwoSubstatements;
7779 }
7780 } else {
7781 NoteLoc = ErrorLoc = Body->getBeginLoc();
7782 NoteRange = ErrorRange =
7783 SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
7784 ErrorFound = NotACompoundStatement;
7785 }
7786 if (ErrorFound != NoError) {
7787 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
7788 << ErrorRange;
7789 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
7790 return StmtError();
7791 }
7792 if (CurContext->isDependentContext())
7793 UE = V = E = X = nullptr;
7794 }
7795 }
7796
7797 setFunctionHasBranchProtectedScope();
7798
7799 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
7800 X, V, E, UE, IsXLHSInRHSPart,
7801 IsPostfixUpdate);
7802}
7803
7804StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
7805 Stmt *AStmt,
7806 SourceLocation StartLoc,
7807 SourceLocation EndLoc) {
7808 if (!AStmt)
7809 return StmtError();
7810
7811 auto *CS = cast<CapturedStmt>(AStmt);
7812 // 1.2.2 OpenMP Language Terminology
7813 // Structured block - An executable statement with a single entry at the
7814 // top and a single exit at the bottom.
7815 // The point of exit cannot be a branch out of the structured block.
7816 // longjmp() and throw() must not violate the entry/exit criteria.
7817 CS->getCapturedDecl()->setNothrow();
7818 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target);
7819 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7820 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7821 // 1.2.2 OpenMP Language Terminology
7822 // Structured block - An executable statement with a single entry at the
7823 // top and a single exit at the bottom.
7824 // The point of exit cannot be a branch out of the structured block.
7825 // longjmp() and throw() must not violate the entry/exit criteria.
7826 CS->getCapturedDecl()->setNothrow();
7827 }
7828
7829 // OpenMP [2.16, Nesting of Regions]
7830 // If specified, a teams construct must be contained within a target
7831 // construct. That target construct must contain no statements or directives
7832 // outside of the teams construct.
7833 if (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasInnerTeamsRegion()) {
7834 const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true);
7835 bool OMPTeamsFound = true;
7836 if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
7837 auto I = CS->body_begin();
7838 while (I != CS->body_end()) {
7839 const auto *OED = dyn_cast<OMPExecutableDirective>(*I);
7840 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind()) ||
7841 OMPTeamsFound) {
7842
7843 OMPTeamsFound = false;
7844 break;
7845 }
7846 ++I;
7847 }
7848 assert(I != CS->body_end() && "Not found statement")((I != CS->body_end() && "Not found statement") ? static_cast
<void> (0) : __assert_fail ("I != CS->body_end() && \"Not found statement\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 7848, __PRETTY_FUNCTION__))
;
7849 S = *I;
7850 } else {
7851 const auto *OED = dyn_cast<OMPExecutableDirective>(S);
7852 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
7853 }
7854 if (!OMPTeamsFound) {
7855 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
7856 Diag(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getInnerTeamsRegionLoc(),
7857 diag::note_omp_nested_teams_construct_here);
7858 Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here)
7859 << isa<OMPExecutableDirective>(S);
7860 return StmtError();
7861 }
7862 }
7863
7864 setFunctionHasBranchProtectedScope();
7865
7866 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
7867}
7868
7869StmtResult
7870Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
7871 Stmt *AStmt, SourceLocation StartLoc,
7872 SourceLocation EndLoc) {
7873 if (!AStmt)
7874 return StmtError();
7875
7876 auto *CS = cast<CapturedStmt>(AStmt);
7877 // 1.2.2 OpenMP Language Terminology
7878 // Structured block - An executable statement with a single entry at the
7879 // top and a single exit at the bottom.
7880 // The point of exit cannot be a branch out of the structured block.
7881 // longjmp() and throw() must not violate the entry/exit criteria.
7882 CS->getCapturedDecl()->setNothrow();
7883 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel);
7884 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7885 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7886 // 1.2.2 OpenMP Language Terminology
7887 // Structured block - An executable statement with a single entry at the
7888 // top and a single exit at the bottom.
7889 // The point of exit cannot be a branch out of the structured block.
7890 // longjmp() and throw() must not violate the entry/exit criteria.
7891 CS->getCapturedDecl()->setNothrow();
7892 }
7893
7894 setFunctionHasBranchProtectedScope();
7895
7896 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
7897 AStmt);
7898}
7899
7900StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
7901 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7902 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7903 if (!AStmt)
7904 return StmtError();
7905
7906 auto *CS = cast<CapturedStmt>(AStmt);
7907 // 1.2.2 OpenMP Language Terminology
7908 // Structured block - An executable statement with a single entry at the
7909 // top and a single exit at the bottom.
7910 // The point of exit cannot be a branch out of the structured block.
7911 // longjmp() and throw() must not violate the entry/exit criteria.
7912 CS->getCapturedDecl()->setNothrow();
7913 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
7914 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7915 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7916 // 1.2.2 OpenMP Language Terminology
7917 // Structured block - An executable statement with a single entry at the
7918 // top and a single exit at the bottom.
7919 // The point of exit cannot be a branch out of the structured block.
7920 // longjmp() and throw() must not violate the entry/exit criteria.
7921 CS->getCapturedDecl()->setNothrow();
7922 }
7923
7924 OMPLoopDirective::HelperExprs B;
7925 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7926 // define the nested loops number.
7927 unsigned NestedLoopCount =
7928 checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
7929 getOrderedNumberExpr(Clauses), CS, *this, *DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
,
7930 VarsWithImplicitDSA, B);
7931 if (NestedLoopCount == 0)
7932 return StmtError();
7933
7934 assert((CurContext->isDependentContext() || B.builtAll()) &&(((CurContext->isDependentContext() || B.builtAll()) &&
"omp target parallel for loop exprs were not built") ? static_cast
<void> (0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp target parallel for loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 7935, __PRETTY_FUNCTION__))
7935 "omp target parallel for loop exprs were not built")(((CurContext->isDependentContext() || B.builtAll()) &&
"omp target parallel for loop exprs were not built") ? static_cast
<void> (0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp target parallel for loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 7935, __PRETTY_FUNCTION__))
;
7936
7937 if (!CurContext->isDependentContext()) {
7938 // Finalize the clauses that need pre-built expressions for CodeGen.
7939 for (OMPClause *C : Clauses) {
7940 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7941 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7942 B.NumIterations, *this, CurScope,
7943 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
))
7944 return StmtError();
7945 }
7946 }
7947
7948 setFunctionHasBranchProtectedScope();
7949 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
7950 NestedLoopCount, Clauses, AStmt,
7951 B, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isCancelRegion());
7952}
7953
7954/// Check for existence of a map clause in the list of clauses.
7955static bool hasClauses(ArrayRef<OMPClause *> Clauses,
7956 const OpenMPClauseKind K) {
7957 return llvm::any_of(
7958 Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
7959}
7960
7961template <typename... Params>
7962static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
7963 const Params... ClauseTypes) {
7964 return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
7965}
7966
7967StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
7968 Stmt *AStmt,
7969 SourceLocation StartLoc,
7970 SourceLocation EndLoc) {
7971 if (!AStmt)
7972 return StmtError();
7973
7974 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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 7974, __PRETTY_FUNCTION__))
;
7975
7976 // OpenMP [2.10.1, Restrictions, p. 97]
7977 // At least one map clause must appear on the directive.
7978 if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
7979 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
7980 << "'map' or 'use_device_ptr'"
7981 << getOpenMPDirectiveName(OMPD_target_data);
7982 return StmtError();
7983 }
7984
7985 setFunctionHasBranchProtectedScope();
7986
7987 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
7988 AStmt);
7989}
7990
7991StmtResult
7992Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
7993 SourceLocation StartLoc,
7994 SourceLocation EndLoc, Stmt *AStmt) {
7995 if (!AStmt)
7996 return StmtError();
7997
7998 auto *CS = cast<CapturedStmt>(AStmt);
7999 // 1.2.2 OpenMP Language Terminology
8000 // Structured block - An executable statement with a single entry at the
8001 // top and a single exit at the bottom.
8002 // The point of exit cannot be a branch out of the structured block.
8003 // longjmp() and throw() must not violate the entry/exit criteria.
8004 CS->getCapturedDecl()->setNothrow();
8005 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
8006 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8007 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8008 // 1.2.2 OpenMP Language Terminology
8009 // Structured block - An executable statement with a single entry at the
8010 // top and a single exit at the bottom.
8011 // The point of exit cannot be a branch out of the structured block.
8012 // longjmp() and throw() must not violate the entry/exit criteria.
8013 CS->getCapturedDecl()->setNothrow();
8014 }
8015
8016 // OpenMP [2.10.2, Restrictions, p. 99]
8017 // At least one map clause must appear on the directive.
8018 if (!hasClauses(Clauses, OMPC_map)) {
8019 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
8020 << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
8021 return StmtError();
8022 }
8023
8024 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
8025 AStmt);
8026}
8027
8028StmtResult
8029Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
8030 SourceLocation StartLoc,
8031 SourceLocation EndLoc, Stmt *AStmt) {
8032 if (!AStmt)
8033 return StmtError();
8034
8035 auto *CS = cast<CapturedStmt>(AStmt);
8036 // 1.2.2 OpenMP Language Terminology
8037 // Structured block - An executable statement with a single entry at the
8038 // top and a single exit at the bottom.
8039 // The point of exit cannot be a branch out of the structured block.
8040 // longjmp() and throw() must not violate the entry/exit criteria.
8041 CS->getCapturedDecl()->setNothrow();
8042 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
8043 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8044 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8045 // 1.2.2 OpenMP Language Terminology
8046 // Structured block - An executable statement with a single entry at the
8047 // top and a single exit at the bottom.
8048 // The point of exit cannot be a branch out of the structured block.
8049 // longjmp() and throw() must not violate the entry/exit criteria.
8050 CS->getCapturedDecl()->setNothrow();
8051 }
8052
8053 // OpenMP [2.10.3, Restrictions, p. 102]
8054 // At least one map clause must appear on the directive.
8055 if (!hasClauses(Clauses, OMPC_map)) {
8056 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
8057 << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
8058 return StmtError();
8059 }
8060
8061 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
8062 AStmt);
8063}
8064
8065StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
8066 SourceLocation StartLoc,
8067 SourceLocation EndLoc,
8068 Stmt *AStmt) {
8069 if (!AStmt)
8070 return StmtError();
8071
8072 auto *CS = cast<CapturedStmt>(AStmt);
8073 // 1.2.2 OpenMP Language Terminology
8074 // Structured block - An executable statement with a single entry at the
8075 // top and a single exit at the bottom.
8076 // The point of exit cannot be a branch out of the structured block.
8077 // longjmp() and throw() must not violate the entry/exit criteria.
8078 CS->getCapturedDecl()->setNothrow();
8079 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
8080 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8081 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8082 // 1.2.2 OpenMP Language Terminology
8083 // Structured block - An executable statement with a single entry at the
8084 // top and a single exit at the bottom.
8085 // The point of exit cannot be a branch out of the structured block.
8086 // longjmp() and throw() must not violate the entry/exit criteria.
8087 CS->getCapturedDecl()->setNothrow();
8088 }
8089
8090 if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
8091 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
8092 return StmtError();
8093 }
8094 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
8095 AStmt);
8096}
8097
8098StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
8099 Stmt *AStmt, SourceLocation StartLoc,
8100 SourceLocation EndLoc) {
8101 if (!AStmt)
8102 return StmtError();
8103
8104 auto *CS = cast<CapturedStmt>(AStmt);
8105 // 1.2.2 OpenMP Language Terminology
8106 // Structured block - An executable statement with a single entry at the
8107 // top and a single exit at the bottom.
8108 // The point of exit cannot be a branch out of the structured block.
8109 // longjmp() and throw() must not violate the entry/exit criteria.
8110 CS->getCapturedDecl()->setNothrow();
8111
8112 setFunctionHasBranchProtectedScope();
8113
8114 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->setParentTeamsRegionLoc(StartLoc);
8115
8116 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
8117}
8118
8119StmtResult
8120Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
8121 SourceLocation EndLoc,
8122 OpenMPDirectiveKind CancelRegion) {
8123 if (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isParentNowaitRegion()) {
8124 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
8125 return StmtError();
8126 }
8127 if (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isParentOrderedRegion()) {
8128 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
8129 return StmtError();
8130 }
8131 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
8132 CancelRegion);
8133}
8134
8135StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
8136 SourceLocation StartLoc,
8137 SourceLocation EndLoc,
8138 OpenMPDirectiveKind CancelRegion) {
8139 if (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isParentNowaitRegion()) {
8140 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
8141 return StmtError();
8142 }
8143 if (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isParentOrderedRegion()) {
8144 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
8145 return StmtError();
8146 }
8147 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->setParentCancelRegion(/*Cancel=*/true);
8148 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
8149 CancelRegion);
8150}
8151
8152static bool checkGrainsizeNumTasksClauses(Sema &S,
8153 ArrayRef<OMPClause *> Clauses) {
8154 const OMPClause *PrevClause = nullptr;
8155 bool ErrorFound = false;
8156 for (const OMPClause *C : Clauses) {
8157 if (C->getClauseKind() == OMPC_grainsize ||
8158 C->getClauseKind() == OMPC_num_tasks) {
8159 if (!PrevClause)
8160 PrevClause = C;
8161 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
8162 S.Diag(C->getBeginLoc(),
8163 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
8164 << getOpenMPClauseName(C->getClauseKind())
8165 << getOpenMPClauseName(PrevClause->getClauseKind());
8166 S.Diag(PrevClause->getBeginLoc(),
8167 diag::note_omp_previous_grainsize_num_tasks)
8168 << getOpenMPClauseName(PrevClause->getClauseKind());
8169 ErrorFound = true;
8170 }
8171 }
8172 }
8173 return ErrorFound;
8174}
8175
8176static bool checkReductionClauseWithNogroup(Sema &S,
8177 ArrayRef<OMPClause *> Clauses) {
8178 const OMPClause *ReductionClause = nullptr;
8179 const OMPClause *NogroupClause = nullptr;
8180 for (const OMPClause *C : Clauses) {
8181 if (C->getClauseKind() == OMPC_reduction) {
8182 ReductionClause = C;
8183 if (NogroupClause)
8184 break;
8185 continue;
8186 }
8187 if (C->getClauseKind() == OMPC_nogroup) {
8188 NogroupClause = C;
8189 if (ReductionClause)
8190 break;
8191 continue;
8192 }
8193 }
8194 if (ReductionClause && NogroupClause) {
8195 S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup)
8196 << SourceRange(NogroupClause->getBeginLoc(),
8197 NogroupClause->getEndLoc());
8198 return true;
8199 }
8200 return false;
8201}
8202
8203StmtResult Sema::ActOnOpenMPTaskLoopDirective(
8204 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8205 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
8206 if (!AStmt)
8207 return StmtError();
8208
8209 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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 8209, __PRETTY_FUNCTION__))
;
8210 OMPLoopDirective::HelperExprs B;
8211 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8212 // define the nested loops number.
8213 unsigned NestedLoopCount =
8214 checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
8215 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
,
8216 VarsWithImplicitDSA, B);
8217 if (NestedLoopCount == 0)
8218 return StmtError();
8219
8220 assert((CurContext->isDependentContext() || B.builtAll()) &&(((CurContext->isDependentContext() || B.builtAll()) &&
"omp for loop exprs were not built") ? static_cast<void>
(0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp for loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 8221, __PRETTY_FUNCTION__))
8221 "omp for loop exprs were not built")(((CurContext->isDependentContext() || B.builtAll()) &&
"omp for loop exprs were not built") ? static_cast<void>
(0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp for loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 8221, __PRETTY_FUNCTION__))
;
8222
8223 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
8224 // The grainsize clause and num_tasks clause are mutually exclusive and may
8225 // not appear on the same taskloop directive.
8226 if (checkGrainsizeNumTasksClauses(*this, Clauses))
8227 return StmtError();
8228 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
8229 // If a reduction clause is present on the taskloop directive, the nogroup
8230 // clause must not be specified.
8231 if (checkReductionClauseWithNogroup(*this, Clauses))
8232 return StmtError();
8233
8234 setFunctionHasBranchProtectedScope();
8235 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
8236 NestedLoopCount, Clauses, AStmt, B);
8237}
8238
8239StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
8240 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8241 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
8242 if (!AStmt)
8243 return StmtError();
8244
8245 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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 8245, __PRETTY_FUNCTION__))
;
8246 OMPLoopDirective::HelperExprs B;
8247 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8248 // define the nested loops number.
8249 unsigned NestedLoopCount =
8250 checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
8251 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
,
8252 VarsWithImplicitDSA, B);
8253 if (NestedLoopCount == 0)
8254 return StmtError();
8255
8256 assert((CurContext->isDependentContext() || B.builtAll()) &&(((CurContext->isDependentContext() || B.builtAll()) &&
"omp for loop exprs were not built") ? static_cast<void>
(0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp for loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 8257, __PRETTY_FUNCTION__))
8257 "omp for loop exprs were not built")(((CurContext->isDependentContext() || B.builtAll()) &&
"omp for loop exprs were not built") ? static_cast<void>
(0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp for loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 8257, __PRETTY_FUNCTION__))
;
8258
8259 if (!CurContext->isDependentContext()) {
8260 // Finalize the clauses that need pre-built expressions for CodeGen.
8261 for (OMPClause *C : Clauses) {
8262 if (auto *LC = dyn_cast<OMPLinearClause>(C))
8263 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8264 B.NumIterations, *this, CurScope,
8265 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
))
8266 return StmtError();
8267 }
8268 }
8269
8270 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
8271 // The grainsize clause and num_tasks clause are mutually exclusive and may
8272 // not appear on the same taskloop directive.
8273 if (checkGrainsizeNumTasksClauses(*this, Clauses))
8274 return StmtError();
8275 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
8276 // If a reduction clause is present on the taskloop directive, the nogroup
8277 // clause must not be specified.
8278 if (checkReductionClauseWithNogroup(*this, Clauses))
8279 return StmtError();
8280 if (checkSimdlenSafelenSpecified(*this, Clauses))
8281 return StmtError();
8282
8283 setFunctionHasBranchProtectedScope();
8284 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
8285 NestedLoopCount, Clauses, AStmt, B);
8286}
8287
8288StmtResult Sema::ActOnOpenMPDistributeDirective(
8289 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8290 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
8291 if (!AStmt)
8292 return StmtError();
8293
8294 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-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 8294, __PRETTY_FUNCTION__))
;
8295 OMPLoopDirective::HelperExprs B;
8296 // In presence of clause 'collapse' with number of loops, it will
8297 // define the nested loops number.
8298 unsigned NestedLoopCount =
8299 checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
8300 nullptr /*ordered not a clause on distribute*/, AStmt,
8301 *this, *DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, VarsWithImplicitDSA, B);
8302 if (NestedLoopCount == 0)
8303 return StmtError();
8304
8305 assert((CurContext->isDependentContext() || B.builtAll()) &&(((CurContext->isDependentContext() || B.builtAll()) &&
"omp for loop exprs were not built") ? static_cast<void>
(0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp for loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 8306, __PRETTY_FUNCTION__))
8306 "omp for loop exprs were not built")(((CurContext->isDependentContext() || B.builtAll()) &&
"omp for loop exprs were not built") ? static_cast<void>
(0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp for loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 8306, __PRETTY_FUNCTION__))
;
8307
8308 setFunctionHasBranchProtectedScope();
8309 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
8310 NestedLoopCount, Clauses, AStmt, B);
8311}
8312
8313StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
8314 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8315 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
8316 if (!AStmt)
8317 return StmtError();
8318
8319 auto *CS = cast<CapturedStmt>(AStmt);
8320 // 1.2.2 OpenMP Language Terminology
8321 // Structured block - An executable statement with a single entry at the
8322 // top and a single exit at the bottom.
8323 // The point of exit cannot be a branch out of the structured block.
8324 // longjmp() and throw() must not violate the entry/exit criteria.
8325 CS->getCapturedDecl()->setNothrow();
8326 for (int ThisCaptureLevel =
8327 getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
8328 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8329 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8330 // 1.2.2 OpenMP Language Terminology
8331 // Structured block - An executable statement with a single entry at the
8332 // top and a single exit at the bottom.
8333 // The point of exit cannot be a branch out of the structured block.
8334 // longjmp() and throw() must not violate the entry/exit criteria.
8335 CS->getCapturedDecl()->setNothrow();
8336 }
8337
8338 OMPLoopDirective::HelperExprs B;
8339 // In presence of clause 'collapse' with number of loops, it will
8340 // define the nested loops number.
8341 unsigned NestedLoopCount = checkOpenMPLoop(
8342 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
8343 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
,
8344 VarsWithImplicitDSA, B);
8345 if (NestedLoopCount == 0)
8346 return StmtError();
8347
8348 assert((CurContext->isDependentContext() || B.builtAll()) &&(((CurContext->isDependentContext() || B.builtAll()) &&
"omp for loop exprs were not built") ? static_cast<void>
(0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp for loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 8349, __PRETTY_FUNCTION__))
8349 "omp for loop exprs were not built")(((CurContext->isDependentContext() || B.builtAll()) &&
"omp for loop exprs were not built") ? static_cast<void>
(0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp for loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 8349, __PRETTY_FUNCTION__))
;
8350
8351 setFunctionHasBranchProtectedScope();
8352 return OMPDistributeParallelForDirective::Create(
8353 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
8354 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isCancelRegion());
8355}
8356
8357StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
8358 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8359 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
8360 if (!AStmt)
8361 return StmtError();
8362
8363 auto *CS = cast<CapturedStmt>(AStmt);
8364 // 1.2.2 OpenMP Language Terminology
8365 // Structured block - An executable statement with a single entry at the
8366 // top and a single exit at the bottom.
8367 // The point of exit cannot be a branch out of the structured block.
8368 // longjmp() and throw() must not violate the entry/exit criteria.
8369 CS->getCapturedDecl()->setNothrow();
8370 for (int ThisCaptureLevel =
8371 getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
8372 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8373 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8374 // 1.2.2 OpenMP Language Terminology
8375 // Structured block - An executable statement with a single entry at the
8376 // top and a single exit at the bottom.
8377 // The point of exit cannot be a branch out of the structured block.
8378 // longjmp() and throw() must not violate the entry/exit criteria.
8379 CS->getCapturedDecl()->setNothrow();
8380 }
8381
8382 OMPLoopDirective::HelperExprs B;
8383 // In presence of clause 'collapse' with number of loops, it will
8384 // define the nested loops number.
8385 unsigned NestedLoopCount = checkOpenMPLoop(
8386 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
8387 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
,
8388 VarsWithImplicitDSA, B);
8389 if (NestedLoopCount == 0)
8390 return StmtError();
8391
8392 assert((CurContext->isDependentContext() || B.builtAll()) &&(((CurContext->isDependentContext() || B.builtAll()) &&
"omp for loop exprs were not built") ? static_cast<void>
(0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp for loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 8393, __PRETTY_FUNCTION__))
8393 "omp for loop exprs were not built")(((CurContext->isDependentContext() || B.builtAll()) &&
"omp for loop exprs were not built") ? static_cast<void>
(0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp for loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 8393, __PRETTY_FUNCTION__))
;
8394
8395 if (!CurContext->isDependentContext()) {
8396 // Finalize the clauses that need pre-built expressions for CodeGen.
8397 for (OMPClause *C : Clauses) {
8398 if (auto *LC = dyn_cast<OMPLinearClause>(C))
8399 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8400 B.NumIterations, *this, CurScope,
8401 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
))
8402 return StmtError();
8403 }
8404 }
8405
8406 if (checkSimdlenSafelenSpecified(*this, Clauses))
8407 return StmtError();
8408
8409 setFunctionHasBranchProtectedScope();
8410 return OMPDistributeParallelForSimdDirective::Create(
8411 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8412}
8413
8414StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
8415 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8416 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
8417 if (!AStmt)
8418 return StmtError();
8419
8420 auto *CS = cast<CapturedStmt>(AStmt);
8421 // 1.2.2 OpenMP Language Terminology
8422 // Structured block - An executable statement with a single entry at the
8423 // top and a single exit at the bottom.
8424 // The point of exit cannot be a branch out of the structured block.
8425 // longjmp() and throw() must not violate the entry/exit criteria.
8426 CS->getCapturedDecl()->setNothrow();
8427 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
8428 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8429 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8430 // 1.2.2 OpenMP Language Terminology
8431 // Structured block - An executable statement with a single entry at the
8432 // top and a single exit at the bottom.
8433 // The point of exit cannot be a branch out of the structured block.
8434 // longjmp() and throw() must not violate the entry/exit criteria.
8435 CS->getCapturedDecl()->setNothrow();
8436 }
8437
8438 OMPLoopDirective::HelperExprs B;
8439 // In presence of clause 'collapse' with number of loops, it will
8440 // define the nested loops number.
8441 unsigned NestedLoopCount =
8442 checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
8443 nullptr /*ordered not a clause on distribute*/, CS, *this,
8444 *DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, VarsWithImplicitDSA, B);
8445 if (NestedLoopCount == 0)
8446 return StmtError();
8447
8448 assert((CurContext->isDependentContext() || B.builtAll()) &&(((CurContext->isDependentContext() || B.builtAll()) &&
"omp for loop exprs were not built") ? static_cast<void>
(0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp for loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 8449, __PRETTY_FUNCTION__))
8449 "omp for loop exprs were not built")(((CurContext->isDependentContext() || B.builtAll()) &&
"omp for loop exprs were not built") ? static_cast<void>
(0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp for loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 8449, __PRETTY_FUNCTION__))
;
8450
8451 if (!CurContext->isDependentContext()) {
8452 // Finalize the clauses that need pre-built expressions for CodeGen.
8453 for (OMPClause *C : Clauses) {
8454 if (auto *LC = dyn_cast<OMPLinearClause>(C))
8455 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8456 B.NumIterations, *this, CurScope,
8457 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
))
8458 return StmtError();
8459 }
8460 }
8461
8462 if (checkSimdlenSafelenSpecified(*this, Clauses))
8463 return StmtError();
8464
8465 setFunctionHasBranchProtectedScope();
8466 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
8467 NestedLoopCount, Clauses, AStmt, B);
8468}
8469
8470StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
8471 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8472 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
8473 if (!AStmt)
8474 return StmtError();
8475
8476 auto *CS = cast<CapturedStmt>(AStmt);
8477 // 1.2.2 OpenMP Language Terminology
8478 // Structured block - An executable statement with a single entry at the
8479 // top and a single exit at the bottom.
8480 // The point of exit cannot be a branch out of the structured block.
8481 // longjmp() and throw() must not violate the entry/exit criteria.
8482 CS->getCapturedDecl()->setNothrow();
8483 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
8484 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8485 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8486 // 1.2.2 OpenMP Language Terminology
8487 // Structured block - An executable statement with a single entry at the
8488 // top and a single exit at the bottom.
8489 // The point of exit cannot be a branch out of the structured block.
8490 // longjmp() and throw() must not violate the entry/exit criteria.
8491 CS->getCapturedDecl()->setNothrow();
8492 }
8493
8494 OMPLoopDirective::HelperExprs B;
8495 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8496 // define the nested loops number.
8497 unsigned NestedLoopCount = checkOpenMPLoop(
8498 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
8499 getOrderedNumberExpr(Clauses), CS, *this, *DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
,
8500 VarsWithImplicitDSA, B);
8501 if (NestedLoopCount == 0)
8502 return StmtError();
8503
8504 assert((CurContext->isDependentContext() || B.builtAll()) &&(((CurContext->isDependentContext() || B.builtAll()) &&
"omp target parallel for simd loop exprs were not built") ? static_cast
<void> (0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp target parallel for simd loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 8505, __PRETTY_FUNCTION__))
8505 "omp target parallel for simd loop exprs were not built")(((CurContext->isDependentContext() || B.builtAll()) &&
"omp target parallel for simd loop exprs were not built") ? static_cast
<void> (0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp target parallel for simd loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 8505, __PRETTY_FUNCTION__))
;
8506
8507 if (!CurContext->isDependentContext()) {
8508 // Finalize the clauses that need pre-built expressions for CodeGen.
8509 for (OMPClause *C : Clauses) {
8510 if (auto *LC = dyn_cast<OMPLinearClause>(C))
8511 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8512 B.NumIterations, *this, CurScope,
8513 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
))
8514 return StmtError();
8515 }
8516 }
8517 if (checkSimdlenSafelenSpecified(*this, Clauses))
8518 return StmtError();
8519
8520 setFunctionHasBranchProtectedScope();
8521 return OMPTargetParallelForSimdDirective::Create(
8522 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8523}
8524
8525StmtResult Sema::ActOnOpenMPTargetSimdDirective(
8526 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8527 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
8528 if (!AStmt)
8529 return StmtError();
8530
8531 auto *CS = cast<CapturedStmt>(AStmt);
8532 // 1.2.2 OpenMP Language Terminology
8533 // Structured block - An executable statement with a single entry at the
8534 // top and a single exit at the bottom.
8535 // The point of exit cannot be a branch out of the structured block.
8536 // longjmp() and throw() must not violate the entry/exit criteria.
8537 CS->getCapturedDecl()->setNothrow();
8538 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
8539 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8540 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8541 // 1.2.2 OpenMP Language Terminology
8542 // Structured block - An executable statement with a single entry at the
8543 // top and a single exit at the bottom.
8544 // The point of exit cannot be a branch out of the structured block.
8545 // longjmp() and throw() must not violate the entry/exit criteria.
8546 CS->getCapturedDecl()->setNothrow();
8547 }
8548
8549 OMPLoopDirective::HelperExprs B;
8550 // In presence of clause 'collapse' with number of loops, it will define the
8551 // nested loops number.
8552 unsigned NestedLoopCount =
8553 checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
8554 getOrderedNumberExpr(Clauses), CS, *this, *DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
,
8555 VarsWithImplicitDSA, B);
8556 if (NestedLoopCount == 0)
8557 return StmtError();
8558
8559 assert((CurContext->isDependentContext() || B.builtAll()) &&(((CurContext->isDependentContext() || B.builtAll()) &&
"omp target simd loop exprs were not built") ? static_cast<
void> (0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp target simd loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 8560, __PRETTY_FUNCTION__))
8560 "omp target simd loop exprs were not built")(((CurContext->isDependentContext() || B.builtAll()) &&
"omp target simd loop exprs were not built") ? static_cast<
void> (0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp target simd loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 8560, __PRETTY_FUNCTION__))
;
8561
8562 if (!CurContext->isDependentContext()) {
8563 // Finalize the clauses that need pre-built expressions for CodeGen.
8564 for (OMPClause *C : Clauses) {
8565 if (auto *LC = dyn_cast<OMPLinearClause>(C))
8566 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8567 B.NumIterations, *this, CurScope,
8568 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
))
8569 return StmtError();
8570 }
8571 }
8572
8573 if (checkSimdlenSafelenSpecified(*this, Clauses))
8574 return StmtError();
8575
8576 setFunctionHasBranchProtectedScope();
8577 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
8578 NestedLoopCount, Clauses, AStmt, B);
8579}
8580
8581StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
8582 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8583 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
8584 if (!AStmt)
8585 return StmtError();
8586
8587 auto *CS = cast<CapturedStmt>(AStmt);
8588 // 1.2.2 OpenMP Language Terminology
8589 // Structured block - An executable statement with a single entry at the
8590 // top and a single exit at the bottom.
8591 // The point of exit cannot be a branch out of the structured block.
8592 // longjmp() and throw() must not violate the entry/exit criteria.
8593 CS->getCapturedDecl()->setNothrow();
8594 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
8595 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8596 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8597 // 1.2.2 OpenMP Language Terminology
8598 // Structured block - An executable statement with a single entry at the
8599 // top and a single exit at the bottom.
8600 // The point of exit cannot be a branch out of the structured block.
8601 // longjmp() and throw() must not violate the entry/exit criteria.
8602 CS->getCapturedDecl()->setNothrow();
8603 }
8604
8605 OMPLoopDirective::HelperExprs B;
8606 // In presence of clause 'collapse' with number of loops, it will
8607 // define the nested loops number.
8608 unsigned NestedLoopCount =
8609 checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
8610 nullptr /*ordered not a clause on distribute*/, CS, *this,
8611 *DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, VarsWithImplicitDSA, B);
8612 if (NestedLoopCount == 0)
8613 return StmtError();
8614
8615 assert((CurContext->isDependentContext() || B.builtAll()) &&(((CurContext->isDependentContext() || B.builtAll()) &&
"omp teams distribute loop exprs were not built") ? static_cast
<void> (0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp teams distribute loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 8616, __PRETTY_FUNCTION__))
8616 "omp teams distribute loop exprs were not built")(((CurContext->isDependentContext() || B.builtAll()) &&
"omp teams distribute loop exprs were not built") ? static_cast
<void> (0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp teams distribute loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 8616, __PRETTY_FUNCTION__))
;
8617
8618 setFunctionHasBranchProtectedScope();
8619
8620 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->setParentTeamsRegionLoc(StartLoc);
8621
8622 return OMPTeamsDistributeDirective::Create(
8623 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8624}
8625
8626StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
8627 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8628 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
8629 if (!AStmt)
8630 return StmtError();
8631
8632 auto *CS = cast<CapturedStmt>(AStmt);
8633 // 1.2.2 OpenMP Language Terminology
8634 // Structured block - An executable statement with a single entry at the
8635 // top and a single exit at the bottom.
8636 // The point of exit cannot be a branch out of the structured block.
8637 // longjmp() and throw() must not violate the entry/exit criteria.
8638 CS->getCapturedDecl()->setNothrow();
8639 for (int ThisCaptureLevel =
8640 getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
8641 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8642 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8643 // 1.2.2 OpenMP Language Terminology
8644 // Structured block - An executable statement with a single entry at the
8645 // top and a single exit at the bottom.
8646 // The point of exit cannot be a branch out of the structured block.
8647 // longjmp() and throw() must not violate the entry/exit criteria.
8648 CS->getCapturedDecl()->setNothrow();
8649 }
8650
8651
8652 OMPLoopDirective::HelperExprs B;
8653 // In presence of clause 'collapse' with number of loops, it will
8654 // define the nested loops number.
8655 unsigned NestedLoopCount = checkOpenMPLoop(
8656 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
8657 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
,
8658 VarsWithImplicitDSA, B);
8659
8660 if (NestedLoopCount == 0)
8661 return StmtError();
8662
8663 assert((CurContext->isDependentContext() || B.builtAll()) &&(((CurContext->isDependentContext() || B.builtAll()) &&
"omp teams distribute simd loop exprs were not built") ? static_cast
<void> (0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp teams distribute simd loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 8664, __PRETTY_FUNCTION__))
8664 "omp teams distribute simd loop exprs were not built")(((CurContext->isDependentContext() || B.builtAll()) &&
"omp teams distribute simd loop exprs were not built") ? static_cast
<void> (0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp teams distribute simd loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 8664, __PRETTY_FUNCTION__))
;
8665
8666 if (!CurContext->isDependentContext()) {
8667 // Finalize the clauses that need pre-built expressions for CodeGen.
8668 for (OMPClause *C : Clauses) {
8669 if (auto *LC = dyn_cast<OMPLinearClause>(C))
8670 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8671 B.NumIterations, *this, CurScope,
8672 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
))
8673 return StmtError();
8674 }
8675 }
8676
8677 if (checkSimdlenSafelenSpecified(*this, Clauses))
8678 return StmtError();
8679
8680 setFunctionHasBranchProtectedScope();
8681
8682 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->setParentTeamsRegionLoc(StartLoc);
8683
8684 return OMPTeamsDistributeSimdDirective::Create(
8685 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8686}
8687
8688StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
8689 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8690 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
8691 if (!AStmt)
8692 return StmtError();
8693
8694 auto *CS = cast<CapturedStmt>(AStmt);
8695 // 1.2.2 OpenMP Language Terminology
8696 // Structured block - An executable statement with a single entry at the
8697 // top and a single exit at the bottom.
8698 // The point of exit cannot be a branch out of the structured block.
8699 // longjmp() and throw() must not violate the entry/exit criteria.
8700 CS->getCapturedDecl()->setNothrow();
8701
8702 for (int ThisCaptureLevel =
8703 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
8704 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8705 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8706 // 1.2.2 OpenMP Language Terminology
8707 // Structured block - An executable statement with a single entry at the
8708 // top and a single exit at the bottom.
8709 // The point of exit cannot be a branch out of the structured block.
8710 // longjmp() and throw() must not violate the entry/exit criteria.
8711 CS->getCapturedDecl()->setNothrow();
8712 }
8713
8714 OMPLoopDirective::HelperExprs B;
8715 // In presence of clause 'collapse' with number of loops, it will
8716 // define the nested loops number.
8717 unsigned NestedLoopCount = checkOpenMPLoop(
8718 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
8719 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
,
8720 VarsWithImplicitDSA, B);
8721
8722 if (NestedLoopCount == 0)
8723 return StmtError();
8724
8725 assert((CurContext->isDependentContext() || B.builtAll()) &&(((CurContext->isDependentContext() || B.builtAll()) &&
"omp for loop exprs were not built") ? static_cast<void>
(0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp for loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 8726, __PRETTY_FUNCTION__))
8726 "omp for loop exprs were not built")(((CurContext->isDependentContext() || B.builtAll()) &&
"omp for loop exprs were not built") ? static_cast<void>
(0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp for loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 8726, __PRETTY_FUNCTION__))
;
8727
8728 if (!CurContext->isDependentContext()) {
8729 // Finalize the clauses that need pre-built expressions for CodeGen.
8730 for (OMPClause *C : Clauses) {
8731 if (auto *LC = dyn_cast<OMPLinearClause>(C))
8732 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8733 B.NumIterations, *this, CurScope,
8734 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
))
8735 return StmtError();
8736 }
8737 }
8738
8739 if (checkSimdlenSafelenSpecified(*this, Clauses))
8740 return StmtError();
8741
8742 setFunctionHasBranchProtectedScope();
8743
8744 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->setParentTeamsRegionLoc(StartLoc);
8745
8746 return OMPTeamsDistributeParallelForSimdDirective::Create(
8747 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8748}
8749
8750StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
8751 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8752 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
8753 if (!AStmt)
8754 return StmtError();
8755
8756 auto *CS = cast<CapturedStmt>(AStmt);
8757 // 1.2.2 OpenMP Language Terminology
8758 // Structured block - An executable statement with a single entry at the
8759 // top and a single exit at the bottom.
8760 // The point of exit cannot be a branch out of the structured block.
8761 // longjmp() and throw() must not violate the entry/exit criteria.
8762 CS->getCapturedDecl()->setNothrow();
8763
8764 for (int ThisCaptureLevel =
8765 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
8766 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8767 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8768 // 1.2.2 OpenMP Language Terminology
8769 // Structured block - An executable statement with a single entry at the
8770 // top and a single exit at the bottom.
8771 // The point of exit cannot be a branch out of the structured block.
8772 // longjmp() and throw() must not violate the entry/exit criteria.
8773 CS->getCapturedDecl()->setNothrow();
8774 }
8775
8776 OMPLoopDirective::HelperExprs B;
8777 // In presence of clause 'collapse' with number of loops, it will
8778 // define the nested loops number.
8779 unsigned NestedLoopCount = checkOpenMPLoop(
8780 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
8781 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
,
8782 VarsWithImplicitDSA, B);
8783
8784 if (NestedLoopCount == 0)
8785 return StmtError();
8786
8787 assert((CurContext->isDependentContext() || B.builtAll()) &&(((CurContext->isDependentContext() || B.builtAll()) &&
"omp for loop exprs were not built") ? static_cast<void>
(0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp for loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 8788, __PRETTY_FUNCTION__))
8788 "omp for loop exprs were not built")(((CurContext->isDependentContext() || B.builtAll()) &&
"omp for loop exprs were not built") ? static_cast<void>
(0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp for loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 8788, __PRETTY_FUNCTION__))
;
8789
8790 setFunctionHasBranchProtectedScope();
8791
8792 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->setParentTeamsRegionLoc(StartLoc);
8793
8794 return OMPTeamsDistributeParallelForDirective::Create(
8795 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
8796 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isCancelRegion());
8797}
8798
8799StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
8800 Stmt *AStmt,
8801 SourceLocation StartLoc,
8802 SourceLocation EndLoc) {
8803 if (!AStmt)
8804 return StmtError();
8805
8806 auto *CS = cast<CapturedStmt>(AStmt);
8807 // 1.2.2 OpenMP Language Terminology
8808 // Structured block - An executable statement with a single entry at the
8809 // top and a single exit at the bottom.
8810 // The point of exit cannot be a branch out of the structured block.
8811 // longjmp() and throw() must not violate the entry/exit criteria.
8812 CS->getCapturedDecl()->setNothrow();
8813
8814 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
8815 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8816 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8817 // 1.2.2 OpenMP Language Terminology
8818 // Structured block - An executable statement with a single entry at the
8819 // top and a single exit at the bottom.
8820 // The point of exit cannot be a branch out of the structured block.
8821 // longjmp() and throw() must not violate the entry/exit criteria.
8822 CS->getCapturedDecl()->setNothrow();
8823 }
8824 setFunctionHasBranchProtectedScope();
8825
8826 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
8827 AStmt);
8828}
8829
8830StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
8831 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8832 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
8833 if (!AStmt)
8834 return StmtError();
8835
8836 auto *CS = cast<CapturedStmt>(AStmt);
8837 // 1.2.2 OpenMP Language Terminology
8838 // Structured block - An executable statement with a single entry at the
8839 // top and a single exit at the bottom.
8840 // The point of exit cannot be a branch out of the structured block.
8841 // longjmp() and throw() must not violate the entry/exit criteria.
8842 CS->getCapturedDecl()->setNothrow();
8843 for (int ThisCaptureLevel =
8844 getOpenMPCaptureLevels(OMPD_target_teams_distribute);
8845 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8846 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8847 // 1.2.2 OpenMP Language Terminology
8848 // Structured block - An executable statement with a single entry at the
8849 // top and a single exit at the bottom.
8850 // The point of exit cannot be a branch out of the structured block.
8851 // longjmp() and throw() must not violate the entry/exit criteria.
8852 CS->getCapturedDecl()->setNothrow();
8853 }
8854
8855 OMPLoopDirective::HelperExprs B;
8856 // In presence of clause 'collapse' with number of loops, it will
8857 // define the nested loops number.
8858 unsigned NestedLoopCount = checkOpenMPLoop(
8859 OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
8860 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
,
8861 VarsWithImplicitDSA, B);
8862 if (NestedLoopCount == 0)
8863 return StmtError();
8864
8865 assert((CurContext->isDependentContext() || B.builtAll()) &&(((CurContext->isDependentContext() || B.builtAll()) &&
"omp target teams distribute loop exprs were not built") ? static_cast
<void> (0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp target teams distribute loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 8866, __PRETTY_FUNCTION__))
8866 "omp target teams distribute loop exprs were not built")(((CurContext->isDependentContext() || B.builtAll()) &&
"omp target teams distribute loop exprs were not built") ? static_cast
<void> (0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp target teams distribute loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 8866, __PRETTY_FUNCTION__))
;
8867
8868 setFunctionHasBranchProtectedScope();
8869 return OMPTargetTeamsDistributeDirective::Create(
8870 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8871}
8872
8873StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
8874 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8875 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
8876 if (!AStmt)
8877 return StmtError();
8878
8879 auto *CS = cast<CapturedStmt>(AStmt);
8880 // 1.2.2 OpenMP Language Terminology
8881 // Structured block - An executable statement with a single entry at the
8882 // top and a single exit at the bottom.
8883 // The point of exit cannot be a branch out of the structured block.
8884 // longjmp() and throw() must not violate the entry/exit criteria.
8885 CS->getCapturedDecl()->setNothrow();
8886 for (int ThisCaptureLevel =
8887 getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for);
8888 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8889 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8890 // 1.2.2 OpenMP Language Terminology
8891 // Structured block - An executable statement with a single entry at the
8892 // top and a single exit at the bottom.
8893 // The point of exit cannot be a branch out of the structured block.
8894 // longjmp() and throw() must not violate the entry/exit criteria.
8895 CS->getCapturedDecl()->setNothrow();
8896 }
8897
8898 OMPLoopDirective::HelperExprs B;
8899 // In presence of clause 'collapse' with number of loops, it will
8900 // define the nested loops number.
8901 unsigned NestedLoopCount = checkOpenMPLoop(
8902 OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
8903 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
,
8904 VarsWithImplicitDSA, B);
8905 if (NestedLoopCount == 0)
8906 return StmtError();
8907
8908 assert((CurContext->isDependentContext() || B.builtAll()) &&(((CurContext->isDependentContext() || B.builtAll()) &&
"omp target teams distribute parallel for loop exprs were not built"
) ? static_cast<void> (0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp target teams distribute parallel for loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 8909, __PRETTY_FUNCTION__))
8909 "omp target teams distribute parallel for loop exprs were not built")(((CurContext->isDependentContext() || B.builtAll()) &&
"omp target teams distribute parallel for loop exprs were not built"
) ? static_cast<void> (0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp target teams distribute parallel for loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 8909, __PRETTY_FUNCTION__))
;
8910
8911 if (!CurContext->isDependentContext()) {
8912 // Finalize the clauses that need pre-built expressions for CodeGen.
8913 for (OMPClause *C : Clauses) {
8914 if (auto *LC = dyn_cast<OMPLinearClause>(C))
8915 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8916 B.NumIterations, *this, CurScope,
8917 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
))
8918 return StmtError();
8919 }
8920 }
8921
8922 setFunctionHasBranchProtectedScope();
8923 return OMPTargetTeamsDistributeParallelForDirective::Create(
8924 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
8925 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isCancelRegion());
8926}
8927
8928StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
8929 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8930 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
8931 if (!AStmt)
8932 return StmtError();
8933
8934 auto *CS = cast<CapturedStmt>(AStmt);
8935 // 1.2.2 OpenMP Language Terminology
8936 // Structured block - An executable statement with a single entry at the
8937 // top and a single exit at the bottom.
8938 // The point of exit cannot be a branch out of the structured block.
8939 // longjmp() and throw() must not violate the entry/exit criteria.
8940 CS->getCapturedDecl()->setNothrow();
8941 for (int ThisCaptureLevel = getOpenMPCaptureLevels(
8942 OMPD_target_teams_distribute_parallel_for_simd);
8943 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8944 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8945 // 1.2.2 OpenMP Language Terminology
8946 // Structured block - An executable statement with a single entry at the
8947 // top and a single exit at the bottom.
8948 // The point of exit cannot be a branch out of the structured block.
8949 // longjmp() and throw() must not violate the entry/exit criteria.
8950 CS->getCapturedDecl()->setNothrow();
8951 }
8952
8953 OMPLoopDirective::HelperExprs B;
8954 // In presence of clause 'collapse' with number of loops, it will
8955 // define the nested loops number.
8956 unsigned NestedLoopCount =
8957 checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd,
8958 getCollapseNumberExpr(Clauses),
8959 nullptr /*ordered not a clause on distribute*/, CS, *this,
8960 *DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, VarsWithImplicitDSA, B);
8961 if (NestedLoopCount == 0)
8962 return StmtError();
8963
8964 assert((CurContext->isDependentContext() || B.builtAll()) &&(((CurContext->isDependentContext() || B.builtAll()) &&
"omp target teams distribute parallel for simd loop exprs were not "
"built") ? static_cast<void> (0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp target teams distribute parallel for simd loop exprs were not \" \"built\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 8966, __PRETTY_FUNCTION__))
8965 "omp target teams distribute parallel for simd loop exprs were not "(((CurContext->isDependentContext() || B.builtAll()) &&
"omp target teams distribute parallel for simd loop exprs were not "
"built") ? static_cast<void> (0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp target teams distribute parallel for simd loop exprs were not \" \"built\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 8966, __PRETTY_FUNCTION__))
8966 "built")(((CurContext->isDependentContext() || B.builtAll()) &&
"omp target teams distribute parallel for simd loop exprs were not "
"built") ? static_cast<void> (0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp target teams distribute parallel for simd loop exprs were not \" \"built\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 8966, __PRETTY_FUNCTION__))
;
8967
8968 if (!CurContext->isDependentContext()) {
8969 // Finalize the clauses that need pre-built expressions for CodeGen.
8970 for (OMPClause *C : Clauses) {
8971 if (auto *LC = dyn_cast<OMPLinearClause>(C))
8972 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8973 B.NumIterations, *this, CurScope,
8974 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
))
8975 return StmtError();
8976 }
8977 }
8978
8979 if (checkSimdlenSafelenSpecified(*this, Clauses))
8980 return StmtError();
8981
8982 setFunctionHasBranchProtectedScope();
8983 return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
8984 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8985}
8986
8987StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
8988 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8989 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
8990 if (!AStmt)
8991 return StmtError();
8992
8993 auto *CS = cast<CapturedStmt>(AStmt);
8994 // 1.2.2 OpenMP Language Terminology
8995 // Structured block - An executable statement with a single entry at the
8996 // top and a single exit at the bottom.
8997 // The point of exit cannot be a branch out of the structured block.
8998 // longjmp() and throw() must not violate the entry/exit criteria.
8999 CS->getCapturedDecl()->setNothrow();
9000 for (int ThisCaptureLevel =
9001 getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd);
9002 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9003 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9004 // 1.2.2 OpenMP Language Terminology
9005 // Structured block - An executable statement with a single entry at the
9006 // top and a single exit at the bottom.
9007 // The point of exit cannot be a branch out of the structured block.
9008 // longjmp() and throw() must not violate the entry/exit criteria.
9009 CS->getCapturedDecl()->setNothrow();
9010 }
9011
9012 OMPLoopDirective::HelperExprs B;
9013 // In presence of clause 'collapse' with number of loops, it will
9014 // define the nested loops number.
9015 unsigned NestedLoopCount = checkOpenMPLoop(
9016 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
9017 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
,
9018 VarsWithImplicitDSA, B);
9019 if (NestedLoopCount == 0)
9020 return StmtError();
9021
9022 assert((CurContext->isDependentContext() || B.builtAll()) &&(((CurContext->isDependentContext() || B.builtAll()) &&
"omp target teams distribute simd loop exprs were not built"
) ? static_cast<void> (0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp target teams distribute simd loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 9023, __PRETTY_FUNCTION__))
9023 "omp target teams distribute simd loop exprs were not built")(((CurContext->isDependentContext() || B.builtAll()) &&
"omp target teams distribute simd loop exprs were not built"
) ? static_cast<void> (0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp target teams distribute simd loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 9023, __PRETTY_FUNCTION__))
;
9024
9025 if (!CurContext->isDependentContext()) {
9026 // Finalize the clauses that need pre-built expressions for CodeGen.
9027 for (OMPClause *C : Clauses) {
9028 if (auto *LC = dyn_cast<OMPLinearClause>(C))
9029 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9030 B.NumIterations, *this, CurScope,
9031 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
))
9032 return StmtError();
9033 }
9034 }
9035
9036 if (checkSimdlenSafelenSpecified(*this, Clauses))
9037 return StmtError();
9038
9039 setFunctionHasBranchProtectedScope();
9040 return OMPTargetTeamsDistributeSimdDirective::Create(
9041 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
9042}
9043
9044OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
9045 SourceLocation StartLoc,
9046 SourceLocation LParenLoc,
9047 SourceLocation EndLoc) {
9048 OMPClause *Res = nullptr;
9049 switch (Kind) {
9050 case OMPC_final:
9051 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
9052 break;
9053 case OMPC_num_threads:
9054 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
9055 break;
9056 case OMPC_safelen:
9057 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
9058 break;
9059 case OMPC_simdlen:
9060 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
9061 break;
9062 case OMPC_allocator:
9063 Res = ActOnOpenMPAllocatorClause(Expr, StartLoc, LParenLoc, EndLoc);
9064 break;
9065 case OMPC_collapse:
9066 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
9067 break;
9068 case OMPC_ordered:
9069 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
9070 break;
9071 case OMPC_device:
9072 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
9073 break;
9074 case OMPC_num_teams:
9075 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
9076 break;
9077 case OMPC_thread_limit:
9078 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
9079 break;
9080 case OMPC_priority:
9081 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
9082 break;
9083 case OMPC_grainsize:
9084 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
9085 break;
9086 case OMPC_num_tasks:
9087 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
9088 break;
9089 case OMPC_hint:
9090 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
9091 break;
9092 case OMPC_if:
9093 case OMPC_default:
9094 case OMPC_proc_bind:
9095 case OMPC_schedule:
9096 case OMPC_private:
9097 case OMPC_firstprivate:
9098 case OMPC_lastprivate:
9099 case OMPC_shared:
9100 case OMPC_reduction:
9101 case OMPC_task_reduction:
9102 case OMPC_in_reduction:
9103 case OMPC_linear:
9104 case OMPC_aligned:
9105 case OMPC_copyin:
9106 case OMPC_copyprivate:
9107 case OMPC_nowait:
9108 case OMPC_untied:
9109 case OMPC_mergeable:
9110 case OMPC_threadprivate:
9111 case OMPC_allocate:
9112 case OMPC_flush:
9113 case OMPC_read:
9114 case OMPC_write:
9115 case OMPC_update:
9116 case OMPC_capture:
9117 case OMPC_seq_cst:
9118 case OMPC_depend:
9119 case OMPC_threads:
9120 case OMPC_simd:
9121 case OMPC_map:
9122 case OMPC_nogroup:
9123 case OMPC_dist_schedule:
9124 case OMPC_defaultmap:
9125 case OMPC_unknown:
9126 case OMPC_uniform:
9127 case OMPC_to:
9128 case OMPC_from:
9129 case OMPC_use_device_ptr:
9130 case OMPC_is_device_ptr:
9131 case OMPC_unified_address:
9132 case OMPC_unified_shared_memory:
9133 case OMPC_reverse_offload:
9134 case OMPC_dynamic_allocators:
9135 case OMPC_atomic_default_mem_order:
9136 llvm_unreachable("Clause is not allowed.")::llvm::llvm_unreachable_internal("Clause is not allowed.", "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 9136)
;
9137 }
9138 return Res;
9139}
9140
9141// An OpenMP directive such as 'target parallel' has two captured regions:
9142// for the 'target' and 'parallel' respectively. This function returns
9143// the region in which to capture expressions associated with a clause.
9144// A return value of OMPD_unknown signifies that the expression should not
9145// be captured.
9146static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
9147 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
9148 OpenMPDirectiveKind NameModifier = OMPD_unknown) {
9149 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
9150 switch (CKind) {
9151 case OMPC_if:
9152 switch (DKind) {
9153 case OMPD_target_parallel:
9154 case OMPD_target_parallel_for:
9155 case OMPD_target_parallel_for_simd:
9156 // If this clause applies to the nested 'parallel' region, capture within
9157 // the 'target' region, otherwise do not capture.
9158 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
9159 CaptureRegion = OMPD_target;
9160 break;
9161 case OMPD_target_teams_distribute_parallel_for:
9162 case OMPD_target_teams_distribute_parallel_for_simd:
9163 // If this clause applies to the nested 'parallel' region, capture within
9164 // the 'teams' region, otherwise do not capture.
9165 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
9166 CaptureRegion = OMPD_teams;
9167 break;
9168 case OMPD_teams_distribute_parallel_for:
9169 case OMPD_teams_distribute_parallel_for_simd:
9170 CaptureRegion = OMPD_teams;
9171 break;
9172 case OMPD_target_update:
9173 case OMPD_target_enter_data:
9174 case OMPD_target_exit_data:
9175 CaptureRegion = OMPD_task;
9176 break;
9177 case OMPD_cancel:
9178 case OMPD_parallel:
9179 case OMPD_parallel_sections:
9180 case OMPD_parallel_for:
9181 case OMPD_parallel_for_simd:
9182 case OMPD_target:
9183 case OMPD_target_simd:
9184 case OMPD_target_teams:
9185 case OMPD_target_teams_distribute:
9186 case OMPD_target_teams_distribute_simd:
9187 case OMPD_distribute_parallel_for:
9188 case OMPD_distribute_parallel_for_simd:
9189 case OMPD_task:
9190 case OMPD_taskloop:
9191 case OMPD_taskloop_simd:
9192 case OMPD_target_data:
9193 // Do not capture if-clause expressions.
9194 break;
9195 case OMPD_threadprivate:
9196 case OMPD_allocate:
9197 case OMPD_taskyield:
9198 case OMPD_barrier:
9199 case OMPD_taskwait:
9200 case OMPD_cancellation_point:
9201 case OMPD_flush:
9202 case OMPD_declare_reduction:
9203 case OMPD_declare_mapper:
9204 case OMPD_declare_simd:
9205 case OMPD_declare_target:
9206 case OMPD_end_declare_target:
9207 case OMPD_teams:
9208 case OMPD_simd:
9209 case OMPD_for:
9210 case OMPD_for_simd:
9211 case OMPD_sections:
9212 case OMPD_section:
9213 case OMPD_single:
9214 case OMPD_master:
9215 case OMPD_critical:
9216 case OMPD_taskgroup:
9217 case OMPD_distribute:
9218 case OMPD_ordered:
9219 case OMPD_atomic:
9220 case OMPD_distribute_simd:
9221 case OMPD_teams_distribute:
9222 case OMPD_teams_distribute_simd:
9223 case OMPD_requires:
9224 llvm_unreachable("Unexpected OpenMP directive with if-clause")::llvm::llvm_unreachable_internal("Unexpected OpenMP directive with if-clause"
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 9224)
;
9225 case OMPD_unknown:
9226 llvm_unreachable("Unknown OpenMP directive")::llvm::llvm_unreachable_internal("Unknown OpenMP directive",
"/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 9226)
;
9227 }
9228 break;
9229 case OMPC_num_threads:
9230 switch (DKind) {
9231 case OMPD_target_parallel:
9232 case OMPD_target_parallel_for:
9233 case OMPD_target_parallel_for_simd:
9234 CaptureRegion = OMPD_target;
9235 break;
9236 case OMPD_teams_distribute_parallel_for:
9237 case OMPD_teams_distribute_parallel_for_simd:
9238 case OMPD_target_teams_distribute_parallel_for:
9239 case OMPD_target_teams_distribute_parallel_for_simd:
9240 CaptureRegion = OMPD_teams;
9241 break;
9242 case OMPD_parallel:
9243 case OMPD_parallel_sections:
9244 case OMPD_parallel_for:
9245 case OMPD_parallel_for_simd:
9246 case OMPD_distribute_parallel_for:
9247 case OMPD_distribute_parallel_for_simd:
9248 // Do not capture num_threads-clause expressions.
9249 break;
9250 case OMPD_target_data:
9251 case OMPD_target_enter_data:
9252 case OMPD_target_exit_data:
9253 case OMPD_target_update:
9254 case OMPD_target:
9255 case OMPD_target_simd:
9256 case OMPD_target_teams:
9257 case OMPD_target_teams_distribute:
9258 case OMPD_target_teams_distribute_simd:
9259 case OMPD_cancel:
9260 case OMPD_task:
9261 case OMPD_taskloop:
9262 case OMPD_taskloop_simd:
9263 case OMPD_threadprivate:
9264 case OMPD_allocate:
9265 case OMPD_taskyield:
9266 case OMPD_barrier:
9267 case OMPD_taskwait:
9268 case OMPD_cancellation_point:
9269 case OMPD_flush:
9270 case OMPD_declare_reduction:
9271 case OMPD_declare_mapper:
9272 case OMPD_declare_simd:
9273 case OMPD_declare_target:
9274 case OMPD_end_declare_target:
9275 case OMPD_teams:
9276 case OMPD_simd:
9277 case OMPD_for:
9278 case OMPD_for_simd:
9279 case OMPD_sections:
9280 case OMPD_section:
9281 case OMPD_single:
9282 case OMPD_master:
9283 case OMPD_critical:
9284 case OMPD_taskgroup:
9285 case OMPD_distribute:
9286 case OMPD_ordered:
9287 case OMPD_atomic:
9288 case OMPD_distribute_simd:
9289 case OMPD_teams_distribute:
9290 case OMPD_teams_distribute_simd:
9291 case OMPD_requires:
9292 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause")::llvm::llvm_unreachable_internal("Unexpected OpenMP directive with num_threads-clause"
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 9292)
;
9293 case OMPD_unknown:
9294 llvm_unreachable("Unknown OpenMP directive")::llvm::llvm_unreachable_internal("Unknown OpenMP directive",
"/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 9294)
;
9295 }
9296 break;
9297 case OMPC_num_teams:
9298 switch (DKind) {
9299 case OMPD_target_teams:
9300 case OMPD_target_teams_distribute:
9301 case OMPD_target_teams_distribute_simd:
9302 case OMPD_target_teams_distribute_parallel_for:
9303 case OMPD_target_teams_distribute_parallel_for_simd:
9304 CaptureRegion = OMPD_target;
9305 break;
9306 case OMPD_teams_distribute_parallel_for:
9307 case OMPD_teams_distribute_parallel_for_simd:
9308 case OMPD_teams:
9309 case OMPD_teams_distribute:
9310 case OMPD_teams_distribute_simd:
9311 // Do not capture num_teams-clause expressions.
9312 break;
9313 case OMPD_distribute_parallel_for:
9314 case OMPD_distribute_parallel_for_simd:
9315 case OMPD_task:
9316 case OMPD_taskloop:
9317 case OMPD_taskloop_simd:
9318 case OMPD_target_data:
9319 case OMPD_target_enter_data:
9320 case OMPD_target_exit_data:
9321 case OMPD_target_update:
9322 case OMPD_cancel:
9323 case OMPD_parallel:
9324 case OMPD_parallel_sections:
9325 case OMPD_parallel_for:
9326 case OMPD_parallel_for_simd:
9327 case OMPD_target:
9328 case OMPD_target_simd:
9329 case OMPD_target_parallel:
9330 case OMPD_target_parallel_for:
9331 case OMPD_target_parallel_for_simd:
9332 case OMPD_threadprivate:
9333 case OMPD_allocate:
9334 case OMPD_taskyield:
9335 case OMPD_barrier:
9336 case OMPD_taskwait:
9337 case OMPD_cancellation_point:
9338 case OMPD_flush:
9339 case OMPD_declare_reduction:
9340 case OMPD_declare_mapper:
9341 case OMPD_declare_simd:
9342 case OMPD_declare_target:
9343 case OMPD_end_declare_target:
9344 case OMPD_simd:
9345 case OMPD_for:
9346 case OMPD_for_simd:
9347 case OMPD_sections:
9348 case OMPD_section:
9349 case OMPD_single:
9350 case OMPD_master:
9351 case OMPD_critical:
9352 case OMPD_taskgroup:
9353 case OMPD_distribute:
9354 case OMPD_ordered:
9355 case OMPD_atomic:
9356 case OMPD_distribute_simd:
9357 case OMPD_requires:
9358 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause")::llvm::llvm_unreachable_internal("Unexpected OpenMP directive with num_teams-clause"
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 9358)
;
9359 case OMPD_unknown:
9360 llvm_unreachable("Unknown OpenMP directive")::llvm::llvm_unreachable_internal("Unknown OpenMP directive",
"/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 9360)
;
9361 }
9362 break;
9363 case OMPC_thread_limit:
9364 switch (DKind) {
9365 case OMPD_target_teams:
9366 case OMPD_target_teams_distribute:
9367 case OMPD_target_teams_distribute_simd:
9368 case OMPD_target_teams_distribute_parallel_for:
9369 case OMPD_target_teams_distribute_parallel_for_simd:
9370 CaptureRegion = OMPD_target;
9371 break;
9372 case OMPD_teams_distribute_parallel_for:
9373 case OMPD_teams_distribute_parallel_for_simd:
9374 case OMPD_teams:
9375 case OMPD_teams_distribute:
9376 case OMPD_teams_distribute_simd:
9377 // Do not capture thread_limit-clause expressions.
9378 break;
9379 case OMPD_distribute_parallel_for:
9380 case OMPD_distribute_parallel_for_simd:
9381 case OMPD_task:
9382 case OMPD_taskloop:
9383 case OMPD_taskloop_simd:
9384 case OMPD_target_data:
9385 case OMPD_target_enter_data:
9386 case OMPD_target_exit_data:
9387 case OMPD_target_update:
9388 case OMPD_cancel:
9389 case OMPD_parallel:
9390 case OMPD_parallel_sections:
9391 case OMPD_parallel_for:
9392 case OMPD_parallel_for_simd:
9393 case OMPD_target:
9394 case OMPD_target_simd:
9395 case OMPD_target_parallel:
9396 case OMPD_target_parallel_for:
9397 case OMPD_target_parallel_for_simd:
9398 case OMPD_threadprivate:
9399 case OMPD_allocate:
9400 case OMPD_taskyield:
9401 case OMPD_barrier:
9402 case OMPD_taskwait:
9403 case OMPD_cancellation_point:
9404 case OMPD_flush:
9405 case OMPD_declare_reduction:
9406 case OMPD_declare_mapper:
9407 case OMPD_declare_simd:
9408 case OMPD_declare_target:
9409 case OMPD_end_declare_target:
9410 case OMPD_simd:
9411 case OMPD_for:
9412 case OMPD_for_simd:
9413 case OMPD_sections:
9414 case OMPD_section:
9415 case OMPD_single:
9416 case OMPD_master:
9417 case OMPD_critical:
9418 case OMPD_taskgroup:
9419 case OMPD_distribute:
9420 case OMPD_ordered:
9421 case OMPD_atomic:
9422 case OMPD_distribute_simd:
9423 case OMPD_requires:
9424 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause")::llvm::llvm_unreachable_internal("Unexpected OpenMP directive with thread_limit-clause"
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 9424)
;
9425 case OMPD_unknown:
9426 llvm_unreachable("Unknown OpenMP directive")::llvm::llvm_unreachable_internal("Unknown OpenMP directive",
"/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 9426)
;
9427 }
9428 break;
9429 case OMPC_schedule:
9430 switch (DKind) {
9431 case OMPD_parallel_for:
9432 case OMPD_parallel_for_simd:
9433 case OMPD_distribute_parallel_for:
9434 case OMPD_distribute_parallel_for_simd:
9435 case OMPD_teams_distribute_parallel_for:
9436 case OMPD_teams_distribute_parallel_for_simd:
9437 case OMPD_target_parallel_for:
9438 case OMPD_target_parallel_for_simd:
9439 case OMPD_target_teams_distribute_parallel_for:
9440 case OMPD_target_teams_distribute_parallel_for_simd:
9441 CaptureRegion = OMPD_parallel;
9442 break;
9443 case OMPD_for:
9444 case OMPD_for_simd:
9445 // Do not capture schedule-clause expressions.
9446 break;
9447 case OMPD_task:
9448 case OMPD_taskloop:
9449 case OMPD_taskloop_simd:
9450 case OMPD_target_data:
9451 case OMPD_target_enter_data:
9452 case OMPD_target_exit_data:
9453 case OMPD_target_update:
9454 case OMPD_teams:
9455 case OMPD_teams_distribute:
9456 case OMPD_teams_distribute_simd:
9457 case OMPD_target_teams_distribute:
9458 case OMPD_target_teams_distribute_simd:
9459 case OMPD_target:
9460 case OMPD_target_simd:
9461 case OMPD_target_parallel:
9462 case OMPD_cancel:
9463 case OMPD_parallel:
9464 case OMPD_parallel_sections:
9465 case OMPD_threadprivate:
9466 case OMPD_allocate:
9467 case OMPD_taskyield:
9468 case OMPD_barrier:
9469 case OMPD_taskwait:
9470 case OMPD_cancellation_point:
9471 case OMPD_flush:
9472 case OMPD_declare_reduction:
9473 case OMPD_declare_mapper:
9474 case OMPD_declare_simd:
9475 case OMPD_declare_target:
9476 case OMPD_end_declare_target:
9477 case OMPD_simd:
9478 case OMPD_sections:
9479 case OMPD_section:
9480 case OMPD_single:
9481 case OMPD_master:
9482 case OMPD_critical:
9483 case OMPD_taskgroup:
9484 case OMPD_distribute:
9485 case OMPD_ordered:
9486 case OMPD_atomic:
9487 case OMPD_distribute_simd:
9488 case OMPD_target_teams:
9489 case OMPD_requires:
9490 llvm_unreachable("Unexpected OpenMP directive with schedule clause")::llvm::llvm_unreachable_internal("Unexpected OpenMP directive with schedule clause"
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 9490)
;
9491 case OMPD_unknown:
9492 llvm_unreachable("Unknown OpenMP directive")::llvm::llvm_unreachable_internal("Unknown OpenMP directive",
"/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 9492)
;
9493 }
9494 break;
9495 case OMPC_dist_schedule:
9496 switch (DKind) {
9497 case OMPD_teams_distribute_parallel_for:
9498 case OMPD_teams_distribute_parallel_for_simd:
9499 case OMPD_teams_distribute:
9500 case OMPD_teams_distribute_simd:
9501 case OMPD_target_teams_distribute_parallel_for:
9502 case OMPD_target_teams_distribute_parallel_for_simd:
9503 case OMPD_target_teams_distribute:
9504 case OMPD_target_teams_distribute_simd:
9505 CaptureRegion = OMPD_teams;
9506 break;
9507 case OMPD_distribute_parallel_for:
9508 case OMPD_distribute_parallel_for_simd:
9509 case OMPD_distribute:
9510 case OMPD_distribute_simd:
9511 // Do not capture thread_limit-clause expressions.
9512 break;
9513 case OMPD_parallel_for:
9514 case OMPD_parallel_for_simd:
9515 case OMPD_target_parallel_for_simd:
9516 case OMPD_target_parallel_for:
9517 case OMPD_task:
9518 case OMPD_taskloop:
9519 case OMPD_taskloop_simd:
9520 case OMPD_target_data:
9521 case OMPD_target_enter_data:
9522 case OMPD_target_exit_data:
9523 case OMPD_target_update:
9524 case OMPD_teams:
9525 case OMPD_target:
9526 case OMPD_target_simd:
9527 case OMPD_target_parallel:
9528 case OMPD_cancel:
9529 case OMPD_parallel:
9530 case OMPD_parallel_sections:
9531 case OMPD_threadprivate:
9532 case OMPD_allocate:
9533 case OMPD_taskyield:
9534 case OMPD_barrier:
9535 case OMPD_taskwait:
9536 case OMPD_cancellation_point:
9537 case OMPD_flush:
9538 case OMPD_declare_reduction:
9539 case OMPD_declare_mapper:
9540 case OMPD_declare_simd:
9541 case OMPD_declare_target:
9542 case OMPD_end_declare_target:
9543 case OMPD_simd:
9544 case OMPD_for:
9545 case OMPD_for_simd:
9546 case OMPD_sections:
9547 case OMPD_section:
9548 case OMPD_single:
9549 case OMPD_master:
9550 case OMPD_critical:
9551 case OMPD_taskgroup:
9552 case OMPD_ordered:
9553 case OMPD_atomic:
9554 case OMPD_target_teams:
9555 case OMPD_requires:
9556 llvm_unreachable("Unexpected OpenMP directive with schedule clause")::llvm::llvm_unreachable_internal("Unexpected OpenMP directive with schedule clause"
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 9556)
;
9557 case OMPD_unknown:
9558 llvm_unreachable("Unknown OpenMP directive")::llvm::llvm_unreachable_internal("Unknown OpenMP directive",
"/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 9558)
;
9559 }
9560 break;
9561 case OMPC_device:
9562 switch (DKind) {
9563 case OMPD_target_update:
9564 case OMPD_target_enter_data:
9565 case OMPD_target_exit_data:
9566 case OMPD_target:
9567 case OMPD_target_simd:
9568 case OMPD_target_teams:
9569 case OMPD_target_parallel:
9570 case OMPD_target_teams_distribute:
9571 case OMPD_target_teams_distribute_simd:
9572 case OMPD_target_parallel_for:
9573 case OMPD_target_parallel_for_simd:
9574 case OMPD_target_teams_distribute_parallel_for:
9575 case OMPD_target_teams_distribute_parallel_for_simd:
9576 CaptureRegion = OMPD_task;
9577 break;
9578 case OMPD_target_data:
9579 // Do not capture device-clause expressions.
9580 break;
9581 case OMPD_teams_distribute_parallel_for:
9582 case OMPD_teams_distribute_parallel_for_simd:
9583 case OMPD_teams:
9584 case OMPD_teams_distribute:
9585 case OMPD_teams_distribute_simd:
9586 case OMPD_distribute_parallel_for:
9587 case OMPD_distribute_parallel_for_simd:
9588 case OMPD_task:
9589 case OMPD_taskloop:
9590 case OMPD_taskloop_simd:
9591 case OMPD_cancel:
9592 case OMPD_parallel:
9593 case OMPD_parallel_sections:
9594 case OMPD_parallel_for:
9595 case OMPD_parallel_for_simd:
9596 case OMPD_threadprivate:
9597 case OMPD_allocate:
9598 case OMPD_taskyield:
9599 case OMPD_barrier:
9600 case OMPD_taskwait:
9601 case OMPD_cancellation_point:
9602 case OMPD_flush:
9603 case OMPD_declare_reduction:
9604 case OMPD_declare_mapper:
9605 case OMPD_declare_simd:
9606 case OMPD_declare_target:
9607 case OMPD_end_declare_target:
9608 case OMPD_simd:
9609 case OMPD_for:
9610 case OMPD_for_simd:
9611 case OMPD_sections:
9612 case OMPD_section:
9613 case OMPD_single:
9614 case OMPD_master:
9615 case OMPD_critical:
9616 case OMPD_taskgroup:
9617 case OMPD_distribute:
9618 case OMPD_ordered:
9619 case OMPD_atomic:
9620 case OMPD_distribute_simd:
9621 case OMPD_requires:
9622 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause")::llvm::llvm_unreachable_internal("Unexpected OpenMP directive with num_teams-clause"
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 9622)
;
9623 case OMPD_unknown:
9624 llvm_unreachable("Unknown OpenMP directive")::llvm::llvm_unreachable_internal("Unknown OpenMP directive",
"/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 9624)
;
9625 }
9626 break;
9627 case OMPC_firstprivate:
9628 case OMPC_lastprivate:
9629 case OMPC_reduction:
9630 case OMPC_task_reduction:
9631 case OMPC_in_reduction:
9632 case OMPC_linear:
9633 case OMPC_default:
9634 case OMPC_proc_bind:
9635 case OMPC_final:
9636 case OMPC_safelen:
9637 case OMPC_simdlen:
9638 case OMPC_allocator:
9639 case OMPC_collapse:
9640 case OMPC_private:
9641 case OMPC_shared:
9642 case OMPC_aligned:
9643 case OMPC_copyin:
9644 case OMPC_copyprivate:
9645 case OMPC_ordered:
9646 case OMPC_nowait:
9647 case OMPC_untied:
9648 case OMPC_mergeable:
9649 case OMPC_threadprivate:
9650 case OMPC_allocate:
9651 case OMPC_flush:
9652 case OMPC_read:
9653 case OMPC_write:
9654 case OMPC_update:
9655 case OMPC_capture:
9656 case OMPC_seq_cst:
9657 case OMPC_depend:
9658 case OMPC_threads:
9659 case OMPC_simd:
9660 case OMPC_map:
9661 case OMPC_priority:
9662 case OMPC_grainsize:
9663 case OMPC_nogroup:
9664 case OMPC_num_tasks:
9665 case OMPC_hint:
9666 case OMPC_defaultmap:
9667 case OMPC_unknown:
9668 case OMPC_uniform:
9669 case OMPC_to:
9670 case OMPC_from:
9671 case OMPC_use_device_ptr:
9672 case OMPC_is_device_ptr:
9673 case OMPC_unified_address:
9674 case OMPC_unified_shared_memory:
9675 case OMPC_reverse_offload:
9676 case OMPC_dynamic_allocators:
9677 case OMPC_atomic_default_mem_order:
9678 llvm_unreachable("Unexpected OpenMP clause.")::llvm::llvm_unreachable_internal("Unexpected OpenMP clause."
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 9678)
;
9679 }
9680 return CaptureRegion;
9681}
9682
9683OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
9684 Expr *Condition, SourceLocation StartLoc,
9685 SourceLocation LParenLoc,
9686 SourceLocation NameModifierLoc,
9687 SourceLocation ColonLoc,
9688 SourceLocation EndLoc) {
9689 Expr *ValExpr = Condition;
9690 Stmt *HelperValStmt = nullptr;
9691 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
9692 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
9693 !Condition->isInstantiationDependent() &&
9694 !Condition->containsUnexpandedParameterPack()) {
9695 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
9696 if (Val.isInvalid())
9697 return nullptr;
9698
9699 ValExpr = Val.get();
9700
9701 OpenMPDirectiveKind DKind = DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective();
9702 CaptureRegion =
9703 getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
9704 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
9705 ValExpr = MakeFullExpr(ValExpr).get();
9706 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
9707 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
9708 HelperValStmt = buildPreInits(Context, Captures);
9709 }
9710 }
9711
9712 return new (Context)
9713 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
9714 LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
9715}
9716
9717OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
9718 SourceLocation StartLoc,
9719 SourceLocation LParenLoc,
9720 SourceLocation EndLoc) {
9721 Expr *ValExpr = Condition;
9722 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
9723 !Condition->isInstantiationDependent() &&
9724 !Condition->containsUnexpandedParameterPack()) {
9725 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
9726 if (Val.isInvalid())
9727 return nullptr;
9728
9729 ValExpr = MakeFullExpr(Val.get()).get();
9730 }
9731
9732 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
9733}
9734ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
9735 Expr *Op) {
9736 if (!Op)
9737 return ExprError();
9738
9739 class IntConvertDiagnoser : public ICEConvertDiagnoser {
9740 public:
9741 IntConvertDiagnoser()
9742 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
9743 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
9744 QualType T) override {
9745 return S.Diag(Loc, diag::err_omp_not_integral) << T;
9746 }
9747 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
9748 QualType T) override {
9749 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
9750 }
9751 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
9752 QualType T,
9753 QualType ConvTy) override {
9754 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
9755 }
9756 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
9757 QualType ConvTy) override {
9758 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
9759 << ConvTy->isEnumeralType() << ConvTy;
9760 }
9761 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
9762 QualType T) override {
9763 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
9764 }
9765 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
9766 QualType ConvTy) override {
9767 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
9768 << ConvTy->isEnumeralType() << ConvTy;
9769 }
9770 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
9771 QualType) override {
9772 llvm_unreachable("conversion functions are permitted")::llvm::llvm_unreachable_internal("conversion functions are permitted"
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 9772)
;
9773 }
9774 } ConvertDiagnoser;
9775 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
9776}
9777
9778static bool isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
9779 OpenMPClauseKind CKind,
9780 bool StrictlyPositive) {
9781 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
9782 !ValExpr->isInstantiationDependent()) {
9783 SourceLocation Loc = ValExpr->getExprLoc();
9784 ExprResult Value =
9785 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
9786 if (Value.isInvalid())
9787 return false;
9788
9789 ValExpr = Value.get();
9790 // The expression must evaluate to a non-negative integer value.
9791 llvm::APSInt Result;
9792 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
9793 Result.isSigned() &&
9794 !((!StrictlyPositive && Result.isNonNegative()) ||
9795 (StrictlyPositive && Result.isStrictlyPositive()))) {
9796 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
9797 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
9798 << ValExpr->getSourceRange();
9799 return false;
9800 }
9801 }
9802 return true;
9803}
9804
9805OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
9806 SourceLocation StartLoc,
9807 SourceLocation LParenLoc,
9808 SourceLocation EndLoc) {
9809 Expr *ValExpr = NumThreads;
9810 Stmt *HelperValStmt = nullptr;
9811
9812 // OpenMP [2.5, Restrictions]
9813 // The num_threads expression must evaluate to a positive integer value.
9814 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
9815 /*StrictlyPositive=*/true))
9816 return nullptr;
9817
9818 OpenMPDirectiveKind DKind = DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective();
9819 OpenMPDirectiveKind CaptureRegion =
9820 getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
9821 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
9822 ValExpr = MakeFullExpr(ValExpr).get();
9823 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
9824 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
9825 HelperValStmt = buildPreInits(Context, Captures);
9826 }
9827
9828 return new (Context) OMPNumThreadsClause(
9829 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
9830}
9831
9832ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
9833 OpenMPClauseKind CKind,
9834 bool StrictlyPositive) {
9835 if (!E)
9836 return ExprError();
9837 if (E->isValueDependent() || E->isTypeDependent() ||
9838 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
9839 return E;
9840 llvm::APSInt Result;
9841 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
9842 if (ICE.isInvalid())
9843 return ExprError();
9844 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
9845 (!StrictlyPositive && !Result.isNonNegative())) {
9846 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
9847 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
9848 << E->getSourceRange();
9849 return ExprError();
9850 }
9851 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
9852 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
9853 << E->getSourceRange();
9854 return ExprError();
9855 }
9856 if (CKind == OMPC_collapse && DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getAssociatedLoops() == 1)
9857 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->setAssociatedLoops(Result.getExtValue());
9858 else if (CKind == OMPC_ordered)
9859 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->setAssociatedLoops(Result.getExtValue());
9860 return ICE;
9861}
9862
9863OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
9864 SourceLocation LParenLoc,
9865 SourceLocation EndLoc) {
9866 // OpenMP [2.8.1, simd construct, Description]
9867 // The parameter of the safelen clause must be a constant
9868 // positive integer expression.
9869 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
9870 if (Safelen.isInvalid())
9871 return nullptr;
9872 return new (Context)
9873 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
9874}
9875
9876OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
9877 SourceLocation LParenLoc,
9878 SourceLocation EndLoc) {
9879 // OpenMP [2.8.1, simd construct, Description]
9880 // The parameter of the simdlen clause must be a constant
9881 // positive integer expression.
9882 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
9883 if (Simdlen.isInvalid())
9884 return nullptr;
9885 return new (Context)
9886 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
9887}
9888
9889/// Tries to find omp_allocator_handle_t type.
9890static bool findOMPAllocatorHandleT(Sema &S, SourceLocation Loc,
9891 DSAStackTy *Stack) {
9892 QualType OMPAllocatorHandleT = Stack->getOMPAllocatorHandleT();
9893 if (!OMPAllocatorHandleT.isNull())
9894 return true;
9895 // Build the predefined allocator expressions.
9896 bool ErrorFound = false;
9897 for (int I = OMPAllocateDeclAttr::OMPDefaultMemAlloc;
9898 I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
9899 auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
9900 StringRef Allocator =
9901 OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind);
9902 DeclarationName AllocatorName = &S.getASTContext().Idents.get(Allocator);
9903 auto *VD = dyn_cast_or_null<ValueDecl>(
9904 S.LookupSingleName(S.TUScope, AllocatorName, Loc, Sema::LookupAnyName));
9905 if (!VD) {
9906 ErrorFound = true;
9907 break;
9908 }
9909 QualType AllocatorType =
9910 VD->getType().getNonLValueExprType(S.getASTContext());
9911 ExprResult Res = S.BuildDeclRefExpr(VD, AllocatorType, VK_LValue, Loc);
9912 if (!Res.isUsable()) {
9913 ErrorFound = true;
9914 break;
9915 }
9916 if (OMPAllocatorHandleT.isNull())
9917 OMPAllocatorHandleT = AllocatorType;
9918 if (!S.getASTContext().hasSameType(OMPAllocatorHandleT, AllocatorType)) {
9919 ErrorFound = true;
9920 break;
9921 }
9922 Stack->setAllocator(AllocatorKind, Res.get());
9923 }
9924 if (ErrorFound) {
9925 S.Diag(Loc, diag::err_implied_omp_allocator_handle_t_not_found);
9926 return false;
9927 }
9928 OMPAllocatorHandleT.addConst();
9929 Stack->setOMPAllocatorHandleT(OMPAllocatorHandleT);
9930 return true;
9931}
9932
9933OMPClause *Sema::ActOnOpenMPAllocatorClause(Expr *A, SourceLocation StartLoc,
9934 SourceLocation LParenLoc,
9935 SourceLocation EndLoc) {
9936 // OpenMP [2.11.3, allocate Directive, Description]
9937 // allocator is an expression of omp_allocator_handle_t type.
9938 if (!findOMPAllocatorHandleT(*this, A->getExprLoc(), DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
))
9939 return nullptr;
9940
9941 ExprResult Allocator = DefaultLvalueConversion(A);
9942 if (Allocator.isInvalid())
9943 return nullptr;
9944 Allocator = PerformImplicitConversion(Allocator.get(),
9945 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getOMPAllocatorHandleT(),
9946 Sema::AA_Initializing,
9947 /*AllowExplicit=*/true);
9948 if (Allocator.isInvalid())
9949 return nullptr;
9950 return new (Context)
9951 OMPAllocatorClause(Allocator.get(), StartLoc, LParenLoc, EndLoc);
9952}
9953
9954OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
9955 SourceLocation StartLoc,
9956 SourceLocation LParenLoc,
9957 SourceLocation EndLoc) {
9958 // OpenMP [2.7.1, loop construct, Description]
9959 // OpenMP [2.8.1, simd construct, Description]
9960 // OpenMP [2.9.6, distribute construct, Description]
9961 // The parameter of the collapse clause must be a constant
9962 // positive integer expression.
9963 ExprResult NumForLoopsResult =
9964 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
9965 if (NumForLoopsResult.isInvalid())
9966 return nullptr;
9967 return new (Context)
9968 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
9969}
9970
9971OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
9972 SourceLocation EndLoc,
9973 SourceLocation LParenLoc,
9974 Expr *NumForLoops) {
9975 // OpenMP [2.7.1, loop construct, Description]
9976 // OpenMP [2.8.1, simd construct, Description]
9977 // OpenMP [2.9.6, distribute construct, Description]
9978 // The parameter of the ordered clause must be a constant
9979 // positive integer expression if any.
9980 if (NumForLoops && LParenLoc.isValid()) {
9981 ExprResult NumForLoopsResult =
9982 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
9983 if (NumForLoopsResult.isInvalid())
9984 return nullptr;
9985 NumForLoops = NumForLoopsResult.get();
9986 } else {
9987 NumForLoops = nullptr;
9988 }
9989 auto *Clause = OMPOrderedClause::Create(
9990 Context, NumForLoops, NumForLoops ? DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getAssociatedLoops() : 0,
9991 StartLoc, LParenLoc, EndLoc);
9992 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause);
9993 return Clause;
9994}
9995
9996OMPClause *Sema::ActOnOpenMPSimpleClause(
9997 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
9998 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
9999 OMPClause *Res = nullptr;
10000 switch (Kind) {
10001 case OMPC_default:
10002 Res =
10003 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
10004 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
10005 break;
10006 case OMPC_proc_bind:
10007 Res = ActOnOpenMPProcBindClause(
10008 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
10009 LParenLoc, EndLoc);
10010 break;
10011 case OMPC_atomic_default_mem_order:
10012 Res = ActOnOpenMPAtomicDefaultMemOrderClause(
10013 static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Argument),
10014 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
10015 break;
10016 case OMPC_if:
10017 case OMPC_final:
10018 case OMPC_num_threads:
10019 case OMPC_safelen:
10020 case OMPC_simdlen:
10021 case OMPC_allocator:
10022 case OMPC_collapse:
10023 case OMPC_schedule:
10024 case OMPC_private:
10025 case OMPC_firstprivate:
10026 case OMPC_lastprivate:
10027 case OMPC_shared:
10028 case OMPC_reduction:
10029 case OMPC_task_reduction:
10030 case OMPC_in_reduction:
10031 case OMPC_linear:
10032 case OMPC_aligned:
10033 case OMPC_copyin:
10034 case OMPC_copyprivate:
10035 case OMPC_ordered:
10036 case OMPC_nowait:
10037 case OMPC_untied:
10038 case OMPC_mergeable:
10039 case OMPC_threadprivate:
10040 case OMPC_allocate:
10041 case OMPC_flush:
10042 case OMPC_read:
10043 case OMPC_write:
10044 case OMPC_update:
10045 case OMPC_capture:
10046 case OMPC_seq_cst:
10047 case OMPC_depend:
10048 case OMPC_device:
10049 case OMPC_threads:
10050 case OMPC_simd:
10051 case OMPC_map:
10052 case OMPC_num_teams:
10053 case OMPC_thread_limit:
10054 case OMPC_priority:
10055 case OMPC_grainsize:
10056 case OMPC_nogroup:
10057 case OMPC_num_tasks:
10058 case OMPC_hint:
10059 case OMPC_dist_schedule:
10060 case OMPC_defaultmap:
10061 case OMPC_unknown:
10062 case OMPC_uniform:
10063 case OMPC_to:
10064 case OMPC_from:
10065 case OMPC_use_device_ptr:
10066 case OMPC_is_device_ptr:
10067 case OMPC_unified_address:
10068 case OMPC_unified_shared_memory:
10069 case OMPC_reverse_offload:
10070 case OMPC_dynamic_allocators:
10071 llvm_unreachable("Clause is not allowed.")::llvm::llvm_unreachable_internal("Clause is not allowed.", "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 10071)
;
10072 }
10073 return Res;
10074}
10075
10076static std::string
10077getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
10078 ArrayRef<unsigned> Exclude = llvm::None) {
10079 SmallString<256> Buffer;
10080 llvm::raw_svector_ostream Out(Buffer);
10081 unsigned Bound = Last >= 2 ? Last - 2 : 0;
10082 unsigned Skipped = Exclude.size();
10083 auto S = Exclude.begin(), E = Exclude.end();
10084 for (unsigned I = First; I < Last; ++I) {
10085 if (std::find(S, E, I) != E) {
10086 --Skipped;
10087 continue;
10088 }
10089 Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'";
10090 if (I == Bound - Skipped)
10091 Out << " or ";
10092 else if (I != Bound + 1 - Skipped)
10093 Out << ", ";
10094 }
10095 return Out.str();
10096}
10097
10098OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
10099 SourceLocation KindKwLoc,
10100 SourceLocation StartLoc,
10101 SourceLocation LParenLoc,
10102 SourceLocation EndLoc) {
10103 if (Kind == OMPC_DEFAULT_unknown) {
10104 static_assert(OMPC_DEFAULT_unknown > 0,
10105 "OMPC_DEFAULT_unknown not greater than 0");
10106 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
10107 << getListOfPossibleValues(OMPC_default, /*First=*/0,
10108 /*Last=*/OMPC_DEFAULT_unknown)
10109 << getOpenMPClauseName(OMPC_default);
10110 return nullptr;
10111 }
10112 switch (Kind) {
10113 case OMPC_DEFAULT_none:
10114 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->setDefaultDSANone(KindKwLoc);
10115 break;
10116 case OMPC_DEFAULT_shared:
10117 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->setDefaultDSAShared(KindKwLoc);
10118 break;
10119 case OMPC_DEFAULT_unknown:
10120 llvm_unreachable("Clause kind is not allowed.")::llvm::llvm_unreachable_internal("Clause kind is not allowed."
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 10120)
;
10121 break;
10122 }
10123 return new (Context)
10124 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
10125}
10126
10127OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
10128 SourceLocation KindKwLoc,
10129 SourceLocation StartLoc,
10130 SourceLocation LParenLoc,
10131 SourceLocation EndLoc) {
10132 if (Kind == OMPC_PROC_BIND_unknown) {
10133 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
10134 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
10135 /*Last=*/OMPC_PROC_BIND_unknown)
10136 << getOpenMPClauseName(OMPC_proc_bind);
10137 return nullptr;
10138 }
10139 return new (Context)
10140 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
10141}
10142
10143OMPClause *Sema::ActOnOpenMPAtomicDefaultMemOrderClause(
10144 OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindKwLoc,
10145 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
10146 if (Kind == OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) {
10147 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
10148 << getListOfPossibleValues(
10149 OMPC_atomic_default_mem_order, /*First=*/0,
10150 /*Last=*/OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown)
10151 << getOpenMPClauseName(OMPC_atomic_default_mem_order);
10152 return nullptr;
10153 }
10154 return new (Context) OMPAtomicDefaultMemOrderClause(Kind, KindKwLoc, StartLoc,
10155 LParenLoc, EndLoc);
10156}
10157
10158OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
10159 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
10160 SourceLocation StartLoc, SourceLocation LParenLoc,
10161 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
10162 SourceLocation EndLoc) {
10163 OMPClause *Res = nullptr;
10164 switch (Kind) {
10165 case OMPC_schedule:
10166 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
10167 assert(Argument.size() == NumberOfElements &&((Argument.size() == NumberOfElements && ArgumentLoc.
size() == NumberOfElements) ? static_cast<void> (0) : __assert_fail
("Argument.size() == NumberOfElements && ArgumentLoc.size() == NumberOfElements"
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 10168, __PRETTY_FUNCTION__))
10168 ArgumentLoc.size() == NumberOfElements)((Argument.size() == NumberOfElements && ArgumentLoc.
size() == NumberOfElements) ? static_cast<void> (0) : __assert_fail
("Argument.size() == NumberOfElements && ArgumentLoc.size() == NumberOfElements"
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 10168, __PRETTY_FUNCTION__))
;
10169 Res = ActOnOpenMPScheduleClause(
10170 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
10171 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
10172 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
10173 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
10174 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
10175 break;
10176 case OMPC_if:
10177 assert(Argument.size() == 1 && ArgumentLoc.size() == 1)((Argument.size() == 1 && ArgumentLoc.size() == 1) ? static_cast
<void> (0) : __assert_fail ("Argument.size() == 1 && ArgumentLoc.size() == 1"
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 10177, __PRETTY_FUNCTION__))
;
10178 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
10179 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
10180 DelimLoc, EndLoc);
10181 break;
10182 case OMPC_dist_schedule:
10183 Res = ActOnOpenMPDistScheduleClause(
10184 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
10185 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
10186 break;
10187 case OMPC_defaultmap:
10188 enum { Modifier, DefaultmapKind };
10189 Res = ActOnOpenMPDefaultmapClause(
10190 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
10191 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
10192 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
10193 EndLoc);
10194 break;
10195 case OMPC_final:
10196 case OMPC_num_threads:
10197 case OMPC_safelen:
10198 case OMPC_simdlen:
10199 case OMPC_allocator:
10200 case OMPC_collapse:
10201 case OMPC_default:
10202 case OMPC_proc_bind:
10203 case OMPC_private:
10204 case OMPC_firstprivate:
10205 case OMPC_lastprivate:
10206 case OMPC_shared:
10207 case OMPC_reduction:
10208 case OMPC_task_reduction:
10209 case OMPC_in_reduction:
10210 case OMPC_linear:
10211 case OMPC_aligned:
10212 case OMPC_copyin:
10213 case OMPC_copyprivate:
10214 case OMPC_ordered:
10215 case OMPC_nowait:
10216 case OMPC_untied:
10217 case OMPC_mergeable:
10218 case OMPC_threadprivate:
10219 case OMPC_allocate:
10220 case OMPC_flush:
10221 case OMPC_read:
10222 case OMPC_write:
10223 case OMPC_update:
10224 case OMPC_capture:
10225 case OMPC_seq_cst:
10226 case OMPC_depend:
10227 case OMPC_device:
10228 case OMPC_threads:
10229 case OMPC_simd:
10230 case OMPC_map:
10231 case OMPC_num_teams:
10232 case OMPC_thread_limit:
10233 case OMPC_priority:
10234 case OMPC_grainsize:
10235 case OMPC_nogroup:
10236 case OMPC_num_tasks:
10237 case OMPC_hint:
10238 case OMPC_unknown:
10239 case OMPC_uniform:
10240 case OMPC_to:
10241 case OMPC_from:
10242 case OMPC_use_device_ptr:
10243 case OMPC_is_device_ptr:
10244 case OMPC_unified_address:
10245 case OMPC_unified_shared_memory:
10246 case OMPC_reverse_offload:
10247 case OMPC_dynamic_allocators:
10248 case OMPC_atomic_default_mem_order:
10249 llvm_unreachable("Clause is not allowed.")::llvm::llvm_unreachable_internal("Clause is not allowed.", "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 10249)
;
10250 }
10251 return Res;
10252}
10253
10254static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
10255 OpenMPScheduleClauseModifier M2,
10256 SourceLocation M1Loc, SourceLocation M2Loc) {
10257 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
10258 SmallVector<unsigned, 2> Excluded;
10259 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
10260 Excluded.push_back(M2);
10261 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
10262 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
10263 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
10264 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
10265 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
10266 << getListOfPossibleValues(OMPC_schedule,
10267 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
10268 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
10269 Excluded)
10270 << getOpenMPClauseName(OMPC_schedule);
10271 return true;
10272 }
10273 return false;
10274}
10275
10276OMPClause *Sema::ActOnOpenMPScheduleClause(
10277 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
10278 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
10279 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
10280 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
10281 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
10282 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
10283 return nullptr;
10284 // OpenMP, 2.7.1, Loop Construct, Restrictions
10285 // Either the monotonic modifier or the nonmonotonic modifier can be specified
10286 // but not both.
10287 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
10288 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
10289 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
10290 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
10291 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
10292 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
10293 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
10294 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
10295 return nullptr;
10296 }
10297 if (Kind == OMPC_SCHEDULE_unknown) {
10298 std::string Values;
10299 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
10300 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
10301 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
10302 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
10303 Exclude);
10304 } else {
10305 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
10306 /*Last=*/OMPC_SCHEDULE_unknown);
10307 }
10308 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
10309 << Values << getOpenMPClauseName(OMPC_schedule);
10310 return nullptr;
10311 }
10312 // OpenMP, 2.7.1, Loop Construct, Restrictions
10313 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
10314 // schedule(guided).
10315 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
10316 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
10317 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
10318 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
10319 diag::err_omp_schedule_nonmonotonic_static);
10320 return nullptr;
10321 }
10322 Expr *ValExpr = ChunkSize;
10323 Stmt *HelperValStmt = nullptr;
10324 if (ChunkSize) {
10325 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
10326 !ChunkSize->isInstantiationDependent() &&
10327 !ChunkSize->containsUnexpandedParameterPack()) {
10328 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
10329 ExprResult Val =
10330 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
10331 if (Val.isInvalid())
10332 return nullptr;
10333
10334 ValExpr = Val.get();
10335
10336 // OpenMP [2.7.1, Restrictions]
10337 // chunk_size must be a loop invariant integer expression with a positive
10338 // value.
10339 llvm::APSInt Result;
10340 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
10341 if (Result.isSigned() && !Result.isStrictlyPositive()) {
10342 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
10343 << "schedule" << 1 << ChunkSize->getSourceRange();
10344 return nullptr;
10345 }
10346 } else if (getOpenMPCaptureRegionForClause(
10347 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective(), OMPC_schedule) !=
10348 OMPD_unknown &&
10349 !CurContext->isDependentContext()) {
10350 ValExpr = MakeFullExpr(ValExpr).get();
10351 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
10352 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
10353 HelperValStmt = buildPreInits(Context, Captures);
10354 }
10355 }
10356 }
10357
10358 return new (Context)
10359 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
10360 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
10361}
10362
10363OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
10364 SourceLocation StartLoc,
10365 SourceLocation EndLoc) {
10366 OMPClause *Res = nullptr;
10367 switch (Kind) {
10368 case OMPC_ordered:
10369 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
10370 break;
10371 case OMPC_nowait:
10372 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
10373 break;
10374 case OMPC_untied:
10375 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
10376 break;
10377 case OMPC_mergeable:
10378 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
10379 break;
10380 case OMPC_read:
10381 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
10382 break;
10383 case OMPC_write:
10384 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
10385 break;
10386 case OMPC_update:
10387 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
10388 break;
10389 case OMPC_capture:
10390 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
10391 break;
10392 case OMPC_seq_cst:
10393 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
10394 break;
10395 case OMPC_threads:
10396 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
10397 break;
10398 case OMPC_simd:
10399 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
10400 break;
10401 case OMPC_nogroup:
10402 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
10403 break;
10404 case OMPC_unified_address:
10405 Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc);
10406 break;
10407 case OMPC_unified_shared_memory:
10408 Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
10409 break;
10410 case OMPC_reverse_offload:
10411 Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc);
10412 break;
10413 case OMPC_dynamic_allocators:
10414 Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc);
10415 break;
10416 case OMPC_if:
10417 case OMPC_final:
10418 case OMPC_num_threads:
10419 case OMPC_safelen:
10420 case OMPC_simdlen:
10421 case OMPC_allocator:
10422 case OMPC_collapse:
10423 case OMPC_schedule:
10424 case OMPC_private:
10425 case OMPC_firstprivate:
10426 case OMPC_lastprivate:
10427 case OMPC_shared:
10428 case OMPC_reduction:
10429 case OMPC_task_reduction:
10430 case OMPC_in_reduction:
10431 case OMPC_linear:
10432 case OMPC_aligned:
10433 case OMPC_copyin:
10434 case OMPC_copyprivate:
10435 case OMPC_default:
10436 case OMPC_proc_bind:
10437 case OMPC_threadprivate:
10438 case OMPC_allocate:
10439 case OMPC_flush:
10440 case OMPC_depend:
10441 case OMPC_device:
10442 case OMPC_map:
10443 case OMPC_num_teams:
10444 case OMPC_thread_limit:
10445 case OMPC_priority:
10446 case OMPC_grainsize:
10447 case OMPC_num_tasks:
10448 case OMPC_hint:
10449 case OMPC_dist_schedule:
10450 case OMPC_defaultmap:
10451 case OMPC_unknown:
10452 case OMPC_uniform:
10453 case OMPC_to:
10454 case OMPC_from:
10455 case OMPC_use_device_ptr:
10456 case OMPC_is_device_ptr:
10457 case OMPC_atomic_default_mem_order:
10458 llvm_unreachable("Clause is not allowed.")::llvm::llvm_unreachable_internal("Clause is not allowed.", "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 10458)
;
10459 }
10460 return Res;
10461}
10462
10463OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
10464 SourceLocation EndLoc) {
10465 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->setNowaitRegion();
10466 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
10467}
10468
10469OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
10470 SourceLocation EndLoc) {
10471 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
10472}
10473
10474OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
10475 SourceLocation EndLoc) {
10476 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
10477}
10478
10479OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
10480 SourceLocation EndLoc) {
10481 return new (Context) OMPReadClause(StartLoc, EndLoc);
10482}
10483
10484OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
10485 SourceLocation EndLoc) {
10486 return new (Context) OMPWriteClause(StartLoc, EndLoc);
10487}
10488
10489OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
10490 SourceLocation EndLoc) {
10491 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
10492}
10493
10494OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
10495 SourceLocation EndLoc) {
10496 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
10497}
10498
10499OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
10500 SourceLocation EndLoc) {
10501 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
10502}
10503
10504OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
10505 SourceLocation EndLoc) {
10506 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
10507}
10508
10509OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
10510 SourceLocation EndLoc) {
10511 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
10512}
10513
10514OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
10515 SourceLocation EndLoc) {
10516 return new (Context) OMPNogroupClause(StartLoc, EndLoc);
10517}
10518
10519OMPClause *Sema::ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
10520 SourceLocation EndLoc) {
10521 return new (Context) OMPUnifiedAddressClause(StartLoc, EndLoc);
10522}
10523
10524OMPClause *Sema::ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
10525 SourceLocation EndLoc) {
10526 return new (Context) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
10527}
10528
10529OMPClause *Sema::ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
10530 SourceLocation EndLoc) {
10531 return new (Context) OMPReverseOffloadClause(StartLoc, EndLoc);
10532}
10533
10534OMPClause *Sema::ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
10535 SourceLocation EndLoc) {
10536 return new (Context) OMPDynamicAllocatorsClause(StartLoc, EndLoc);
10537}
10538
10539OMPClause *Sema::ActOnOpenMPVarListClause(
10540 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
10541 const OMPVarListLocTy &Locs, SourceLocation ColonLoc,
10542 CXXScopeSpec &ReductionOrMapperIdScopeSpec,
10543 DeclarationNameInfo &ReductionOrMapperId, OpenMPDependClauseKind DepKind,
10544 OpenMPLinearClauseKind LinKind,
10545 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
10546 ArrayRef<SourceLocation> MapTypeModifiersLoc, OpenMPMapClauseKind MapType,
10547 bool IsMapTypeImplicit, SourceLocation DepLinMapLoc) {
10548 SourceLocation StartLoc = Locs.StartLoc;
10549 SourceLocation LParenLoc = Locs.LParenLoc;
10550 SourceLocation EndLoc = Locs.EndLoc;
10551 OMPClause *Res = nullptr;
10552 switch (Kind) {
10553 case OMPC_private:
10554 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
10555 break;
10556 case OMPC_firstprivate:
10557 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
10558 break;
10559 case OMPC_lastprivate:
10560 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
10561 break;
10562 case OMPC_shared:
10563 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
10564 break;
10565 case OMPC_reduction:
10566 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
10567 EndLoc, ReductionOrMapperIdScopeSpec,
10568 ReductionOrMapperId);
10569 break;
10570 case OMPC_task_reduction:
10571 Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
10572 EndLoc, ReductionOrMapperIdScopeSpec,
10573 ReductionOrMapperId);
10574 break;
10575 case OMPC_in_reduction:
10576 Res = ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
10577 EndLoc, ReductionOrMapperIdScopeSpec,
10578 ReductionOrMapperId);
10579 break;
10580 case OMPC_linear:
10581 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
10582 LinKind, DepLinMapLoc, ColonLoc, EndLoc);
10583 break;
10584 case OMPC_aligned:
10585 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
10586 ColonLoc, EndLoc);
10587 break;
10588 case OMPC_copyin:
10589 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
10590 break;
10591 case OMPC_copyprivate:
10592 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
10593 break;
10594 case OMPC_flush:
10595 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
10596 break;
10597 case OMPC_depend:
10598 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
10599 StartLoc, LParenLoc, EndLoc);
10600 break;
10601 case OMPC_map:
10602 Res = ActOnOpenMPMapClause(MapTypeModifiers, MapTypeModifiersLoc,
10603 ReductionOrMapperIdScopeSpec,
10604 ReductionOrMapperId, MapType, IsMapTypeImplicit,
10605 DepLinMapLoc, ColonLoc, VarList, Locs);
10606 break;
10607 case OMPC_to:
10608 Res = ActOnOpenMPToClause(VarList, ReductionOrMapperIdScopeSpec,
10609 ReductionOrMapperId, Locs);
10610 break;
10611 case OMPC_from:
10612 Res = ActOnOpenMPFromClause(VarList, ReductionOrMapperIdScopeSpec,
10613 ReductionOrMapperId, Locs);
10614 break;
10615 case OMPC_use_device_ptr:
10616 Res = ActOnOpenMPUseDevicePtrClause(VarList, Locs);
10617 break;
10618 case OMPC_is_device_ptr:
10619 Res = ActOnOpenMPIsDevicePtrClause(VarList, Locs);
10620 break;
10621 case OMPC_allocate:
10622 Res = ActOnOpenMPAllocateClause(TailExpr, VarList, StartLoc, LParenLoc,
10623 ColonLoc, EndLoc);
10624 break;
10625 case OMPC_if:
10626 case OMPC_final:
10627 case OMPC_num_threads:
10628 case OMPC_safelen:
10629 case OMPC_simdlen:
10630 case OMPC_allocator:
10631 case OMPC_collapse:
10632 case OMPC_default:
10633 case OMPC_proc_bind:
10634 case OMPC_schedule:
10635 case OMPC_ordered:
10636 case OMPC_nowait:
10637 case OMPC_untied:
10638 case OMPC_mergeable:
10639 case OMPC_threadprivate:
10640 case OMPC_read:
10641 case OMPC_write:
10642 case OMPC_update:
10643 case OMPC_capture:
10644 case OMPC_seq_cst:
10645 case OMPC_device:
10646 case OMPC_threads:
10647 case OMPC_simd:
10648 case OMPC_num_teams:
10649 case OMPC_thread_limit:
10650 case OMPC_priority:
10651 case OMPC_grainsize:
10652 case OMPC_nogroup:
10653 case OMPC_num_tasks:
10654 case OMPC_hint:
10655 case OMPC_dist_schedule:
10656 case OMPC_defaultmap:
10657 case OMPC_unknown:
10658 case OMPC_uniform:
10659 case OMPC_unified_address:
10660 case OMPC_unified_shared_memory:
10661 case OMPC_reverse_offload:
10662 case OMPC_dynamic_allocators:
10663 case OMPC_atomic_default_mem_order:
10664 llvm_unreachable("Clause is not allowed.")::llvm::llvm_unreachable_internal("Clause is not allowed.", "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 10664)
;
10665 }
10666 return Res;
10667}
10668
10669ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
10670 ExprObjectKind OK, SourceLocation Loc) {
10671 ExprResult Res = BuildDeclRefExpr(
10672 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
10673 if (!Res.isUsable())
10674 return ExprError();
10675 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
10676 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
10677 if (!Res.isUsable())
10678 return ExprError();
10679 }
10680 if (VK != VK_LValue && Res.get()->isGLValue()) {
10681 Res = DefaultLvalueConversion(Res.get());
10682 if (!Res.isUsable())
10683 return ExprError();
10684 }
10685 return Res;
10686}
10687
10688OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
10689 SourceLocation StartLoc,
10690 SourceLocation LParenLoc,
10691 SourceLocation EndLoc) {
10692 SmallVector<Expr *, 8> Vars;
10693 SmallVector<Expr *, 8> PrivateCopies;
10694 for (Expr *RefExpr : VarList) {
10695 assert(RefExpr && "NULL expr in OpenMP private clause.")((RefExpr && "NULL expr in OpenMP private clause.") ?
static_cast<void> (0) : __assert_fail ("RefExpr && \"NULL expr in OpenMP private clause.\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 10695, __PRETTY_FUNCTION__))
;
10696 SourceLocation ELoc;
10697 SourceRange ERange;
10698 Expr *SimpleRefExpr = RefExpr;
10699 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
10700 if (Res.second) {
10701 // It will be analyzed later.
10702 Vars.push_back(RefExpr);
10703 PrivateCopies.push_back(nullptr);
10704 }
10705 ValueDecl *D = Res.first;
10706 if (!D)
10707 continue;
10708
10709 QualType Type = D->getType();
10710 auto *VD = dyn_cast<VarDecl>(D);
10711
10712 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
10713 // A variable that appears in a private clause must not have an incomplete
10714 // type or a reference type.
10715 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
10716 continue;
10717 Type = Type.getNonReferenceType();
10718
10719 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
10720 // A variable that is privatized must not have a const-qualified type
10721 // unless it is of class type with a mutable member. This restriction does
10722 // not apply to the firstprivate clause.
10723 //
10724 // OpenMP 3.1 [2.9.3.3, private clause, Restrictions]
10725 // A variable that appears in a private clause must not have a
10726 // const-qualified type unless it is of class type with a mutable member.
10727 if (rejectConstNotMutableType(*this, D, Type, OMPC_private, ELoc))
10728 continue;
10729
10730 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
10731 // in a Construct]
10732 // Variables with the predetermined data-sharing attributes may not be
10733 // listed in data-sharing attributes clauses, except for the cases
10734 // listed below. For these exceptions only, listing a predetermined
10735 // variable in a data-sharing attribute clause is allowed and overrides
10736 // the variable's predetermined data-sharing attributes.
10737 DSAStackTy::DSAVarData DVar = DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getTopDSA(D, /*FromParent=*/false);
10738 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
10739 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
10740 << getOpenMPClauseName(OMPC_private);
10741 reportOriginalDsa(*this, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, D, DVar);
10742 continue;
10743 }
10744
10745 OpenMPDirectiveKind CurrDir = DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective();
10746 // Variably modified types are not supported for tasks.
10747 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
10748 isOpenMPTaskingDirective(CurrDir)) {
10749 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
10750 << getOpenMPClauseName(OMPC_private) << Type
10751 << getOpenMPDirectiveName(CurrDir);
10752 bool IsDecl =
10753 !VD ||
10754 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
10755 Diag(D->getLocation(),
10756 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
10757 << D;
10758 continue;
10759 }
10760
10761 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
10762 // A list item cannot appear in both a map clause and a data-sharing
10763 // attribute clause on the same construct
10764 if (isOpenMPTargetExecutionDirective(CurrDir)) {
10765 OpenMPClauseKind ConflictKind;
10766 if (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->checkMappableExprComponentListsForDecl(
10767 VD, /*CurrentRegionOnly=*/true,
10768 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
10769 OpenMPClauseKind WhereFoundClauseKind) -> bool {
10770 ConflictKind = WhereFoundClauseKind;
10771 return true;
10772 })) {
10773 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
10774 << getOpenMPClauseName(OMPC_private)
10775 << getOpenMPClauseName(ConflictKind)
10776 << getOpenMPDirectiveName(CurrDir);
10777 reportOriginalDsa(*this, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, D, DVar);
10778 continue;
10779 }
10780 }
10781
10782 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
10783 // A variable of class type (or array thereof) that appears in a private
10784 // clause requires an accessible, unambiguous default constructor for the
10785 // class type.
10786 // Generate helper private variable and initialize it with the default
10787 // value. The address of the original variable is replaced by the address of
10788 // the new private variable in CodeGen. This new variable is not added to
10789 // IdResolver, so the code in the OpenMP region uses original variable for
10790 // proper diagnostics.
10791 Type = Type.getUnqualifiedType();
10792 VarDecl *VDPrivate =
10793 buildVarDecl(*this, ELoc, Type, D->getName(),
10794 D->hasAttrs() ? &D->getAttrs() : nullptr,
10795 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
10796 ActOnUninitializedDecl(VDPrivate);
10797 if (VDPrivate->isInvalidDecl())
10798 continue;
10799 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
10800 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
10801
10802 DeclRefExpr *Ref = nullptr;
10803 if (!VD && !CurContext->isDependentContext())
10804 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
10805 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
10806 Vars.push_back((VD || CurContext->isDependentContext())
10807 ? RefExpr->IgnoreParens()
10808 : Ref);
10809 PrivateCopies.push_back(VDPrivateRefExpr);
10810 }
10811
10812 if (Vars.empty())
10813 return nullptr;
10814
10815 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
10816 PrivateCopies);
10817}
10818
10819namespace {
10820class DiagsUninitializedSeveretyRAII {
10821private:
10822 DiagnosticsEngine &Diags;
10823 SourceLocation SavedLoc;
10824 bool IsIgnored = false;
10825
10826public:
10827 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
10828 bool IsIgnored)
10829 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
10830 if (!IsIgnored) {
10831 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
10832 /*Map*/ diag::Severity::Ignored, Loc);
10833 }
10834 }
10835 ~DiagsUninitializedSeveretyRAII() {
10836 if (!IsIgnored)
10837 Diags.popMappings(SavedLoc);
10838 }
10839};
10840}
10841
10842OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
10843 SourceLocation StartLoc,
10844 SourceLocation LParenLoc,
10845 SourceLocation EndLoc) {
10846 SmallVector<Expr *, 8> Vars;
10847 SmallVector<Expr *, 8> PrivateCopies;
10848 SmallVector<Expr *, 8> Inits;
10849 SmallVector<Decl *, 4> ExprCaptures;
10850 bool IsImplicitClause =
10851 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
10852 SourceLocation ImplicitClauseLoc = DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc();
10853
10854 for (Expr *RefExpr : VarList) {
10855 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.")((RefExpr && "NULL expr in OpenMP firstprivate clause."
) ? static_cast<void> (0) : __assert_fail ("RefExpr && \"NULL expr in OpenMP firstprivate clause.\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 10855, __PRETTY_FUNCTION__))
;
10856 SourceLocation ELoc;
10857 SourceRange ERange;
10858 Expr *SimpleRefExpr = RefExpr;
10859 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
10860 if (Res.second) {
10861 // It will be analyzed later.
10862 Vars.push_back(RefExpr);
10863 PrivateCopies.push_back(nullptr);
10864 Inits.push_back(nullptr);
10865 }
10866 ValueDecl *D = Res.first;
10867 if (!D)
10868 continue;
10869
10870 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
10871 QualType Type = D->getType();
10872 auto *VD = dyn_cast<VarDecl>(D);
10873
10874 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
10875 // A variable that appears in a private clause must not have an incomplete
10876 // type or a reference type.
10877 if (RequireCompleteType(ELoc, Type,
10878 diag::err_omp_firstprivate_incomplete_type))
10879 continue;
10880 Type = Type.getNonReferenceType();
10881
10882 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
10883 // A variable of class type (or array thereof) that appears in a private
10884 // clause requires an accessible, unambiguous copy constructor for the
10885 // class type.
10886 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
10887
10888 // If an implicit firstprivate variable found it was checked already.
10889 DSAStackTy::DSAVarData TopDVar;
10890 if (!IsImplicitClause) {
10891 DSAStackTy::DSAVarData DVar =
10892 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getTopDSA(D, /*FromParent=*/false);
10893 TopDVar = DVar;
10894 OpenMPDirectiveKind CurrDir = DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective();
10895 bool IsConstant = ElemType.isConstant(Context);
10896 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
10897 // A list item that specifies a given variable may not appear in more
10898 // than one clause on the same directive, except that a variable may be
10899 // specified in both firstprivate and lastprivate clauses.
10900 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
10901 // A list item may appear in a firstprivate or lastprivate clause but not
10902 // both.
10903 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
10904 (isOpenMPDistributeDirective(CurrDir) ||
10905 DVar.CKind != OMPC_lastprivate) &&
10906 DVar.RefExpr) {
10907 Diag(ELoc, diag::err_omp_wrong_dsa)
10908 << getOpenMPClauseName(DVar.CKind)
10909 << getOpenMPClauseName(OMPC_firstprivate);
10910 reportOriginalDsa(*this, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, D, DVar);
10911 continue;
10912 }
10913
10914 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
10915 // in a Construct]
10916 // Variables with the predetermined data-sharing attributes may not be
10917 // listed in data-sharing attributes clauses, except for the cases
10918 // listed below. For these exceptions only, listing a predetermined
10919 // variable in a data-sharing attribute clause is allowed and overrides
10920 // the variable's predetermined data-sharing attributes.
10921 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
10922 // in a Construct, C/C++, p.2]
10923 // Variables with const-qualified type having no mutable member may be
10924 // listed in a firstprivate clause, even if they are static data members.
10925 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
10926 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
10927 Diag(ELoc, diag::err_omp_wrong_dsa)
10928 << getOpenMPClauseName(DVar.CKind)
10929 << getOpenMPClauseName(OMPC_firstprivate);
10930 reportOriginalDsa(*this, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, D, DVar);
10931 continue;
10932 }
10933
10934 // OpenMP [2.9.3.4, Restrictions, p.2]
10935 // A list item that is private within a parallel region must not appear
10936 // in a firstprivate clause on a worksharing construct if any of the
10937 // worksharing regions arising from the worksharing construct ever bind
10938 // to any of the parallel regions arising from the parallel construct.
10939 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
10940 // A list item that is private within a teams region must not appear in a
10941 // firstprivate clause on a distribute construct if any of the distribute
10942 // regions arising from the distribute construct ever bind to any of the
10943 // teams regions arising from the teams construct.
10944 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
10945 // A list item that appears in a reduction clause of a teams construct
10946 // must not appear in a firstprivate clause on a distribute construct if
10947 // any of the distribute regions arising from the distribute construct
10948 // ever bind to any of the teams regions arising from the teams construct.
10949 if ((isOpenMPWorksharingDirective(CurrDir) ||
10950 isOpenMPDistributeDirective(CurrDir)) &&
10951 !isOpenMPParallelDirective(CurrDir) &&
10952 !isOpenMPTeamsDirective(CurrDir)) {
10953 DVar = DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getImplicitDSA(D, true);
10954 if (DVar.CKind != OMPC_shared &&
10955 (isOpenMPParallelDirective(DVar.DKind) ||
10956 isOpenMPTeamsDirective(DVar.DKind) ||
10957 DVar.DKind == OMPD_unknown)) {
10958 Diag(ELoc, diag::err_omp_required_access)
10959 << getOpenMPClauseName(OMPC_firstprivate)
10960 << getOpenMPClauseName(OMPC_shared);
10961 reportOriginalDsa(*this, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, D, DVar);
10962 continue;
10963 }
10964 }
10965 // OpenMP [2.9.3.4, Restrictions, p.3]
10966 // A list item that appears in a reduction clause of a parallel construct
10967 // must not appear in a firstprivate clause on a worksharing or task
10968 // construct if any of the worksharing or task regions arising from the
10969 // worksharing or task construct ever bind to any of the parallel regions
10970 // arising from the parallel construct.
10971 // OpenMP [2.9.3.4, Restrictions, p.4]
10972 // A list item that appears in a reduction clause in worksharing
10973 // construct must not appear in a firstprivate clause in a task construct
10974 // encountered during execution of any of the worksharing regions arising
10975 // from the worksharing construct.
10976 if (isOpenMPTaskingDirective(CurrDir)) {
10977 DVar = DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasInnermostDSA(
10978 D, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
10979 [](OpenMPDirectiveKind K) {
10980 return isOpenMPParallelDirective(K) ||
10981 isOpenMPWorksharingDirective(K) ||
10982 isOpenMPTeamsDirective(K);
10983 },
10984 /*FromParent=*/true);
10985 if (DVar.CKind == OMPC_reduction &&
10986 (isOpenMPParallelDirective(DVar.DKind) ||
10987 isOpenMPWorksharingDirective(DVar.DKind) ||
10988 isOpenMPTeamsDirective(DVar.DKind))) {
10989 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
10990 << getOpenMPDirectiveName(DVar.DKind);
10991 reportOriginalDsa(*this, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, D, DVar);
10992 continue;
10993 }
10994 }
10995
10996 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
10997 // A list item cannot appear in both a map clause and a data-sharing
10998 // attribute clause on the same construct
10999 if (isOpenMPTargetExecutionDirective(CurrDir)) {
11000 OpenMPClauseKind ConflictKind;
11001 if (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->checkMappableExprComponentListsForDecl(
11002 VD, /*CurrentRegionOnly=*/true,
11003 [&ConflictKind](
11004 OMPClauseMappableExprCommon::MappableExprComponentListRef,
11005 OpenMPClauseKind WhereFoundClauseKind) {
11006 ConflictKind = WhereFoundClauseKind;
11007 return true;
11008 })) {
11009 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
11010 << getOpenMPClauseName(OMPC_firstprivate)
11011 << getOpenMPClauseName(ConflictKind)
11012 << getOpenMPDirectiveName(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective());
11013 reportOriginalDsa(*this, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, D, DVar);
11014 continue;
11015 }
11016 }
11017 }
11018
11019 // Variably modified types are not supported for tasks.
11020 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
11021 isOpenMPTaskingDirective(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective())) {
11022 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
11023 << getOpenMPClauseName(OMPC_firstprivate) << Type
11024 << getOpenMPDirectiveName(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective());
11025 bool IsDecl =
11026 !VD ||
11027 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
11028 Diag(D->getLocation(),
11029 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
11030 << D;
11031 continue;
11032 }
11033
11034 Type = Type.getUnqualifiedType();
11035 VarDecl *VDPrivate =
11036 buildVarDecl(*this, ELoc, Type, D->getName(),
11037 D->hasAttrs() ? &D->getAttrs() : nullptr,
11038 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
11039 // Generate helper private variable and initialize it with the value of the
11040 // original variable. The address of the original variable is replaced by
11041 // the address of the new private variable in the CodeGen. This new variable
11042 // is not added to IdResolver, so the code in the OpenMP region uses
11043 // original variable for proper diagnostics and variable capturing.
11044 Expr *VDInitRefExpr = nullptr;
11045 // For arrays generate initializer for single element and replace it by the
11046 // original array element in CodeGen.
11047 if (Type->isArrayType()) {
11048 VarDecl *VDInit =
11049 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
11050 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
11051 Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get();
11052 ElemType = ElemType.getUnqualifiedType();
11053 VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
11054 ".firstprivate.temp");
11055 InitializedEntity Entity =
11056 InitializedEntity::InitializeVariable(VDInitTemp);
11057 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
11058
11059 InitializationSequence InitSeq(*this, Entity, Kind, Init);
11060 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
11061 if (Result.isInvalid())
11062 VDPrivate->setInvalidDecl();
11063 else
11064 VDPrivate->setInit(Result.getAs<Expr>());
11065 // Remove temp variable declaration.
11066 Context.Deallocate(VDInitTemp);
11067 } else {
11068 VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
11069 ".firstprivate.temp");
11070 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
11071 RefExpr->getExprLoc());
11072 AddInitializerToDecl(VDPrivate,
11073 DefaultLvalueConversion(VDInitRefExpr).get(),
11074 /*DirectInit=*/false);
11075 }
11076 if (VDPrivate->isInvalidDecl()) {
11077 if (IsImplicitClause) {
11078 Diag(RefExpr->getExprLoc(),
11079 diag::note_omp_task_predetermined_firstprivate_here);
11080 }
11081 continue;
11082 }
11083 CurContext->addDecl(VDPrivate);
11084 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
11085 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
11086 RefExpr->getExprLoc());
11087 DeclRefExpr *Ref = nullptr;
11088 if (!VD && !CurContext->isDependentContext()) {
11089 if (TopDVar.CKind == OMPC_lastprivate) {
11090 Ref = TopDVar.PrivateCopy;
11091 } else {
11092 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
11093 if (!isOpenMPCapturedDecl(D))
11094 ExprCaptures.push_back(Ref->getDecl());
11095 }
11096 }
11097 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
11098 Vars.push_back((VD || CurContext->isDependentContext())
11099 ? RefExpr->IgnoreParens()
11100 : Ref);
11101 PrivateCopies.push_back(VDPrivateRefExpr);
11102 Inits.push_back(VDInitRefExpr);
11103 }
11104
11105 if (Vars.empty())
11106 return nullptr;
11107
11108 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11109 Vars, PrivateCopies, Inits,
11110 buildPreInits(Context, ExprCaptures));
11111}
11112
11113OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
11114 SourceLocation StartLoc,
11115 SourceLocation LParenLoc,
11116 SourceLocation EndLoc) {
11117 SmallVector<Expr *, 8> Vars;
11118 SmallVector<Expr *, 8> SrcExprs;
11119 SmallVector<Expr *, 8> DstExprs;
11120 SmallVector<Expr *, 8> AssignmentOps;
11121 SmallVector<Decl *, 4> ExprCaptures;
11122 SmallVector<Expr *, 4> ExprPostUpdates;
11123 for (Expr *RefExpr : VarList) {
11124 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.")((RefExpr && "NULL expr in OpenMP lastprivate clause."
) ? static_cast<void> (0) : __assert_fail ("RefExpr && \"NULL expr in OpenMP lastprivate clause.\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 11124, __PRETTY_FUNCTION__))
;
11125 SourceLocation ELoc;
11126 SourceRange ERange;
11127 Expr *SimpleRefExpr = RefExpr;
11128 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
11129 if (Res.second) {
11130 // It will be analyzed later.
11131 Vars.push_back(RefExpr);
11132 SrcExprs.push_back(nullptr);
11133 DstExprs.push_back(nullptr);
11134 AssignmentOps.push_back(nullptr);
11135 }
11136 ValueDecl *D = Res.first;
11137 if (!D)
11138 continue;
11139
11140 QualType Type = D->getType();
11141 auto *VD = dyn_cast<VarDecl>(D);
11142
11143 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
11144 // A variable that appears in a lastprivate clause must not have an
11145 // incomplete type or a reference type.
11146 if (RequireCompleteType(ELoc, Type,
11147 diag::err_omp_lastprivate_incomplete_type))
11148 continue;
11149 Type = Type.getNonReferenceType();
11150
11151 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
11152 // A variable that is privatized must not have a const-qualified type
11153 // unless it is of class type with a mutable member. This restriction does
11154 // not apply to the firstprivate clause.
11155 //
11156 // OpenMP 3.1 [2.9.3.5, lastprivate clause, Restrictions]
11157 // A variable that appears in a lastprivate clause must not have a
11158 // const-qualified type unless it is of class type with a mutable member.
11159 if (rejectConstNotMutableType(*this, D, Type, OMPC_lastprivate, ELoc))
11160 continue;
11161
11162 OpenMPDirectiveKind CurrDir = DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective();
11163 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
11164 // in a Construct]
11165 // Variables with the predetermined data-sharing attributes may not be
11166 // listed in data-sharing attributes clauses, except for the cases
11167 // listed below.
11168 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
11169 // A list item may appear in a firstprivate or lastprivate clause but not
11170 // both.
11171 DSAStackTy::DSAVarData DVar = DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getTopDSA(D, /*FromParent=*/false);
11172 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
11173 (isOpenMPDistributeDirective(CurrDir) ||
11174 DVar.CKind != OMPC_firstprivate) &&
11175 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
11176 Diag(ELoc, diag::err_omp_wrong_dsa)
11177 << getOpenMPClauseName(DVar.CKind)
11178 << getOpenMPClauseName(OMPC_lastprivate);
11179 reportOriginalDsa(*this, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, D, DVar);
11180 continue;
11181 }
11182
11183 // OpenMP [2.14.3.5, Restrictions, p.2]
11184 // A list item that is private within a parallel region, or that appears in
11185 // the reduction clause of a parallel construct, must not appear in a
11186 // lastprivate clause on a worksharing construct if any of the corresponding
11187 // worksharing regions ever binds to any of the corresponding parallel
11188 // regions.
11189 DSAStackTy::DSAVarData TopDVar = DVar;
11190 if (isOpenMPWorksharingDirective(CurrDir) &&
11191 !isOpenMPParallelDirective(CurrDir) &&
11192 !isOpenMPTeamsDirective(CurrDir)) {
11193 DVar = DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getImplicitDSA(D, true);
11194 if (DVar.CKind != OMPC_shared) {
11195 Diag(ELoc, diag::err_omp_required_access)
11196 << getOpenMPClauseName(OMPC_lastprivate)
11197 << getOpenMPClauseName(OMPC_shared);
11198 reportOriginalDsa(*this, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, D, DVar);
11199 continue;
11200 }
11201 }
11202
11203 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
11204 // A variable of class type (or array thereof) that appears in a
11205 // lastprivate clause requires an accessible, unambiguous default
11206 // constructor for the class type, unless the list item is also specified
11207 // in a firstprivate clause.
11208 // A variable of class type (or array thereof) that appears in a
11209 // lastprivate clause requires an accessible, unambiguous copy assignment
11210 // operator for the class type.
11211 Type = Context.getBaseElementType(Type).getNonReferenceType();
11212 VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(),
11213 Type.getUnqualifiedType(), ".lastprivate.src",
11214 D->hasAttrs() ? &D->getAttrs() : nullptr);
11215 DeclRefExpr *PseudoSrcExpr =
11216 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
11217 VarDecl *DstVD =
11218 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
11219 D->hasAttrs() ? &D->getAttrs() : nullptr);
11220 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
11221 // For arrays generate assignment operation for single element and replace
11222 // it by the original array element in CodeGen.
11223 ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
11224 PseudoDstExpr, PseudoSrcExpr);
11225 if (AssignmentOp.isInvalid())
11226 continue;
11227 AssignmentOp =
11228 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
11229 if (AssignmentOp.isInvalid())
11230 continue;
11231
11232 DeclRefExpr *Ref = nullptr;
11233 if (!VD && !CurContext->isDependentContext()) {
11234 if (TopDVar.CKind == OMPC_firstprivate) {
11235 Ref = TopDVar.PrivateCopy;
11236 } else {
11237 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
11238 if (!isOpenMPCapturedDecl(D))
11239 ExprCaptures.push_back(Ref->getDecl());
11240 }
11241 if (TopDVar.CKind == OMPC_firstprivate ||
11242 (!isOpenMPCapturedDecl(D) &&
11243 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
11244 ExprResult RefRes = DefaultLvalueConversion(Ref);
11245 if (!RefRes.isUsable())
11246 continue;
11247 ExprResult PostUpdateRes =
11248 BuildBinOp(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
11249 RefRes.get());
11250 if (!PostUpdateRes.isUsable())
11251 continue;
11252 ExprPostUpdates.push_back(
11253 IgnoredValueConversions(PostUpdateRes.get()).get());
11254 }
11255 }
11256 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
11257 Vars.push_back((VD || CurContext->isDependentContext())
11258 ? RefExpr->IgnoreParens()
11259 : Ref);
11260 SrcExprs.push_back(PseudoSrcExpr);
11261 DstExprs.push_back(PseudoDstExpr);
11262 AssignmentOps.push_back(AssignmentOp.get());
11263 }
11264
11265 if (Vars.empty())
11266 return nullptr;
11267
11268 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11269 Vars, SrcExprs, DstExprs, AssignmentOps,
11270 buildPreInits(Context, ExprCaptures),
11271 buildPostUpdate(*this, ExprPostUpdates));
11272}
11273
11274OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
11275 SourceLocation StartLoc,
11276 SourceLocation LParenLoc,
11277 SourceLocation EndLoc) {
11278 SmallVector<Expr *, 8> Vars;
11279 for (Expr *RefExpr : VarList) {
11280 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.")((RefExpr && "NULL expr in OpenMP lastprivate clause."
) ? static_cast<void> (0) : __assert_fail ("RefExpr && \"NULL expr in OpenMP lastprivate clause.\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 11280, __PRETTY_FUNCTION__))
;
11281 SourceLocation ELoc;
11282 SourceRange ERange;
11283 Expr *SimpleRefExpr = RefExpr;
11284 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
11285 if (Res.second) {
11286 // It will be analyzed later.
11287 Vars.push_back(RefExpr);
11288 }
11289 ValueDecl *D = Res.first;
11290 if (!D)
11291 continue;
11292
11293 auto *VD = dyn_cast<VarDecl>(D);
11294 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
11295 // in a Construct]
11296 // Variables with the predetermined data-sharing attributes may not be
11297 // listed in data-sharing attributes clauses, except for the cases
11298 // listed below. For these exceptions only, listing a predetermined
11299 // variable in a data-sharing attribute clause is allowed and overrides
11300 // the variable's predetermined data-sharing attributes.
11301 DSAStackTy::DSAVarData DVar = DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getTopDSA(D, /*FromParent=*/false);
11302 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
11303 DVar.RefExpr) {
11304 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
11305 << getOpenMPClauseName(OMPC_shared);
11306 reportOriginalDsa(*this, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, D, DVar);
11307 continue;
11308 }
11309
11310 DeclRefExpr *Ref = nullptr;
11311 if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
11312 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
11313 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
11314 Vars.push_back((VD || !Ref || CurContext->isDependentContext())
11315 ? RefExpr->IgnoreParens()
11316 : Ref);
11317 }
11318
11319 if (Vars.empty())
11320 return nullptr;
11321
11322 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
11323}
11324
11325namespace {
11326class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
11327 DSAStackTy *Stack;
11328
11329public:
11330 bool VisitDeclRefExpr(DeclRefExpr *E) {
11331 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
11332 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
11333 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
11334 return false;
11335 if (DVar.CKind != OMPC_unknown)
11336 return true;
11337 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
11338 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) { return true; },
11339 /*FromParent=*/true);
11340 return DVarPrivate.CKind != OMPC_unknown;
11341 }
11342 return false;
11343 }
11344 bool VisitStmt(Stmt *S) {
11345 for (Stmt *Child : S->children()) {
11346 if (Child && Visit(Child))
11347 return true;
11348 }
11349 return false;
11350 }
11351 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
11352};
11353} // namespace
11354
11355namespace {
11356// Transform MemberExpression for specified FieldDecl of current class to
11357// DeclRefExpr to specified OMPCapturedExprDecl.
11358class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
11359 typedef TreeTransform<TransformExprToCaptures> BaseTransform;
11360 ValueDecl *Field = nullptr;
11361 DeclRefExpr *CapturedExpr = nullptr;
11362
11363public:
11364 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
11365 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
11366
11367 ExprResult TransformMemberExpr(MemberExpr *E) {
11368 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
11369 E->getMemberDecl() == Field) {
11370 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
11371 return CapturedExpr;
11372 }
11373 return BaseTransform::TransformMemberExpr(E);
11374 }
11375 DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
11376};
11377} // namespace
11378
11379template <typename T, typename U>
11380static T filterLookupForUDReductionAndMapper(
11381 SmallVectorImpl<U> &Lookups, const llvm::function_ref<T(ValueDecl *)> Gen) {
11382 for (U &Set : Lookups) {
11383 for (auto *D : Set) {
11384 if (T Res = Gen(cast<ValueDecl>(D)))
11385 return Res;
11386 }
11387 }
11388 return T();
11389}
11390
11391static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
11392 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case")((!LookupResult::isVisible(SemaRef, D) && "not in slow case"
) ? static_cast<void> (0) : __assert_fail ("!LookupResult::isVisible(SemaRef, D) && \"not in slow case\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 11392, __PRETTY_FUNCTION__))
;
11393
11394 for (auto RD : D->redecls()) {
11395 // Don't bother with extra checks if we already know this one isn't visible.
11396 if (RD == D)
11397 continue;
11398
11399 auto ND = cast<NamedDecl>(RD);
11400 if (LookupResult::isVisible(SemaRef, ND))
11401 return ND;
11402 }
11403
11404 return nullptr;
11405}
11406
11407static void
11408argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &Id,
11409 SourceLocation Loc, QualType Ty,
11410 SmallVectorImpl<UnresolvedSet<8>> &Lookups) {
11411 // Find all of the associated namespaces and classes based on the
11412 // arguments we have.
11413 Sema::AssociatedNamespaceSet AssociatedNamespaces;
11414 Sema::AssociatedClassSet AssociatedClasses;
11415 OpaqueValueExpr OVE(Loc, Ty, VK_LValue);
11416 SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces,
11417 AssociatedClasses);
11418
11419 // C++ [basic.lookup.argdep]p3:
11420 // Let X be the lookup set produced by unqualified lookup (3.4.1)
11421 // and let Y be the lookup set produced by argument dependent
11422 // lookup (defined as follows). If X contains [...] then Y is
11423 // empty. Otherwise Y is the set of declarations found in the
11424 // namespaces associated with the argument types as described
11425 // below. The set of declarations found by the lookup of the name
11426 // is the union of X and Y.
11427 //
11428 // Here, we compute Y and add its members to the overloaded
11429 // candidate set.
11430 for (auto *NS : AssociatedNamespaces) {
11431 // When considering an associated namespace, the lookup is the
11432 // same as the lookup performed when the associated namespace is
11433 // used as a qualifier (3.4.3.2) except that:
11434 //
11435 // -- Any using-directives in the associated namespace are
11436 // ignored.
11437 //
11438 // -- Any namespace-scope friend functions declared in
11439 // associated classes are visible within their respective
11440 // namespaces even if they are not visible during an ordinary
11441 // lookup (11.4).
11442 DeclContext::lookup_result R = NS->lookup(Id.getName());
11443 for (auto *D : R) {
11444 auto *Underlying = D;
11445 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
11446 Underlying = USD->getTargetDecl();
11447
11448 if (!isa<OMPDeclareReductionDecl>(Underlying) &&
11449 !isa<OMPDeclareMapperDecl>(Underlying))
11450 continue;
11451
11452 if (!SemaRef.isVisible(D)) {
11453 D = findAcceptableDecl(SemaRef, D);
11454 if (!D)
11455 continue;
11456 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
11457 Underlying = USD->getTargetDecl();
11458 }
11459 Lookups.emplace_back();
11460 Lookups.back().addDecl(Underlying);
11461 }
11462 }
11463}
11464
11465static ExprResult
11466buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
11467 Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
11468 const DeclarationNameInfo &ReductionId, QualType Ty,
11469 CXXCastPath &BasePath, Expr *UnresolvedReduction) {
11470 if (ReductionIdScopeSpec.isInvalid())
11471 return ExprError();
11472 SmallVector<UnresolvedSet<8>, 4> Lookups;
11473 if (S) {
11474 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
11475 Lookup.suppressDiagnostics();
11476 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
11477 NamedDecl *D = Lookup.getRepresentativeDecl();
11478 do {
11479 S = S->getParent();
11480 } while (S && !S->isDeclScope(D));
11481 if (S)
11482 S = S->getParent();
11483 Lookups.emplace_back();
11484 Lookups.back().append(Lookup.begin(), Lookup.end());
11485 Lookup.clear();
11486 }
11487 } else if (auto *ULE =
11488 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
11489 Lookups.push_back(UnresolvedSet<8>());
11490 Decl *PrevD = nullptr;
11491 for (NamedDecl *D : ULE->decls()) {
11492 if (D == PrevD)
11493 Lookups.push_back(UnresolvedSet<8>());
11494 else if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(D))
11495 Lookups.back().addDecl(DRD);
11496 PrevD = D;
11497 }
11498 }
11499 if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
11500 Ty->isInstantiationDependentType() ||
11501 Ty->containsUnexpandedParameterPack() ||
11502 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
11503 return !D->isInvalidDecl() &&
11504 (D->getType()->isDependentType() ||
11505 D->getType()->isInstantiationDependentType() ||
11506 D->getType()->containsUnexpandedParameterPack());
11507 })) {
11508 UnresolvedSet<8> ResSet;
11509 for (const UnresolvedSet<8> &Set : Lookups) {
11510 if (Set.empty())
11511 continue;
11512 ResSet.append(Set.begin(), Set.end());
11513 // The last item marks the end of all declarations at the specified scope.
11514 ResSet.addDecl(Set[Set.size() - 1]);
11515 }
11516 return UnresolvedLookupExpr::Create(
11517 SemaRef.Context, /*NamingClass=*/nullptr,
11518 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
11519 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
11520 }
11521 // Lookup inside the classes.
11522 // C++ [over.match.oper]p3:
11523 // For a unary operator @ with an operand of a type whose
11524 // cv-unqualified version is T1, and for a binary operator @ with
11525 // a left operand of a type whose cv-unqualified version is T1 and
11526 // a right operand of a type whose cv-unqualified version is T2,
11527 // three sets of candidate functions, designated member
11528 // candidates, non-member candidates and built-in candidates, are
11529 // constructed as follows:
11530 // -- If T1 is a complete class type or a class currently being
11531 // defined, the set of member candidates is the result of the
11532 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
11533 // the set of member candidates is empty.
11534 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
11535 Lookup.suppressDiagnostics();
11536 if (const auto *TyRec = Ty->getAs<RecordType>()) {
11537 // Complete the type if it can be completed.
11538 // If the type is neither complete nor being defined, bail out now.
11539 if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() ||
11540 TyRec->getDecl()->getDefinition()) {
11541 Lookup.clear();
11542 SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl());
11543 if (Lookup.empty()) {
11544 Lookups.emplace_back();
11545 Lookups.back().append(Lookup.begin(), Lookup.end());
11546 }
11547 }
11548 }
11549 // Perform ADL.
11550 if (SemaRef.getLangOpts().CPlusPlus)
11551 argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups);
11552 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
11553 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
11554 if (!D->isInvalidDecl() &&
11555 SemaRef.Context.hasSameType(D->getType(), Ty))
11556 return D;
11557 return nullptr;
11558 }))
11559 return SemaRef.BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(),
11560 VK_LValue, Loc);
11561 if (SemaRef.getLangOpts().CPlusPlus) {
11562 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
11563 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
11564 if (!D->isInvalidDecl() &&
11565 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
11566 !Ty.isMoreQualifiedThan(D->getType()))
11567 return D;
11568 return nullptr;
11569 })) {
11570 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
11571 /*DetectVirtual=*/false);
11572 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
11573 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
11574 VD->getType().getUnqualifiedType()))) {
11575 if (SemaRef.CheckBaseClassAccess(
11576 Loc, VD->getType(), Ty, Paths.front(),
11577 /*DiagID=*/0) != Sema::AR_inaccessible) {
11578 SemaRef.BuildBasePathArray(Paths, BasePath);
11579 return SemaRef.BuildDeclRefExpr(
11580 VD, VD->getType().getNonReferenceType(), VK_LValue, Loc);
11581 }
11582 }
11583 }
11584 }
11585 }
11586 if (ReductionIdScopeSpec.isSet()) {
11587 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
11588 return ExprError();
11589 }
11590 return ExprEmpty();
11591}
11592
11593namespace {
11594/// Data for the reduction-based clauses.
11595struct ReductionData {
11596 /// List of original reduction items.
11597 SmallVector<Expr *, 8> Vars;
11598 /// List of private copies of the reduction items.
11599 SmallVector<Expr *, 8> Privates;
11600 /// LHS expressions for the reduction_op expressions.
11601 SmallVector<Expr *, 8> LHSs;
11602 /// RHS expressions for the reduction_op expressions.
11603 SmallVector<Expr *, 8> RHSs;
11604 /// Reduction operation expression.
11605 SmallVector<Expr *, 8> ReductionOps;
11606 /// Taskgroup descriptors for the corresponding reduction items in
11607 /// in_reduction clauses.
11608 SmallVector<Expr *, 8> TaskgroupDescriptors;
11609 /// List of captures for clause.
11610 SmallVector<Decl *, 4> ExprCaptures;
11611 /// List of postupdate expressions.
11612 SmallVector<Expr *, 4> ExprPostUpdates;
11613 ReductionData() = delete;
11614 /// Reserves required memory for the reduction data.
11615 ReductionData(unsigned Size) {
11616 Vars.reserve(Size);
11617 Privates.reserve(Size);
11618 LHSs.reserve(Size);
11619 RHSs.reserve(Size);
11620 ReductionOps.reserve(Size);
11621 TaskgroupDescriptors.reserve(Size);
11622 ExprCaptures.reserve(Size);
11623 ExprPostUpdates.reserve(Size);
11624 }
11625 /// Stores reduction item and reduction operation only (required for dependent
11626 /// reduction item).
11627 void push(Expr *Item, Expr *ReductionOp) {
11628 Vars.emplace_back(Item);
11629 Privates.emplace_back(nullptr);
11630 LHSs.emplace_back(nullptr);
11631 RHSs.emplace_back(nullptr);
11632 ReductionOps.emplace_back(ReductionOp);
11633 TaskgroupDescriptors.emplace_back(nullptr);
11634 }
11635 /// Stores reduction data.
11636 void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
11637 Expr *TaskgroupDescriptor) {
11638 Vars.emplace_back(Item);
11639 Privates.emplace_back(Private);
11640 LHSs.emplace_back(LHS);
11641 RHSs.emplace_back(RHS);
11642 ReductionOps.emplace_back(ReductionOp);
11643 TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
11644 }
11645};
11646} // namespace
11647
11648static bool checkOMPArraySectionConstantForReduction(
11649 ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
11650 SmallVectorImpl<llvm::APSInt> &ArraySizes) {
11651 const Expr *Length = OASE->getLength();
11652 if (Length == nullptr) {
11653 // For array sections of the form [1:] or [:], we would need to analyze
11654 // the lower bound...
11655 if (OASE->getColonLoc().isValid())
11656 return false;
11657
11658 // This is an array subscript which has implicit length 1!
11659 SingleElement = true;
11660 ArraySizes.push_back(llvm::APSInt::get(1));
11661 } else {
11662 Expr::EvalResult Result;
11663 if (!Length->EvaluateAsInt(Result, Context))
11664 return false;
11665
11666 llvm::APSInt ConstantLengthValue = Result.Val.getInt();
11667 SingleElement = (ConstantLengthValue.getSExtValue() == 1);
11668 ArraySizes.push_back(ConstantLengthValue);
11669 }
11670
11671 // Get the base of this array section and walk up from there.
11672 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
11673
11674 // We require length = 1 for all array sections except the right-most to
11675 // guarantee that the memory region is contiguous and has no holes in it.
11676 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
11677 Length = TempOASE->getLength();
11678 if (Length == nullptr) {
11679 // For array sections of the form [1:] or [:], we would need to analyze
11680 // the lower bound...
11681 if (OASE->getColonLoc().isValid())
11682 return false;
11683
11684 // This is an array subscript which has implicit length 1!
11685 ArraySizes.push_back(llvm::APSInt::get(1));
11686 } else {
11687 Expr::EvalResult Result;
11688 if (!Length->EvaluateAsInt(Result, Context))
11689 return false;
11690
11691 llvm::APSInt ConstantLengthValue = Result.Val.getInt();
11692 if (ConstantLengthValue.getSExtValue() != 1)
11693 return false;
11694
11695 ArraySizes.push_back(ConstantLengthValue);
11696 }
11697 Base = TempOASE->getBase()->IgnoreParenImpCasts();
11698 }
11699
11700 // If we have a single element, we don't need to add the implicit lengths.
11701 if (!SingleElement) {
11702 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
11703 // Has implicit length 1!
11704 ArraySizes.push_back(llvm::APSInt::get(1));
11705 Base = TempASE->getBase()->IgnoreParenImpCasts();
11706 }
11707 }
11708
11709 // This array section can be privatized as a single value or as a constant
11710 // sized array.
11711 return true;
11712}
11713
11714static bool actOnOMPReductionKindClause(
11715 Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
11716 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
11717 SourceLocation ColonLoc, SourceLocation EndLoc,
11718 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
11719 ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
11720 DeclarationName DN = ReductionId.getName();
11721 OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator();
11722 BinaryOperatorKind BOK = BO_Comma;
11723
11724 ASTContext &Context = S.Context;
11725 // OpenMP [2.14.3.6, reduction clause]
11726 // C
11727 // reduction-identifier is either an identifier or one of the following
11728 // operators: +, -, *, &, |, ^, && and ||
11729 // C++
11730 // reduction-identifier is either an id-expression or one of the following
11731 // operators: +, -, *, &, |, ^, && and ||
11732 switch (OOK) {
11733 case OO_Plus:
11734 case OO_Minus:
11735 BOK = BO_Add;
11736 break;
11737 case OO_Star:
11738 BOK = BO_Mul;
11739 break;
11740 case OO_Amp:
11741 BOK = BO_And;
11742 break;
11743 case OO_Pipe:
11744 BOK = BO_Or;
11745 break;
11746 case OO_Caret:
11747 BOK = BO_Xor;
11748 break;
11749 case OO_AmpAmp:
11750 BOK = BO_LAnd;
11751 break;
11752 case OO_PipePipe:
11753 BOK = BO_LOr;
11754 break;
11755 case OO_New:
11756 case OO_Delete:
11757 case OO_Array_New:
11758 case OO_Array_Delete:
11759 case OO_Slash:
11760 case OO_Percent:
11761 case OO_Tilde:
11762 case OO_Exclaim:
11763 case OO_Equal:
11764 case OO_Less:
11765 case OO_Greater:
11766 case OO_LessEqual:
11767 case OO_GreaterEqual:
11768 case OO_PlusEqual:
11769 case OO_MinusEqual:
11770 case OO_StarEqual:
11771 case OO_SlashEqual:
11772 case OO_PercentEqual:
11773 case OO_CaretEqual:
11774 case OO_AmpEqual:
11775 case OO_PipeEqual:
11776 case OO_LessLess:
11777 case OO_GreaterGreater:
11778 case OO_LessLessEqual:
11779 case OO_GreaterGreaterEqual:
11780 case OO_EqualEqual:
11781 case OO_ExclaimEqual:
11782 case OO_Spaceship:
11783 case OO_PlusPlus:
11784 case OO_MinusMinus:
11785 case OO_Comma:
11786 case OO_ArrowStar:
11787 case OO_Arrow:
11788 case OO_Call:
11789 case OO_Subscript:
11790 case OO_Conditional:
11791 case OO_Coawait:
11792 case NUM_OVERLOADED_OPERATORS:
11793 llvm_unreachable("Unexpected reduction identifier")::llvm::llvm_unreachable_internal("Unexpected reduction identifier"
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 11793)
;
11794 case OO_None:
11795 if (IdentifierInfo *II = DN.getAsIdentifierInfo()) {
11796 if (II->isStr("max"))
11797 BOK = BO_GT;
11798 else if (II->isStr("min"))
11799 BOK = BO_LT;
11800 }
11801 break;
11802 }
11803 SourceRange ReductionIdRange;
11804 if (ReductionIdScopeSpec.isValid())
11805 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
11806 else
11807 ReductionIdRange.setBegin(ReductionId.getBeginLoc());
11808 ReductionIdRange.setEnd(ReductionId.getEndLoc());
11809
11810 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
11811 bool FirstIter = true;
11812 for (Expr *RefExpr : VarList) {
11813 assert(RefExpr && "nullptr expr in OpenMP reduction clause.")((RefExpr && "nullptr expr in OpenMP reduction clause."
) ? static_cast<void> (0) : __assert_fail ("RefExpr && \"nullptr expr in OpenMP reduction clause.\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 11813, __PRETTY_FUNCTION__))
;
11814 // OpenMP [2.1, C/C++]
11815 // A list item is a variable or array section, subject to the restrictions
11816 // specified in Section 2.4 on page 42 and in each of the sections
11817 // describing clauses and directives for which a list appears.
11818 // OpenMP [2.14.3.3, Restrictions, p.1]
11819 // A variable that is part of another variable (as an array or
11820 // structure element) cannot appear in a private clause.
11821 if (!FirstIter && IR != ER)
11822 ++IR;
11823 FirstIter = false;
11824 SourceLocation ELoc;
11825 SourceRange ERange;
11826 Expr *SimpleRefExpr = RefExpr;
11827 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
11828 /*AllowArraySection=*/true);
11829 if (Res.second) {
11830 // Try to find 'declare reduction' corresponding construct before using
11831 // builtin/overloaded operators.
11832 QualType Type = Context.DependentTy;
11833 CXXCastPath BasePath;
11834 ExprResult DeclareReductionRef = buildDeclareReductionRef(
11835 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
11836 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
11837 Expr *ReductionOp = nullptr;
11838 if (S.CurContext->isDependentContext() &&
11839 (DeclareReductionRef.isUnset() ||
11840 isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
11841 ReductionOp = DeclareReductionRef.get();
11842 // It will be analyzed later.
11843 RD.push(RefExpr, ReductionOp);
11844 }
11845 ValueDecl *D = Res.first;
11846 if (!D)
11847 continue;
11848
11849 Expr *TaskgroupDescriptor = nullptr;
11850 QualType Type;
11851 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
11852 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
11853 if (ASE) {
11854 Type = ASE->getType().getNonReferenceType();
11855 } else if (OASE) {
11856 QualType BaseType =
11857 OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
11858 if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
11859 Type = ATy->getElementType();
11860 else
11861 Type = BaseType->getPointeeType();
11862 Type = Type.getNonReferenceType();
11863 } else {
11864 Type = Context.getBaseElementType(D->getType().getNonReferenceType());
11865 }
11866 auto *VD = dyn_cast<VarDecl>(D);
11867
11868 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
11869 // A variable that appears in a private clause must not have an incomplete
11870 // type or a reference type.
11871 if (S.RequireCompleteType(ELoc, D->getType(),
11872 diag::err_omp_reduction_incomplete_type))
11873 continue;
11874 // OpenMP [2.14.3.6, reduction clause, Restrictions]
11875 // A list item that appears in a reduction clause must not be
11876 // const-qualified.
11877 if (rejectConstNotMutableType(S, D, Type, ClauseKind, ELoc,
11878 /*AcceptIfMutable*/ false, ASE || OASE))
11879 continue;
11880
11881 OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
11882 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
11883 // If a list-item is a reference type then it must bind to the same object
11884 // for all threads of the team.
11885 if (!ASE && !OASE) {
11886 if (VD) {
11887 VarDecl *VDDef = VD->getDefinition();
11888 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
11889 DSARefChecker Check(Stack);
11890 if (Check.Visit(VDDef->getInit())) {
11891 S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
11892 << getOpenMPClauseName(ClauseKind) << ERange;
11893 S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
11894 continue;
11895 }
11896 }
11897 }
11898
11899 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
11900 // in a Construct]
11901 // Variables with the predetermined data-sharing attributes may not be
11902 // listed in data-sharing attributes clauses, except for the cases
11903 // listed below. For these exceptions only, listing a predetermined
11904 // variable in a data-sharing attribute clause is allowed and overrides
11905 // the variable's predetermined data-sharing attributes.
11906 // OpenMP [2.14.3.6, Restrictions, p.3]
11907 // Any number of reduction clauses can be specified on the directive,
11908 // but a list item can appear only once in the reduction clauses for that
11909 // directive.
11910 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
11911 if (DVar.CKind == OMPC_reduction) {
11912 S.Diag(ELoc, diag::err_omp_once_referenced)
11913 << getOpenMPClauseName(ClauseKind);
11914 if (DVar.RefExpr)
11915 S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
11916 continue;
11917 }
11918 if (DVar.CKind != OMPC_unknown) {
11919 S.Diag(ELoc, diag::err_omp_wrong_dsa)
11920 << getOpenMPClauseName(DVar.CKind)
11921 << getOpenMPClauseName(OMPC_reduction);
11922 reportOriginalDsa(S, Stack, D, DVar);
11923 continue;
11924 }
11925
11926 // OpenMP [2.14.3.6, Restrictions, p.1]
11927 // A list item that appears in a reduction clause of a worksharing
11928 // construct must be shared in the parallel regions to which any of the
11929 // worksharing regions arising from the worksharing construct bind.
11930 if (isOpenMPWorksharingDirective(CurrDir) &&
11931 !isOpenMPParallelDirective(CurrDir) &&
11932 !isOpenMPTeamsDirective(CurrDir)) {
11933 DVar = Stack->getImplicitDSA(D, true);
11934 if (DVar.CKind != OMPC_shared) {
11935 S.Diag(ELoc, diag::err_omp_required_access)
11936 << getOpenMPClauseName(OMPC_reduction)
11937 << getOpenMPClauseName(OMPC_shared);
11938 reportOriginalDsa(S, Stack, D, DVar);
11939 continue;
11940 }
11941 }
11942 }
11943
11944 // Try to find 'declare reduction' corresponding construct before using
11945 // builtin/overloaded operators.
11946 CXXCastPath BasePath;
11947 ExprResult DeclareReductionRef = buildDeclareReductionRef(
11948 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
11949 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
11950 if (DeclareReductionRef.isInvalid())
11951 continue;
11952 if (S.CurContext->isDependentContext() &&
11953 (DeclareReductionRef.isUnset() ||
11954 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
11955 RD.push(RefExpr, DeclareReductionRef.get());
11956 continue;
11957 }
11958 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
11959 // Not allowed reduction identifier is found.
11960 S.Diag(ReductionId.getBeginLoc(),
11961 diag::err_omp_unknown_reduction_identifier)
11962 << Type << ReductionIdRange;
11963 continue;
11964 }
11965
11966 // OpenMP [2.14.3.6, reduction clause, Restrictions]
11967 // The type of a list item that appears in a reduction clause must be valid
11968 // for the reduction-identifier. For a max or min reduction in C, the type
11969 // of the list item must be an allowed arithmetic data type: char, int,
11970 // float, double, or _Bool, possibly modified with long, short, signed, or
11971 // unsigned. For a max or min reduction in C++, the type of the list item
11972 // must be an allowed arithmetic data type: char, wchar_t, int, float,
11973 // double, or bool, possibly modified with long, short, signed, or unsigned.
11974 if (DeclareReductionRef.isUnset()) {
11975 if ((BOK == BO_GT || BOK == BO_LT) &&
11976 !(Type->isScalarType() ||
11977 (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
11978 S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
11979 << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
11980 if (!ASE && !OASE) {
11981 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
11982 VarDecl::DeclarationOnly;
11983 S.Diag(D->getLocation(),
11984 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
11985 << D;
11986 }
11987 continue;
11988 }
11989 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
11990 !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
11991 S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
11992 << getOpenMPClauseName(ClauseKind);
11993 if (!ASE && !OASE) {
11994 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
11995 VarDecl::DeclarationOnly;
11996 S.Diag(D->getLocation(),
11997 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
11998 << D;
11999 }
12000 continue;
12001 }
12002 }
12003
12004 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
12005 VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
12006 D->hasAttrs() ? &D->getAttrs() : nullptr);
12007 VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
12008 D->hasAttrs() ? &D->getAttrs() : nullptr);
12009 QualType PrivateTy = Type;
12010
12011 // Try if we can determine constant lengths for all array sections and avoid
12012 // the VLA.
12013 bool ConstantLengthOASE = false;
12014 if (OASE) {
12015 bool SingleElement;
12016 llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
12017 ConstantLengthOASE = checkOMPArraySectionConstantForReduction(
12018 Context, OASE, SingleElement, ArraySizes);
12019
12020 // If we don't have a single element, we must emit a constant array type.
12021 if (ConstantLengthOASE && !SingleElement) {
12022 for (llvm::APSInt &Size : ArraySizes)
12023 PrivateTy = Context.getConstantArrayType(
12024 PrivateTy, Size, ArrayType::Normal, /*IndexTypeQuals=*/0);
12025 }
12026 }
12027
12028 if ((OASE && !ConstantLengthOASE) ||
12029 (!OASE && !ASE &&
12030 D->getType().getNonReferenceType()->isVariablyModifiedType())) {
12031 if (!Context.getTargetInfo().isVLASupported() &&
12032 S.shouldDiagnoseTargetSupportFromOpenMP()) {
12033 S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
12034 S.Diag(ELoc, diag::note_vla_unsupported);
12035 continue;
12036 }
12037 // For arrays/array sections only:
12038 // Create pseudo array type for private copy. The size for this array will
12039 // be generated during codegen.
12040 // For array subscripts or single variables Private Ty is the same as Type
12041 // (type of the variable or single array element).
12042 PrivateTy = Context.getVariableArrayType(
12043 Type,
12044 new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
12045 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
12046 } else if (!ASE && !OASE &&
12047 Context.getAsArrayType(D->getType().getNonReferenceType())) {
12048 PrivateTy = D->getType().getNonReferenceType();
12049 }
12050 // Private copy.
12051 VarDecl *PrivateVD =
12052 buildVarDecl(S, ELoc, PrivateTy, D->getName(),
12053 D->hasAttrs() ? &D->getAttrs() : nullptr,
12054 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
12055 // Add initializer for private variable.
12056 Expr *Init = nullptr;
12057 DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
12058 DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
12059 if (DeclareReductionRef.isUsable()) {
12060 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
12061 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
12062 if (DRD->getInitializer()) {
12063 Init = DRDRef;
12064 RHSVD->setInit(DRDRef);
12065 RHSVD->setInitStyle(VarDecl::CallInit);
12066 }
12067 } else {
12068 switch (BOK) {
12069 case BO_Add:
12070 case BO_Xor:
12071 case BO_Or:
12072 case BO_LOr:
12073 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
12074 if (Type->isScalarType() || Type->isAnyComplexType())
12075 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
12076 break;
12077 case BO_Mul:
12078 case BO_LAnd:
12079 if (Type->isScalarType() || Type->isAnyComplexType()) {
12080 // '*' and '&&' reduction ops - initializer is '1'.
12081 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
12082 }
12083 break;
12084 case BO_And: {
12085 // '&' reduction op - initializer is '~0'.
12086 QualType OrigType = Type;
12087 if (auto *ComplexTy = OrigType->getAs<ComplexType>())
12088 Type = ComplexTy->getElementType();
12089 if (Type->isRealFloatingType()) {
12090 llvm::APFloat InitValue =
12091 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
12092 /*isIEEE=*/true);
12093 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
12094 Type, ELoc);
12095 } else if (Type->isScalarType()) {
12096 uint64_t Size = Context.getTypeSize(Type);
12097 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
12098 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
12099 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
12100 }
12101 if (Init && OrigType->isAnyComplexType()) {
12102 // Init = 0xFFFF + 0xFFFFi;
12103 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
12104 Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
12105 }
12106 Type = OrigType;
12107 break;
12108 }
12109 case BO_LT:
12110 case BO_GT: {
12111 // 'min' reduction op - initializer is 'Largest representable number in
12112 // the reduction list item type'.
12113 // 'max' reduction op - initializer is 'Least representable number in
12114 // the reduction list item type'.
12115 if (Type->isIntegerType() || Type->isPointerType()) {
12116 bool IsSigned = Type->hasSignedIntegerRepresentation();
12117 uint64_t Size = Context.getTypeSize(Type);
12118 QualType IntTy =
12119 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
12120 llvm::APInt InitValue =
12121 (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
12122 : llvm::APInt::getMinValue(Size)
12123 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
12124 : llvm::APInt::getMaxValue(Size);
12125 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
12126 if (Type->isPointerType()) {
12127 // Cast to pointer type.
12128 ExprResult CastExpr = S.BuildCStyleCastExpr(
12129 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
12130 if (CastExpr.isInvalid())
12131 continue;
12132 Init = CastExpr.get();
12133 }
12134 } else if (Type->isRealFloatingType()) {
12135 llvm::APFloat InitValue = llvm::APFloat::getLargest(
12136 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
12137 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
12138 Type, ELoc);
12139 }
12140 break;
12141 }
12142 case BO_PtrMemD:
12143 case BO_PtrMemI:
12144 case BO_MulAssign:
12145 case BO_Div:
12146 case BO_Rem:
12147 case BO_Sub:
12148 case BO_Shl:
12149 case BO_Shr:
12150 case BO_LE:
12151 case BO_GE:
12152 case BO_EQ:
12153 case BO_NE:
12154 case BO_Cmp:
12155 case BO_AndAssign:
12156 case BO_XorAssign:
12157 case BO_OrAssign:
12158 case BO_Assign:
12159 case BO_AddAssign:
12160 case BO_SubAssign:
12161 case BO_DivAssign:
12162 case BO_RemAssign:
12163 case BO_ShlAssign:
12164 case BO_ShrAssign:
12165 case BO_Comma:
12166 llvm_unreachable("Unexpected reduction operation")::llvm::llvm_unreachable_internal("Unexpected reduction operation"
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 12166)
;
12167 }
12168 }
12169 if (Init && DeclareReductionRef.isUnset())
12170 S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
12171 else if (!Init)
12172 S.ActOnUninitializedDecl(RHSVD);
12173 if (RHSVD->isInvalidDecl())
12174 continue;
12175 if (!RHSVD->hasInit() &&
12176 (DeclareReductionRef.isUnset() || !S.LangOpts.CPlusPlus)) {
12177 S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
12178 << Type << ReductionIdRange;
12179 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
12180 VarDecl::DeclarationOnly;
12181 S.Diag(D->getLocation(),
12182 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
12183 << D;
12184 continue;
12185 }
12186 // Store initializer for single element in private copy. Will be used during
12187 // codegen.
12188 PrivateVD->setInit(RHSVD->getInit());
12189 PrivateVD->setInitStyle(RHSVD->getInitStyle());
12190 DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
12191 ExprResult ReductionOp;
12192 if (DeclareReductionRef.isUsable()) {
12193 QualType RedTy = DeclareReductionRef.get()->getType();
12194 QualType PtrRedTy = Context.getPointerType(RedTy);
12195 ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
12196 ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
12197 if (!BasePath.empty()) {
12198 LHS = S.DefaultLvalueConversion(LHS.get());
12199 RHS = S.DefaultLvalueConversion(RHS.get());
12200 LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
12201 CK_UncheckedDerivedToBase, LHS.get(),
12202 &BasePath, LHS.get()->getValueKind());
12203 RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
12204 CK_UncheckedDerivedToBase, RHS.get(),
12205 &BasePath, RHS.get()->getValueKind());
12206 }
12207 FunctionProtoType::ExtProtoInfo EPI;
12208 QualType Params[] = {PtrRedTy, PtrRedTy};
12209 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
12210 auto *OVE = new (Context) OpaqueValueExpr(
12211 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
12212 S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
12213 Expr *Args[] = {LHS.get(), RHS.get()};
12214 ReductionOp =
12215 CallExpr::Create(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
12216 } else {
12217 ReductionOp = S.BuildBinOp(
12218 Stack->getCurScope(), ReductionId.getBeginLoc(), BOK, LHSDRE, RHSDRE);
12219 if (ReductionOp.isUsable()) {
12220 if (BOK != BO_LT && BOK != BO_GT) {
12221 ReductionOp =
12222 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
12223 BO_Assign, LHSDRE, ReductionOp.get());
12224 } else {
12225 auto *ConditionalOp = new (Context)
12226 ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE,
12227 Type, VK_LValue, OK_Ordinary);
12228 ReductionOp =
12229 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
12230 BO_Assign, LHSDRE, ConditionalOp);
12231 }
12232 if (ReductionOp.isUsable())
12233 ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get(),
12234 /*DiscardedValue*/ false);
12235 }
12236 if (!ReductionOp.isUsable())
12237 continue;
12238 }
12239
12240 // OpenMP [2.15.4.6, Restrictions, p.2]
12241 // A list item that appears in an in_reduction clause of a task construct
12242 // must appear in a task_reduction clause of a construct associated with a
12243 // taskgroup region that includes the participating task in its taskgroup
12244 // set. The construct associated with the innermost region that meets this
12245 // condition must specify the same reduction-identifier as the in_reduction
12246 // clause.
12247 if (ClauseKind == OMPC_in_reduction) {
12248 SourceRange ParentSR;
12249 BinaryOperatorKind ParentBOK;
12250 const Expr *ParentReductionOp;
12251 Expr *ParentBOKTD, *ParentReductionOpTD;
12252 DSAStackTy::DSAVarData ParentBOKDSA =
12253 Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
12254 ParentBOKTD);
12255 DSAStackTy::DSAVarData ParentReductionOpDSA =
12256 Stack->getTopMostTaskgroupReductionData(
12257 D, ParentSR, ParentReductionOp, ParentReductionOpTD);
12258 bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
12259 bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
12260 if (!IsParentBOK && !IsParentReductionOp) {
12261 S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
12262 continue;
12263 }
12264 if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
12265 (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
12266 IsParentReductionOp) {
12267 bool EmitError = true;
12268 if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
12269 llvm::FoldingSetNodeID RedId, ParentRedId;
12270 ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
12271 DeclareReductionRef.get()->Profile(RedId, Context,
12272 /*Canonical=*/true);
12273 EmitError = RedId != ParentRedId;
12274 }
12275 if (EmitError) {
12276 S.Diag(ReductionId.getBeginLoc(),
12277 diag::err_omp_reduction_identifier_mismatch)
12278 << ReductionIdRange << RefExpr->getSourceRange();
12279 S.Diag(ParentSR.getBegin(),
12280 diag::note_omp_previous_reduction_identifier)
12281 << ParentSR
12282 << (IsParentBOK ? ParentBOKDSA.RefExpr
12283 : ParentReductionOpDSA.RefExpr)
12284 ->getSourceRange();
12285 continue;
12286 }
12287 }
12288 TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
12289 assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined.")((TaskgroupDescriptor && "Taskgroup descriptor must be defined."
) ? static_cast<void> (0) : __assert_fail ("TaskgroupDescriptor && \"Taskgroup descriptor must be defined.\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 12289, __PRETTY_FUNCTION__))
;
12290 }
12291
12292 DeclRefExpr *Ref = nullptr;
12293 Expr *VarsExpr = RefExpr->IgnoreParens();
12294 if (!VD && !S.CurContext->isDependentContext()) {
12295 if (ASE || OASE) {
12296 TransformExprToCaptures RebuildToCapture(S, D);
12297 VarsExpr =
12298 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
12299 Ref = RebuildToCapture.getCapturedExpr();
12300 } else {
12301 VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
12302 }
12303 if (!S.isOpenMPCapturedDecl(D)) {
12304 RD.ExprCaptures.emplace_back(Ref->getDecl());
12305 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
12306 ExprResult RefRes = S.DefaultLvalueConversion(Ref);
12307 if (!RefRes.isUsable())
12308 continue;
12309 ExprResult PostUpdateRes =
12310 S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
12311 RefRes.get());
12312 if (!PostUpdateRes.isUsable())
12313 continue;
12314 if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
12315 Stack->getCurrentDirective() == OMPD_taskgroup) {
12316 S.Diag(RefExpr->getExprLoc(),
12317 diag::err_omp_reduction_non_addressable_expression)
12318 << RefExpr->getSourceRange();
12319 continue;
12320 }
12321 RD.ExprPostUpdates.emplace_back(
12322 S.IgnoredValueConversions(PostUpdateRes.get()).get());
12323 }
12324 }
12325 }
12326 // All reduction items are still marked as reduction (to do not increase
12327 // code base size).
12328 Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
12329 if (CurrDir == OMPD_taskgroup) {
12330 if (DeclareReductionRef.isUsable())
12331 Stack->addTaskgroupReductionData(D, ReductionIdRange,
12332 DeclareReductionRef.get());
12333 else
12334 Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
12335 }
12336 RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
12337 TaskgroupDescriptor);
12338 }
12339 return RD.Vars.empty();
12340}
12341
12342OMPClause *Sema::ActOnOpenMPReductionClause(
12343 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
12344 SourceLocation ColonLoc, SourceLocation EndLoc,
12345 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
12346 ArrayRef<Expr *> UnresolvedReductions) {
12347 ReductionData RD(VarList.size());
12348 if (actOnOMPReductionKindClause(*this, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, OMPC_reduction, VarList,
12349 StartLoc, LParenLoc, ColonLoc, EndLoc,
12350 ReductionIdScopeSpec, ReductionId,
12351 UnresolvedReductions, RD))
12352 return nullptr;
12353
12354 return OMPReductionClause::Create(
12355 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
12356 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
12357 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
12358 buildPreInits(Context, RD.ExprCaptures),
12359 buildPostUpdate(*this, RD.ExprPostUpdates));
12360}
12361
12362OMPClause *Sema::ActOnOpenMPTaskReductionClause(
12363 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
12364 SourceLocation ColonLoc, SourceLocation EndLoc,
12365 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
12366 ArrayRef<Expr *> UnresolvedReductions) {
12367 ReductionData RD(VarList.size());
12368 if (actOnOMPReductionKindClause(*this, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, OMPC_task_reduction, VarList,
12369 StartLoc, LParenLoc, ColonLoc, EndLoc,
12370 ReductionIdScopeSpec, ReductionId,
12371 UnresolvedReductions, RD))
12372 return nullptr;
12373
12374 return OMPTaskReductionClause::Create(
12375 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
12376 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
12377 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
12378 buildPreInits(Context, RD.ExprCaptures),
12379 buildPostUpdate(*this, RD.ExprPostUpdates));
12380}
12381
12382OMPClause *Sema::ActOnOpenMPInReductionClause(
12383 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
12384 SourceLocation ColonLoc, SourceLocation EndLoc,
12385 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
12386 ArrayRef<Expr *> UnresolvedReductions) {
12387 ReductionData RD(VarList.size());
12388 if (actOnOMPReductionKindClause(*this, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, OMPC_in_reduction, VarList,
12389 StartLoc, LParenLoc, ColonLoc, EndLoc,
12390 ReductionIdScopeSpec, ReductionId,
12391 UnresolvedReductions, RD))
12392 return nullptr;
12393
12394 return OMPInReductionClause::Create(
12395 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
12396 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
12397 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
12398 buildPreInits(Context, RD.ExprCaptures),
12399 buildPostUpdate(*this, RD.ExprPostUpdates));
12400}
12401
12402bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
12403 SourceLocation LinLoc) {
12404 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
12405 LinKind == OMPC_LINEAR_unknown) {
12406 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
12407 return true;
12408 }
12409 return false;
12410}
12411
12412bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
12413 OpenMPLinearClauseKind LinKind,
12414 QualType Type) {
12415 const auto *VD = dyn_cast_or_null<VarDecl>(D);
12416 // A variable must not have an incomplete type or a reference type.
12417 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
12418 return true;
12419 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
12420 !Type->isReferenceType()) {
12421 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
12422 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
12423 return true;
12424 }
12425 Type = Type.getNonReferenceType();
12426
12427 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
12428 // A variable that is privatized must not have a const-qualified type
12429 // unless it is of class type with a mutable member. This restriction does
12430 // not apply to the firstprivate clause.
12431 if (rejectConstNotMutableType(*this, D, Type, OMPC_linear, ELoc))
12432 return true;
12433
12434 // A list item must be of integral or pointer type.
12435 Type = Type.getUnqualifiedType().getCanonicalType();
12436 const auto *Ty = Type.getTypePtrOrNull();
12437 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
12438 !Ty->isPointerType())) {
12439 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
12440 if (D) {
12441 bool IsDecl =
12442 !VD ||
12443 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
12444 Diag(D->getLocation(),
12445 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
12446 << D;
12447 }
12448 return true;
12449 }
12450 return false;
12451}
12452
12453OMPClause *Sema::ActOnOpenMPLinearClause(
12454 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
12455 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
12456 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
12457 SmallVector<Expr *, 8> Vars;
12458 SmallVector<Expr *, 8> Privates;
12459 SmallVector<Expr *, 8> Inits;
12460 SmallVector<Decl *, 4> ExprCaptures;
12461 SmallVector<Expr *, 4> ExprPostUpdates;
12462 if (CheckOpenMPLinearModifier(LinKind, LinLoc))
12463 LinKind = OMPC_LINEAR_val;
12464 for (Expr *RefExpr : VarList) {
12465 assert(RefExpr && "NULL expr in OpenMP linear clause.")((RefExpr && "NULL expr in OpenMP linear clause.") ? static_cast
<void> (0) : __assert_fail ("RefExpr && \"NULL expr in OpenMP linear clause.\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 12465, __PRETTY_FUNCTION__))
;
12466 SourceLocation ELoc;
12467 SourceRange ERange;
12468 Expr *SimpleRefExpr = RefExpr;
12469 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
12470 if (Res.second) {
12471 // It will be analyzed later.
12472 Vars.push_back(RefExpr);
12473 Privates.push_back(nullptr);
12474 Inits.push_back(nullptr);
12475 }
12476 ValueDecl *D = Res.first;
12477 if (!D)
12478 continue;
12479
12480 QualType Type = D->getType();
12481 auto *VD = dyn_cast<VarDecl>(D);
12482
12483 // OpenMP [2.14.3.7, linear clause]
12484 // A list-item cannot appear in more than one linear clause.
12485 // A list-item that appears in a linear clause cannot appear in any
12486 // other data-sharing attribute clause.
12487 DSAStackTy::DSAVarData DVar = DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getTopDSA(D, /*FromParent=*/false);
12488 if (DVar.RefExpr) {
12489 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
12490 << getOpenMPClauseName(OMPC_linear);
12491 reportOriginalDsa(*this, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, D, DVar);
12492 continue;
12493 }
12494
12495 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
12496 continue;
12497 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
12498
12499 // Build private copy of original var.
12500 VarDecl *Private =
12501 buildVarDecl(*this, ELoc, Type, D->getName(),
12502 D->hasAttrs() ? &D->getAttrs() : nullptr,
12503 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
12504 DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
12505 // Build var to save initial value.
12506 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
12507 Expr *InitExpr;
12508 DeclRefExpr *Ref = nullptr;
12509 if (!VD && !CurContext->isDependentContext()) {
12510 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
12511 if (!isOpenMPCapturedDecl(D)) {
12512 ExprCaptures.push_back(Ref->getDecl());
12513 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
12514 ExprResult RefRes = DefaultLvalueConversion(Ref);
12515 if (!RefRes.isUsable())
12516 continue;
12517 ExprResult PostUpdateRes =
12518 BuildBinOp(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurScope(), ELoc, BO_Assign,
12519 SimpleRefExpr, RefRes.get());
12520 if (!PostUpdateRes.isUsable())
12521 continue;
12522 ExprPostUpdates.push_back(
12523 IgnoredValueConversions(PostUpdateRes.get()).get());
12524 }
12525 }
12526 }
12527 if (LinKind == OMPC_LINEAR_uval)
12528 InitExpr = VD ? VD->getInit() : SimpleRefExpr;
12529 else
12530 InitExpr = VD ? SimpleRefExpr : Ref;
12531 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
12532 /*DirectInit=*/false);
12533 DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
12534
12535 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
12536 Vars.push_back((VD || CurContext->isDependentContext())
12537 ? RefExpr->IgnoreParens()
12538 : Ref);
12539 Privates.push_back(PrivateRef);
12540 Inits.push_back(InitRef);
12541 }
12542
12543 if (Vars.empty())
12544 return nullptr;
12545
12546 Expr *StepExpr = Step;
12547 Expr *CalcStepExpr = nullptr;
12548 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
12549 !Step->isInstantiationDependent() &&
12550 !Step->containsUnexpandedParameterPack()) {
12551 SourceLocation StepLoc = Step->getBeginLoc();
12552 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
12553 if (Val.isInvalid())
12554 return nullptr;
12555 StepExpr = Val.get();
12556
12557 // Build var to save the step value.
12558 VarDecl *SaveVar =
12559 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
12560 ExprResult SaveRef =
12561 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
12562 ExprResult CalcStep =
12563 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
12564 CalcStep = ActOnFinishFullExpr(CalcStep.get(), /*DiscardedValue*/ false);
12565
12566 // Warn about zero linear step (it would be probably better specified as
12567 // making corresponding variables 'const').
12568 llvm::APSInt Result;
12569 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
12570 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
12571 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
12572 << (Vars.size() > 1);
12573 if (!IsConstant && CalcStep.isUsable()) {
12574 // Calculate the step beforehand instead of doing this on each iteration.
12575 // (This is not used if the number of iterations may be kfold-ed).
12576 CalcStepExpr = CalcStep.get();
12577 }
12578 }
12579
12580 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
12581 ColonLoc, EndLoc, Vars, Privates, Inits,
12582 StepExpr, CalcStepExpr,
12583 buildPreInits(Context, ExprCaptures),
12584 buildPostUpdate(*this, ExprPostUpdates));
12585}
12586
12587static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
12588 Expr *NumIterations, Sema &SemaRef,
12589 Scope *S, DSAStackTy *Stack) {
12590 // Walk the vars and build update/final expressions for the CodeGen.
12591 SmallVector<Expr *, 8> Updates;
12592 SmallVector<Expr *, 8> Finals;
12593 Expr *Step = Clause.getStep();
12594 Expr *CalcStep = Clause.getCalcStep();
12595 // OpenMP [2.14.3.7, linear clause]
12596 // If linear-step is not specified it is assumed to be 1.
12597 if (!Step)
12598 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
12599 else if (CalcStep)
12600 Step = cast<BinaryOperator>(CalcStep)->getLHS();
12601 bool HasErrors = false;
12602 auto CurInit = Clause.inits().begin();
12603 auto CurPrivate = Clause.privates().begin();
12604 OpenMPLinearClauseKind LinKind = Clause.getModifier();
12605 for (Expr *RefExpr : Clause.varlists()) {
12606 SourceLocation ELoc;
12607 SourceRange ERange;
12608 Expr *SimpleRefExpr = RefExpr;
12609 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange);
12610 ValueDecl *D = Res.first;
12611 if (Res.second || !D) {
12612 Updates.push_back(nullptr);
12613 Finals.push_back(nullptr);
12614 HasErrors = true;
12615 continue;
12616 }
12617 auto &&Info = Stack->isLoopControlVariable(D);
12618 // OpenMP [2.15.11, distribute simd Construct]
12619 // A list item may not appear in a linear clause, unless it is the loop
12620 // iteration variable.
12621 if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
12622 isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
12623 SemaRef.Diag(ELoc,
12624 diag::err_omp_linear_distribute_var_non_loop_iteration);
12625 Updates.push_back(nullptr);
12626 Finals.push_back(nullptr);
12627 HasErrors = true;
12628 continue;
12629 }
12630 Expr *InitExpr = *CurInit;
12631
12632 // Build privatized reference to the current linear var.
12633 auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
12634 Expr *CapturedRef;
12635 if (LinKind == OMPC_LINEAR_uval)
12636 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
12637 else
12638 CapturedRef =
12639 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
12640 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
12641 /*RefersToCapture=*/true);
12642
12643 // Build update: Var = InitExpr + IV * Step
12644 ExprResult Update;
12645 if (!Info.first)
12646 Update =
12647 buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
12648 InitExpr, IV, Step, /* Subtract */ false);
12649 else
12650 Update = *CurPrivate;
12651 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(),
12652 /*DiscardedValue*/ false);
12653
12654 // Build final: Var = InitExpr + NumIterations * Step
12655 ExprResult Final;
12656 if (!Info.first)
12657 Final =
12658 buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
12659 InitExpr, NumIterations, Step, /*Subtract=*/false);
12660 else
12661 Final = *CurPrivate;
12662 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(),
12663 /*DiscardedValue*/ false);
12664
12665 if (!Update.isUsable() || !Final.isUsable()) {
12666 Updates.push_back(nullptr);
12667 Finals.push_back(nullptr);
12668 HasErrors = true;
12669 } else {
12670 Updates.push_back(Update.get());
12671 Finals.push_back(Final.get());
12672 }
12673 ++CurInit;
12674 ++CurPrivate;
12675 }
12676 Clause.setUpdates(Updates);
12677 Clause.setFinals(Finals);
12678 return HasErrors;
12679}
12680
12681OMPClause *Sema::ActOnOpenMPAlignedClause(
12682 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
12683 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
12684 SmallVector<Expr *, 8> Vars;
12685 for (Expr *RefExpr : VarList) {
12686 assert(RefExpr && "NULL expr in OpenMP linear clause.")((RefExpr && "NULL expr in OpenMP linear clause.") ? static_cast
<void> (0) : __assert_fail ("RefExpr && \"NULL expr in OpenMP linear clause.\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 12686, __PRETTY_FUNCTION__))
;
12687 SourceLocation ELoc;
12688 SourceRange ERange;
12689 Expr *SimpleRefExpr = RefExpr;
12690 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
12691 if (Res.second) {
12692 // It will be analyzed later.
12693 Vars.push_back(RefExpr);
12694 }
12695 ValueDecl *D = Res.first;
12696 if (!D)
12697 continue;
12698
12699 QualType QType = D->getType();
12700 auto *VD = dyn_cast<VarDecl>(D);
12701
12702 // OpenMP [2.8.1, simd construct, Restrictions]
12703 // The type of list items appearing in the aligned clause must be
12704 // array, pointer, reference to array, or reference to pointer.
12705 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
12706 const Type *Ty = QType.getTypePtrOrNull();
12707 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
12708 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
12709 << QType << getLangOpts().CPlusPlus << ERange;
12710 bool IsDecl =
12711 !VD ||
12712 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
12713 Diag(D->getLocation(),
12714 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
12715 << D;
12716 continue;
12717 }
12718
12719 // OpenMP [2.8.1, simd construct, Restrictions]
12720 // A list-item cannot appear in more than one aligned clause.
12721 if (const Expr *PrevRef = DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->addUniqueAligned(D, SimpleRefExpr)) {
12722 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
12723 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
12724 << getOpenMPClauseName(OMPC_aligned);
12725 continue;
12726 }
12727
12728 DeclRefExpr *Ref = nullptr;
12729 if (!VD && isOpenMPCapturedDecl(D))
12730 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
12731 Vars.push_back(DefaultFunctionArrayConversion(
12732 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
12733 .get());
12734 }
12735
12736 // OpenMP [2.8.1, simd construct, Description]
12737 // The parameter of the aligned clause, alignment, must be a constant
12738 // positive integer expression.
12739 // If no optional parameter is specified, implementation-defined default
12740 // alignments for SIMD instructions on the target platforms are assumed.
12741 if (Alignment != nullptr) {
12742 ExprResult AlignResult =
12743 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
12744 if (AlignResult.isInvalid())
12745 return nullptr;
12746 Alignment = AlignResult.get();
12747 }
12748 if (Vars.empty())
12749 return nullptr;
12750
12751 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
12752 EndLoc, Vars, Alignment);
12753}
12754
12755OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
12756 SourceLocation StartLoc,
12757 SourceLocation LParenLoc,
12758 SourceLocation EndLoc) {
12759 SmallVector<Expr *, 8> Vars;
12760 SmallVector<Expr *, 8> SrcExprs;
12761 SmallVector<Expr *, 8> DstExprs;
12762 SmallVector<Expr *, 8> AssignmentOps;
12763 for (Expr *RefExpr : VarList) {
12764 assert(RefExpr && "NULL expr in OpenMP copyin clause.")((RefExpr && "NULL expr in OpenMP copyin clause.") ? static_cast
<void> (0) : __assert_fail ("RefExpr && \"NULL expr in OpenMP copyin clause.\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 12764, __PRETTY_FUNCTION__))
;
12765 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
12766 // It will be analyzed later.
12767 Vars.push_back(RefExpr);
12768 SrcExprs.push_back(nullptr);
12769 DstExprs.push_back(nullptr);
12770 AssignmentOps.push_back(nullptr);
12771 continue;
12772 }
12773
12774 SourceLocation ELoc = RefExpr->getExprLoc();
12775 // OpenMP [2.1, C/C++]
12776 // A list item is a variable name.
12777 // OpenMP [2.14.4.1, Restrictions, p.1]
12778 // A list item that appears in a copyin clause must be threadprivate.
12779 auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
12780 if (!DE || !isa<VarDecl>(DE->getDecl())) {
12781 Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
12782 << 0 << RefExpr->getSourceRange();
12783 continue;
12784 }
12785
12786 Decl *D = DE->getDecl();
12787 auto *VD = cast<VarDecl>(D);
12788
12789 QualType Type = VD->getType();
12790 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
12791 // It will be analyzed later.
12792 Vars.push_back(DE);
12793 SrcExprs.push_back(nullptr);
12794 DstExprs.push_back(nullptr);
12795 AssignmentOps.push_back(nullptr);
12796 continue;
12797 }
12798
12799 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
12800 // A list item that appears in a copyin clause must be threadprivate.
12801 if (!DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isThreadPrivate(VD)) {
12802 Diag(ELoc, diag::err_omp_required_access)
12803 << getOpenMPClauseName(OMPC_copyin)
12804 << getOpenMPDirectiveName(OMPD_threadprivate);
12805 continue;
12806 }
12807
12808 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
12809 // A variable of class type (or array thereof) that appears in a
12810 // copyin clause requires an accessible, unambiguous copy assignment
12811 // operator for the class type.
12812 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
12813 VarDecl *SrcVD =
12814 buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(),
12815 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
12816 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(
12817 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
12818 VarDecl *DstVD =
12819 buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst",
12820 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
12821 DeclRefExpr *PseudoDstExpr =
12822 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
12823 // For arrays generate assignment operation for single element and replace
12824 // it by the original array element in CodeGen.
12825 ExprResult AssignmentOp =
12826 BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr,
12827 PseudoSrcExpr);
12828 if (AssignmentOp.isInvalid())
12829 continue;
12830 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
12831 /*DiscardedValue*/ false);
12832 if (AssignmentOp.isInvalid())
12833 continue;
12834
12835 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->addDSA(VD, DE, OMPC_copyin);
12836 Vars.push_back(DE);
12837 SrcExprs.push_back(PseudoSrcExpr);
12838 DstExprs.push_back(PseudoDstExpr);
12839 AssignmentOps.push_back(AssignmentOp.get());
12840 }
12841
12842 if (Vars.empty())
12843 return nullptr;
12844
12845 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
12846 SrcExprs, DstExprs, AssignmentOps);
12847}
12848
12849OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
12850 SourceLocation StartLoc,
12851 SourceLocation LParenLoc,
12852 SourceLocation EndLoc) {
12853 SmallVector<Expr *, 8> Vars;
12854 SmallVector<Expr *, 8> SrcExprs;
12855 SmallVector<Expr *, 8> DstExprs;
12856 SmallVector<Expr *, 8> AssignmentOps;
12857 for (Expr *RefExpr : VarList) {
12858 assert(RefExpr && "NULL expr in OpenMP linear clause.")((RefExpr && "NULL expr in OpenMP linear clause.") ? static_cast
<void> (0) : __assert_fail ("RefExpr && \"NULL expr in OpenMP linear clause.\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 12858, __PRETTY_FUNCTION__))
;
12859 SourceLocation ELoc;
12860 SourceRange ERange;
12861 Expr *SimpleRefExpr = RefExpr;
12862 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
12863 if (Res.second) {
12864 // It will be analyzed later.
12865 Vars.push_back(RefExpr);
12866 SrcExprs.push_back(nullptr);
12867 DstExprs.push_back(nullptr);
12868 AssignmentOps.push_back(nullptr);
12869 }
12870 ValueDecl *D = Res.first;
12871 if (!D)
12872 continue;
12873
12874 QualType Type = D->getType();
12875 auto *VD = dyn_cast<VarDecl>(D);
12876
12877 // OpenMP [2.14.4.2, Restrictions, p.2]
12878 // A list item that appears in a copyprivate clause may not appear in a
12879 // private or firstprivate clause on the single construct.
12880 if (!VD || !DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isThreadPrivate(VD)) {
12881 DSAStackTy::DSAVarData DVar =
12882 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getTopDSA(D, /*FromParent=*/false);
12883 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
12884 DVar.RefExpr) {
12885 Diag(ELoc, diag::err_omp_wrong_dsa)
12886 << getOpenMPClauseName(DVar.CKind)
12887 << getOpenMPClauseName(OMPC_copyprivate);
12888 reportOriginalDsa(*this, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, D, DVar);
12889 continue;
12890 }
12891
12892 // OpenMP [2.11.4.2, Restrictions, p.1]
12893 // All list items that appear in a copyprivate clause must be either
12894 // threadprivate or private in the enclosing context.
12895 if (DVar.CKind == OMPC_unknown) {
12896 DVar = DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getImplicitDSA(D, false);
12897 if (DVar.CKind == OMPC_shared) {
12898 Diag(ELoc, diag::err_omp_required_access)
12899 << getOpenMPClauseName(OMPC_copyprivate)
12900 << "threadprivate or private in the enclosing context";
12901 reportOriginalDsa(*this, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, D, DVar);
12902 continue;
12903 }
12904 }
12905 }
12906
12907 // Variably modified types are not supported.
12908 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
12909 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
12910 << getOpenMPClauseName(OMPC_copyprivate) << Type
12911 << getOpenMPDirectiveName(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective());
12912 bool IsDecl =
12913 !VD ||
12914 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
12915 Diag(D->getLocation(),
12916 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
12917 << D;
12918 continue;
12919 }
12920
12921 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
12922 // A variable of class type (or array thereof) that appears in a
12923 // copyin clause requires an accessible, unambiguous copy assignment
12924 // operator for the class type.
12925 Type = Context.getBaseElementType(Type.getNonReferenceType())
12926 .getUnqualifiedType();
12927 VarDecl *SrcVD =
12928 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src",
12929 D->hasAttrs() ? &D->getAttrs() : nullptr);
12930 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
12931 VarDecl *DstVD =
12932 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst",
12933 D->hasAttrs() ? &D->getAttrs() : nullptr);
12934 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
12935 ExprResult AssignmentOp = BuildBinOp(
12936 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr);
12937 if (AssignmentOp.isInvalid())
12938 continue;
12939 AssignmentOp =
12940 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
12941 if (AssignmentOp.isInvalid())
12942 continue;
12943
12944 // No need to mark vars as copyprivate, they are already threadprivate or
12945 // implicitly private.
12946 assert(VD || isOpenMPCapturedDecl(D))((VD || isOpenMPCapturedDecl(D)) ? static_cast<void> (0
) : __assert_fail ("VD || isOpenMPCapturedDecl(D)", "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 12946, __PRETTY_FUNCTION__))
;
12947 Vars.push_back(
12948 VD ? RefExpr->IgnoreParens()
12949 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
12950 SrcExprs.push_back(PseudoSrcExpr);
12951 DstExprs.push_back(PseudoDstExpr);
12952 AssignmentOps.push_back(AssignmentOp.get());
12953 }
12954
12955 if (Vars.empty())
12956 return nullptr;
12957
12958 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
12959 Vars, SrcExprs, DstExprs, AssignmentOps);
12960}
12961
12962OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
12963 SourceLocation StartLoc,
12964 SourceLocation LParenLoc,
12965 SourceLocation EndLoc) {
12966 if (VarList.empty())
12967 return nullptr;
12968
12969 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
12970}
12971
12972OMPClause *
12973Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
12974 SourceLocation DepLoc, SourceLocation ColonLoc,
12975 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
12976 SourceLocation LParenLoc, SourceLocation EndLoc) {
12977 if (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective() == OMPD_ordered &&
12978 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
12979 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
12980 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
12981 return nullptr;
12982 }
12983 if (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective() != OMPD_ordered &&
12984 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
12985 DepKind == OMPC_DEPEND_sink)) {
12986 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
12987 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
12988 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
12989 /*Last=*/OMPC_DEPEND_unknown, Except)
12990 << getOpenMPClauseName(OMPC_depend);
12991 return nullptr;
12992 }
12993 SmallVector<Expr *, 8> Vars;
12994 DSAStackTy::OperatorOffsetTy OpsOffs;
12995 llvm::APSInt DepCounter(/*BitWidth=*/32);
12996 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
12997 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) {
12998 if (const Expr *OrderedCountExpr =
12999 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getParentOrderedRegionParam().first) {
13000 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
13001 TotalDepCount.setIsUnsigned(/*Val=*/true);
13002 }
13003 }
13004 for (Expr *RefExpr : VarList) {
13005 assert(RefExpr && "NULL expr in OpenMP shared clause.")((RefExpr && "NULL expr in OpenMP shared clause.") ? static_cast
<void> (0) : __assert_fail ("RefExpr && \"NULL expr in OpenMP shared clause.\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 13005, __PRETTY_FUNCTION__))
;
13006 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
13007 // It will be analyzed later.
13008 Vars.push_back(RefExpr);
13009 continue;
13010 }
13011
13012 SourceLocation ELoc = RefExpr->getExprLoc();
13013 Expr *SimpleExpr = RefExpr->IgnoreParenCasts();
13014 if (DepKind == OMPC_DEPEND_sink) {
13015 if (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getParentOrderedRegionParam().first &&
13016 DepCounter >= TotalDepCount) {
13017 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
13018 continue;
13019 }
13020 ++DepCounter;
13021 // OpenMP [2.13.9, Summary]
13022 // depend(dependence-type : vec), where dependence-type is:
13023 // 'sink' and where vec is the iteration vector, which has the form:
13024 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
13025 // where n is the value specified by the ordered clause in the loop
13026 // directive, xi denotes the loop iteration variable of the i-th nested
13027 // loop associated with the loop directive, and di is a constant
13028 // non-negative integer.
13029 if (CurContext->isDependentContext()) {
13030 // It will be analyzed later.
13031 Vars.push_back(RefExpr);
13032 continue;
13033 }
13034 SimpleExpr = SimpleExpr->IgnoreImplicit();
13035 OverloadedOperatorKind OOK = OO_None;
13036 SourceLocation OOLoc;
13037 Expr *LHS = SimpleExpr;
13038 Expr *RHS = nullptr;
13039 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
13040 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
13041 OOLoc = BO->getOperatorLoc();
13042 LHS = BO->getLHS()->IgnoreParenImpCasts();
13043 RHS = BO->getRHS()->IgnoreParenImpCasts();
13044 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
13045 OOK = OCE->getOperator();
13046 OOLoc = OCE->getOperatorLoc();
13047 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
13048 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
13049 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
13050 OOK = MCE->getMethodDecl()
13051 ->getNameInfo()
13052 .getName()
13053 .getCXXOverloadedOperator();
13054 OOLoc = MCE->getCallee()->getExprLoc();
13055 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
13056 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
13057 }
13058 SourceLocation ELoc;
13059 SourceRange ERange;
13060 auto Res = getPrivateItem(*this, LHS, ELoc, ERange);
13061 if (Res.second) {
13062 // It will be analyzed later.
13063 Vars.push_back(RefExpr);
13064 }
13065 ValueDecl *D = Res.first;
13066 if (!D)
13067 continue;
13068
13069 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
13070 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
13071 continue;
13072 }
13073 if (RHS) {
13074 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
13075 RHS, OMPC_depend, /*StrictlyPositive=*/false);
13076 if (RHSRes.isInvalid())
13077 continue;
13078 }
13079 if (!CurContext->isDependentContext() &&
13080 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getParentOrderedRegionParam().first &&
13081 DepCounter != DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isParentLoopControlVariable(D).first) {
13082 const ValueDecl *VD =
13083 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getParentLoopControlVariable(DepCounter.getZExtValue());
13084 if (VD)
13085 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
13086 << 1 << VD;
13087 else
13088 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
13089 continue;
13090 }
13091 OpsOffs.emplace_back(RHS, OOK);
13092 } else {
13093 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
13094 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
13095 (ASE &&
13096 !ASE->getBase()->getType().getNonReferenceType()->isPointerType() &&
13097 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
13098 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
13099 << RefExpr->getSourceRange();
13100 continue;
13101 }
13102 bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
13103 getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
13104 ExprResult Res =
13105 CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RefExpr->IgnoreParenImpCasts());
13106 getDiagnostics().setSuppressAllDiagnostics(Suppress);
13107 if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) {
13108 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
13109 << RefExpr->getSourceRange();
13110 continue;
13111 }
13112 }
13113 Vars.push_back(RefExpr->IgnoreParenImpCasts());
13114 }
13115
13116 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
13117 TotalDepCount > VarList.size() &&
13118 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getParentOrderedRegionParam().first &&
13119 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getParentLoopControlVariable(VarList.size() + 1)) {
13120 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
13121 << 1 << DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getParentLoopControlVariable(VarList.size() + 1);
13122 }
13123 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
13124 Vars.empty())
13125 return nullptr;
13126
13127 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
13128 DepKind, DepLoc, ColonLoc, Vars,
13129 TotalDepCount.getZExtValue());
13130 if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) &&
13131 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isParentOrderedRegion())
13132 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->addDoacrossDependClause(C, OpsOffs);
13133 return C;
13134}
13135
13136OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
13137 SourceLocation LParenLoc,
13138 SourceLocation EndLoc) {
13139 Expr *ValExpr = Device;
13140 Stmt *HelperValStmt = nullptr;
13141
13142 // OpenMP [2.9.1, Restrictions]
13143 // The device expression must evaluate to a non-negative integer value.
13144 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
13145 /*StrictlyPositive=*/false))
13146 return nullptr;
13147
13148 OpenMPDirectiveKind DKind = DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective();
13149 OpenMPDirectiveKind CaptureRegion =
13150 getOpenMPCaptureRegionForClause(DKind, OMPC_device);
13151 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
13152 ValExpr = MakeFullExpr(ValExpr).get();
13153 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
13154 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
13155 HelperValStmt = buildPreInits(Context, Captures);
13156 }
13157
13158 return new (Context) OMPDeviceClause(ValExpr, HelperValStmt, CaptureRegion,
13159 StartLoc, LParenLoc, EndLoc);
13160}
13161
13162static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
13163 DSAStackTy *Stack, QualType QTy,
13164 bool FullCheck = true) {
13165 NamedDecl *ND;
13166 if (QTy->isIncompleteType(&ND)) {
13167 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
13168 return false;
13169 }
13170 if (FullCheck && !SemaRef.CurContext->isDependentContext() &&
13171 !QTy.isTrivialType(SemaRef.Context))
13172 SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR;
13173 return true;
13174}
13175
13176/// Return true if it can be proven that the provided array expression
13177/// (array section or array subscript) does NOT specify the whole size of the
13178/// array whose base type is \a BaseQTy.
13179static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
13180 const Expr *E,
13181 QualType BaseQTy) {
13182 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
13183
13184 // If this is an array subscript, it refers to the whole size if the size of
13185 // the dimension is constant and equals 1. Also, an array section assumes the
13186 // format of an array subscript if no colon is used.
13187 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
13188 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
13189 return ATy->getSize().getSExtValue() != 1;
13190 // Size can't be evaluated statically.
13191 return false;
13192 }
13193
13194 assert(OASE && "Expecting array section if not an array subscript.")((OASE && "Expecting array section if not an array subscript."
) ? static_cast<void> (0) : __assert_fail ("OASE && \"Expecting array section if not an array subscript.\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 13194, __PRETTY_FUNCTION__))
;
13195 const Expr *LowerBound = OASE->getLowerBound();
13196 const Expr *Length = OASE->getLength();
13197
13198 // If there is a lower bound that does not evaluates to zero, we are not
13199 // covering the whole dimension.
13200 if (LowerBound) {
13201 Expr::EvalResult Result;
13202 if (!LowerBound->EvaluateAsInt(Result, SemaRef.getASTContext()))
13203 return false; // Can't get the integer value as a constant.
13204
13205 llvm::APSInt ConstLowerBound = Result.Val.getInt();
13206 if (ConstLowerBound.getSExtValue())
13207 return true;
13208 }
13209
13210 // If we don't have a length we covering the whole dimension.
13211 if (!Length)
13212 return false;
13213
13214 // If the base is a pointer, we don't have a way to get the size of the
13215 // pointee.
13216 if (BaseQTy->isPointerType())
13217 return false;
13218
13219 // We can only check if the length is the same as the size of the dimension
13220 // if we have a constant array.
13221 const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
13222 if (!CATy)
13223 return false;
13224
13225 Expr::EvalResult Result;
13226 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
13227 return false; // Can't get the integer value as a constant.
13228
13229 llvm::APSInt ConstLength = Result.Val.getInt();
13230 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
13231}
13232
13233// Return true if it can be proven that the provided array expression (array
13234// section or array subscript) does NOT specify a single element of the array
13235// whose base type is \a BaseQTy.
13236static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
13237 const Expr *E,
13238 QualType BaseQTy) {
13239 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
13240
13241 // An array subscript always refer to a single element. Also, an array section
13242 // assumes the format of an array subscript if no colon is used.
13243 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
13244 return false;
13245
13246 assert(OASE && "Expecting array section if not an array subscript.")((OASE && "Expecting array section if not an array subscript."
) ? static_cast<void> (0) : __assert_fail ("OASE && \"Expecting array section if not an array subscript.\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 13246, __PRETTY_FUNCTION__))
;
13247 const Expr *Length = OASE->getLength();
13248
13249 // If we don't have a length we have to check if the array has unitary size
13250 // for this dimension. Also, we should always expect a length if the base type
13251 // is pointer.
13252 if (!Length) {
13253 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
13254 return ATy->getSize().getSExtValue() != 1;
13255 // We cannot assume anything.
13256 return false;
13257 }
13258
13259 // Check if the length evaluates to 1.
13260 Expr::EvalResult Result;
13261 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
13262 return false; // Can't get the integer value as a constant.
13263
13264 llvm::APSInt ConstLength = Result.Val.getInt();
13265 return ConstLength.getSExtValue() != 1;
13266}
13267
13268// Return the expression of the base of the mappable expression or null if it
13269// cannot be determined and do all the necessary checks to see if the expression
13270// is valid as a standalone mappable expression. In the process, record all the
13271// components of the expression.
13272static const Expr *checkMapClauseExpressionBase(
13273 Sema &SemaRef, Expr *E,
13274 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
13275 OpenMPClauseKind CKind, bool NoDiagnose) {
13276 SourceLocation ELoc = E->getExprLoc();
13277 SourceRange ERange = E->getSourceRange();
13278
13279 // The base of elements of list in a map clause have to be either:
13280 // - a reference to variable or field.
13281 // - a member expression.
13282 // - an array expression.
13283 //
13284 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
13285 // reference to 'r'.
13286 //
13287 // If we have:
13288 //
13289 // struct SS {
13290 // Bla S;
13291 // foo() {
13292 // #pragma omp target map (S.Arr[:12]);
13293 // }
13294 // }
13295 //
13296 // We want to retrieve the member expression 'this->S';
13297
13298 const Expr *RelevantExpr = nullptr;
13299
13300 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
13301 // If a list item is an array section, it must specify contiguous storage.
13302 //
13303 // For this restriction it is sufficient that we make sure only references
13304 // to variables or fields and array expressions, and that no array sections
13305 // exist except in the rightmost expression (unless they cover the whole
13306 // dimension of the array). E.g. these would be invalid:
13307 //
13308 // r.ArrS[3:5].Arr[6:7]
13309 //
13310 // r.ArrS[3:5].x
13311 //
13312 // but these would be valid:
13313 // r.ArrS[3].Arr[6:7]
13314 //
13315 // r.ArrS[3].x
13316
13317 bool AllowUnitySizeArraySection = true;
13318 bool AllowWholeSizeArraySection = true;
13319
13320 while (!RelevantExpr) {
13321 E = E->IgnoreParenImpCasts();
13322
13323 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
13324 if (!isa<VarDecl>(CurE->getDecl()))
13325 return nullptr;
13326
13327 RelevantExpr = CurE;
13328
13329 // If we got a reference to a declaration, we should not expect any array
13330 // section before that.
13331 AllowUnitySizeArraySection = false;
13332 AllowWholeSizeArraySection = false;
13333
13334 // Record the component.
13335 CurComponents.emplace_back(CurE, CurE->getDecl());
13336 } else if (auto *CurE = dyn_cast<MemberExpr>(E)) {
13337 Expr *BaseE = CurE->getBase()->IgnoreParenImpCasts();
13338
13339 if (isa<CXXThisExpr>(BaseE))
13340 // We found a base expression: this->Val.
13341 RelevantExpr = CurE;
13342 else
13343 E = BaseE;
13344
13345 if (!isa<FieldDecl>(CurE->getMemberDecl())) {
13346 if (!NoDiagnose) {
13347 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
13348 << CurE->getSourceRange();
13349 return nullptr;
13350 }
13351 if (RelevantExpr)
13352 return nullptr;
13353 continue;
13354 }
13355
13356 auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
13357
13358 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
13359 // A bit-field cannot appear in a map clause.
13360 //
13361 if (FD->isBitField()) {
13362 if (!NoDiagnose) {
13363 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
13364 << CurE->getSourceRange() << getOpenMPClauseName(CKind);
13365 return nullptr;
13366 }
13367 if (RelevantExpr)
13368 return nullptr;
13369 continue;
13370 }
13371
13372 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
13373 // If the type of a list item is a reference to a type T then the type
13374 // will be considered to be T for all purposes of this clause.
13375 QualType CurType = BaseE->getType().getNonReferenceType();
13376
13377 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
13378 // A list item cannot be a variable that is a member of a structure with
13379 // a union type.
13380 //
13381 if (CurType->isUnionType()) {
13382 if (!NoDiagnose) {
13383 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
13384 << CurE->getSourceRange();
13385 return nullptr;
13386 }
13387 continue;
13388 }
13389
13390 // If we got a member expression, we should not expect any array section
13391 // before that:
13392 //
13393 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
13394 // If a list item is an element of a structure, only the rightmost symbol
13395 // of the variable reference can be an array section.
13396 //
13397 AllowUnitySizeArraySection = false;
13398 AllowWholeSizeArraySection = false;
13399
13400 // Record the component.
13401 CurComponents.emplace_back(CurE, FD);
13402 } else if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
13403 E = CurE->getBase()->IgnoreParenImpCasts();
13404
13405 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
13406 if (!NoDiagnose) {
13407 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
13408 << 0 << CurE->getSourceRange();
13409 return nullptr;
13410 }
13411 continue;
13412 }
13413
13414 // If we got an array subscript that express the whole dimension we
13415 // can have any array expressions before. If it only expressing part of
13416 // the dimension, we can only have unitary-size array expressions.
13417 if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
13418 E->getType()))
13419 AllowWholeSizeArraySection = false;
13420
13421 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
13422 Expr::EvalResult Result;
13423 if (CurE->getIdx()->EvaluateAsInt(Result, SemaRef.getASTContext())) {
13424 if (!Result.Val.getInt().isNullValue()) {
13425 SemaRef.Diag(CurE->getIdx()->getExprLoc(),
13426 diag::err_omp_invalid_map_this_expr);
13427 SemaRef.Diag(CurE->getIdx()->getExprLoc(),
13428 diag::note_omp_invalid_subscript_on_this_ptr_map);
13429 }
13430 }
13431 RelevantExpr = TE;
13432 }
13433
13434 // Record the component - we don't have any declaration associated.
13435 CurComponents.emplace_back(CurE, nullptr);
13436 } else if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
13437 assert(!NoDiagnose && "Array sections cannot be implicitly mapped.")((!NoDiagnose && "Array sections cannot be implicitly mapped."
) ? static_cast<void> (0) : __assert_fail ("!NoDiagnose && \"Array sections cannot be implicitly mapped.\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 13437, __PRETTY_FUNCTION__))
;
13438 E = CurE->getBase()->IgnoreParenImpCasts();
13439
13440 QualType CurType =
13441 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
13442
13443 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
13444 // If the type of a list item is a reference to a type T then the type
13445 // will be considered to be T for all purposes of this clause.
13446 if (CurType->isReferenceType())
13447 CurType = CurType->getPointeeType();
13448
13449 bool IsPointer = CurType->isAnyPointerType();
13450
13451 if (!IsPointer && !CurType->isArrayType()) {
13452 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
13453 << 0 << CurE->getSourceRange();
13454 return nullptr;
13455 }
13456
13457 bool NotWhole =
13458 checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
13459 bool NotUnity =
13460 checkArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
13461
13462 if (AllowWholeSizeArraySection) {
13463 // Any array section is currently allowed. Allowing a whole size array
13464 // section implies allowing a unity array section as well.
13465 //
13466 // If this array section refers to the whole dimension we can still
13467 // accept other array sections before this one, except if the base is a
13468 // pointer. Otherwise, only unitary sections are accepted.
13469 if (NotWhole || IsPointer)
13470 AllowWholeSizeArraySection = false;
13471 } else if (AllowUnitySizeArraySection && NotUnity) {
13472 // A unity or whole array section is not allowed and that is not
13473 // compatible with the properties of the current array section.
13474 SemaRef.Diag(
13475 ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
13476 << CurE->getSourceRange();
13477 return nullptr;
13478 }
13479
13480 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
13481 Expr::EvalResult ResultR;
13482 Expr::EvalResult ResultL;
13483 if (CurE->getLength()->EvaluateAsInt(ResultR,
13484 SemaRef.getASTContext())) {
13485 if (!ResultR.Val.getInt().isOneValue()) {
13486 SemaRef.Diag(CurE->getLength()->getExprLoc(),
13487 diag::err_omp_invalid_map_this_expr);
13488 SemaRef.Diag(CurE->getLength()->getExprLoc(),
13489 diag::note_omp_invalid_length_on_this_ptr_mapping);
13490 }
13491 }
13492 if (CurE->getLowerBound() && CurE->getLowerBound()->EvaluateAsInt(
13493 ResultL, SemaRef.getASTContext())) {
13494 if (!ResultL.Val.getInt().isNullValue()) {
13495 SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
13496 diag::err_omp_invalid_map_this_expr);
13497 SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
13498 diag::note_omp_invalid_lower_bound_on_this_ptr_mapping);
13499 }
13500 }
13501 RelevantExpr = TE;
13502 }
13503
13504 // Record the component - we don't have any declaration associated.
13505 CurComponents.emplace_back(CurE, nullptr);
13506 } else {
13507 if (!NoDiagnose) {
13508 // If nothing else worked, this is not a valid map clause expression.
13509 SemaRef.Diag(
13510 ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
13511 << ERange;
13512 }
13513 return nullptr;
13514 }
13515 }
13516
13517 return RelevantExpr;
13518}
13519
13520// Return true if expression E associated with value VD has conflicts with other
13521// map information.
13522static bool checkMapConflicts(
13523 Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E,
13524 bool CurrentRegionOnly,
13525 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
13526 OpenMPClauseKind CKind) {
13527 assert(VD && E)((VD && E) ? static_cast<void> (0) : __assert_fail
("VD && E", "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 13527, __PRETTY_FUNCTION__))
;
13528 SourceLocation ELoc = E->getExprLoc();
13529 SourceRange ERange = E->getSourceRange();
13530
13531 // In order to easily check the conflicts we need to match each component of
13532 // the expression under test with the components of the expressions that are
13533 // already in the stack.
13534
13535 assert(!CurComponents.empty() && "Map clause expression with no components!")((!CurComponents.empty() && "Map clause expression with no components!"
) ? static_cast<void> (0) : __assert_fail ("!CurComponents.empty() && \"Map clause expression with no components!\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 13535, __PRETTY_FUNCTION__))
;
13536 assert(CurComponents.back().getAssociatedDeclaration() == VD &&((CurComponents.back().getAssociatedDeclaration() == VD &&
"Map clause expression with unexpected base!") ? static_cast
<void> (0) : __assert_fail ("CurComponents.back().getAssociatedDeclaration() == VD && \"Map clause expression with unexpected base!\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 13537, __PRETTY_FUNCTION__))
13537 "Map clause expression with unexpected base!")((CurComponents.back().getAssociatedDeclaration() == VD &&
"Map clause expression with unexpected base!") ? static_cast
<void> (0) : __assert_fail ("CurComponents.back().getAssociatedDeclaration() == VD && \"Map clause expression with unexpected base!\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 13537, __PRETTY_FUNCTION__))
;
13538
13539 // Variables to help detecting enclosing problems in data environment nests.
13540 bool IsEnclosedByDataEnvironmentExpr = false;
13541 const Expr *EnclosingExpr = nullptr;
13542
13543 bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
13544 VD, CurrentRegionOnly,
13545 [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc,
13546 ERange, CKind, &EnclosingExpr,
13547 CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef
13548 StackComponents,
13549 OpenMPClauseKind) {
13550 assert(!StackComponents.empty() &&((!StackComponents.empty() && "Map clause expression with no components!"
) ? static_cast<void> (0) : __assert_fail ("!StackComponents.empty() && \"Map clause expression with no components!\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 13551, __PRETTY_FUNCTION__))
13551 "Map clause expression with no components!")((!StackComponents.empty() && "Map clause expression with no components!"
) ? static_cast<void> (0) : __assert_fail ("!StackComponents.empty() && \"Map clause expression with no components!\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 13551, __PRETTY_FUNCTION__))
;
13552 assert(StackComponents.back().getAssociatedDeclaration() == VD &&((StackComponents.back().getAssociatedDeclaration() == VD &&
"Map clause expression with unexpected base!") ? static_cast
<void> (0) : __assert_fail ("StackComponents.back().getAssociatedDeclaration() == VD && \"Map clause expression with unexpected base!\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 13553, __PRETTY_FUNCTION__))
13553 "Map clause expression with unexpected base!")((StackComponents.back().getAssociatedDeclaration() == VD &&
"Map clause expression with unexpected base!") ? static_cast
<void> (0) : __assert_fail ("StackComponents.back().getAssociatedDeclaration() == VD && \"Map clause expression with unexpected base!\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 13553, __PRETTY_FUNCTION__))
;
13554 (void)VD;
13555
13556 // The whole expression in the stack.
13557 const Expr *RE = StackComponents.front().getAssociatedExpression();
13558
13559 // Expressions must start from the same base. Here we detect at which
13560 // point both expressions diverge from each other and see if we can
13561 // detect if the memory referred to both expressions is contiguous and
13562 // do not overlap.
13563 auto CI = CurComponents.rbegin();
13564 auto CE = CurComponents.rend();
13565 auto SI = StackComponents.rbegin();
13566 auto SE = StackComponents.rend();
13567 for (; CI != CE && SI != SE; ++CI, ++SI) {
13568
13569 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
13570 // At most one list item can be an array item derived from a given
13571 // variable in map clauses of the same construct.
13572 if (CurrentRegionOnly &&
13573 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
13574 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
13575 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
13576 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
13577 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
13578 diag::err_omp_multiple_array_items_in_map_clause)
13579 << CI->getAssociatedExpression()->getSourceRange();
13580 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
13581 diag::note_used_here)
13582 << SI->getAssociatedExpression()->getSourceRange();
13583 return true;
13584 }
13585
13586 // Do both expressions have the same kind?
13587 if (CI->getAssociatedExpression()->getStmtClass() !=
13588 SI->getAssociatedExpression()->getStmtClass())
13589 break;
13590
13591 // Are we dealing with different variables/fields?
13592 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
13593 break;
13594 }
13595 // Check if the extra components of the expressions in the enclosing
13596 // data environment are redundant for the current base declaration.
13597 // If they are, the maps completely overlap, which is legal.
13598 for (; SI != SE; ++SI) {
13599 QualType Type;
13600 if (const auto *ASE =
13601 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
13602 Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
13603 } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(
13604 SI->getAssociatedExpression())) {
13605 const Expr *E = OASE->getBase()->IgnoreParenImpCasts();
13606 Type =
13607 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
13608 }
13609 if (Type.isNull() || Type->isAnyPointerType() ||
13610 checkArrayExpressionDoesNotReferToWholeSize(
13611 SemaRef, SI->getAssociatedExpression(), Type))
13612 break;
13613 }
13614
13615 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
13616 // List items of map clauses in the same construct must not share
13617 // original storage.
13618 //
13619 // If the expressions are exactly the same or one is a subset of the
13620 // other, it means they are sharing storage.
13621 if (CI == CE && SI == SE) {
13622 if (CurrentRegionOnly) {
13623 if (CKind == OMPC_map) {
13624 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
13625 } else {
13626 assert(CKind == OMPC_to || CKind == OMPC_from)((CKind == OMPC_to || CKind == OMPC_from) ? static_cast<void
> (0) : __assert_fail ("CKind == OMPC_to || CKind == OMPC_from"
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 13626, __PRETTY_FUNCTION__))
;
13627 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
13628 << ERange;
13629 }
13630 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
13631 << RE->getSourceRange();
13632 return true;
13633 }
13634 // If we find the same expression in the enclosing data environment,
13635 // that is legal.
13636 IsEnclosedByDataEnvironmentExpr = true;
13637 return false;
13638 }
13639
13640 QualType DerivedType =
13641 std::prev(CI)->getAssociatedDeclaration()->getType();
13642 SourceLocation DerivedLoc =
13643 std::prev(CI)->getAssociatedExpression()->getExprLoc();
13644
13645 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
13646 // If the type of a list item is a reference to a type T then the type
13647 // will be considered to be T for all purposes of this clause.
13648 DerivedType = DerivedType.getNonReferenceType();
13649
13650 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
13651 // A variable for which the type is pointer and an array section
13652 // derived from that variable must not appear as list items of map
13653 // clauses of the same construct.
13654 //
13655 // Also, cover one of the cases in:
13656 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
13657 // If any part of the original storage of a list item has corresponding
13658 // storage in the device data environment, all of the original storage
13659 // must have corresponding storage in the device data environment.
13660 //
13661 if (DerivedType->isAnyPointerType()) {
13662 if (CI == CE || SI == SE) {
13663 SemaRef.Diag(
13664 DerivedLoc,
13665 diag::err_omp_pointer_mapped_along_with_derived_section)
13666 << DerivedLoc;
13667 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
13668 << RE->getSourceRange();
13669 return true;
13670 }
13671 if (CI->getAssociatedExpression()->getStmtClass() !=
13672 SI->getAssociatedExpression()->getStmtClass() ||
13673 CI->getAssociatedDeclaration()->getCanonicalDecl() ==
13674 SI->getAssociatedDeclaration()->getCanonicalDecl()) {
13675 assert(CI != CE && SI != SE)((CI != CE && SI != SE) ? static_cast<void> (0)
: __assert_fail ("CI != CE && SI != SE", "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 13675, __PRETTY_FUNCTION__))
;
13676 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced)
13677 << DerivedLoc;
13678 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
13679 << RE->getSourceRange();
13680 return true;
13681 }
13682 }
13683
13684 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
13685 // List items of map clauses in the same construct must not share
13686 // original storage.
13687 //
13688 // An expression is a subset of the other.
13689 if (CurrentRegionOnly && (CI == CE || SI == SE)) {
13690 if (CKind == OMPC_map) {
13691 if (CI != CE || SI != SE) {
13692 // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is
13693 // a pointer.
13694 auto Begin =
13695 CI != CE ? CurComponents.begin() : StackComponents.begin();
13696 auto End = CI != CE ? CurComponents.end() : StackComponents.end();
13697 auto It = Begin;
13698 while (It != End && !It->getAssociatedDeclaration())
13699 std::advance(It, 1);
13700 assert(It != End &&((It != End && "Expected at least one component with the declaration."
) ? static_cast<void> (0) : __assert_fail ("It != End && \"Expected at least one component with the declaration.\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 13701, __PRETTY_FUNCTION__))
13701 "Expected at least one component with the declaration.")((It != End && "Expected at least one component with the declaration."
) ? static_cast<void> (0) : __assert_fail ("It != End && \"Expected at least one component with the declaration.\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 13701, __PRETTY_FUNCTION__))
;
13702 if (It != Begin && It->getAssociatedDeclaration()
13703 ->getType()
13704 .getCanonicalType()
13705 ->isAnyPointerType()) {
13706 IsEnclosedByDataEnvironmentExpr = false;
13707 EnclosingExpr = nullptr;
13708 return false;
13709 }
13710 }
13711 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
13712 } else {
13713 assert(CKind == OMPC_to || CKind == OMPC_from)((CKind == OMPC_to || CKind == OMPC_from) ? static_cast<void
> (0) : __assert_fail ("CKind == OMPC_to || CKind == OMPC_from"
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 13713, __PRETTY_FUNCTION__))
;
13714 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
13715 << ERange;
13716 }
13717 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
13718 << RE->getSourceRange();
13719 return true;
13720 }
13721
13722 // The current expression uses the same base as other expression in the
13723 // data environment but does not contain it completely.
13724 if (!CurrentRegionOnly && SI != SE)
13725 EnclosingExpr = RE;
13726
13727 // The current expression is a subset of the expression in the data
13728 // environment.
13729 IsEnclosedByDataEnvironmentExpr |=
13730 (!CurrentRegionOnly && CI != CE && SI == SE);
13731
13732 return false;
13733 });
13734
13735 if (CurrentRegionOnly)
13736 return FoundError;
13737
13738 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
13739 // If any part of the original storage of a list item has corresponding
13740 // storage in the device data environment, all of the original storage must
13741 // have corresponding storage in the device data environment.
13742 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
13743 // If a list item is an element of a structure, and a different element of
13744 // the structure has a corresponding list item in the device data environment
13745 // prior to a task encountering the construct associated with the map clause,
13746 // then the list item must also have a corresponding list item in the device
13747 // data environment prior to the task encountering the construct.
13748 //
13749 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
13750 SemaRef.Diag(ELoc,
13751 diag::err_omp_original_storage_is_shared_and_does_not_contain)
13752 << ERange;
13753 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
13754 << EnclosingExpr->getSourceRange();
13755 return true;
13756 }
13757
13758 return FoundError;
13759}
13760
13761// Look up the user-defined mapper given the mapper name and mapped type, and
13762// build a reference to it.
13763static ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S,
13764 CXXScopeSpec &MapperIdScopeSpec,
13765 const DeclarationNameInfo &MapperId,
13766 QualType Type,
13767 Expr *UnresolvedMapper) {
13768 if (MapperIdScopeSpec.isInvalid())
13769 return ExprError();
13770 // Find all user-defined mappers with the given MapperId.
13771 SmallVector<UnresolvedSet<8>, 4> Lookups;
13772 LookupResult Lookup(SemaRef, MapperId, Sema::LookupOMPMapperName);
13773 Lookup.suppressDiagnostics();
13774 if (S) {
13775 while (S && SemaRef.LookupParsedName(Lookup, S, &MapperIdScopeSpec)) {
13776 NamedDecl *D = Lookup.getRepresentativeDecl();
13777 while (S && !S->isDeclScope(D))
13778 S = S->getParent();
13779 if (S)
13780 S = S->getParent();
13781 Lookups.emplace_back();
13782 Lookups.back().append(Lookup.begin(), Lookup.end());
13783 Lookup.clear();
13784 }
13785 } else if (auto *ULE = cast_or_null<UnresolvedLookupExpr>(UnresolvedMapper)) {
13786 // Extract the user-defined mappers with the given MapperId.
13787 Lookups.push_back(UnresolvedSet<8>());
13788 for (NamedDecl *D : ULE->decls()) {
13789 auto *DMD = cast<OMPDeclareMapperDecl>(D);
13790 assert(DMD && "Expect valid OMPDeclareMapperDecl during instantiation.")((DMD && "Expect valid OMPDeclareMapperDecl during instantiation."
) ? static_cast<void> (0) : __assert_fail ("DMD && \"Expect valid OMPDeclareMapperDecl during instantiation.\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 13790, __PRETTY_FUNCTION__))
;
13791 Lookups.back().addDecl(DMD);
13792 }
13793 }
13794 // Defer the lookup for dependent types. The results will be passed through
13795 // UnresolvedMapper on instantiation.
13796 if (SemaRef.CurContext->isDependentContext() || Type->isDependentType() ||
13797 Type->isInstantiationDependentType() ||
13798 Type->containsUnexpandedParameterPack() ||
13799 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
13800 return !D->isInvalidDecl() &&
13801 (D->getType()->isDependentType() ||
13802 D->getType()->isInstantiationDependentType() ||
13803 D->getType()->containsUnexpandedParameterPack());
13804 })) {
13805 UnresolvedSet<8> URS;
13806 for (const UnresolvedSet<8> &Set : Lookups) {
13807 if (Set.empty())
13808 continue;
13809 URS.append(Set.begin(), Set.end());
13810 }
13811 return UnresolvedLookupExpr::Create(
13812 SemaRef.Context, /*NamingClass=*/nullptr,
13813 MapperIdScopeSpec.getWithLocInContext(SemaRef.Context), MapperId,
13814 /*ADL=*/false, /*Overloaded=*/true, URS.begin(), URS.end());
13815 }
13816 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
13817 // The type must be of struct, union or class type in C and C++
13818 if (!Type->isStructureOrClassType() && !Type->isUnionType())
13819 return ExprEmpty();
13820 SourceLocation Loc = MapperId.getLoc();
13821 // Perform argument dependent lookup.
13822 if (SemaRef.getLangOpts().CPlusPlus && !MapperIdScopeSpec.isSet())
13823 argumentDependentLookup(SemaRef, MapperId, Loc, Type, Lookups);
13824 // Return the first user-defined mapper with the desired type.
13825 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
13826 Lookups, [&SemaRef, Type](ValueDecl *D) -> ValueDecl * {
13827 if (!D->isInvalidDecl() &&
13828 SemaRef.Context.hasSameType(D->getType(), Type))
13829 return D;
13830 return nullptr;
13831 }))
13832 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
13833 // Find the first user-defined mapper with a type derived from the desired
13834 // type.
13835 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
13836 Lookups, [&SemaRef, Type, Loc](ValueDecl *D) -> ValueDecl * {
13837 if (!D->isInvalidDecl() &&
13838 SemaRef.IsDerivedFrom(Loc, Type, D->getType()) &&
13839 !Type.isMoreQualifiedThan(D->getType()))
13840 return D;
13841 return nullptr;
13842 })) {
13843 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
13844 /*DetectVirtual=*/false);
13845 if (SemaRef.IsDerivedFrom(Loc, Type, VD->getType(), Paths)) {
13846 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
13847 VD->getType().getUnqualifiedType()))) {
13848 if (SemaRef.CheckBaseClassAccess(
13849 Loc, VD->getType(), Type, Paths.front(),
13850 /*DiagID=*/0) != Sema::AR_inaccessible) {
13851 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
13852 }
13853 }
13854 }
13855 }
13856 // Report error if a mapper is specified, but cannot be found.
13857 if (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default") {
13858 SemaRef.Diag(Loc, diag::err_omp_invalid_mapper)
13859 << Type << MapperId.getName();
13860 return ExprError();
13861 }
13862 return ExprEmpty();
13863}
13864
13865namespace {
13866// Utility struct that gathers all the related lists associated with a mappable
13867// expression.
13868struct MappableVarListInfo {
13869 // The list of expressions.
13870 ArrayRef<Expr *> VarList;
13871 // The list of processed expressions.
13872 SmallVector<Expr *, 16> ProcessedVarList;
13873 // The mappble components for each expression.
13874 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
13875 // The base declaration of the variable.
13876 SmallVector<ValueDecl *, 16> VarBaseDeclarations;
13877 // The reference to the user-defined mapper associated with every expression.
13878 SmallVector<Expr *, 16> UDMapperList;
13879
13880 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
13881 // We have a list of components and base declarations for each entry in the
13882 // variable list.
13883 VarComponents.reserve(VarList.size());
13884 VarBaseDeclarations.reserve(VarList.size());
13885 }
13886};
13887}
13888
13889// Check the validity of the provided variable list for the provided clause kind
13890// \a CKind. In the check process the valid expressions, mappable expression
13891// components, variables, and user-defined mappers are extracted and used to
13892// fill \a ProcessedVarList, \a VarComponents, \a VarBaseDeclarations, and \a
13893// UDMapperList in MVLI. \a MapType, \a IsMapTypeImplicit, \a MapperIdScopeSpec,
13894// and \a MapperId are expected to be valid if the clause kind is 'map'.
13895static void checkMappableExpressionList(
13896 Sema &SemaRef, DSAStackTy *DSAS, OpenMPClauseKind CKind,
13897 MappableVarListInfo &MVLI, SourceLocation StartLoc,
13898 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo MapperId,
13899 ArrayRef<Expr *> UnresolvedMappers,
13900 OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
13901 bool IsMapTypeImplicit = false) {
13902 // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
13903 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&(((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from
) && "Unexpected clause kind with mappable expressions!"
) ? static_cast<void> (0) : __assert_fail ("(CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) && \"Unexpected clause kind with mappable expressions!\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 13904, __PRETTY_FUNCTION__))
13904 "Unexpected clause kind with mappable expressions!")(((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from
) && "Unexpected clause kind with mappable expressions!"
) ? static_cast<void> (0) : __assert_fail ("(CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) && \"Unexpected clause kind with mappable expressions!\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 13904, __PRETTY_FUNCTION__))
;
13905
13906 // If the identifier of user-defined mapper is not specified, it is "default".
13907 // We do not change the actual name in this clause to distinguish whether a
13908 // mapper is specified explicitly, i.e., it is not explicitly specified when
13909 // MapperId.getName() is empty.
13910 if (!MapperId.getName() || MapperId.getName().isEmpty()) {
13911 auto &DeclNames = SemaRef.getASTContext().DeclarationNames;
13912 MapperId.setName(DeclNames.getIdentifier(
13913 &SemaRef.getASTContext().Idents.get("default")));
13914 }
13915
13916 // Iterators to find the current unresolved mapper expression.
13917 auto UMIt = UnresolvedMappers.begin(), UMEnd = UnresolvedMappers.end();
13918 bool UpdateUMIt = false;
13919 Expr *UnresolvedMapper = nullptr;
13920
13921 // Keep track of the mappable components and base declarations in this clause.
13922 // Each entry in the list is going to have a list of components associated. We
13923 // record each set of the components so that we can build the clause later on.
13924 // In the end we should have the same amount of declarations and component
13925 // lists.
13926
13927 for (Expr *RE : MVLI.VarList) {
13928 assert(RE && "Null expr in omp to/from/map clause")((RE && "Null expr in omp to/from/map clause") ? static_cast
<void> (0) : __assert_fail ("RE && \"Null expr in omp to/from/map clause\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 13928, __PRETTY_FUNCTION__))
;
13929 SourceLocation ELoc = RE->getExprLoc();
13930
13931 // Find the current unresolved mapper expression.
13932 if (UpdateUMIt && UMIt != UMEnd) {
13933 UMIt++;
13934 assert(((UMIt != UMEnd && "Expect the size of UnresolvedMappers to match with that of VarList"
) ? static_cast<void> (0) : __assert_fail ("UMIt != UMEnd && \"Expect the size of UnresolvedMappers to match with that of VarList\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 13936, __PRETTY_FUNCTION__))
13935 UMIt != UMEnd &&((UMIt != UMEnd && "Expect the size of UnresolvedMappers to match with that of VarList"
) ? static_cast<void> (0) : __assert_fail ("UMIt != UMEnd && \"Expect the size of UnresolvedMappers to match with that of VarList\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 13936, __PRETTY_FUNCTION__))
13936 "Expect the size of UnresolvedMappers to match with that of VarList")((UMIt != UMEnd && "Expect the size of UnresolvedMappers to match with that of VarList"
) ? static_cast<void> (0) : __assert_fail ("UMIt != UMEnd && \"Expect the size of UnresolvedMappers to match with that of VarList\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 13936, __PRETTY_FUNCTION__))
;
13937 }
13938 UpdateUMIt = true;
13939 if (UMIt != UMEnd)
13940 UnresolvedMapper = *UMIt;
13941
13942 const Expr *VE = RE->IgnoreParenLValueCasts();
13943
13944 if (VE->isValueDependent() || VE->isTypeDependent() ||
13945 VE->isInstantiationDependent() ||
13946 VE->containsUnexpandedParameterPack()) {
13947 // Try to find the associated user-defined mapper.
13948 ExprResult ER = buildUserDefinedMapperRef(
13949 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
13950 VE->getType().getCanonicalType(), UnresolvedMapper);
13951 if (ER.isInvalid())
13952 continue;
13953 MVLI.UDMapperList.push_back(ER.get());
13954 // We can only analyze this information once the missing information is
13955 // resolved.
13956 MVLI.ProcessedVarList.push_back(RE);
13957 continue;
13958 }
13959
13960 Expr *SimpleExpr = RE->IgnoreParenCasts();
13961
13962 if (!RE->IgnoreParenImpCasts()->isLValue()) {
13963 SemaRef.Diag(ELoc,
13964 diag::err_omp_expected_named_var_member_or_array_expression)
13965 << RE->getSourceRange();
13966 continue;
13967 }
13968
13969 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
13970 ValueDecl *CurDeclaration = nullptr;
13971
13972 // Obtain the array or member expression bases if required. Also, fill the
13973 // components array with all the components identified in the process.
13974 const Expr *BE = checkMapClauseExpressionBase(
13975 SemaRef, SimpleExpr, CurComponents, CKind, /*NoDiagnose=*/false);
13976 if (!BE)
13977 continue;
13978
13979 assert(!CurComponents.empty() &&((!CurComponents.empty() && "Invalid mappable expression information."
) ? static_cast<void> (0) : __assert_fail ("!CurComponents.empty() && \"Invalid mappable expression information.\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 13980, __PRETTY_FUNCTION__))
13980 "Invalid mappable expression information.")((!CurComponents.empty() && "Invalid mappable expression information."
) ? static_cast<void> (0) : __assert_fail ("!CurComponents.empty() && \"Invalid mappable expression information.\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 13980, __PRETTY_FUNCTION__))
;
13981
13982 if (const auto *TE = dyn_cast<CXXThisExpr>(BE)) {
13983 // Add store "this" pointer to class in DSAStackTy for future checking
13984 DSAS->addMappedClassesQualTypes(TE->getType());
13985 // Try to find the associated user-defined mapper.
13986 ExprResult ER = buildUserDefinedMapperRef(
13987 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
13988 VE->getType().getCanonicalType(), UnresolvedMapper);
13989 if (ER.isInvalid())
13990 continue;
13991 MVLI.UDMapperList.push_back(ER.get());
13992 // Skip restriction checking for variable or field declarations
13993 MVLI.ProcessedVarList.push_back(RE);
13994 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
13995 MVLI.VarComponents.back().append(CurComponents.begin(),
13996 CurComponents.end());
13997 MVLI.VarBaseDeclarations.push_back(nullptr);
13998 continue;
13999 }
14000
14001 // For the following checks, we rely on the base declaration which is
14002 // expected to be associated with the last component. The declaration is
14003 // expected to be a variable or a field (if 'this' is being mapped).
14004 CurDeclaration = CurComponents.back().getAssociatedDeclaration();
14005 assert(CurDeclaration && "Null decl on map clause.")((CurDeclaration && "Null decl on map clause.") ? static_cast
<void> (0) : __assert_fail ("CurDeclaration && \"Null decl on map clause.\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 14005, __PRETTY_FUNCTION__))
;
14006 assert(((CurDeclaration->isCanonicalDecl() && "Expecting components to have associated only canonical declarations."
) ? static_cast<void> (0) : __assert_fail ("CurDeclaration->isCanonicalDecl() && \"Expecting components to have associated only canonical declarations.\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 14008, __PRETTY_FUNCTION__))
14007 CurDeclaration->isCanonicalDecl() &&((CurDeclaration->isCanonicalDecl() && "Expecting components to have associated only canonical declarations."
) ? static_cast<void> (0) : __assert_fail ("CurDeclaration->isCanonicalDecl() && \"Expecting components to have associated only canonical declarations.\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 14008, __PRETTY_FUNCTION__))
14008 "Expecting components to have associated only canonical declarations.")((CurDeclaration->isCanonicalDecl() && "Expecting components to have associated only canonical declarations."
) ? static_cast<void> (0) : __assert_fail ("CurDeclaration->isCanonicalDecl() && \"Expecting components to have associated only canonical declarations.\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 14008, __PRETTY_FUNCTION__))
;
14009
14010 auto *VD = dyn_cast<VarDecl>(CurDeclaration);
14011 const auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
14012
14013 assert((VD || FD) && "Only variables or fields are expected here!")(((VD || FD) && "Only variables or fields are expected here!"
) ? static_cast<void> (0) : __assert_fail ("(VD || FD) && \"Only variables or fields are expected here!\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 14013, __PRETTY_FUNCTION__))
;
14014 (void)FD;
14015
14016 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
14017 // threadprivate variables cannot appear in a map clause.
14018 // OpenMP 4.5 [2.10.5, target update Construct]
14019 // threadprivate variables cannot appear in a from clause.
14020 if (VD && DSAS->isThreadPrivate(VD)) {
14021 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
14022 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
14023 << getOpenMPClauseName(CKind);
14024 reportOriginalDsa(SemaRef, DSAS, VD, DVar);
14025 continue;
14026 }
14027
14028 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
14029 // A list item cannot appear in both a map clause and a data-sharing
14030 // attribute clause on the same construct.
14031
14032 // Check conflicts with other map clause expressions. We check the conflicts
14033 // with the current construct separately from the enclosing data
14034 // environment, because the restrictions are different. We only have to
14035 // check conflicts across regions for the map clauses.
14036 if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
14037 /*CurrentRegionOnly=*/true, CurComponents, CKind))
14038 break;
14039 if (CKind == OMPC_map &&
14040 checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
14041 /*CurrentRegionOnly=*/false, CurComponents, CKind))
14042 break;
14043
14044 // OpenMP 4.5 [2.10.5, target update Construct]
14045 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
14046 // If the type of a list item is a reference to a type T then the type will
14047 // be considered to be T for all purposes of this clause.
14048 auto I = llvm::find_if(
14049 CurComponents,
14050 [](const OMPClauseMappableExprCommon::MappableComponent &MC) {
14051 return MC.getAssociatedDeclaration();
14052 });
14053 assert(I != CurComponents.end() && "Null decl on map clause.")((I != CurComponents.end() && "Null decl on map clause."
) ? static_cast<void> (0) : __assert_fail ("I != CurComponents.end() && \"Null decl on map clause.\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 14053, __PRETTY_FUNCTION__))
;
14054 QualType Type =
14055 I->getAssociatedDeclaration()->getType().getNonReferenceType();
14056
14057 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
14058 // A list item in a to or from clause must have a mappable type.
14059 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
14060 // A list item must have a mappable type.
14061 if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
14062 DSAS, Type))
14063 continue;
14064
14065 if (CKind == OMPC_map) {
14066 // target enter data
14067 // OpenMP [2.10.2, Restrictions, p. 99]
14068 // A map-type must be specified in all map clauses and must be either
14069 // to or alloc.
14070 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
14071 if (DKind == OMPD_target_enter_data &&
14072 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
14073 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
14074 << (IsMapTypeImplicit ? 1 : 0)
14075 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
14076 << getOpenMPDirectiveName(DKind);
14077 continue;
14078 }
14079
14080 // target exit_data
14081 // OpenMP [2.10.3, Restrictions, p. 102]
14082 // A map-type must be specified in all map clauses and must be either
14083 // from, release, or delete.
14084 if (DKind == OMPD_target_exit_data &&
14085 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
14086 MapType == OMPC_MAP_delete)) {
14087 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
14088 << (IsMapTypeImplicit ? 1 : 0)
14089 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
14090 << getOpenMPDirectiveName(DKind);
14091 continue;
14092 }
14093
14094 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
14095 // A list item cannot appear in both a map clause and a data-sharing
14096 // attribute clause on the same construct
14097 if (VD && isOpenMPTargetExecutionDirective(DKind)) {
14098 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
14099 if (isOpenMPPrivate(DVar.CKind)) {
14100 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
14101 << getOpenMPClauseName(DVar.CKind)
14102 << getOpenMPClauseName(OMPC_map)
14103 << getOpenMPDirectiveName(DSAS->getCurrentDirective());
14104 reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar);
14105 continue;
14106 }
14107 }
14108 }
14109
14110 // Try to find the associated user-defined mapper.
14111 ExprResult ER = buildUserDefinedMapperRef(
14112 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
14113 Type.getCanonicalType(), UnresolvedMapper);
14114 if (ER.isInvalid())
14115 continue;
14116 MVLI.UDMapperList.push_back(ER.get());
14117
14118 // Save the current expression.
14119 MVLI.ProcessedVarList.push_back(RE);
14120
14121 // Store the components in the stack so that they can be used to check
14122 // against other clauses later on.
14123 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
14124 /*WhereFoundClauseKind=*/OMPC_map);
14125
14126 // Save the components and declaration to create the clause. For purposes of
14127 // the clause creation, any component list that has has base 'this' uses
14128 // null as base declaration.
14129 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
14130 MVLI.VarComponents.back().append(CurComponents.begin(),
14131 CurComponents.end());
14132 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
14133 : CurDeclaration);
14134 }
14135}
14136
14137OMPClause *Sema::ActOnOpenMPMapClause(
14138 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
14139 ArrayRef<SourceLocation> MapTypeModifiersLoc,
14140 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
14141 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc,
14142 SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
14143 const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
14144 OpenMPMapModifierKind Modifiers[] = {OMPC_MAP_MODIFIER_unknown,
14145 OMPC_MAP_MODIFIER_unknown,
14146 OMPC_MAP_MODIFIER_unknown};
14147 SourceLocation ModifiersLoc[OMPMapClause::NumberOfModifiers];
14148
14149 // Process map-type-modifiers, flag errors for duplicate modifiers.
14150 unsigned Count = 0;
14151 for (unsigned I = 0, E = MapTypeModifiers.size(); I < E; ++I) {
14152 if (MapTypeModifiers[I] != OMPC_MAP_MODIFIER_unknown &&
14153 llvm::find(Modifiers, MapTypeModifiers[I]) != std::end(Modifiers)) {
14154 Diag(MapTypeModifiersLoc[I], diag::err_omp_duplicate_map_type_modifier);
14155 continue;
14156 }
14157 assert(Count < OMPMapClause::NumberOfModifiers &&((Count < OMPMapClause::NumberOfModifiers && "Modifiers exceed the allowed number of map type modifiers"
) ? static_cast<void> (0) : __assert_fail ("Count < OMPMapClause::NumberOfModifiers && \"Modifiers exceed the allowed number of map type modifiers\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 14158, __PRETTY_FUNCTION__))
14158 "Modifiers exceed the allowed number of map type modifiers")((Count < OMPMapClause::NumberOfModifiers && "Modifiers exceed the allowed number of map type modifiers"
) ? static_cast<void> (0) : __assert_fail ("Count < OMPMapClause::NumberOfModifiers && \"Modifiers exceed the allowed number of map type modifiers\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 14158, __PRETTY_FUNCTION__))
;
14159 Modifiers[Count] = MapTypeModifiers[I];
14160 ModifiersLoc[Count] = MapTypeModifiersLoc[I];
14161 ++Count;
14162 }
14163
14164 MappableVarListInfo MVLI(VarList);
14165 checkMappableExpressionList(*this, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, OMPC_map, MVLI, Locs.StartLoc,
14166 MapperIdScopeSpec, MapperId, UnresolvedMappers,
14167 MapType, IsMapTypeImplicit);
14168
14169 // We need to produce a map clause even if we don't have variables so that
14170 // other diagnostics related with non-existing map clauses are accurate.
14171 return OMPMapClause::Create(Context, Locs, MVLI.ProcessedVarList,
14172 MVLI.VarBaseDeclarations, MVLI.VarComponents,
14173 MVLI.UDMapperList, Modifiers, ModifiersLoc,
14174 MapperIdScopeSpec.getWithLocInContext(Context),
14175 MapperId, MapType, IsMapTypeImplicit, MapLoc);
14176}
14177
14178QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
14179 TypeResult ParsedType) {
14180 assert(ParsedType.isUsable())((ParsedType.isUsable()) ? static_cast<void> (0) : __assert_fail
("ParsedType.isUsable()", "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 14180, __PRETTY_FUNCTION__))
;
14181
14182 QualType ReductionType = GetTypeFromParser(ParsedType.get());
14183 if (ReductionType.isNull())
14184 return QualType();
14185
14186 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
14187 // A type name in a declare reduction directive cannot be a function type, an
14188 // array type, a reference type, or a type qualified with const, volatile or
14189 // restrict.
14190 if (ReductionType.hasQualifiers()) {
14191 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
14192 return QualType();
14193 }
14194
14195 if (ReductionType->isFunctionType()) {
14196 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
14197 return QualType();
14198 }
14199 if (ReductionType->isReferenceType()) {
14200 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
14201 return QualType();
14202 }
14203 if (ReductionType->isArrayType()) {
14204 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
14205 return QualType();
14206 }
14207 return ReductionType;
14208}
14209
14210Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
14211 Scope *S, DeclContext *DC, DeclarationName Name,
14212 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
14213 AccessSpecifier AS, Decl *PrevDeclInScope) {
14214 SmallVector<Decl *, 8> Decls;
14215 Decls.reserve(ReductionTypes.size());
14216
14217 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
14218 forRedeclarationInCurContext());
14219 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
14220 // A reduction-identifier may not be re-declared in the current scope for the
14221 // same type or for a type that is compatible according to the base language
14222 // rules.
14223 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
14224 OMPDeclareReductionDecl *PrevDRD = nullptr;
14225 bool InCompoundScope = true;
14226 if (S != nullptr) {
14227 // Find previous declaration with the same name not referenced in other
14228 // declarations.
14229 FunctionScopeInfo *ParentFn = getEnclosingFunction();
14230 InCompoundScope =
14231 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
14232 LookupName(Lookup, S);
14233 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
14234 /*AllowInlineNamespace=*/false);
14235 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
14236 LookupResult::Filter Filter = Lookup.makeFilter();
14237 while (Filter.hasNext()) {
14238 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
14239 if (InCompoundScope) {
14240 auto I = UsedAsPrevious.find(PrevDecl);
14241 if (I == UsedAsPrevious.end())
14242 UsedAsPrevious[PrevDecl] = false;
14243 if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope())
14244 UsedAsPrevious[D] = true;
14245 }
14246 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
14247 PrevDecl->getLocation();
14248 }
14249 Filter.done();
14250 if (InCompoundScope) {
14251 for (const auto &PrevData : UsedAsPrevious) {
14252 if (!PrevData.second) {
14253 PrevDRD = PrevData.first;
14254 break;
14255 }
14256 }
14257 }
14258 } else if (PrevDeclInScope != nullptr) {
14259 auto *PrevDRDInScope = PrevDRD =
14260 cast<OMPDeclareReductionDecl>(PrevDeclInScope);
14261 do {
14262 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
14263 PrevDRDInScope->getLocation();
14264 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
14265 } while (PrevDRDInScope != nullptr);
14266 }
14267 for (const auto &TyData : ReductionTypes) {
14268 const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
14269 bool Invalid = false;
14270 if (I != PreviousRedeclTypes.end()) {
14271 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
14272 << TyData.first;
14273 Diag(I->second, diag::note_previous_definition);
14274 Invalid = true;
14275 }
14276 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
14277 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
14278 Name, TyData.first, PrevDRD);
14279 DC->addDecl(DRD);
14280 DRD->setAccess(AS);
14281 Decls.push_back(DRD);
14282 if (Invalid)
14283 DRD->setInvalidDecl();
14284 else
14285 PrevDRD = DRD;
14286 }
14287
14288 return DeclGroupPtrTy::make(
14289 DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
14290}
14291
14292void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
14293 auto *DRD = cast<OMPDeclareReductionDecl>(D);
14294
14295 // Enter new function scope.
14296 PushFunctionScope();
14297 setFunctionHasBranchProtectedScope();
14298 getCurFunction()->setHasOMPDeclareReductionCombiner();
14299
14300 if (S != nullptr)
14301 PushDeclContext(S, DRD);
14302 else
14303 CurContext = DRD;
14304
14305 PushExpressionEvaluationContext(
14306 ExpressionEvaluationContext::PotentiallyEvaluated);
14307
14308 QualType ReductionType = DRD->getType();
14309 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
14310 // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
14311 // uses semantics of argument handles by value, but it should be passed by
14312 // reference. C lang does not support references, so pass all parameters as
14313 // pointers.
14314 // Create 'T omp_in;' variable.
14315 VarDecl *OmpInParm =
14316 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
14317 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
14318 // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
14319 // uses semantics of argument handles by value, but it should be passed by
14320 // reference. C lang does not support references, so pass all parameters as
14321 // pointers.
14322 // Create 'T omp_out;' variable.
14323 VarDecl *OmpOutParm =
14324 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
14325 if (S != nullptr) {
14326 PushOnScopeChains(OmpInParm, S);
14327 PushOnScopeChains(OmpOutParm, S);
14328 } else {
14329 DRD->addDecl(OmpInParm);
14330 DRD->addDecl(OmpOutParm);
14331 }
14332 Expr *InE =
14333 ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation());
14334 Expr *OutE =
14335 ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation());
14336 DRD->setCombinerData(InE, OutE);
14337}
14338
14339void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
14340 auto *DRD = cast<OMPDeclareReductionDecl>(D);
14341 DiscardCleanupsInEvaluationContext();
14342 PopExpressionEvaluationContext();
14343
14344 PopDeclContext();
14345 PopFunctionScopeInfo();
14346
14347 if (Combiner != nullptr)
14348 DRD->setCombiner(Combiner);
14349 else
14350 DRD->setInvalidDecl();
14351}
14352
14353VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
14354 auto *DRD = cast<OMPDeclareReductionDecl>(D);
14355
14356 // Enter new function scope.
14357 PushFunctionScope();
14358 setFunctionHasBranchProtectedScope();
14359
14360 if (S != nullptr)
14361 PushDeclContext(S, DRD);
14362 else
14363 CurContext = DRD;
14364
14365 PushExpressionEvaluationContext(
14366 ExpressionEvaluationContext::PotentiallyEvaluated);
14367
14368 QualType ReductionType = DRD->getType();
14369 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
14370 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
14371 // uses semantics of argument handles by value, but it should be passed by
14372 // reference. C lang does not support references, so pass all parameters as
14373 // pointers.
14374 // Create 'T omp_priv;' variable.
14375 VarDecl *OmpPrivParm =
14376 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
14377 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
14378 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
14379 // uses semantics of argument handles by value, but it should be passed by
14380 // reference. C lang does not support references, so pass all parameters as
14381 // pointers.
14382 // Create 'T omp_orig;' variable.
14383 VarDecl *OmpOrigParm =
14384 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
14385 if (S != nullptr) {
14386 PushOnScopeChains(OmpPrivParm, S);
14387 PushOnScopeChains(OmpOrigParm, S);
14388 } else {
14389 DRD->addDecl(OmpPrivParm);
14390 DRD->addDecl(OmpOrigParm);
14391 }
14392 Expr *OrigE =
14393 ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation());
14394 Expr *PrivE =
14395 ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation());
14396 DRD->setInitializerData(OrigE, PrivE);
14397 return OmpPrivParm;
14398}
14399
14400void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
14401 VarDecl *OmpPrivParm) {
14402 auto *DRD = cast<OMPDeclareReductionDecl>(D);
14403 DiscardCleanupsInEvaluationContext();
14404 PopExpressionEvaluationContext();
14405
14406 PopDeclContext();
14407 PopFunctionScopeInfo();
14408
14409 if (Initializer != nullptr) {
14410 DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
14411 } else if (OmpPrivParm->hasInit()) {
14412 DRD->setInitializer(OmpPrivParm->getInit(),
14413 OmpPrivParm->isDirectInit()
14414 ? OMPDeclareReductionDecl::DirectInit
14415 : OMPDeclareReductionDecl::CopyInit);
14416 } else {
14417 DRD->setInvalidDecl();
14418 }
14419}
14420
14421Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
14422 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
14423 for (Decl *D : DeclReductions.get()) {
14424 if (IsValid) {
14425 if (S)
14426 PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S,
14427 /*AddToContext=*/false);
14428 } else {
14429 D->setInvalidDecl();
14430 }
14431 }
14432 return DeclReductions;
14433}
14434
14435TypeResult Sema::ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D) {
14436 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14437 QualType T = TInfo->getType();
14438 if (D.isInvalidType())
14439 return true;
14440
14441 if (getLangOpts().CPlusPlus) {
14442 // Check that there are no default arguments (C++ only).
14443 CheckExtraCXXDefaultArguments(D);
14444 }
14445
14446 return CreateParsedType(T, TInfo);
14447}
14448
14449QualType Sema::ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
14450 TypeResult ParsedType) {
14451 assert(ParsedType.isUsable() && "Expect usable parsed mapper type")((ParsedType.isUsable() && "Expect usable parsed mapper type"
) ? static_cast<void> (0) : __assert_fail ("ParsedType.isUsable() && \"Expect usable parsed mapper type\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 14451, __PRETTY_FUNCTION__))
;
14452
14453 QualType MapperType = GetTypeFromParser(ParsedType.get());
14454 assert(!MapperType.isNull() && "Expect valid mapper type")((!MapperType.isNull() && "Expect valid mapper type")
? static_cast<void> (0) : __assert_fail ("!MapperType.isNull() && \"Expect valid mapper type\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 14454, __PRETTY_FUNCTION__))
;
14455
14456 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
14457 // The type must be of struct, union or class type in C and C++
14458 if (!MapperType->isStructureOrClassType() && !MapperType->isUnionType()) {
14459 Diag(TyLoc, diag::err_omp_mapper_wrong_type);
14460 return QualType();
14461 }
14462 return MapperType;
14463}
14464
14465OMPDeclareMapperDecl *Sema::ActOnOpenMPDeclareMapperDirectiveStart(
14466 Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
14467 SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
14468 Decl *PrevDeclInScope) {
14469 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPMapperName,
14470 forRedeclarationInCurContext());
14471 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
14472 // A mapper-identifier may not be redeclared in the current scope for the
14473 // same type or for a type that is compatible according to the base language
14474 // rules.
14475 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
14476 OMPDeclareMapperDecl *PrevDMD = nullptr;
14477 bool InCompoundScope = true;
14478 if (S != nullptr) {
14479 // Find previous declaration with the same name not referenced in other
14480 // declarations.
14481 FunctionScopeInfo *ParentFn = getEnclosingFunction();
14482 InCompoundScope =
14483 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
14484 LookupName(Lookup, S);
14485 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
14486 /*AllowInlineNamespace=*/false);
14487 llvm::DenseMap<OMPDeclareMapperDecl *, bool> UsedAsPrevious;
14488 LookupResult::Filter Filter = Lookup.makeFilter();
14489 while (Filter.hasNext()) {
14490 auto *PrevDecl = cast<OMPDeclareMapperDecl>(Filter.next());
14491 if (InCompoundScope) {
14492 auto I = UsedAsPrevious.find(PrevDecl);
14493 if (I == UsedAsPrevious.end())
14494 UsedAsPrevious[PrevDecl] = false;
14495 if (OMPDeclareMapperDecl *D = PrevDecl->getPrevDeclInScope())
14496 UsedAsPrevious[D] = true;
14497 }
14498 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
14499 PrevDecl->getLocation();
14500 }
14501 Filter.done();
14502 if (InCompoundScope) {
14503 for (const auto &PrevData : UsedAsPrevious) {
14504 if (!PrevData.second) {
14505 PrevDMD = PrevData.first;
14506 break;
14507 }
14508 }
14509 }
14510 } else if (PrevDeclInScope) {
14511 auto *PrevDMDInScope = PrevDMD =
14512 cast<OMPDeclareMapperDecl>(PrevDeclInScope);
14513 do {
14514 PreviousRedeclTypes[PrevDMDInScope->getType().getCanonicalType()] =
14515 PrevDMDInScope->getLocation();
14516 PrevDMDInScope = PrevDMDInScope->getPrevDeclInScope();
14517 } while (PrevDMDInScope != nullptr);
14518 }
14519 const auto I = PreviousRedeclTypes.find(MapperType.getCanonicalType());
14520 bool Invalid = false;
14521 if (I != PreviousRedeclTypes.end()) {
14522 Diag(StartLoc, diag::err_omp_declare_mapper_redefinition)
14523 << MapperType << Name;
14524 Diag(I->second, diag::note_previous_definition);
14525 Invalid = true;
14526 }
14527 auto *DMD = OMPDeclareMapperDecl::Create(Context, DC, StartLoc, Name,
14528 MapperType, VN, PrevDMD);
14529 DC->addDecl(DMD);
14530 DMD->setAccess(AS);
14531 if (Invalid)
14532 DMD->setInvalidDecl();
14533
14534 // Enter new function scope.
14535 PushFunctionScope();
14536 setFunctionHasBranchProtectedScope();
14537
14538 CurContext = DMD;
14539
14540 return DMD;
14541}
14542
14543void Sema::ActOnOpenMPDeclareMapperDirectiveVarDecl(OMPDeclareMapperDecl *DMD,
14544 Scope *S,
14545 QualType MapperType,
14546 SourceLocation StartLoc,
14547 DeclarationName VN) {
14548 VarDecl *VD = buildVarDecl(*this, StartLoc, MapperType, VN.getAsString());
14549 if (S)
14550 PushOnScopeChains(VD, S);
14551 else
14552 DMD->addDecl(VD);
14553 Expr *MapperVarRefExpr = buildDeclRefExpr(*this, VD, MapperType, StartLoc);
14554 DMD->setMapperVarRef(MapperVarRefExpr);
14555}
14556
14557Sema::DeclGroupPtrTy
14558Sema::ActOnOpenMPDeclareMapperDirectiveEnd(OMPDeclareMapperDecl *D, Scope *S,
14559 ArrayRef<OMPClause *> ClauseList) {
14560 PopDeclContext();
14561 PopFunctionScopeInfo();
14562
14563 if (D) {
14564 if (S)
14565 PushOnScopeChains(D, S, /*AddToContext=*/false);
14566 D->CreateClauses(Context, ClauseList);
14567 }
14568
14569 return DeclGroupPtrTy::make(DeclGroupRef(D));
14570}
14571
14572OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
14573 SourceLocation StartLoc,
14574 SourceLocation LParenLoc,
14575 SourceLocation EndLoc) {
14576 Expr *ValExpr = NumTeams;
14577 Stmt *HelperValStmt = nullptr;
14578
14579 // OpenMP [teams Constrcut, Restrictions]
14580 // The num_teams expression must evaluate to a positive integer value.
14581 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
14582 /*StrictlyPositive=*/true))
14583 return nullptr;
14584
14585 OpenMPDirectiveKind DKind = DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective();
14586 OpenMPDirectiveKind CaptureRegion =
14587 getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
14588 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
14589 ValExpr = MakeFullExpr(ValExpr).get();
14590 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
14591 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
14592 HelperValStmt = buildPreInits(Context, Captures);
14593 }
14594
14595 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
14596 StartLoc, LParenLoc, EndLoc);
14597}
14598
14599OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
14600 SourceLocation StartLoc,
14601 SourceLocation LParenLoc,
14602 SourceLocation EndLoc) {
14603 Expr *ValExpr = ThreadLimit;
14604 Stmt *HelperValStmt = nullptr;
14605
14606 // OpenMP [teams Constrcut, Restrictions]
14607 // The thread_limit expression must evaluate to a positive integer value.
14608 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
14609 /*StrictlyPositive=*/true))
14610 return nullptr;
14611
14612 OpenMPDirectiveKind DKind = DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective();
14613 OpenMPDirectiveKind CaptureRegion =
14614 getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
14615 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
14616 ValExpr = MakeFullExpr(ValExpr).get();
14617 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
14618 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
14619 HelperValStmt = buildPreInits(Context, Captures);
14620 }
14621
14622 return new (Context) OMPThreadLimitClause(
14623 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
14624}
14625
14626OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
14627 SourceLocation StartLoc,
14628 SourceLocation LParenLoc,
14629 SourceLocation EndLoc) {
14630 Expr *ValExpr = Priority;
14631
14632 // OpenMP [2.9.1, task Constrcut]
14633 // The priority-value is a non-negative numerical scalar expression.
14634 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
14635 /*StrictlyPositive=*/false))
14636 return nullptr;
14637
14638 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
14639}
14640
14641OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
14642 SourceLocation StartLoc,
14643 SourceLocation LParenLoc,
14644 SourceLocation EndLoc) {
14645 Expr *ValExpr = Grainsize;
14646
14647 // OpenMP [2.9.2, taskloop Constrcut]
14648 // The parameter of the grainsize clause must be a positive integer
14649 // expression.
14650 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
14651 /*StrictlyPositive=*/true))
14652 return nullptr;
14653
14654 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
14655}
14656
14657OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
14658 SourceLocation StartLoc,
14659 SourceLocation LParenLoc,
14660 SourceLocation EndLoc) {
14661 Expr *ValExpr = NumTasks;
14662
14663 // OpenMP [2.9.2, taskloop Constrcut]
14664 // The parameter of the num_tasks clause must be a positive integer
14665 // expression.
14666 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
14667 /*StrictlyPositive=*/true))
14668 return nullptr;
14669
14670 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
14671}
14672
14673OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
14674 SourceLocation LParenLoc,
14675 SourceLocation EndLoc) {
14676 // OpenMP [2.13.2, critical construct, Description]
14677 // ... where hint-expression is an integer constant expression that evaluates
14678 // to a valid lock hint.
14679 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
14680 if (HintExpr.isInvalid())
14681 return nullptr;
14682 return new (Context)
14683 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
14684}
14685
14686OMPClause *Sema::ActOnOpenMPDistScheduleClause(
14687 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
14688 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
14689 SourceLocation EndLoc) {
14690 if (Kind == OMPC_DIST_SCHEDULE_unknown) {
14691 std::string Values;
14692 Values += "'";
14693 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
14694 Values += "'";
14695 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
14696 << Values << getOpenMPClauseName(OMPC_dist_schedule);
14697 return nullptr;
14698 }
14699 Expr *ValExpr = ChunkSize;
14700 Stmt *HelperValStmt = nullptr;
14701 if (ChunkSize) {
14702 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
14703 !ChunkSize->isInstantiationDependent() &&
14704 !ChunkSize->containsUnexpandedParameterPack()) {
14705 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
14706 ExprResult Val =
14707 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
14708 if (Val.isInvalid())
14709 return nullptr;
14710
14711 ValExpr = Val.get();
14712
14713 // OpenMP [2.7.1, Restrictions]
14714 // chunk_size must be a loop invariant integer expression with a positive
14715 // value.
14716 llvm::APSInt Result;
14717 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
14718 if (Result.isSigned() && !Result.isStrictlyPositive()) {
14719 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
14720 << "dist_schedule" << ChunkSize->getSourceRange();
14721 return nullptr;
14722 }
14723 } else if (getOpenMPCaptureRegionForClause(
14724 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective(), OMPC_dist_schedule) !=
14725 OMPD_unknown &&
14726 !CurContext->isDependentContext()) {
14727 ValExpr = MakeFullExpr(ValExpr).get();
14728 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
14729 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
14730 HelperValStmt = buildPreInits(Context, Captures);
14731 }
14732 }
14733 }
14734
14735 return new (Context)
14736 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
14737 Kind, ValExpr, HelperValStmt);
14738}
14739
14740OMPClause *Sema::ActOnOpenMPDefaultmapClause(
14741 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
14742 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
14743 SourceLocation KindLoc, SourceLocation EndLoc) {
14744 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
14745 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
14746 std::string Value;
14747 SourceLocation Loc;
14748 Value += "'";
14749 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
14750 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
14751 OMPC_DEFAULTMAP_MODIFIER_tofrom);
14752 Loc = MLoc;
14753 } else {
14754 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
14755 OMPC_DEFAULTMAP_scalar);
14756 Loc = KindLoc;
14757 }
14758 Value += "'";
14759 Diag(Loc, diag::err_omp_unexpected_clause_value)
14760 << Value << getOpenMPClauseName(OMPC_defaultmap);
14761 return nullptr;
14762 }
14763 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->setDefaultDMAToFromScalar(StartLoc);
14764
14765 return new (Context)
14766 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
14767}
14768
14769bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
14770 DeclContext *CurLexicalContext = getCurLexicalContext();
14771 if (!CurLexicalContext->isFileContext() &&
14772 !CurLexicalContext->isExternCContext() &&
14773 !CurLexicalContext->isExternCXXContext() &&
14774 !isa<CXXRecordDecl>(CurLexicalContext) &&
14775 !isa<ClassTemplateDecl>(CurLexicalContext) &&
14776 !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
14777 !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
14778 Diag(Loc, diag::err_omp_region_not_file_context);
14779 return false;
14780 }
14781 ++DeclareTargetNestingLevel;
14782 return true;
14783}
14784
14785void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
14786 assert(DeclareTargetNestingLevel > 0 &&((DeclareTargetNestingLevel > 0 && "Unexpected ActOnFinishOpenMPDeclareTargetDirective"
) ? static_cast<void> (0) : __assert_fail ("DeclareTargetNestingLevel > 0 && \"Unexpected ActOnFinishOpenMPDeclareTargetDirective\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 14787, __PRETTY_FUNCTION__))
14787 "Unexpected ActOnFinishOpenMPDeclareTargetDirective")((DeclareTargetNestingLevel > 0 && "Unexpected ActOnFinishOpenMPDeclareTargetDirective"
) ? static_cast<void> (0) : __assert_fail ("DeclareTargetNestingLevel > 0 && \"Unexpected ActOnFinishOpenMPDeclareTargetDirective\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 14787, __PRETTY_FUNCTION__))
;
14788 --DeclareTargetNestingLevel;
14789}
14790
14791void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
14792 CXXScopeSpec &ScopeSpec,
14793 const DeclarationNameInfo &Id,
14794 OMPDeclareTargetDeclAttr::MapTypeTy MT,
14795 NamedDeclSetType &SameDirectiveDecls) {
14796 LookupResult Lookup(*this, Id, LookupOrdinaryName);
14797 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
14798
14799 if (Lookup.isAmbiguous())
14800 return;
14801 Lookup.suppressDiagnostics();
14802
14803 if (!Lookup.isSingleResult()) {
14804 VarOrFuncDeclFilterCCC CCC(*this);
14805 if (TypoCorrection Corrected =
14806 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
14807 CTK_ErrorRecovery)) {
14808 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
14809 << Id.getName());
14810 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
14811 return;
14812 }
14813
14814 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
14815 return;
14816 }
14817
14818 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
14819 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND) ||
14820 isa<FunctionTemplateDecl>(ND)) {
14821 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
14822 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
14823 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
14824 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
14825 cast<ValueDecl>(ND));
14826 if (!Res) {
14827 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
14828 ND->addAttr(A);
14829 if (ASTMutationListener *ML = Context.getASTMutationListener())
14830 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
14831 checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Id.getLoc());
14832 } else if (*Res != MT) {
14833 Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
14834 << Id.getName();
14835 }
14836 } else {
14837 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
14838 }
14839}
14840
14841static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
14842 Sema &SemaRef, Decl *D) {
14843 if (!D || !isa<VarDecl>(D))
14844 return;
14845 auto *VD = cast<VarDecl>(D);
14846 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
14847 return;
14848 SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context);
14849 SemaRef.Diag(SL, diag::note_used_here) << SR;
14850}
14851
14852static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
14853 Sema &SemaRef, DSAStackTy *Stack,
14854 ValueDecl *VD) {
14855 return VD->hasAttr<OMPDeclareTargetDeclAttr>() ||
14856 checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(),
14857 /*FullCheck=*/false);
14858}
14859
14860void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
14861 SourceLocation IdLoc) {
14862 if (!D || D->isInvalidDecl())
14863 return;
14864 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
14865 SourceLocation SL = E ? E->getBeginLoc() : D->getLocation();
14866 if (auto *VD = dyn_cast<VarDecl>(D)) {
14867 // Only global variables can be marked as declare target.
14868 if (!VD->isFileVarDecl() && !VD->isStaticLocal() &&
14869 !VD->isStaticDataMember())
14870 return;
14871 // 2.10.6: threadprivate variable cannot appear in a declare target
14872 // directive.
14873 if (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isThreadPrivate(VD)) {
14874 Diag(SL, diag::err_omp_threadprivate_in_target);
14875 reportOriginalDsa(*this, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, VD, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getTopDSA(VD, false));
14876 return;
14877 }
14878 }
14879 if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
14880 D = FTD->getTemplatedDecl();
14881 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
14882 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
14883 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD);
14884 if (Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
14885 assert(IdLoc.isValid() && "Source location is expected")((IdLoc.isValid() && "Source location is expected") ?
static_cast<void> (0) : __assert_fail ("IdLoc.isValid() && \"Source location is expected\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 14885, __PRETTY_FUNCTION__))
;
14886 Diag(IdLoc, diag::err_omp_function_in_link_clause);
14887 Diag(FD->getLocation(), diag::note_defined_here) << FD;
14888 return;
14889 }
14890 }
14891 if (auto *VD = dyn_cast<ValueDecl>(D)) {
14892 // Problem if any with var declared with incomplete type will be reported
14893 // as normal, so no need to check it here.
14894 if ((E || !VD->getType()->isIncompleteType()) &&
14895 !checkValueDeclInTarget(SL, SR, *this, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, VD))
14896 return;
14897 if (!E && !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
14898 // Checking declaration inside declare target region.
14899 if (isa<VarDecl>(D) || isa<FunctionDecl>(D) ||
14900 isa<FunctionTemplateDecl>(D)) {
14901 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
14902 Context, OMPDeclareTargetDeclAttr::MT_To);
14903 D->addAttr(A);
14904 if (ASTMutationListener *ML = Context.getASTMutationListener())
14905 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
14906 }
14907 return;
14908 }
14909 }
14910 if (!E)
14911 return;
14912 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
14913}
14914
14915OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
14916 CXXScopeSpec &MapperIdScopeSpec,
14917 DeclarationNameInfo &MapperId,
14918 const OMPVarListLocTy &Locs,
14919 ArrayRef<Expr *> UnresolvedMappers) {
14920 MappableVarListInfo MVLI(VarList);
14921 checkMappableExpressionList(*this, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, OMPC_to, MVLI, Locs.StartLoc,
14922 MapperIdScopeSpec, MapperId, UnresolvedMappers);
14923 if (MVLI.ProcessedVarList.empty())
14924 return nullptr;
14925
14926 return OMPToClause::Create(
14927 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
14928 MVLI.VarComponents, MVLI.UDMapperList,
14929 MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
14930}
14931
14932OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
14933 CXXScopeSpec &MapperIdScopeSpec,
14934 DeclarationNameInfo &MapperId,
14935 const OMPVarListLocTy &Locs,
14936 ArrayRef<Expr *> UnresolvedMappers) {
14937 MappableVarListInfo MVLI(VarList);
14938 checkMappableExpressionList(*this, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, OMPC_from, MVLI, Locs.StartLoc,
14939 MapperIdScopeSpec, MapperId, UnresolvedMappers);
14940 if (MVLI.ProcessedVarList.empty())
14941 return nullptr;
14942
14943 return OMPFromClause::Create(
14944 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
14945 MVLI.VarComponents, MVLI.UDMapperList,
14946 MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
14947}
14948
14949OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
14950 const OMPVarListLocTy &Locs) {
14951 MappableVarListInfo MVLI(VarList);
14952 SmallVector<Expr *, 8> PrivateCopies;
14953 SmallVector<Expr *, 8> Inits;
14954
14955 for (Expr *RefExpr : VarList) {
14956 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.")((RefExpr && "NULL expr in OpenMP use_device_ptr clause."
) ? static_cast<void> (0) : __assert_fail ("RefExpr && \"NULL expr in OpenMP use_device_ptr clause.\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 14956, __PRETTY_FUNCTION__))
;
14957 SourceLocation ELoc;
14958 SourceRange ERange;
14959 Expr *SimpleRefExpr = RefExpr;
14960 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
14961 if (Res.second) {
14962 // It will be analyzed later.
14963 MVLI.ProcessedVarList.push_back(RefExpr);
14964 PrivateCopies.push_back(nullptr);
14965 Inits.push_back(nullptr);
14966 }
14967 ValueDecl *D = Res.first;
14968 if (!D)
14969 continue;
14970
14971 QualType Type = D->getType();
14972 Type = Type.getNonReferenceType().getUnqualifiedType();
14973
14974 auto *VD = dyn_cast<VarDecl>(D);
14975
14976 // Item should be a pointer or reference to pointer.
14977 if (!Type->isPointerType()) {
14978 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
14979 << 0 << RefExpr->getSourceRange();
14980 continue;
14981 }
14982
14983 // Build the private variable and the expression that refers to it.
14984 auto VDPrivate =
14985 buildVarDecl(*this, ELoc, Type, D->getName(),
14986 D->hasAttrs() ? &D->getAttrs() : nullptr,
14987 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
14988 if (VDPrivate->isInvalidDecl())
14989 continue;
14990
14991 CurContext->addDecl(VDPrivate);
14992 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
14993 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
14994
14995 // Add temporary variable to initialize the private copy of the pointer.
14996 VarDecl *VDInit =
14997 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
14998 DeclRefExpr *VDInitRefExpr = buildDeclRefExpr(
14999 *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc());
15000 AddInitializerToDecl(VDPrivate,
15001 DefaultLvalueConversion(VDInitRefExpr).get(),
15002 /*DirectInit=*/false);
15003
15004 // If required, build a capture to implement the privatization initialized
15005 // with the current list item value.
15006 DeclRefExpr *Ref = nullptr;
15007 if (!VD)
15008 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
15009 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
15010 PrivateCopies.push_back(VDPrivateRefExpr);
15011 Inits.push_back(VDInitRefExpr);
15012
15013 // We need to add a data sharing attribute for this variable to make sure it
15014 // is correctly captured. A variable that shows up in a use_device_ptr has
15015 // similar properties of a first private variable.
15016 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
15017
15018 // Create a mappable component for the list item. List items in this clause
15019 // only need a component.
15020 MVLI.VarBaseDeclarations.push_back(D);
15021 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
15022 MVLI.VarComponents.back().push_back(
15023 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
15024 }
15025
15026 if (MVLI.ProcessedVarList.empty())
15027 return nullptr;
15028
15029 return OMPUseDevicePtrClause::Create(
15030 Context, Locs, MVLI.ProcessedVarList, PrivateCopies, Inits,
15031 MVLI.VarBaseDeclarations, MVLI.VarComponents);
15032}
15033
15034OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
15035 const OMPVarListLocTy &Locs) {
15036 MappableVarListInfo MVLI(VarList);
15037 for (Expr *RefExpr : VarList) {
15038 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.")((RefExpr && "NULL expr in OpenMP is_device_ptr clause."
) ? static_cast<void> (0) : __assert_fail ("RefExpr && \"NULL expr in OpenMP is_device_ptr clause.\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 15038, __PRETTY_FUNCTION__))
;
15039 SourceLocation ELoc;
15040 SourceRange ERange;
15041 Expr *SimpleRefExpr = RefExpr;
15042 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
15043 if (Res.second) {
15044 // It will be analyzed later.
15045 MVLI.ProcessedVarList.push_back(RefExpr);
15046 }
15047 ValueDecl *D = Res.first;
15048 if (!D)
15049 continue;
15050
15051 QualType Type = D->getType();
15052 // item should be a pointer or array or reference to pointer or array
15053 if (!Type.getNonReferenceType()->isPointerType() &&
15054 !Type.getNonReferenceType()->isArrayType()) {
15055 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
15056 << 0 << RefExpr->getSourceRange();
15057 continue;
15058 }
15059
15060 // Check if the declaration in the clause does not show up in any data
15061 // sharing attribute.
15062 DSAStackTy::DSAVarData DVar = DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getTopDSA(D, /*FromParent=*/false);
15063 if (isOpenMPPrivate(DVar.CKind)) {
15064 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
15065 << getOpenMPClauseName(DVar.CKind)
15066 << getOpenMPClauseName(OMPC_is_device_ptr)
15067 << getOpenMPDirectiveName(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective());
15068 reportOriginalDsa(*this, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, D, DVar);
15069 continue;
15070 }
15071
15072 const Expr *ConflictExpr;
15073 if (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->checkMappableExprComponentListsForDecl(
15074 D, /*CurrentRegionOnly=*/true,
15075 [&ConflictExpr](
15076 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
15077 OpenMPClauseKind) -> bool {
15078 ConflictExpr = R.front().getAssociatedExpression();
15079 return true;
15080 })) {
15081 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
15082 Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
15083 << ConflictExpr->getSourceRange();
15084 continue;
15085 }
15086
15087 // Store the components in the stack so that they can be used to check
15088 // against other clauses later on.
15089 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
15090 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->addMappableExpressionComponents(
15091 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
15092
15093 // Record the expression we've just processed.
15094 MVLI.ProcessedVarList.push_back(SimpleRefExpr);
15095
15096 // Create a mappable component for the list item. List items in this clause
15097 // only need a component. We use a null declaration to signal fields in
15098 // 'this'.
15099 assert((isa<DeclRefExpr>(SimpleRefExpr) ||(((isa<DeclRefExpr>(SimpleRefExpr) || isa<CXXThisExpr
>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
"Unexpected device pointer expression!") ? static_cast<void
> (0) : __assert_fail ("(isa<DeclRefExpr>(SimpleRefExpr) || isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) && \"Unexpected device pointer expression!\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 15101, __PRETTY_FUNCTION__))
15100 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&(((isa<DeclRefExpr>(SimpleRefExpr) || isa<CXXThisExpr
>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
"Unexpected device pointer expression!") ? static_cast<void
> (0) : __assert_fail ("(isa<DeclRefExpr>(SimpleRefExpr) || isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) && \"Unexpected device pointer expression!\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 15101, __PRETTY_FUNCTION__))
15101 "Unexpected device pointer expression!")(((isa<DeclRefExpr>(SimpleRefExpr) || isa<CXXThisExpr
>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
"Unexpected device pointer expression!") ? static_cast<void
> (0) : __assert_fail ("(isa<DeclRefExpr>(SimpleRefExpr) || isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) && \"Unexpected device pointer expression!\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 15101, __PRETTY_FUNCTION__))
;
15102 MVLI.VarBaseDeclarations.push_back(
15103 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
15104 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
15105 MVLI.VarComponents.back().push_back(MC);
15106 }
15107
15108 if (MVLI.ProcessedVarList.empty())
15109 return nullptr;
15110
15111 return OMPIsDevicePtrClause::Create(Context, Locs, MVLI.ProcessedVarList,
15112 MVLI.VarBaseDeclarations,
15113 MVLI.VarComponents);
15114}
15115
15116OMPClause *Sema::ActOnOpenMPAllocateClause(
15117 Expr *Allocator, ArrayRef<Expr *> VarList, SourceLocation StartLoc,
15118 SourceLocation ColonLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
15119 if (Allocator) {
15120 // OpenMP [2.11.4 allocate Clause, Description]
15121 // allocator is an expression of omp_allocator_handle_t type.
15122 if (!findOMPAllocatorHandleT(*this, Allocator->getExprLoc(), DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
))
15123 return nullptr;
15124
15125 ExprResult AllocatorRes = DefaultLvalueConversion(Allocator);
15126 if (AllocatorRes.isInvalid())
15127 return nullptr;
15128 AllocatorRes = PerformImplicitConversion(AllocatorRes.get(),
15129 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getOMPAllocatorHandleT(),
15130 Sema::AA_Initializing,
15131 /*AllowExplicit=*/true);
15132 if (AllocatorRes.isInvalid())
15133 return nullptr;
15134 Allocator = AllocatorRes.get();
15135 } else {
15136 // OpenMP 5.0, 2.11.4 allocate Clause, Restrictions.
15137 // allocate clauses that appear on a target construct or on constructs in a
15138 // target region must specify an allocator expression unless a requires
15139 // directive with the dynamic_allocators clause is present in the same
15140 // compilation unit.
15141 if (LangOpts.OpenMPIsDevice &&
15142 !DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
15143 targetDiag(StartLoc, diag::err_expected_allocator_expression);
15144 }
15145 // Analyze and build list of variables.
15146 SmallVector<Expr *, 8> Vars;
15147 for (Expr *RefExpr : VarList) {
15148 assert(RefExpr && "NULL expr in OpenMP private clause.")((RefExpr && "NULL expr in OpenMP private clause.") ?
static_cast<void> (0) : __assert_fail ("RefExpr && \"NULL expr in OpenMP private clause.\""
, "/build/llvm-toolchain-snapshot-9~svn360825/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 15148, __PRETTY_FUNCTION__))
;
15149 SourceLocation ELoc;
15150 SourceRange ERange;
15151 Expr *SimpleRefExpr = RefExpr;
15152 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
15153 if (Res.second) {
15154 // It will be analyzed later.
15155 Vars.push_back(RefExpr);
15156 }
15157 ValueDecl *D = Res.first;
15158 if (!D)
15159 continue;
15160
15161 auto *VD = dyn_cast<VarDecl>(D);
15162 DeclRefExpr *Ref = nullptr;
15163 if (!VD && !CurContext->isDependentContext())
15164 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
15165 Vars.push_back((VD || CurContext->isDependentContext())
15166 ? RefExpr->IgnoreParens()
15167 : Ref);
15168 }
15169
15170 if (Vars.empty())
15171 return nullptr;
15172
15173 return OMPAllocateClause::Create(Context, StartLoc, LParenLoc, Allocator,
15174 ColonLoc, EndLoc, Vars);
15175}