Bug Summary

File:clang/lib/AST/Expr.cpp
Warning:line 818, column 7
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name Expr.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/build-llvm/tools/clang/lib/AST -resource-dir /usr/lib/llvm-13/lib/clang/13.0.0 -D CLANG_ROUND_TRIP_CC1_ARGS=ON -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/build-llvm/tools/clang/lib/AST -I /build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST -I /build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/include -I /build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/build-llvm/include -I /build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/llvm/include -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-13/lib/clang/13.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/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-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/build-llvm/tools/clang/lib/AST -fdebug-prefix-map=/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2021-06-13-111025-38230-1 -x c++ /build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp

/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp

1//===--- Expr.cpp - Expression AST Node Implementation --------------------===//
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//
9// This file implements the Expr class and subclasses.
10//
11//===----------------------------------------------------------------------===//
12
13#include "clang/AST/Expr.h"
14#include "clang/AST/APValue.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/Attr.h"
17#include "clang/AST/ComputeDependence.h"
18#include "clang/AST/DeclCXX.h"
19#include "clang/AST/DeclObjC.h"
20#include "clang/AST/DeclTemplate.h"
21#include "clang/AST/DependenceFlags.h"
22#include "clang/AST/EvaluatedExprVisitor.h"
23#include "clang/AST/ExprCXX.h"
24#include "clang/AST/IgnoreExpr.h"
25#include "clang/AST/Mangle.h"
26#include "clang/AST/RecordLayout.h"
27#include "clang/AST/StmtVisitor.h"
28#include "clang/Basic/Builtins.h"
29#include "clang/Basic/CharInfo.h"
30#include "clang/Basic/SourceManager.h"
31#include "clang/Basic/TargetInfo.h"
32#include "clang/Lex/Lexer.h"
33#include "clang/Lex/LiteralSupport.h"
34#include "llvm/Support/ErrorHandling.h"
35#include "llvm/Support/Format.h"
36#include "llvm/Support/raw_ostream.h"
37#include <algorithm>
38#include <cstring>
39using namespace clang;
40
41const Expr *Expr::getBestDynamicClassTypeExpr() const {
42 const Expr *E = this;
43 while (true) {
44 E = E->IgnoreParenBaseCasts();
45
46 // Follow the RHS of a comma operator.
47 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
48 if (BO->getOpcode() == BO_Comma) {
49 E = BO->getRHS();
50 continue;
51 }
52 }
53
54 // Step into initializer for materialized temporaries.
55 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
56 E = MTE->getSubExpr();
57 continue;
58 }
59
60 break;
61 }
62
63 return E;
64}
65
66const CXXRecordDecl *Expr::getBestDynamicClassType() const {
67 const Expr *E = getBestDynamicClassTypeExpr();
68 QualType DerivedType = E->getType();
69 if (const PointerType *PTy = DerivedType->getAs<PointerType>())
70 DerivedType = PTy->getPointeeType();
71
72 if (DerivedType->isDependentType())
73 return nullptr;
74
75 const RecordType *Ty = DerivedType->castAs<RecordType>();
76 Decl *D = Ty->getDecl();
77 return cast<CXXRecordDecl>(D);
78}
79
80const Expr *Expr::skipRValueSubobjectAdjustments(
81 SmallVectorImpl<const Expr *> &CommaLHSs,
82 SmallVectorImpl<SubobjectAdjustment> &Adjustments) const {
83 const Expr *E = this;
84 while (true) {
85 E = E->IgnoreParens();
86
87 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
88 if ((CE->getCastKind() == CK_DerivedToBase ||
89 CE->getCastKind() == CK_UncheckedDerivedToBase) &&
90 E->getType()->isRecordType()) {
91 E = CE->getSubExpr();
92 auto *Derived =
93 cast<CXXRecordDecl>(E->getType()->castAs<RecordType>()->getDecl());
94 Adjustments.push_back(SubobjectAdjustment(CE, Derived));
95 continue;
96 }
97
98 if (CE->getCastKind() == CK_NoOp) {
99 E = CE->getSubExpr();
100 continue;
101 }
102 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
103 if (!ME->isArrow()) {
104 assert(ME->getBase()->getType()->isRecordType())(static_cast <bool> (ME->getBase()->getType()->
isRecordType()) ? void (0) : __assert_fail ("ME->getBase()->getType()->isRecordType()"
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 104, __extension__ __PRETTY_FUNCTION__))
;
105 if (FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
106 if (!Field->isBitField() && !Field->getType()->isReferenceType()) {
107 E = ME->getBase();
108 Adjustments.push_back(SubobjectAdjustment(Field));
109 continue;
110 }
111 }
112 }
113 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
114 if (BO->getOpcode() == BO_PtrMemD) {
115 assert(BO->getRHS()->isPRValue())(static_cast <bool> (BO->getRHS()->isPRValue()) ?
void (0) : __assert_fail ("BO->getRHS()->isPRValue()",
"/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 115, __extension__ __PRETTY_FUNCTION__))
;
116 E = BO->getLHS();
117 const MemberPointerType *MPT =
118 BO->getRHS()->getType()->getAs<MemberPointerType>();
119 Adjustments.push_back(SubobjectAdjustment(MPT, BO->getRHS()));
120 continue;
121 }
122 if (BO->getOpcode() == BO_Comma) {
123 CommaLHSs.push_back(BO->getLHS());
124 E = BO->getRHS();
125 continue;
126 }
127 }
128
129 // Nothing changed.
130 break;
131 }
132 return E;
133}
134
135bool Expr::isKnownToHaveBooleanValue(bool Semantic) const {
136 const Expr *E = IgnoreParens();
137
138 // If this value has _Bool type, it is obvious 0/1.
139 if (E->getType()->isBooleanType()) return true;
140 // If this is a non-scalar-integer type, we don't care enough to try.
141 if (!E->getType()->isIntegralOrEnumerationType()) return false;
142
143 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
144 switch (UO->getOpcode()) {
145 case UO_Plus:
146 return UO->getSubExpr()->isKnownToHaveBooleanValue(Semantic);
147 case UO_LNot:
148 return true;
149 default:
150 return false;
151 }
152 }
153
154 // Only look through implicit casts. If the user writes
155 // '(int) (a && b)' treat it as an arbitrary int.
156 // FIXME: Should we look through any cast expression in !Semantic mode?
157 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
158 return CE->getSubExpr()->isKnownToHaveBooleanValue(Semantic);
159
160 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
161 switch (BO->getOpcode()) {
162 default: return false;
163 case BO_LT: // Relational operators.
164 case BO_GT:
165 case BO_LE:
166 case BO_GE:
167 case BO_EQ: // Equality operators.
168 case BO_NE:
169 case BO_LAnd: // AND operator.
170 case BO_LOr: // Logical OR operator.
171 return true;
172
173 case BO_And: // Bitwise AND operator.
174 case BO_Xor: // Bitwise XOR operator.
175 case BO_Or: // Bitwise OR operator.
176 // Handle things like (x==2)|(y==12).
177 return BO->getLHS()->isKnownToHaveBooleanValue(Semantic) &&
178 BO->getRHS()->isKnownToHaveBooleanValue(Semantic);
179
180 case BO_Comma:
181 case BO_Assign:
182 return BO->getRHS()->isKnownToHaveBooleanValue(Semantic);
183 }
184 }
185
186 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
187 return CO->getTrueExpr()->isKnownToHaveBooleanValue(Semantic) &&
188 CO->getFalseExpr()->isKnownToHaveBooleanValue(Semantic);
189
190 if (isa<ObjCBoolLiteralExpr>(E))
191 return true;
192
193 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
194 return OVE->getSourceExpr()->isKnownToHaveBooleanValue(Semantic);
195
196 if (const FieldDecl *FD = E->getSourceBitField())
197 if (!Semantic && FD->getType()->isUnsignedIntegerType() &&
198 !FD->getBitWidth()->isValueDependent() &&
199 FD->getBitWidthValue(FD->getASTContext()) == 1)
200 return true;
201
202 return false;
203}
204
205// Amusing macro metaprogramming hack: check whether a class provides
206// a more specific implementation of getExprLoc().
207//
208// See also Stmt.cpp:{getBeginLoc(),getEndLoc()}.
209namespace {
210 /// This implementation is used when a class provides a custom
211 /// implementation of getExprLoc.
212 template <class E, class T>
213 SourceLocation getExprLocImpl(const Expr *expr,
214 SourceLocation (T::*v)() const) {
215 return static_cast<const E*>(expr)->getExprLoc();
216 }
217
218 /// This implementation is used when a class doesn't provide
219 /// a custom implementation of getExprLoc. Overload resolution
220 /// should pick it over the implementation above because it's
221 /// more specialized according to function template partial ordering.
222 template <class E>
223 SourceLocation getExprLocImpl(const Expr *expr,
224 SourceLocation (Expr::*v)() const) {
225 return static_cast<const E *>(expr)->getBeginLoc();
226 }
227}
228
229SourceLocation Expr::getExprLoc() const {
230 switch (getStmtClass()) {
231 case Stmt::NoStmtClass: llvm_unreachable("statement without class")::llvm::llvm_unreachable_internal("statement without class", "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 231)
;
232#define ABSTRACT_STMT(type)
233#define STMT(type, base) \
234 case Stmt::type##Class: break;
235#define EXPR(type, base) \
236 case Stmt::type##Class: return getExprLocImpl<type>(this, &type::getExprLoc);
237#include "clang/AST/StmtNodes.inc"
238 }
239 llvm_unreachable("unknown expression kind")::llvm::llvm_unreachable_internal("unknown expression kind", "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 239)
;
240}
241
242//===----------------------------------------------------------------------===//
243// Primary Expressions.
244//===----------------------------------------------------------------------===//
245
246static void AssertResultStorageKind(ConstantExpr::ResultStorageKind Kind) {
247 assert((Kind == ConstantExpr::RSK_APValue ||(static_cast <bool> ((Kind == ConstantExpr::RSK_APValue
|| Kind == ConstantExpr::RSK_Int64 || Kind == ConstantExpr::
RSK_None) && "Invalid StorageKind Value") ? void (0) :
__assert_fail ("(Kind == ConstantExpr::RSK_APValue || Kind == ConstantExpr::RSK_Int64 || Kind == ConstantExpr::RSK_None) && \"Invalid StorageKind Value\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 249, __extension__ __PRETTY_FUNCTION__))
248 Kind == ConstantExpr::RSK_Int64 || Kind == ConstantExpr::RSK_None) &&(static_cast <bool> ((Kind == ConstantExpr::RSK_APValue
|| Kind == ConstantExpr::RSK_Int64 || Kind == ConstantExpr::
RSK_None) && "Invalid StorageKind Value") ? void (0) :
__assert_fail ("(Kind == ConstantExpr::RSK_APValue || Kind == ConstantExpr::RSK_Int64 || Kind == ConstantExpr::RSK_None) && \"Invalid StorageKind Value\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 249, __extension__ __PRETTY_FUNCTION__))
249 "Invalid StorageKind Value")(static_cast <bool> ((Kind == ConstantExpr::RSK_APValue
|| Kind == ConstantExpr::RSK_Int64 || Kind == ConstantExpr::
RSK_None) && "Invalid StorageKind Value") ? void (0) :
__assert_fail ("(Kind == ConstantExpr::RSK_APValue || Kind == ConstantExpr::RSK_Int64 || Kind == ConstantExpr::RSK_None) && \"Invalid StorageKind Value\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 249, __extension__ __PRETTY_FUNCTION__))
;
250 (void)Kind;
251}
252
253ConstantExpr::ResultStorageKind
254ConstantExpr::getStorageKind(const APValue &Value) {
255 switch (Value.getKind()) {
256 case APValue::None:
257 case APValue::Indeterminate:
258 return ConstantExpr::RSK_None;
259 case APValue::Int:
260 if (!Value.getInt().needsCleanup())
261 return ConstantExpr::RSK_Int64;
262 LLVM_FALLTHROUGH[[gnu::fallthrough]];
263 default:
264 return ConstantExpr::RSK_APValue;
265 }
266}
267
268ConstantExpr::ResultStorageKind
269ConstantExpr::getStorageKind(const Type *T, const ASTContext &Context) {
270 if (T->isIntegralOrEnumerationType() && Context.getTypeInfo(T).Width <= 64)
271 return ConstantExpr::RSK_Int64;
272 return ConstantExpr::RSK_APValue;
273}
274
275ConstantExpr::ConstantExpr(Expr *SubExpr, ResultStorageKind StorageKind,
276 bool IsImmediateInvocation)
277 : FullExpr(ConstantExprClass, SubExpr) {
278 ConstantExprBits.ResultKind = StorageKind;
279 ConstantExprBits.APValueKind = APValue::None;
280 ConstantExprBits.IsUnsigned = false;
281 ConstantExprBits.BitWidth = 0;
282 ConstantExprBits.HasCleanup = false;
283 ConstantExprBits.IsImmediateInvocation = IsImmediateInvocation;
284
285 if (StorageKind == ConstantExpr::RSK_APValue)
286 ::new (getTrailingObjects<APValue>()) APValue();
287}
288
289ConstantExpr *ConstantExpr::Create(const ASTContext &Context, Expr *E,
290 ResultStorageKind StorageKind,
291 bool IsImmediateInvocation) {
292 assert(!isa<ConstantExpr>(E))(static_cast <bool> (!isa<ConstantExpr>(E)) ? void
(0) : __assert_fail ("!isa<ConstantExpr>(E)", "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 292, __extension__ __PRETTY_FUNCTION__))
;
293 AssertResultStorageKind(StorageKind);
294
295 unsigned Size = totalSizeToAlloc<APValue, uint64_t>(
296 StorageKind == ConstantExpr::RSK_APValue,
297 StorageKind == ConstantExpr::RSK_Int64);
298 void *Mem = Context.Allocate(Size, alignof(ConstantExpr));
299 return new (Mem) ConstantExpr(E, StorageKind, IsImmediateInvocation);
300}
301
302ConstantExpr *ConstantExpr::Create(const ASTContext &Context, Expr *E,
303 const APValue &Result) {
304 ResultStorageKind StorageKind = getStorageKind(Result);
305 ConstantExpr *Self = Create(Context, E, StorageKind);
306 Self->SetResult(Result, Context);
307 return Self;
308}
309
310ConstantExpr::ConstantExpr(EmptyShell Empty, ResultStorageKind StorageKind)
311 : FullExpr(ConstantExprClass, Empty) {
312 ConstantExprBits.ResultKind = StorageKind;
313
314 if (StorageKind == ConstantExpr::RSK_APValue)
315 ::new (getTrailingObjects<APValue>()) APValue();
316}
317
318ConstantExpr *ConstantExpr::CreateEmpty(const ASTContext &Context,
319 ResultStorageKind StorageKind) {
320 AssertResultStorageKind(StorageKind);
321
322 unsigned Size = totalSizeToAlloc<APValue, uint64_t>(
323 StorageKind == ConstantExpr::RSK_APValue,
324 StorageKind == ConstantExpr::RSK_Int64);
325 void *Mem = Context.Allocate(Size, alignof(ConstantExpr));
326 return new (Mem) ConstantExpr(EmptyShell(), StorageKind);
327}
328
329void ConstantExpr::MoveIntoResult(APValue &Value, const ASTContext &Context) {
330 assert((unsigned)getStorageKind(Value) <= ConstantExprBits.ResultKind &&(static_cast <bool> ((unsigned)getStorageKind(Value) <=
ConstantExprBits.ResultKind && "Invalid storage for this value kind"
) ? void (0) : __assert_fail ("(unsigned)getStorageKind(Value) <= ConstantExprBits.ResultKind && \"Invalid storage for this value kind\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 331, __extension__ __PRETTY_FUNCTION__))
331 "Invalid storage for this value kind")(static_cast <bool> ((unsigned)getStorageKind(Value) <=
ConstantExprBits.ResultKind && "Invalid storage for this value kind"
) ? void (0) : __assert_fail ("(unsigned)getStorageKind(Value) <= ConstantExprBits.ResultKind && \"Invalid storage for this value kind\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 331, __extension__ __PRETTY_FUNCTION__))
;
332 ConstantExprBits.APValueKind = Value.getKind();
333 switch (ConstantExprBits.ResultKind) {
334 case RSK_None:
335 return;
336 case RSK_Int64:
337 Int64Result() = *Value.getInt().getRawData();
338 ConstantExprBits.BitWidth = Value.getInt().getBitWidth();
339 ConstantExprBits.IsUnsigned = Value.getInt().isUnsigned();
340 return;
341 case RSK_APValue:
342 if (!ConstantExprBits.HasCleanup && Value.needsCleanup()) {
343 ConstantExprBits.HasCleanup = true;
344 Context.addDestruction(&APValueResult());
345 }
346 APValueResult() = std::move(Value);
347 return;
348 }
349 llvm_unreachable("Invalid ResultKind Bits")::llvm::llvm_unreachable_internal("Invalid ResultKind Bits", "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 349)
;
350}
351
352llvm::APSInt ConstantExpr::getResultAsAPSInt() const {
353 switch (ConstantExprBits.ResultKind) {
354 case ConstantExpr::RSK_APValue:
355 return APValueResult().getInt();
356 case ConstantExpr::RSK_Int64:
357 return llvm::APSInt(llvm::APInt(ConstantExprBits.BitWidth, Int64Result()),
358 ConstantExprBits.IsUnsigned);
359 default:
360 llvm_unreachable("invalid Accessor")::llvm::llvm_unreachable_internal("invalid Accessor", "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 360)
;
361 }
362}
363
364APValue ConstantExpr::getAPValueResult() const {
365
366 switch (ConstantExprBits.ResultKind) {
367 case ConstantExpr::RSK_APValue:
368 return APValueResult();
369 case ConstantExpr::RSK_Int64:
370 return APValue(
371 llvm::APSInt(llvm::APInt(ConstantExprBits.BitWidth, Int64Result()),
372 ConstantExprBits.IsUnsigned));
373 case ConstantExpr::RSK_None:
374 if (ConstantExprBits.APValueKind == APValue::Indeterminate)
375 return APValue::IndeterminateValue();
376 return APValue();
377 }
378 llvm_unreachable("invalid ResultKind")::llvm::llvm_unreachable_internal("invalid ResultKind", "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 378)
;
379}
380
381DeclRefExpr::DeclRefExpr(const ASTContext &Ctx, ValueDecl *D,
382 bool RefersToEnclosingVariableOrCapture, QualType T,
383 ExprValueKind VK, SourceLocation L,
384 const DeclarationNameLoc &LocInfo,
385 NonOdrUseReason NOUR)
386 : Expr(DeclRefExprClass, T, VK, OK_Ordinary), D(D), DNLoc(LocInfo) {
387 DeclRefExprBits.HasQualifier = false;
388 DeclRefExprBits.HasTemplateKWAndArgsInfo = false;
389 DeclRefExprBits.HasFoundDecl = false;
390 DeclRefExprBits.HadMultipleCandidates = false;
391 DeclRefExprBits.RefersToEnclosingVariableOrCapture =
392 RefersToEnclosingVariableOrCapture;
393 DeclRefExprBits.NonOdrUseReason = NOUR;
394 DeclRefExprBits.Loc = L;
395 setDependence(computeDependence(this, Ctx));
396}
397
398DeclRefExpr::DeclRefExpr(const ASTContext &Ctx,
399 NestedNameSpecifierLoc QualifierLoc,
400 SourceLocation TemplateKWLoc, ValueDecl *D,
401 bool RefersToEnclosingVariableOrCapture,
402 const DeclarationNameInfo &NameInfo, NamedDecl *FoundD,
403 const TemplateArgumentListInfo *TemplateArgs,
404 QualType T, ExprValueKind VK, NonOdrUseReason NOUR)
405 : Expr(DeclRefExprClass, T, VK, OK_Ordinary), D(D),
406 DNLoc(NameInfo.getInfo()) {
407 DeclRefExprBits.Loc = NameInfo.getLoc();
408 DeclRefExprBits.HasQualifier = QualifierLoc ? 1 : 0;
409 if (QualifierLoc)
410 new (getTrailingObjects<NestedNameSpecifierLoc>())
411 NestedNameSpecifierLoc(QualifierLoc);
412 DeclRefExprBits.HasFoundDecl = FoundD ? 1 : 0;
413 if (FoundD)
414 *getTrailingObjects<NamedDecl *>() = FoundD;
415 DeclRefExprBits.HasTemplateKWAndArgsInfo
416 = (TemplateArgs || TemplateKWLoc.isValid()) ? 1 : 0;
417 DeclRefExprBits.RefersToEnclosingVariableOrCapture =
418 RefersToEnclosingVariableOrCapture;
419 DeclRefExprBits.NonOdrUseReason = NOUR;
420 if (TemplateArgs) {
421 auto Deps = TemplateArgumentDependence::None;
422 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
423 TemplateKWLoc, *TemplateArgs, getTrailingObjects<TemplateArgumentLoc>(),
424 Deps);
425 assert(!(Deps & TemplateArgumentDependence::Dependent) &&(static_cast <bool> (!(Deps & TemplateArgumentDependence
::Dependent) && "built a DeclRefExpr with dependent template args"
) ? void (0) : __assert_fail ("!(Deps & TemplateArgumentDependence::Dependent) && \"built a DeclRefExpr with dependent template args\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 426, __extension__ __PRETTY_FUNCTION__))
426 "built a DeclRefExpr with dependent template args")(static_cast <bool> (!(Deps & TemplateArgumentDependence
::Dependent) && "built a DeclRefExpr with dependent template args"
) ? void (0) : __assert_fail ("!(Deps & TemplateArgumentDependence::Dependent) && \"built a DeclRefExpr with dependent template args\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 426, __extension__ __PRETTY_FUNCTION__))
;
427 } else if (TemplateKWLoc.isValid()) {
428 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
429 TemplateKWLoc);
430 }
431 DeclRefExprBits.HadMultipleCandidates = 0;
432 setDependence(computeDependence(this, Ctx));
433}
434
435DeclRefExpr *DeclRefExpr::Create(const ASTContext &Context,
436 NestedNameSpecifierLoc QualifierLoc,
437 SourceLocation TemplateKWLoc, ValueDecl *D,
438 bool RefersToEnclosingVariableOrCapture,
439 SourceLocation NameLoc, QualType T,
440 ExprValueKind VK, NamedDecl *FoundD,
441 const TemplateArgumentListInfo *TemplateArgs,
442 NonOdrUseReason NOUR) {
443 return Create(Context, QualifierLoc, TemplateKWLoc, D,
444 RefersToEnclosingVariableOrCapture,
445 DeclarationNameInfo(D->getDeclName(), NameLoc),
446 T, VK, FoundD, TemplateArgs, NOUR);
447}
448
449DeclRefExpr *DeclRefExpr::Create(const ASTContext &Context,
450 NestedNameSpecifierLoc QualifierLoc,
451 SourceLocation TemplateKWLoc, ValueDecl *D,
452 bool RefersToEnclosingVariableOrCapture,
453 const DeclarationNameInfo &NameInfo,
454 QualType T, ExprValueKind VK,
455 NamedDecl *FoundD,
456 const TemplateArgumentListInfo *TemplateArgs,
457 NonOdrUseReason NOUR) {
458 // Filter out cases where the found Decl is the same as the value refenenced.
459 if (D == FoundD)
460 FoundD = nullptr;
461
462 bool HasTemplateKWAndArgsInfo = TemplateArgs || TemplateKWLoc.isValid();
463 std::size_t Size =
464 totalSizeToAlloc<NestedNameSpecifierLoc, NamedDecl *,
465 ASTTemplateKWAndArgsInfo, TemplateArgumentLoc>(
466 QualifierLoc ? 1 : 0, FoundD ? 1 : 0,
467 HasTemplateKWAndArgsInfo ? 1 : 0,
468 TemplateArgs ? TemplateArgs->size() : 0);
469
470 void *Mem = Context.Allocate(Size, alignof(DeclRefExpr));
471 return new (Mem) DeclRefExpr(Context, QualifierLoc, TemplateKWLoc, D,
472 RefersToEnclosingVariableOrCapture, NameInfo,
473 FoundD, TemplateArgs, T, VK, NOUR);
474}
475
476DeclRefExpr *DeclRefExpr::CreateEmpty(const ASTContext &Context,
477 bool HasQualifier,
478 bool HasFoundDecl,
479 bool HasTemplateKWAndArgsInfo,
480 unsigned NumTemplateArgs) {
481 assert(NumTemplateArgs == 0 || HasTemplateKWAndArgsInfo)(static_cast <bool> (NumTemplateArgs == 0 || HasTemplateKWAndArgsInfo
) ? void (0) : __assert_fail ("NumTemplateArgs == 0 || HasTemplateKWAndArgsInfo"
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 481, __extension__ __PRETTY_FUNCTION__))
;
482 std::size_t Size =
483 totalSizeToAlloc<NestedNameSpecifierLoc, NamedDecl *,
484 ASTTemplateKWAndArgsInfo, TemplateArgumentLoc>(
485 HasQualifier ? 1 : 0, HasFoundDecl ? 1 : 0, HasTemplateKWAndArgsInfo,
486 NumTemplateArgs);
487 void *Mem = Context.Allocate(Size, alignof(DeclRefExpr));
488 return new (Mem) DeclRefExpr(EmptyShell());
489}
490
491void DeclRefExpr::setDecl(ValueDecl *NewD) {
492 D = NewD;
493 setDependence(computeDependence(this, NewD->getASTContext()));
494}
495
496SourceLocation DeclRefExpr::getBeginLoc() const {
497 if (hasQualifier())
498 return getQualifierLoc().getBeginLoc();
499 return getNameInfo().getBeginLoc();
500}
501SourceLocation DeclRefExpr::getEndLoc() const {
502 if (hasExplicitTemplateArgs())
503 return getRAngleLoc();
504 return getNameInfo().getEndLoc();
505}
506
507SYCLUniqueStableNameExpr::SYCLUniqueStableNameExpr(SourceLocation OpLoc,
508 SourceLocation LParen,
509 SourceLocation RParen,
510 QualType ResultTy,
511 TypeSourceInfo *TSI)
512 : Expr(SYCLUniqueStableNameExprClass, ResultTy, VK_PRValue, OK_Ordinary),
513 OpLoc(OpLoc), LParen(LParen), RParen(RParen) {
514 setTypeSourceInfo(TSI);
515 setDependence(computeDependence(this));
516}
517
518SYCLUniqueStableNameExpr::SYCLUniqueStableNameExpr(EmptyShell Empty,
519 QualType ResultTy)
520 : Expr(SYCLUniqueStableNameExprClass, ResultTy, VK_PRValue, OK_Ordinary) {}
521
522SYCLUniqueStableNameExpr *
523SYCLUniqueStableNameExpr::Create(const ASTContext &Ctx, SourceLocation OpLoc,
524 SourceLocation LParen, SourceLocation RParen,
525 TypeSourceInfo *TSI) {
526 QualType ResultTy = Ctx.getPointerType(Ctx.CharTy.withConst());
527 return new (Ctx)
528 SYCLUniqueStableNameExpr(OpLoc, LParen, RParen, ResultTy, TSI);
529}
530
531SYCLUniqueStableNameExpr *
532SYCLUniqueStableNameExpr::CreateEmpty(const ASTContext &Ctx) {
533 QualType ResultTy = Ctx.getPointerType(Ctx.CharTy.withConst());
534 return new (Ctx) SYCLUniqueStableNameExpr(EmptyShell(), ResultTy);
535}
536
537std::string SYCLUniqueStableNameExpr::ComputeName(ASTContext &Context) const {
538 return SYCLUniqueStableNameExpr::ComputeName(Context,
539 getTypeSourceInfo()->getType());
540}
541
542std::string SYCLUniqueStableNameExpr::ComputeName(ASTContext &Context,
543 QualType Ty) {
544 auto MangleCallback = [](ASTContext &Ctx,
545 const NamedDecl *ND) -> llvm::Optional<unsigned> {
546 // This replaces the 'lambda number' in the mangling with a unique number
547 // based on its order in the declaration. To provide some level of visual
548 // notability (actual uniqueness from normal lambdas isn't necessary, as
549 // these are used differently), we add 10,000 to the number.
550 // For example:
551 // _ZTSZ3foovEUlvE10005_
552 // Demangles to: typeinfo name for foo()::'lambda10005'()
553 // Note that the mangler subtracts 2, since with normal lambdas the lambda
554 // mangling number '0' is an anonymous struct mangle, and '1' is omitted.
555 // So 10,002 results in the first number being 10,000.
556 if (Ctx.IsSYCLKernelNamingDecl(ND))
557 return 10'002 + Ctx.GetSYCLKernelNamingIndex(ND);
558 return llvm::None;
559 };
560 std::unique_ptr<MangleContext> Ctx{ItaniumMangleContext::create(
561 Context, Context.getDiagnostics(), MangleCallback)};
562
563 std::string Buffer;
564 Buffer.reserve(128);
565 llvm::raw_string_ostream Out(Buffer);
566 Ctx->mangleTypeName(Ty, Out);
567
568 return Out.str();
569}
570
571PredefinedExpr::PredefinedExpr(SourceLocation L, QualType FNTy, IdentKind IK,
572 StringLiteral *SL)
573 : Expr(PredefinedExprClass, FNTy, VK_LValue, OK_Ordinary) {
574 PredefinedExprBits.Kind = IK;
575 assert((getIdentKind() == IK) &&(static_cast <bool> ((getIdentKind() == IK) && "IdentKind do not fit in PredefinedExprBitfields!"
) ? void (0) : __assert_fail ("(getIdentKind() == IK) && \"IdentKind do not fit in PredefinedExprBitfields!\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 576, __extension__ __PRETTY_FUNCTION__))
576 "IdentKind do not fit in PredefinedExprBitfields!")(static_cast <bool> ((getIdentKind() == IK) && "IdentKind do not fit in PredefinedExprBitfields!"
) ? void (0) : __assert_fail ("(getIdentKind() == IK) && \"IdentKind do not fit in PredefinedExprBitfields!\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 576, __extension__ __PRETTY_FUNCTION__))
;
577 bool HasFunctionName = SL != nullptr;
578 PredefinedExprBits.HasFunctionName = HasFunctionName;
579 PredefinedExprBits.Loc = L;
580 if (HasFunctionName)
581 setFunctionName(SL);
582 setDependence(computeDependence(this));
583}
584
585PredefinedExpr::PredefinedExpr(EmptyShell Empty, bool HasFunctionName)
586 : Expr(PredefinedExprClass, Empty) {
587 PredefinedExprBits.HasFunctionName = HasFunctionName;
588}
589
590PredefinedExpr *PredefinedExpr::Create(const ASTContext &Ctx, SourceLocation L,
591 QualType FNTy, IdentKind IK,
592 StringLiteral *SL) {
593 bool HasFunctionName = SL != nullptr;
594 void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *>(HasFunctionName),
595 alignof(PredefinedExpr));
596 return new (Mem) PredefinedExpr(L, FNTy, IK, SL);
597}
598
599PredefinedExpr *PredefinedExpr::CreateEmpty(const ASTContext &Ctx,
600 bool HasFunctionName) {
601 void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *>(HasFunctionName),
602 alignof(PredefinedExpr));
603 return new (Mem) PredefinedExpr(EmptyShell(), HasFunctionName);
604}
605
606StringRef PredefinedExpr::getIdentKindName(PredefinedExpr::IdentKind IK) {
607 switch (IK) {
608 case Func:
609 return "__func__";
610 case Function:
611 return "__FUNCTION__";
612 case FuncDName:
613 return "__FUNCDNAME__";
614 case LFunction:
615 return "L__FUNCTION__";
616 case PrettyFunction:
617 return "__PRETTY_FUNCTION__";
618 case FuncSig:
619 return "__FUNCSIG__";
620 case LFuncSig:
621 return "L__FUNCSIG__";
622 case PrettyFunctionNoVirtual:
623 break;
624 }
625 llvm_unreachable("Unknown ident kind for PredefinedExpr")::llvm::llvm_unreachable_internal("Unknown ident kind for PredefinedExpr"
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 625)
;
626}
627
628// FIXME: Maybe this should use DeclPrinter with a special "print predefined
629// expr" policy instead.
630std::string PredefinedExpr::ComputeName(IdentKind IK, const Decl *CurrentDecl) {
631 ASTContext &Context = CurrentDecl->getASTContext();
632
633 if (IK == PredefinedExpr::FuncDName) {
1
Assuming 'IK' is not equal to FuncDName
2
Taking false branch
634 if (const NamedDecl *ND = dyn_cast<NamedDecl>(CurrentDecl)) {
635 std::unique_ptr<MangleContext> MC;
636 MC.reset(Context.createMangleContext());
637
638 if (MC->shouldMangleDeclName(ND)) {
639 SmallString<256> Buffer;
640 llvm::raw_svector_ostream Out(Buffer);
641 GlobalDecl GD;
642 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(ND))
643 GD = GlobalDecl(CD, Ctor_Base);
644 else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(ND))
645 GD = GlobalDecl(DD, Dtor_Base);
646 else if (ND->hasAttr<CUDAGlobalAttr>())
647 GD = GlobalDecl(cast<FunctionDecl>(ND));
648 else
649 GD = GlobalDecl(ND);
650 MC->mangleName(GD, Out);
651
652 if (!Buffer.empty() && Buffer.front() == '\01')
653 return std::string(Buffer.substr(1));
654 return std::string(Buffer.str());
655 }
656 return std::string(ND->getIdentifier()->getName());
657 }
658 return "";
659 }
660 if (isa<BlockDecl>(CurrentDecl)) {
3
Assuming 'CurrentDecl' is not a 'BlockDecl'
4
Taking false branch
661 // For blocks we only emit something if it is enclosed in a function
662 // For top-level block we'd like to include the name of variable, but we
663 // don't have it at this point.
664 auto DC = CurrentDecl->getDeclContext();
665 if (DC->isFileContext())
666 return "";
667
668 SmallString<256> Buffer;
669 llvm::raw_svector_ostream Out(Buffer);
670 if (auto *DCBlock = dyn_cast<BlockDecl>(DC))
671 // For nested blocks, propagate up to the parent.
672 Out << ComputeName(IK, DCBlock);
673 else if (auto *DCDecl = dyn_cast<Decl>(DC))
674 Out << ComputeName(IK, DCDecl) << "_block_invoke";
675 return std::string(Out.str());
676 }
677 if (const FunctionDecl *FD
5.1
'FD' is non-null
5.1
'FD' is non-null
= dyn_cast<FunctionDecl>(CurrentDecl)) {
5
Assuming 'CurrentDecl' is a 'FunctionDecl'
6
Taking true branch
678 if (IK != PrettyFunction && IK != PrettyFunctionNoVirtual &&
7
Assuming 'IK' is equal to PrettyFunction
679 IK != FuncSig && IK != LFuncSig)
680 return FD->getNameAsString();
681
682 SmallString<256> Name;
683 llvm::raw_svector_ostream Out(Name);
684
685 if (const CXXMethodDecl *MD
8.1
'MD' is null
8.1
'MD' is null
= dyn_cast<CXXMethodDecl>(FD)) {
8
Assuming 'FD' is not a 'CXXMethodDecl'
9
Taking false branch
686 if (MD->isVirtual() && IK != PrettyFunctionNoVirtual)
687 Out << "virtual ";
688 if (MD->isStatic())
689 Out << "static ";
690 }
691
692 PrintingPolicy Policy(Context.getLangOpts());
693 std::string Proto;
694 llvm::raw_string_ostream POut(Proto);
695
696 const FunctionDecl *Decl = FD;
697 if (const FunctionDecl* Pattern = FD->getTemplateInstantiationPattern())
10
Assuming 'Pattern' is null
11
Taking false branch
698 Decl = Pattern;
699 const FunctionType *AFT = Decl->getType()->getAs<FunctionType>();
12
Assuming the object is not a 'FunctionType'
13
'AFT' initialized to a null pointer value
700 const FunctionProtoType *FT = nullptr;
701 if (FD->hasWrittenPrototype())
14
Assuming the condition is false
15
Taking false branch
702 FT = dyn_cast<FunctionProtoType>(AFT);
703
704 if (IK
15.1
'IK' is not equal to FuncSig
15.1
'IK' is not equal to FuncSig
== FuncSig || IK
15.2
'IK' is not equal to LFuncSig
15.2
'IK' is not equal to LFuncSig
== LFuncSig) {
16
Taking false branch
705 switch (AFT->getCallConv()) {
706 case CC_C: POut << "__cdecl "; break;
707 case CC_X86StdCall: POut << "__stdcall "; break;
708 case CC_X86FastCall: POut << "__fastcall "; break;
709 case CC_X86ThisCall: POut << "__thiscall "; break;
710 case CC_X86VectorCall: POut << "__vectorcall "; break;
711 case CC_X86RegCall: POut << "__regcall "; break;
712 // Only bother printing the conventions that MSVC knows about.
713 default: break;
714 }
715 }
716
717 FD->printQualifiedName(POut, Policy);
718
719 POut << "(";
720 if (FT
16.1
'FT' is null
16.1
'FT' is null
) {
17
Taking false branch
721 for (unsigned i = 0, e = Decl->getNumParams(); i != e; ++i) {
722 if (i) POut << ", ";
723 POut << Decl->getParamDecl(i)->getType().stream(Policy);
724 }
725
726 if (FT->isVariadic()) {
727 if (FD->getNumParams()) POut << ", ";
728 POut << "...";
729 } else if ((IK == FuncSig || IK == LFuncSig ||
730 !Context.getLangOpts().CPlusPlus) &&
731 !Decl->getNumParams()) {
732 POut << "void";
733 }
734 }
735 POut << ")";
736
737 if (const CXXMethodDecl *MD
18.1
'MD' is null
18.1
'MD' is null
= dyn_cast<CXXMethodDecl>(FD)) {
18
'FD' is not a 'CXXMethodDecl'
19
Taking false branch
738 assert(FT && "We must have a written prototype in this case.")(static_cast <bool> (FT && "We must have a written prototype in this case."
) ? void (0) : __assert_fail ("FT && \"We must have a written prototype in this case.\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 738, __extension__ __PRETTY_FUNCTION__))
;
739 if (FT->isConst())
740 POut << " const";
741 if (FT->isVolatile())
742 POut << " volatile";
743 RefQualifierKind Ref = MD->getRefQualifier();
744 if (Ref == RQ_LValue)
745 POut << " &";
746 else if (Ref == RQ_RValue)
747 POut << " &&";
748 }
749
750 typedef SmallVector<const ClassTemplateSpecializationDecl *, 8> SpecsTy;
751 SpecsTy Specs;
752 const DeclContext *Ctx = FD->getDeclContext();
753 while (Ctx && isa<NamedDecl>(Ctx)) {
20
Assuming 'Ctx' is null
754 const ClassTemplateSpecializationDecl *Spec
755 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx);
756 if (Spec && !Spec->isExplicitSpecialization())
757 Specs.push_back(Spec);
758 Ctx = Ctx->getParent();
759 }
760
761 std::string TemplateParams;
762 llvm::raw_string_ostream TOut(TemplateParams);
763 for (SpecsTy::reverse_iterator I = Specs.rbegin(), E = Specs.rend();
28
Loop condition is false. Execution continues on line 781
764 I != E; ++I) {
21
Calling 'operator!=<const clang::ClassTemplateSpecializationDecl **>'
27
Returning from 'operator!=<const clang::ClassTemplateSpecializationDecl **>'
765 const TemplateParameterList *Params
766 = (*I)->getSpecializedTemplate()->getTemplateParameters();
767 const TemplateArgumentList &Args = (*I)->getTemplateArgs();
768 assert(Params->size() == Args.size())(static_cast <bool> (Params->size() == Args.size()) ?
void (0) : __assert_fail ("Params->size() == Args.size()"
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 768, __extension__ __PRETTY_FUNCTION__))
;
769 for (unsigned i = 0, numParams = Params->size(); i != numParams; ++i) {
770 StringRef Param = Params->getParam(i)->getName();
771 if (Param.empty()) continue;
772 TOut << Param << " = ";
773 Args.get(i).print(
774 Policy, TOut,
775 TemplateParameterList::shouldIncludeTypeForArgument(Params, i));
776 TOut << ", ";
777 }
778 }
779
780 FunctionTemplateSpecializationInfo *FSI
781 = FD->getTemplateSpecializationInfo();
782 if (FSI && !FSI->isExplicitSpecialization()) {
29
Assuming 'FSI' is null
783 const TemplateParameterList* Params
784 = FSI->getTemplate()->getTemplateParameters();
785 const TemplateArgumentList* Args = FSI->TemplateArguments;
786 assert(Params->size() == Args->size())(static_cast <bool> (Params->size() == Args->size
()) ? void (0) : __assert_fail ("Params->size() == Args->size()"
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 786, __extension__ __PRETTY_FUNCTION__))
;
787 for (unsigned i = 0, e = Params->size(); i != e; ++i) {
788 StringRef Param = Params->getParam(i)->getName();
789 if (Param.empty()) continue;
790 TOut << Param << " = ";
791 Args->get(i).print(Policy, TOut, /*IncludeType*/ true);
792 TOut << ", ";
793 }
794 }
795
796 TOut.flush();
797 if (!TemplateParams.empty()) {
30
Assuming the condition is false
31
Taking false branch
798 // remove the trailing comma and space
799 TemplateParams.resize(TemplateParams.size() - 2);
800 POut << " [" << TemplateParams << "]";
801 }
802
803 POut.flush();
804
805 // Print "auto" for all deduced return types. This includes C++1y return
806 // type deduction and lambdas. For trailing return types resolve the
807 // decltype expression. Otherwise print the real type when this is
808 // not a constructor or destructor.
809 if (isa<CXXMethodDecl>(FD) &&
32
'FD' is not a 'CXXMethodDecl'
810 cast<CXXMethodDecl>(FD)->getParent()->isLambda())
811 Proto = "auto " + Proto;
812 else if (FT
32.1
'FT' is null
32.1
'FT' is null
&& FT->getReturnType()->getAs<DecltypeType>())
33
Taking false branch
813 FT->getReturnType()
814 ->getAs<DecltypeType>()
815 ->getUnderlyingType()
816 .getAsStringInternal(Proto, Policy);
817 else if (!isa<CXXConstructorDecl>(FD) && !isa<CXXDestructorDecl>(FD))
34
Assuming 'FD' is not a 'CXXConstructorDecl'
35
Assuming 'FD' is not a 'CXXDestructorDecl'
36
Taking true branch
818 AFT->getReturnType().getAsStringInternal(Proto, Policy);
37
Called C++ object pointer is null
819
820 Out << Proto;
821
822 return std::string(Name);
823 }
824 if (const CapturedDecl *CD = dyn_cast<CapturedDecl>(CurrentDecl)) {
825 for (const DeclContext *DC = CD->getParent(); DC; DC = DC->getParent())
826 // Skip to its enclosing function or method, but not its enclosing
827 // CapturedDecl.
828 if (DC->isFunctionOrMethod() && (DC->getDeclKind() != Decl::Captured)) {
829 const Decl *D = Decl::castFromDeclContext(DC);
830 return ComputeName(IK, D);
831 }
832 llvm_unreachable("CapturedDecl not inside a function or method")::llvm::llvm_unreachable_internal("CapturedDecl not inside a function or method"
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 832)
;
833 }
834 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurrentDecl)) {
835 SmallString<256> Name;
836 llvm::raw_svector_ostream Out(Name);
837 Out << (MD->isInstanceMethod() ? '-' : '+');
838 Out << '[';
839
840 // For incorrect code, there might not be an ObjCInterfaceDecl. Do
841 // a null check to avoid a crash.
842 if (const ObjCInterfaceDecl *ID = MD->getClassInterface())
843 Out << *ID;
844
845 if (const ObjCCategoryImplDecl *CID =
846 dyn_cast<ObjCCategoryImplDecl>(MD->getDeclContext()))
847 Out << '(' << *CID << ')';
848
849 Out << ' ';
850 MD->getSelector().print(Out);
851 Out << ']';
852
853 return std::string(Name);
854 }
855 if (isa<TranslationUnitDecl>(CurrentDecl) && IK == PrettyFunction) {
856 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
857 return "top level";
858 }
859 return "";
860}
861
862void APNumericStorage::setIntValue(const ASTContext &C,
863 const llvm::APInt &Val) {
864 if (hasAllocation())
865 C.Deallocate(pVal);
866
867 BitWidth = Val.getBitWidth();
868 unsigned NumWords = Val.getNumWords();
869 const uint64_t* Words = Val.getRawData();
870 if (NumWords > 1) {
871 pVal = new (C) uint64_t[NumWords];
872 std::copy(Words, Words + NumWords, pVal);
873 } else if (NumWords == 1)
874 VAL = Words[0];
875 else
876 VAL = 0;
877}
878
879IntegerLiteral::IntegerLiteral(const ASTContext &C, const llvm::APInt &V,
880 QualType type, SourceLocation l)
881 : Expr(IntegerLiteralClass, type, VK_PRValue, OK_Ordinary), Loc(l) {
882 assert(type->isIntegerType() && "Illegal type in IntegerLiteral")(static_cast <bool> (type->isIntegerType() &&
"Illegal type in IntegerLiteral") ? void (0) : __assert_fail
("type->isIntegerType() && \"Illegal type in IntegerLiteral\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 882, __extension__ __PRETTY_FUNCTION__))
;
883 assert(V.getBitWidth() == C.getIntWidth(type) &&(static_cast <bool> (V.getBitWidth() == C.getIntWidth(type
) && "Integer type is not the correct size for constant."
) ? void (0) : __assert_fail ("V.getBitWidth() == C.getIntWidth(type) && \"Integer type is not the correct size for constant.\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 884, __extension__ __PRETTY_FUNCTION__))
884 "Integer type is not the correct size for constant.")(static_cast <bool> (V.getBitWidth() == C.getIntWidth(type
) && "Integer type is not the correct size for constant."
) ? void (0) : __assert_fail ("V.getBitWidth() == C.getIntWidth(type) && \"Integer type is not the correct size for constant.\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 884, __extension__ __PRETTY_FUNCTION__))
;
885 setValue(C, V);
886 setDependence(ExprDependence::None);
887}
888
889IntegerLiteral *
890IntegerLiteral::Create(const ASTContext &C, const llvm::APInt &V,
891 QualType type, SourceLocation l) {
892 return new (C) IntegerLiteral(C, V, type, l);
893}
894
895IntegerLiteral *
896IntegerLiteral::Create(const ASTContext &C, EmptyShell Empty) {
897 return new (C) IntegerLiteral(Empty);
898}
899
900FixedPointLiteral::FixedPointLiteral(const ASTContext &C, const llvm::APInt &V,
901 QualType type, SourceLocation l,
902 unsigned Scale)
903 : Expr(FixedPointLiteralClass, type, VK_PRValue, OK_Ordinary), Loc(l),
904 Scale(Scale) {
905 assert(type->isFixedPointType() && "Illegal type in FixedPointLiteral")(static_cast <bool> (type->isFixedPointType() &&
"Illegal type in FixedPointLiteral") ? void (0) : __assert_fail
("type->isFixedPointType() && \"Illegal type in FixedPointLiteral\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 905, __extension__ __PRETTY_FUNCTION__))
;
906 assert(V.getBitWidth() == C.getTypeInfo(type).Width &&(static_cast <bool> (V.getBitWidth() == C.getTypeInfo(type
).Width && "Fixed point type is not the correct size for constant."
) ? void (0) : __assert_fail ("V.getBitWidth() == C.getTypeInfo(type).Width && \"Fixed point type is not the correct size for constant.\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 907, __extension__ __PRETTY_FUNCTION__))
907 "Fixed point type is not the correct size for constant.")(static_cast <bool> (V.getBitWidth() == C.getTypeInfo(type
).Width && "Fixed point type is not the correct size for constant."
) ? void (0) : __assert_fail ("V.getBitWidth() == C.getTypeInfo(type).Width && \"Fixed point type is not the correct size for constant.\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 907, __extension__ __PRETTY_FUNCTION__))
;
908 setValue(C, V);
909 setDependence(ExprDependence::None);
910}
911
912FixedPointLiteral *FixedPointLiteral::CreateFromRawInt(const ASTContext &C,
913 const llvm::APInt &V,
914 QualType type,
915 SourceLocation l,
916 unsigned Scale) {
917 return new (C) FixedPointLiteral(C, V, type, l, Scale);
918}
919
920FixedPointLiteral *FixedPointLiteral::Create(const ASTContext &C,
921 EmptyShell Empty) {
922 return new (C) FixedPointLiteral(Empty);
923}
924
925std::string FixedPointLiteral::getValueAsString(unsigned Radix) const {
926 // Currently the longest decimal number that can be printed is the max for an
927 // unsigned long _Accum: 4294967295.99999999976716935634613037109375
928 // which is 43 characters.
929 SmallString<64> S;
930 FixedPointValueToString(
931 S, llvm::APSInt::getUnsigned(getValue().getZExtValue()), Scale);
932 return std::string(S.str());
933}
934
935void CharacterLiteral::print(unsigned Val, CharacterKind Kind,
936 raw_ostream &OS) {
937 switch (Kind) {
938 case CharacterLiteral::Ascii:
939 break; // no prefix.
940 case CharacterLiteral::Wide:
941 OS << 'L';
942 break;
943 case CharacterLiteral::UTF8:
944 OS << "u8";
945 break;
946 case CharacterLiteral::UTF16:
947 OS << 'u';
948 break;
949 case CharacterLiteral::UTF32:
950 OS << 'U';
951 break;
952 }
953
954 switch (Val) {
955 case '\\':
956 OS << "'\\\\'";
957 break;
958 case '\'':
959 OS << "'\\''";
960 break;
961 case '\a':
962 // TODO: K&R: the meaning of '\\a' is different in traditional C
963 OS << "'\\a'";
964 break;
965 case '\b':
966 OS << "'\\b'";
967 break;
968 // Nonstandard escape sequence.
969 /*case '\e':
970 OS << "'\\e'";
971 break;*/
972 case '\f':
973 OS << "'\\f'";
974 break;
975 case '\n':
976 OS << "'\\n'";
977 break;
978 case '\r':
979 OS << "'\\r'";
980 break;
981 case '\t':
982 OS << "'\\t'";
983 break;
984 case '\v':
985 OS << "'\\v'";
986 break;
987 default:
988 // A character literal might be sign-extended, which
989 // would result in an invalid \U escape sequence.
990 // FIXME: multicharacter literals such as '\xFF\xFF\xFF\xFF'
991 // are not correctly handled.
992 if ((Val & ~0xFFu) == ~0xFFu && Kind == CharacterLiteral::Ascii)
993 Val &= 0xFFu;
994 if (Val < 256 && isPrintable((unsigned char)Val))
995 OS << "'" << (char)Val << "'";
996 else if (Val < 256)
997 OS << "'\\x" << llvm::format("%02x", Val) << "'";
998 else if (Val <= 0xFFFF)
999 OS << "'\\u" << llvm::format("%04x", Val) << "'";
1000 else
1001 OS << "'\\U" << llvm::format("%08x", Val) << "'";
1002 }
1003}
1004
1005FloatingLiteral::FloatingLiteral(const ASTContext &C, const llvm::APFloat &V,
1006 bool isexact, QualType Type, SourceLocation L)
1007 : Expr(FloatingLiteralClass, Type, VK_PRValue, OK_Ordinary), Loc(L) {
1008 setSemantics(V.getSemantics());
1009 FloatingLiteralBits.IsExact = isexact;
1010 setValue(C, V);
1011 setDependence(ExprDependence::None);
1012}
1013
1014FloatingLiteral::FloatingLiteral(const ASTContext &C, EmptyShell Empty)
1015 : Expr(FloatingLiteralClass, Empty) {
1016 setRawSemantics(llvm::APFloatBase::S_IEEEhalf);
1017 FloatingLiteralBits.IsExact = false;
1018}
1019
1020FloatingLiteral *
1021FloatingLiteral::Create(const ASTContext &C, const llvm::APFloat &V,
1022 bool isexact, QualType Type, SourceLocation L) {
1023 return new (C) FloatingLiteral(C, V, isexact, Type, L);
1024}
1025
1026FloatingLiteral *
1027FloatingLiteral::Create(const ASTContext &C, EmptyShell Empty) {
1028 return new (C) FloatingLiteral(C, Empty);
1029}
1030
1031/// getValueAsApproximateDouble - This returns the value as an inaccurate
1032/// double. Note that this may cause loss of precision, but is useful for
1033/// debugging dumps, etc.
1034double FloatingLiteral::getValueAsApproximateDouble() const {
1035 llvm::APFloat V = getValue();
1036 bool ignored;
1037 V.convert(llvm::APFloat::IEEEdouble(), llvm::APFloat::rmNearestTiesToEven,
1038 &ignored);
1039 return V.convertToDouble();
1040}
1041
1042unsigned StringLiteral::mapCharByteWidth(TargetInfo const &Target,
1043 StringKind SK) {
1044 unsigned CharByteWidth = 0;
1045 switch (SK) {
1046 case Ascii:
1047 case UTF8:
1048 CharByteWidth = Target.getCharWidth();
1049 break;
1050 case Wide:
1051 CharByteWidth = Target.getWCharWidth();
1052 break;
1053 case UTF16:
1054 CharByteWidth = Target.getChar16Width();
1055 break;
1056 case UTF32:
1057 CharByteWidth = Target.getChar32Width();
1058 break;
1059 }
1060 assert((CharByteWidth & 7) == 0 && "Assumes character size is byte multiple")(static_cast <bool> ((CharByteWidth & 7) == 0 &&
"Assumes character size is byte multiple") ? void (0) : __assert_fail
("(CharByteWidth & 7) == 0 && \"Assumes character size is byte multiple\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 1060, __extension__ __PRETTY_FUNCTION__))
;
1061 CharByteWidth /= 8;
1062 assert((CharByteWidth == 1 || CharByteWidth == 2 || CharByteWidth == 4) &&(static_cast <bool> ((CharByteWidth == 1 || CharByteWidth
== 2 || CharByteWidth == 4) && "The only supported character byte widths are 1,2 and 4!"
) ? void (0) : __assert_fail ("(CharByteWidth == 1 || CharByteWidth == 2 || CharByteWidth == 4) && \"The only supported character byte widths are 1,2 and 4!\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 1063, __extension__ __PRETTY_FUNCTION__))
1063 "The only supported character byte widths are 1,2 and 4!")(static_cast <bool> ((CharByteWidth == 1 || CharByteWidth
== 2 || CharByteWidth == 4) && "The only supported character byte widths are 1,2 and 4!"
) ? void (0) : __assert_fail ("(CharByteWidth == 1 || CharByteWidth == 2 || CharByteWidth == 4) && \"The only supported character byte widths are 1,2 and 4!\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 1063, __extension__ __PRETTY_FUNCTION__))
;
1064 return CharByteWidth;
1065}
1066
1067StringLiteral::StringLiteral(const ASTContext &Ctx, StringRef Str,
1068 StringKind Kind, bool Pascal, QualType Ty,
1069 const SourceLocation *Loc,
1070 unsigned NumConcatenated)
1071 : Expr(StringLiteralClass, Ty, VK_LValue, OK_Ordinary) {
1072 assert(Ctx.getAsConstantArrayType(Ty) &&(static_cast <bool> (Ctx.getAsConstantArrayType(Ty) &&
"StringLiteral must be of constant array type!") ? void (0) :
__assert_fail ("Ctx.getAsConstantArrayType(Ty) && \"StringLiteral must be of constant array type!\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 1073, __extension__ __PRETTY_FUNCTION__))
1073 "StringLiteral must be of constant array type!")(static_cast <bool> (Ctx.getAsConstantArrayType(Ty) &&
"StringLiteral must be of constant array type!") ? void (0) :
__assert_fail ("Ctx.getAsConstantArrayType(Ty) && \"StringLiteral must be of constant array type!\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 1073, __extension__ __PRETTY_FUNCTION__))
;
1074 unsigned CharByteWidth = mapCharByteWidth(Ctx.getTargetInfo(), Kind);
1075 unsigned ByteLength = Str.size();
1076 assert((ByteLength % CharByteWidth == 0) &&(static_cast <bool> ((ByteLength % CharByteWidth == 0) &&
"The size of the data must be a multiple of CharByteWidth!")
? void (0) : __assert_fail ("(ByteLength % CharByteWidth == 0) && \"The size of the data must be a multiple of CharByteWidth!\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 1077, __extension__ __PRETTY_FUNCTION__))
1077 "The size of the data must be a multiple of CharByteWidth!")(static_cast <bool> ((ByteLength % CharByteWidth == 0) &&
"The size of the data must be a multiple of CharByteWidth!")
? void (0) : __assert_fail ("(ByteLength % CharByteWidth == 0) && \"The size of the data must be a multiple of CharByteWidth!\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 1077, __extension__ __PRETTY_FUNCTION__))
;
1078
1079 // Avoid the expensive division. The compiler should be able to figure it
1080 // out by itself. However as of clang 7, even with the appropriate
1081 // llvm_unreachable added just here, it is not able to do so.
1082 unsigned Length;
1083 switch (CharByteWidth) {
1084 case 1:
1085 Length = ByteLength;
1086 break;
1087 case 2:
1088 Length = ByteLength / 2;
1089 break;
1090 case 4:
1091 Length = ByteLength / 4;
1092 break;
1093 default:
1094 llvm_unreachable("Unsupported character width!")::llvm::llvm_unreachable_internal("Unsupported character width!"
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 1094)
;
1095 }
1096
1097 StringLiteralBits.Kind = Kind;
1098 StringLiteralBits.CharByteWidth = CharByteWidth;
1099 StringLiteralBits.IsPascal = Pascal;
1100 StringLiteralBits.NumConcatenated = NumConcatenated;
1101 *getTrailingObjects<unsigned>() = Length;
1102
1103 // Initialize the trailing array of SourceLocation.
1104 // This is safe since SourceLocation is POD-like.
1105 std::memcpy(getTrailingObjects<SourceLocation>(), Loc,
1106 NumConcatenated * sizeof(SourceLocation));
1107
1108 // Initialize the trailing array of char holding the string data.
1109 std::memcpy(getTrailingObjects<char>(), Str.data(), ByteLength);
1110
1111 setDependence(ExprDependence::None);
1112}
1113
1114StringLiteral::StringLiteral(EmptyShell Empty, unsigned NumConcatenated,
1115 unsigned Length, unsigned CharByteWidth)
1116 : Expr(StringLiteralClass, Empty) {
1117 StringLiteralBits.CharByteWidth = CharByteWidth;
1118 StringLiteralBits.NumConcatenated = NumConcatenated;
1119 *getTrailingObjects<unsigned>() = Length;
1120}
1121
1122StringLiteral *StringLiteral::Create(const ASTContext &Ctx, StringRef Str,
1123 StringKind Kind, bool Pascal, QualType Ty,
1124 const SourceLocation *Loc,
1125 unsigned NumConcatenated) {
1126 void *Mem = Ctx.Allocate(totalSizeToAlloc<unsigned, SourceLocation, char>(
1127 1, NumConcatenated, Str.size()),
1128 alignof(StringLiteral));
1129 return new (Mem)
1130 StringLiteral(Ctx, Str, Kind, Pascal, Ty, Loc, NumConcatenated);
1131}
1132
1133StringLiteral *StringLiteral::CreateEmpty(const ASTContext &Ctx,
1134 unsigned NumConcatenated,
1135 unsigned Length,
1136 unsigned CharByteWidth) {
1137 void *Mem = Ctx.Allocate(totalSizeToAlloc<unsigned, SourceLocation, char>(
1138 1, NumConcatenated, Length * CharByteWidth),
1139 alignof(StringLiteral));
1140 return new (Mem)
1141 StringLiteral(EmptyShell(), NumConcatenated, Length, CharByteWidth);
1142}
1143
1144void StringLiteral::outputString(raw_ostream &OS) const {
1145 switch (getKind()) {
1146 case Ascii: break; // no prefix.
1147 case Wide: OS << 'L'; break;
1148 case UTF8: OS << "u8"; break;
1149 case UTF16: OS << 'u'; break;
1150 case UTF32: OS << 'U'; break;
1151 }
1152 OS << '"';
1153 static const char Hex[] = "0123456789ABCDEF";
1154
1155 unsigned LastSlashX = getLength();
1156 for (unsigned I = 0, N = getLength(); I != N; ++I) {
1157 switch (uint32_t Char = getCodeUnit(I)) {
1158 default:
1159 // FIXME: Convert UTF-8 back to codepoints before rendering.
1160
1161 // Convert UTF-16 surrogate pairs back to codepoints before rendering.
1162 // Leave invalid surrogates alone; we'll use \x for those.
1163 if (getKind() == UTF16 && I != N - 1 && Char >= 0xd800 &&
1164 Char <= 0xdbff) {
1165 uint32_t Trail = getCodeUnit(I + 1);
1166 if (Trail >= 0xdc00 && Trail <= 0xdfff) {
1167 Char = 0x10000 + ((Char - 0xd800) << 10) + (Trail - 0xdc00);
1168 ++I;
1169 }
1170 }
1171
1172 if (Char > 0xff) {
1173 // If this is a wide string, output characters over 0xff using \x
1174 // escapes. Otherwise, this is a UTF-16 or UTF-32 string, and Char is a
1175 // codepoint: use \x escapes for invalid codepoints.
1176 if (getKind() == Wide ||
1177 (Char >= 0xd800 && Char <= 0xdfff) || Char >= 0x110000) {
1178 // FIXME: Is this the best way to print wchar_t?
1179 OS << "\\x";
1180 int Shift = 28;
1181 while ((Char >> Shift) == 0)
1182 Shift -= 4;
1183 for (/**/; Shift >= 0; Shift -= 4)
1184 OS << Hex[(Char >> Shift) & 15];
1185 LastSlashX = I;
1186 break;
1187 }
1188
1189 if (Char > 0xffff)
1190 OS << "\\U00"
1191 << Hex[(Char >> 20) & 15]
1192 << Hex[(Char >> 16) & 15];
1193 else
1194 OS << "\\u";
1195 OS << Hex[(Char >> 12) & 15]
1196 << Hex[(Char >> 8) & 15]
1197 << Hex[(Char >> 4) & 15]
1198 << Hex[(Char >> 0) & 15];
1199 break;
1200 }
1201
1202 // If we used \x... for the previous character, and this character is a
1203 // hexadecimal digit, prevent it being slurped as part of the \x.
1204 if (LastSlashX + 1 == I) {
1205 switch (Char) {
1206 case '0': case '1': case '2': case '3': case '4':
1207 case '5': case '6': case '7': case '8': case '9':
1208 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
1209 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
1210 OS << "\"\"";
1211 }
1212 }
1213
1214 assert(Char <= 0xff &&(static_cast <bool> (Char <= 0xff && "Characters above 0xff should already have been handled."
) ? void (0) : __assert_fail ("Char <= 0xff && \"Characters above 0xff should already have been handled.\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 1215, __extension__ __PRETTY_FUNCTION__))
1215 "Characters above 0xff should already have been handled.")(static_cast <bool> (Char <= 0xff && "Characters above 0xff should already have been handled."
) ? void (0) : __assert_fail ("Char <= 0xff && \"Characters above 0xff should already have been handled.\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 1215, __extension__ __PRETTY_FUNCTION__))
;
1216
1217 if (isPrintable(Char))
1218 OS << (char)Char;
1219 else // Output anything hard as an octal escape.
1220 OS << '\\'
1221 << (char)('0' + ((Char >> 6) & 7))
1222 << (char)('0' + ((Char >> 3) & 7))
1223 << (char)('0' + ((Char >> 0) & 7));
1224 break;
1225 // Handle some common non-printable cases to make dumps prettier.
1226 case '\\': OS << "\\\\"; break;
1227 case '"': OS << "\\\""; break;
1228 case '\a': OS << "\\a"; break;
1229 case '\b': OS << "\\b"; break;
1230 case '\f': OS << "\\f"; break;
1231 case '\n': OS << "\\n"; break;
1232 case '\r': OS << "\\r"; break;
1233 case '\t': OS << "\\t"; break;
1234 case '\v': OS << "\\v"; break;
1235 }
1236 }
1237 OS << '"';
1238}
1239
1240/// getLocationOfByte - Return a source location that points to the specified
1241/// byte of this string literal.
1242///
1243/// Strings are amazingly complex. They can be formed from multiple tokens and
1244/// can have escape sequences in them in addition to the usual trigraph and
1245/// escaped newline business. This routine handles this complexity.
1246///
1247/// The *StartToken sets the first token to be searched in this function and
1248/// the *StartTokenByteOffset is the byte offset of the first token. Before
1249/// returning, it updates the *StartToken to the TokNo of the token being found
1250/// and sets *StartTokenByteOffset to the byte offset of the token in the
1251/// string.
1252/// Using these two parameters can reduce the time complexity from O(n^2) to
1253/// O(n) if one wants to get the location of byte for all the tokens in a
1254/// string.
1255///
1256SourceLocation
1257StringLiteral::getLocationOfByte(unsigned ByteNo, const SourceManager &SM,
1258 const LangOptions &Features,
1259 const TargetInfo &Target, unsigned *StartToken,
1260 unsigned *StartTokenByteOffset) const {
1261 assert((getKind() == StringLiteral::Ascii ||(static_cast <bool> ((getKind() == StringLiteral::Ascii
|| getKind() == StringLiteral::UTF8) && "Only narrow string literals are currently supported"
) ? void (0) : __assert_fail ("(getKind() == StringLiteral::Ascii || getKind() == StringLiteral::UTF8) && \"Only narrow string literals are currently supported\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 1263, __extension__ __PRETTY_FUNCTION__))
1262 getKind() == StringLiteral::UTF8) &&(static_cast <bool> ((getKind() == StringLiteral::Ascii
|| getKind() == StringLiteral::UTF8) && "Only narrow string literals are currently supported"
) ? void (0) : __assert_fail ("(getKind() == StringLiteral::Ascii || getKind() == StringLiteral::UTF8) && \"Only narrow string literals are currently supported\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 1263, __extension__ __PRETTY_FUNCTION__))
1263 "Only narrow string literals are currently supported")(static_cast <bool> ((getKind() == StringLiteral::Ascii
|| getKind() == StringLiteral::UTF8) && "Only narrow string literals are currently supported"
) ? void (0) : __assert_fail ("(getKind() == StringLiteral::Ascii || getKind() == StringLiteral::UTF8) && \"Only narrow string literals are currently supported\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 1263, __extension__ __PRETTY_FUNCTION__))
;
1264
1265 // Loop over all of the tokens in this string until we find the one that
1266 // contains the byte we're looking for.
1267 unsigned TokNo = 0;
1268 unsigned StringOffset = 0;
1269 if (StartToken)
1270 TokNo = *StartToken;
1271 if (StartTokenByteOffset) {
1272 StringOffset = *StartTokenByteOffset;
1273 ByteNo -= StringOffset;
1274 }
1275 while (1) {
1276 assert(TokNo < getNumConcatenated() && "Invalid byte number!")(static_cast <bool> (TokNo < getNumConcatenated() &&
"Invalid byte number!") ? void (0) : __assert_fail ("TokNo < getNumConcatenated() && \"Invalid byte number!\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 1276, __extension__ __PRETTY_FUNCTION__))
;
1277 SourceLocation StrTokLoc = getStrTokenLoc(TokNo);
1278
1279 // Get the spelling of the string so that we can get the data that makes up
1280 // the string literal, not the identifier for the macro it is potentially
1281 // expanded through.
1282 SourceLocation StrTokSpellingLoc = SM.getSpellingLoc(StrTokLoc);
1283
1284 // Re-lex the token to get its length and original spelling.
1285 std::pair<FileID, unsigned> LocInfo =
1286 SM.getDecomposedLoc(StrTokSpellingLoc);
1287 bool Invalid = false;
1288 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
1289 if (Invalid) {
1290 if (StartTokenByteOffset != nullptr)
1291 *StartTokenByteOffset = StringOffset;
1292 if (StartToken != nullptr)
1293 *StartToken = TokNo;
1294 return StrTokSpellingLoc;
1295 }
1296
1297 const char *StrData = Buffer.data()+LocInfo.second;
1298
1299 // Create a lexer starting at the beginning of this token.
1300 Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), Features,
1301 Buffer.begin(), StrData, Buffer.end());
1302 Token TheTok;
1303 TheLexer.LexFromRawLexer(TheTok);
1304
1305 // Use the StringLiteralParser to compute the length of the string in bytes.
1306 StringLiteralParser SLP(TheTok, SM, Features, Target);
1307 unsigned TokNumBytes = SLP.GetStringLength();
1308
1309 // If the byte is in this token, return the location of the byte.
1310 if (ByteNo < TokNumBytes ||
1311 (ByteNo == TokNumBytes && TokNo == getNumConcatenated() - 1)) {
1312 unsigned Offset = SLP.getOffsetOfStringByte(TheTok, ByteNo);
1313
1314 // Now that we know the offset of the token in the spelling, use the
1315 // preprocessor to get the offset in the original source.
1316 if (StartTokenByteOffset != nullptr)
1317 *StartTokenByteOffset = StringOffset;
1318 if (StartToken != nullptr)
1319 *StartToken = TokNo;
1320 return Lexer::AdvanceToTokenCharacter(StrTokLoc, Offset, SM, Features);
1321 }
1322
1323 // Move to the next string token.
1324 StringOffset += TokNumBytes;
1325 ++TokNo;
1326 ByteNo -= TokNumBytes;
1327 }
1328}
1329
1330/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1331/// corresponds to, e.g. "sizeof" or "[pre]++".
1332StringRef UnaryOperator::getOpcodeStr(Opcode Op) {
1333 switch (Op) {
1334#define UNARY_OPERATION(Name, Spelling) case UO_##Name: return Spelling;
1335#include "clang/AST/OperationKinds.def"
1336 }
1337 llvm_unreachable("Unknown unary operator")::llvm::llvm_unreachable_internal("Unknown unary operator", "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 1337)
;
1338}
1339
1340UnaryOperatorKind
1341UnaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix) {
1342 switch (OO) {
1343 default: llvm_unreachable("No unary operator for overloaded function")::llvm::llvm_unreachable_internal("No unary operator for overloaded function"
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 1343)
;
1344 case OO_PlusPlus: return Postfix ? UO_PostInc : UO_PreInc;
1345 case OO_MinusMinus: return Postfix ? UO_PostDec : UO_PreDec;
1346 case OO_Amp: return UO_AddrOf;
1347 case OO_Star: return UO_Deref;
1348 case OO_Plus: return UO_Plus;
1349 case OO_Minus: return UO_Minus;
1350 case OO_Tilde: return UO_Not;
1351 case OO_Exclaim: return UO_LNot;
1352 case OO_Coawait: return UO_Coawait;
1353 }
1354}
1355
1356OverloadedOperatorKind UnaryOperator::getOverloadedOperator(Opcode Opc) {
1357 switch (Opc) {
1358 case UO_PostInc: case UO_PreInc: return OO_PlusPlus;
1359 case UO_PostDec: case UO_PreDec: return OO_MinusMinus;
1360 case UO_AddrOf: return OO_Amp;
1361 case UO_Deref: return OO_Star;
1362 case UO_Plus: return OO_Plus;
1363 case UO_Minus: return OO_Minus;
1364 case UO_Not: return OO_Tilde;
1365 case UO_LNot: return OO_Exclaim;
1366 case UO_Coawait: return OO_Coawait;
1367 default: return OO_None;
1368 }
1369}
1370
1371
1372//===----------------------------------------------------------------------===//
1373// Postfix Operators.
1374//===----------------------------------------------------------------------===//
1375
1376CallExpr::CallExpr(StmtClass SC, Expr *Fn, ArrayRef<Expr *> PreArgs,
1377 ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,
1378 SourceLocation RParenLoc, FPOptionsOverride FPFeatures,
1379 unsigned MinNumArgs, ADLCallKind UsesADL)
1380 : Expr(SC, Ty, VK, OK_Ordinary), RParenLoc(RParenLoc) {
1381 NumArgs = std::max<unsigned>(Args.size(), MinNumArgs);
1382 unsigned NumPreArgs = PreArgs.size();
1383 CallExprBits.NumPreArgs = NumPreArgs;
1384 assert((NumPreArgs == getNumPreArgs()) && "NumPreArgs overflow!")(static_cast <bool> ((NumPreArgs == getNumPreArgs()) &&
"NumPreArgs overflow!") ? void (0) : __assert_fail ("(NumPreArgs == getNumPreArgs()) && \"NumPreArgs overflow!\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 1384, __extension__ __PRETTY_FUNCTION__))
;
1385
1386 unsigned OffsetToTrailingObjects = offsetToTrailingObjects(SC);
1387 CallExprBits.OffsetToTrailingObjects = OffsetToTrailingObjects;
1388 assert((CallExprBits.OffsetToTrailingObjects == OffsetToTrailingObjects) &&(static_cast <bool> ((CallExprBits.OffsetToTrailingObjects
== OffsetToTrailingObjects) && "OffsetToTrailingObjects overflow!"
) ? void (0) : __assert_fail ("(CallExprBits.OffsetToTrailingObjects == OffsetToTrailingObjects) && \"OffsetToTrailingObjects overflow!\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 1389, __extension__ __PRETTY_FUNCTION__))
1389 "OffsetToTrailingObjects overflow!")(static_cast <bool> ((CallExprBits.OffsetToTrailingObjects
== OffsetToTrailingObjects) && "OffsetToTrailingObjects overflow!"
) ? void (0) : __assert_fail ("(CallExprBits.OffsetToTrailingObjects == OffsetToTrailingObjects) && \"OffsetToTrailingObjects overflow!\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 1389, __extension__ __PRETTY_FUNCTION__))
;
1390
1391 CallExprBits.UsesADL = static_cast<bool>(UsesADL);
1392
1393 setCallee(Fn);
1394 for (unsigned I = 0; I != NumPreArgs; ++I)
1395 setPreArg(I, PreArgs[I]);
1396 for (unsigned I = 0; I != Args.size(); ++I)
1397 setArg(I, Args[I]);
1398 for (unsigned I = Args.size(); I != NumArgs; ++I)
1399 setArg(I, nullptr);
1400
1401 setDependence(computeDependence(this, PreArgs));
1402
1403 CallExprBits.HasFPFeatures = FPFeatures.requiresTrailingStorage();
1404 if (hasStoredFPFeatures())
1405 setStoredFPFeatures(FPFeatures);
1406}
1407
1408CallExpr::CallExpr(StmtClass SC, unsigned NumPreArgs, unsigned NumArgs,
1409 bool HasFPFeatures, EmptyShell Empty)
1410 : Expr(SC, Empty), NumArgs(NumArgs) {
1411 CallExprBits.NumPreArgs = NumPreArgs;
1412 assert((NumPreArgs == getNumPreArgs()) && "NumPreArgs overflow!")(static_cast <bool> ((NumPreArgs == getNumPreArgs()) &&
"NumPreArgs overflow!") ? void (0) : __assert_fail ("(NumPreArgs == getNumPreArgs()) && \"NumPreArgs overflow!\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 1412, __extension__ __PRETTY_FUNCTION__))
;
1413
1414 unsigned OffsetToTrailingObjects = offsetToTrailingObjects(SC);
1415 CallExprBits.OffsetToTrailingObjects = OffsetToTrailingObjects;
1416 assert((CallExprBits.OffsetToTrailingObjects == OffsetToTrailingObjects) &&(static_cast <bool> ((CallExprBits.OffsetToTrailingObjects
== OffsetToTrailingObjects) && "OffsetToTrailingObjects overflow!"
) ? void (0) : __assert_fail ("(CallExprBits.OffsetToTrailingObjects == OffsetToTrailingObjects) && \"OffsetToTrailingObjects overflow!\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 1417, __extension__ __PRETTY_FUNCTION__))
1417 "OffsetToTrailingObjects overflow!")(static_cast <bool> ((CallExprBits.OffsetToTrailingObjects
== OffsetToTrailingObjects) && "OffsetToTrailingObjects overflow!"
) ? void (0) : __assert_fail ("(CallExprBits.OffsetToTrailingObjects == OffsetToTrailingObjects) && \"OffsetToTrailingObjects overflow!\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 1417, __extension__ __PRETTY_FUNCTION__))
;
1418 CallExprBits.HasFPFeatures = HasFPFeatures;
1419}
1420
1421CallExpr *CallExpr::Create(const ASTContext &Ctx, Expr *Fn,
1422 ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,
1423 SourceLocation RParenLoc,
1424 FPOptionsOverride FPFeatures, unsigned MinNumArgs,
1425 ADLCallKind UsesADL) {
1426 unsigned NumArgs = std::max<unsigned>(Args.size(), MinNumArgs);
1427 unsigned SizeOfTrailingObjects = CallExpr::sizeOfTrailingObjects(
1428 /*NumPreArgs=*/0, NumArgs, FPFeatures.requiresTrailingStorage());
1429 void *Mem =
1430 Ctx.Allocate(sizeof(CallExpr) + SizeOfTrailingObjects, alignof(CallExpr));
1431 return new (Mem) CallExpr(CallExprClass, Fn, /*PreArgs=*/{}, Args, Ty, VK,
1432 RParenLoc, FPFeatures, MinNumArgs, UsesADL);
1433}
1434
1435CallExpr *CallExpr::CreateTemporary(void *Mem, Expr *Fn, QualType Ty,
1436 ExprValueKind VK, SourceLocation RParenLoc,
1437 ADLCallKind UsesADL) {
1438 assert(!(reinterpret_cast<uintptr_t>(Mem) % alignof(CallExpr)) &&(static_cast <bool> (!(reinterpret_cast<uintptr_t>
(Mem) % alignof(CallExpr)) && "Misaligned memory in CallExpr::CreateTemporary!"
) ? void (0) : __assert_fail ("!(reinterpret_cast<uintptr_t>(Mem) % alignof(CallExpr)) && \"Misaligned memory in CallExpr::CreateTemporary!\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 1439, __extension__ __PRETTY_FUNCTION__))
1439 "Misaligned memory in CallExpr::CreateTemporary!")(static_cast <bool> (!(reinterpret_cast<uintptr_t>
(Mem) % alignof(CallExpr)) && "Misaligned memory in CallExpr::CreateTemporary!"
) ? void (0) : __assert_fail ("!(reinterpret_cast<uintptr_t>(Mem) % alignof(CallExpr)) && \"Misaligned memory in CallExpr::CreateTemporary!\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 1439, __extension__ __PRETTY_FUNCTION__))
;
1440 return new (Mem) CallExpr(CallExprClass, Fn, /*PreArgs=*/{}, /*Args=*/{}, Ty,
1441 VK, RParenLoc, FPOptionsOverride(),
1442 /*MinNumArgs=*/0, UsesADL);
1443}
1444
1445CallExpr *CallExpr::CreateEmpty(const ASTContext &Ctx, unsigned NumArgs,
1446 bool HasFPFeatures, EmptyShell Empty) {
1447 unsigned SizeOfTrailingObjects =
1448 CallExpr::sizeOfTrailingObjects(/*NumPreArgs=*/0, NumArgs, HasFPFeatures);
1449 void *Mem =
1450 Ctx.Allocate(sizeof(CallExpr) + SizeOfTrailingObjects, alignof(CallExpr));
1451 return new (Mem)
1452 CallExpr(CallExprClass, /*NumPreArgs=*/0, NumArgs, HasFPFeatures, Empty);
1453}
1454
1455unsigned CallExpr::offsetToTrailingObjects(StmtClass SC) {
1456 switch (SC) {
1457 case CallExprClass:
1458 return sizeof(CallExpr);
1459 case CXXOperatorCallExprClass:
1460 return sizeof(CXXOperatorCallExpr);
1461 case CXXMemberCallExprClass:
1462 return sizeof(CXXMemberCallExpr);
1463 case UserDefinedLiteralClass:
1464 return sizeof(UserDefinedLiteral);
1465 case CUDAKernelCallExprClass:
1466 return sizeof(CUDAKernelCallExpr);
1467 default:
1468 llvm_unreachable("unexpected class deriving from CallExpr!")::llvm::llvm_unreachable_internal("unexpected class deriving from CallExpr!"
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 1468)
;
1469 }
1470}
1471
1472Decl *Expr::getReferencedDeclOfCallee() {
1473 Expr *CEE = IgnoreParenImpCasts();
1474
1475 while (SubstNonTypeTemplateParmExpr *NTTP =
1476 dyn_cast<SubstNonTypeTemplateParmExpr>(CEE)) {
1477 CEE = NTTP->getReplacement()->IgnoreParenImpCasts();
1478 }
1479
1480 // If we're calling a dereference, look at the pointer instead.
1481 while (true) {
1482 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CEE)) {
1483 if (BO->isPtrMemOp()) {
1484 CEE = BO->getRHS()->IgnoreParenImpCasts();
1485 continue;
1486 }
1487 } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(CEE)) {
1488 if (UO->getOpcode() == UO_Deref || UO->getOpcode() == UO_AddrOf ||
1489 UO->getOpcode() == UO_Plus) {
1490 CEE = UO->getSubExpr()->IgnoreParenImpCasts();
1491 continue;
1492 }
1493 }
1494 break;
1495 }
1496
1497 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CEE))
1498 return DRE->getDecl();
1499 if (MemberExpr *ME = dyn_cast<MemberExpr>(CEE))
1500 return ME->getMemberDecl();
1501 if (auto *BE = dyn_cast<BlockExpr>(CEE))
1502 return BE->getBlockDecl();
1503
1504 return nullptr;
1505}
1506
1507/// If this is a call to a builtin, return the builtin ID. If not, return 0.
1508unsigned CallExpr::getBuiltinCallee() const {
1509 auto *FDecl =
1510 dyn_cast_or_null<FunctionDecl>(getCallee()->getReferencedDeclOfCallee());
1511 return FDecl ? FDecl->getBuiltinID() : 0;
1512}
1513
1514bool CallExpr::isUnevaluatedBuiltinCall(const ASTContext &Ctx) const {
1515 if (unsigned BI = getBuiltinCallee())
1516 return Ctx.BuiltinInfo.isUnevaluated(BI);
1517 return false;
1518}
1519
1520QualType CallExpr::getCallReturnType(const ASTContext &Ctx) const {
1521 const Expr *Callee = getCallee();
1522 QualType CalleeType = Callee->getType();
1523 if (const auto *FnTypePtr = CalleeType->getAs<PointerType>()) {
1524 CalleeType = FnTypePtr->getPointeeType();
1525 } else if (const auto *BPT = CalleeType->getAs<BlockPointerType>()) {
1526 CalleeType = BPT->getPointeeType();
1527 } else if (CalleeType->isSpecificPlaceholderType(BuiltinType::BoundMember)) {
1528 if (isa<CXXPseudoDestructorExpr>(Callee->IgnoreParens()))
1529 return Ctx.VoidTy;
1530
1531 if (isa<UnresolvedMemberExpr>(Callee->IgnoreParens()))
1532 return Ctx.DependentTy;
1533
1534 // This should never be overloaded and so should never return null.
1535 CalleeType = Expr::findBoundMemberType(Callee);
1536 assert(!CalleeType.isNull())(static_cast <bool> (!CalleeType.isNull()) ? void (0) :
__assert_fail ("!CalleeType.isNull()", "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 1536, __extension__ __PRETTY_FUNCTION__))
;
1537 } else if (CalleeType->isDependentType() ||
1538 CalleeType->isSpecificPlaceholderType(BuiltinType::Overload)) {
1539 return Ctx.DependentTy;
1540 }
1541
1542 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
1543 return FnType->getReturnType();
1544}
1545
1546const Attr *CallExpr::getUnusedResultAttr(const ASTContext &Ctx) const {
1547 // If the return type is a struct, union, or enum that is marked nodiscard,
1548 // then return the return type attribute.
1549 if (const TagDecl *TD = getCallReturnType(Ctx)->getAsTagDecl())
1550 if (const auto *A = TD->getAttr<WarnUnusedResultAttr>())
1551 return A;
1552
1553 // Otherwise, see if the callee is marked nodiscard and return that attribute
1554 // instead.
1555 const Decl *D = getCalleeDecl();
1556 return D ? D->getAttr<WarnUnusedResultAttr>() : nullptr;
1557}
1558
1559SourceLocation CallExpr::getBeginLoc() const {
1560 if (isa<CXXOperatorCallExpr>(this))
1561 return cast<CXXOperatorCallExpr>(this)->getBeginLoc();
1562
1563 SourceLocation begin = getCallee()->getBeginLoc();
1564 if (begin.isInvalid() && getNumArgs() > 0 && getArg(0))
1565 begin = getArg(0)->getBeginLoc();
1566 return begin;
1567}
1568SourceLocation CallExpr::getEndLoc() const {
1569 if (isa<CXXOperatorCallExpr>(this))
1570 return cast<CXXOperatorCallExpr>(this)->getEndLoc();
1571
1572 SourceLocation end = getRParenLoc();
1573 if (end.isInvalid() && getNumArgs() > 0 && getArg(getNumArgs() - 1))
1574 end = getArg(getNumArgs() - 1)->getEndLoc();
1575 return end;
1576}
1577
1578OffsetOfExpr *OffsetOfExpr::Create(const ASTContext &C, QualType type,
1579 SourceLocation OperatorLoc,
1580 TypeSourceInfo *tsi,
1581 ArrayRef<OffsetOfNode> comps,
1582 ArrayRef<Expr*> exprs,
1583 SourceLocation RParenLoc) {
1584 void *Mem = C.Allocate(
1585 totalSizeToAlloc<OffsetOfNode, Expr *>(comps.size(), exprs.size()));
1586
1587 return new (Mem) OffsetOfExpr(C, type, OperatorLoc, tsi, comps, exprs,
1588 RParenLoc);
1589}
1590
1591OffsetOfExpr *OffsetOfExpr::CreateEmpty(const ASTContext &C,
1592 unsigned numComps, unsigned numExprs) {
1593 void *Mem =
1594 C.Allocate(totalSizeToAlloc<OffsetOfNode, Expr *>(numComps, numExprs));
1595 return new (Mem) OffsetOfExpr(numComps, numExprs);
1596}
1597
1598OffsetOfExpr::OffsetOfExpr(const ASTContext &C, QualType type,
1599 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
1600 ArrayRef<OffsetOfNode> comps, ArrayRef<Expr *> exprs,
1601 SourceLocation RParenLoc)
1602 : Expr(OffsetOfExprClass, type, VK_PRValue, OK_Ordinary),
1603 OperatorLoc(OperatorLoc), RParenLoc(RParenLoc), TSInfo(tsi),
1604 NumComps(comps.size()), NumExprs(exprs.size()) {
1605 for (unsigned i = 0; i != comps.size(); ++i)
1606 setComponent(i, comps[i]);
1607 for (unsigned i = 0; i != exprs.size(); ++i)
1608 setIndexExpr(i, exprs[i]);
1609
1610 setDependence(computeDependence(this));
1611}
1612
1613IdentifierInfo *OffsetOfNode::getFieldName() const {
1614 assert(getKind() == Field || getKind() == Identifier)(static_cast <bool> (getKind() == Field || getKind() ==
Identifier) ? void (0) : __assert_fail ("getKind() == Field || getKind() == Identifier"
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 1614, __extension__ __PRETTY_FUNCTION__))
;
1615 if (getKind() == Field)
1616 return getField()->getIdentifier();
1617
1618 return reinterpret_cast<IdentifierInfo *> (Data & ~(uintptr_t)Mask);
1619}
1620
1621UnaryExprOrTypeTraitExpr::UnaryExprOrTypeTraitExpr(
1622 UnaryExprOrTypeTrait ExprKind, Expr *E, QualType resultType,
1623 SourceLocation op, SourceLocation rp)
1624 : Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_PRValue, OK_Ordinary),
1625 OpLoc(op), RParenLoc(rp) {
1626 assert(ExprKind <= UETT_Last && "invalid enum value!")(static_cast <bool> (ExprKind <= UETT_Last &&
"invalid enum value!") ? void (0) : __assert_fail ("ExprKind <= UETT_Last && \"invalid enum value!\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 1626, __extension__ __PRETTY_FUNCTION__))
;
1627 UnaryExprOrTypeTraitExprBits.Kind = ExprKind;
1628 assert(static_cast<unsigned>(ExprKind) == UnaryExprOrTypeTraitExprBits.Kind &&(static_cast <bool> (static_cast<unsigned>(ExprKind
) == UnaryExprOrTypeTraitExprBits.Kind && "UnaryExprOrTypeTraitExprBits.Kind overflow!"
) ? void (0) : __assert_fail ("static_cast<unsigned>(ExprKind) == UnaryExprOrTypeTraitExprBits.Kind && \"UnaryExprOrTypeTraitExprBits.Kind overflow!\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 1629, __extension__ __PRETTY_FUNCTION__))
1629 "UnaryExprOrTypeTraitExprBits.Kind overflow!")(static_cast <bool> (static_cast<unsigned>(ExprKind
) == UnaryExprOrTypeTraitExprBits.Kind && "UnaryExprOrTypeTraitExprBits.Kind overflow!"
) ? void (0) : __assert_fail ("static_cast<unsigned>(ExprKind) == UnaryExprOrTypeTraitExprBits.Kind && \"UnaryExprOrTypeTraitExprBits.Kind overflow!\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 1629, __extension__ __PRETTY_FUNCTION__))
;
1630 UnaryExprOrTypeTraitExprBits.IsType = false;
1631 Argument.Ex = E;
1632 setDependence(computeDependence(this));
1633}
1634
1635MemberExpr::MemberExpr(Expr *Base, bool IsArrow, SourceLocation OperatorLoc,
1636 ValueDecl *MemberDecl,
1637 const DeclarationNameInfo &NameInfo, QualType T,
1638 ExprValueKind VK, ExprObjectKind OK,
1639 NonOdrUseReason NOUR)
1640 : Expr(MemberExprClass, T, VK, OK), Base(Base), MemberDecl(MemberDecl),
1641 MemberDNLoc(NameInfo.getInfo()), MemberLoc(NameInfo.getLoc()) {
1642 assert(!NameInfo.getName() ||(static_cast <bool> (!NameInfo.getName() || MemberDecl->
getDeclName() == NameInfo.getName()) ? void (0) : __assert_fail
("!NameInfo.getName() || MemberDecl->getDeclName() == NameInfo.getName()"
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 1643, __extension__ __PRETTY_FUNCTION__))
1643 MemberDecl->getDeclName() == NameInfo.getName())(static_cast <bool> (!NameInfo.getName() || MemberDecl->
getDeclName() == NameInfo.getName()) ? void (0) : __assert_fail
("!NameInfo.getName() || MemberDecl->getDeclName() == NameInfo.getName()"
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 1643, __extension__ __PRETTY_FUNCTION__))
;
1644 MemberExprBits.IsArrow = IsArrow;
1645 MemberExprBits.HasQualifierOrFoundDecl = false;
1646 MemberExprBits.HasTemplateKWAndArgsInfo = false;
1647 MemberExprBits.HadMultipleCandidates = false;
1648 MemberExprBits.NonOdrUseReason = NOUR;
1649 MemberExprBits.OperatorLoc = OperatorLoc;
1650 setDependence(computeDependence(this));
1651}
1652
1653MemberExpr *MemberExpr::Create(
1654 const ASTContext &C, Expr *Base, bool IsArrow, SourceLocation OperatorLoc,
1655 NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,
1656 ValueDecl *MemberDecl, DeclAccessPair FoundDecl,
1657 DeclarationNameInfo NameInfo, const TemplateArgumentListInfo *TemplateArgs,
1658 QualType T, ExprValueKind VK, ExprObjectKind OK, NonOdrUseReason NOUR) {
1659 bool HasQualOrFound = QualifierLoc || FoundDecl.getDecl() != MemberDecl ||
1660 FoundDecl.getAccess() != MemberDecl->getAccess();
1661 bool HasTemplateKWAndArgsInfo = TemplateArgs || TemplateKWLoc.isValid();
1662 std::size_t Size =
1663 totalSizeToAlloc<MemberExprNameQualifier, ASTTemplateKWAndArgsInfo,
1664 TemplateArgumentLoc>(
1665 HasQualOrFound ? 1 : 0, HasTemplateKWAndArgsInfo ? 1 : 0,
1666 TemplateArgs ? TemplateArgs->size() : 0);
1667
1668 void *Mem = C.Allocate(Size, alignof(MemberExpr));
1669 MemberExpr *E = new (Mem) MemberExpr(Base, IsArrow, OperatorLoc, MemberDecl,
1670 NameInfo, T, VK, OK, NOUR);
1671
1672 // FIXME: remove remaining dependence computation to computeDependence().
1673 auto Deps = E->getDependence();
1674 if (HasQualOrFound) {
1675 // FIXME: Wrong. We should be looking at the member declaration we found.
1676 if (QualifierLoc && QualifierLoc.getNestedNameSpecifier()->isDependent())
1677 Deps |= ExprDependence::TypeValueInstantiation;
1678 else if (QualifierLoc &&
1679 QualifierLoc.getNestedNameSpecifier()->isInstantiationDependent())
1680 Deps |= ExprDependence::Instantiation;
1681
1682 E->MemberExprBits.HasQualifierOrFoundDecl = true;
1683
1684 MemberExprNameQualifier *NQ =
1685 E->getTrailingObjects<MemberExprNameQualifier>();
1686 NQ->QualifierLoc = QualifierLoc;
1687 NQ->FoundDecl = FoundDecl;
1688 }
1689
1690 E->MemberExprBits.HasTemplateKWAndArgsInfo =
1691 TemplateArgs || TemplateKWLoc.isValid();
1692
1693 if (TemplateArgs) {
1694 auto TemplateArgDeps = TemplateArgumentDependence::None;
1695 E->getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
1696 TemplateKWLoc, *TemplateArgs,
1697 E->getTrailingObjects<TemplateArgumentLoc>(), TemplateArgDeps);
1698 if (TemplateArgDeps & TemplateArgumentDependence::Instantiation)
1699 Deps |= ExprDependence::Instantiation;
1700 } else if (TemplateKWLoc.isValid()) {
1701 E->getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
1702 TemplateKWLoc);
1703 }
1704 E->setDependence(Deps);
1705
1706 return E;
1707}
1708
1709MemberExpr *MemberExpr::CreateEmpty(const ASTContext &Context,
1710 bool HasQualifier, bool HasFoundDecl,
1711 bool HasTemplateKWAndArgsInfo,
1712 unsigned NumTemplateArgs) {
1713 assert((!NumTemplateArgs || HasTemplateKWAndArgsInfo) &&(static_cast <bool> ((!NumTemplateArgs || HasTemplateKWAndArgsInfo
) && "template args but no template arg info?") ? void
(0) : __assert_fail ("(!NumTemplateArgs || HasTemplateKWAndArgsInfo) && \"template args but no template arg info?\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 1714, __extension__ __PRETTY_FUNCTION__))
1714 "template args but no template arg info?")(static_cast <bool> ((!NumTemplateArgs || HasTemplateKWAndArgsInfo
) && "template args but no template arg info?") ? void
(0) : __assert_fail ("(!NumTemplateArgs || HasTemplateKWAndArgsInfo) && \"template args but no template arg info?\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 1714, __extension__ __PRETTY_FUNCTION__))
;
1715 bool HasQualOrFound = HasQualifier || HasFoundDecl;
1716 std::size_t Size =
1717 totalSizeToAlloc<MemberExprNameQualifier, ASTTemplateKWAndArgsInfo,
1718 TemplateArgumentLoc>(HasQualOrFound ? 1 : 0,
1719 HasTemplateKWAndArgsInfo ? 1 : 0,
1720 NumTemplateArgs);
1721 void *Mem = Context.Allocate(Size, alignof(MemberExpr));
1722 return new (Mem) MemberExpr(EmptyShell());
1723}
1724
1725void MemberExpr::setMemberDecl(ValueDecl *D) {
1726 MemberDecl = D;
1727 setDependence(computeDependence(this));
1728}
1729
1730SourceLocation MemberExpr::getBeginLoc() const {
1731 if (isImplicitAccess()) {
1732 if (hasQualifier())
1733 return getQualifierLoc().getBeginLoc();
1734 return MemberLoc;
1735 }
1736
1737 // FIXME: We don't want this to happen. Rather, we should be able to
1738 // detect all kinds of implicit accesses more cleanly.
1739 SourceLocation BaseStartLoc = getBase()->getBeginLoc();
1740 if (BaseStartLoc.isValid())
1741 return BaseStartLoc;
1742 return MemberLoc;
1743}
1744SourceLocation MemberExpr::getEndLoc() const {
1745 SourceLocation EndLoc = getMemberNameInfo().getEndLoc();
1746 if (hasExplicitTemplateArgs())
1747 EndLoc = getRAngleLoc();
1748 else if (EndLoc.isInvalid())
1749 EndLoc = getBase()->getEndLoc();
1750 return EndLoc;
1751}
1752
1753bool CastExpr::CastConsistency() const {
1754 switch (getCastKind()) {
1755 case CK_DerivedToBase:
1756 case CK_UncheckedDerivedToBase:
1757 case CK_DerivedToBaseMemberPointer:
1758 case CK_BaseToDerived:
1759 case CK_BaseToDerivedMemberPointer:
1760 assert(!path_empty() && "Cast kind should have a base path!")(static_cast <bool> (!path_empty() && "Cast kind should have a base path!"
) ? void (0) : __assert_fail ("!path_empty() && \"Cast kind should have a base path!\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 1760, __extension__ __PRETTY_FUNCTION__))
;
1761 break;
1762
1763 case CK_CPointerToObjCPointerCast:
1764 assert(getType()->isObjCObjectPointerType())(static_cast <bool> (getType()->isObjCObjectPointerType
()) ? void (0) : __assert_fail ("getType()->isObjCObjectPointerType()"
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 1764, __extension__ __PRETTY_FUNCTION__))
;
1765 assert(getSubExpr()->getType()->isPointerType())(static_cast <bool> (getSubExpr()->getType()->isPointerType
()) ? void (0) : __assert_fail ("getSubExpr()->getType()->isPointerType()"
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 1765, __extension__ __PRETTY_FUNCTION__))
;
1766 goto CheckNoBasePath;
1767
1768 case CK_BlockPointerToObjCPointerCast:
1769 assert(getType()->isObjCObjectPointerType())(static_cast <bool> (getType()->isObjCObjectPointerType
()) ? void (0) : __assert_fail ("getType()->isObjCObjectPointerType()"
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 1769, __extension__ __PRETTY_FUNCTION__))
;
1770 assert(getSubExpr()->getType()->isBlockPointerType())(static_cast <bool> (getSubExpr()->getType()->isBlockPointerType
()) ? void (0) : __assert_fail ("getSubExpr()->getType()->isBlockPointerType()"
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 1770, __extension__ __PRETTY_FUNCTION__))
;
1771 goto CheckNoBasePath;
1772
1773 case CK_ReinterpretMemberPointer:
1774 assert(getType()->isMemberPointerType())(static_cast <bool> (getType()->isMemberPointerType(
)) ? void (0) : __assert_fail ("getType()->isMemberPointerType()"
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 1774, __extension__ __PRETTY_FUNCTION__))
;
1775 assert(getSubExpr()->getType()->isMemberPointerType())(static_cast <bool> (getSubExpr()->getType()->isMemberPointerType
()) ? void (0) : __assert_fail ("getSubExpr()->getType()->isMemberPointerType()"
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 1775, __extension__ __PRETTY_FUNCTION__))
;
1776 goto CheckNoBasePath;
1777
1778 case CK_BitCast:
1779 // Arbitrary casts to C pointer types count as bitcasts.
1780 // Otherwise, we should only have block and ObjC pointer casts
1781 // here if they stay within the type kind.
1782 if (!getType()->isPointerType()) {
1783 assert(getType()->isObjCObjectPointerType() ==(static_cast <bool> (getType()->isObjCObjectPointerType
() == getSubExpr()->getType()->isObjCObjectPointerType(
)) ? void (0) : __assert_fail ("getType()->isObjCObjectPointerType() == getSubExpr()->getType()->isObjCObjectPointerType()"
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 1784, __extension__ __PRETTY_FUNCTION__))
1784 getSubExpr()->getType()->isObjCObjectPointerType())(static_cast <bool> (getType()->isObjCObjectPointerType
() == getSubExpr()->getType()->isObjCObjectPointerType(
)) ? void (0) : __assert_fail ("getType()->isObjCObjectPointerType() == getSubExpr()->getType()->isObjCObjectPointerType()"
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 1784, __extension__ __PRETTY_FUNCTION__))
;
1785 assert(getType()->isBlockPointerType() ==(static_cast <bool> (getType()->isBlockPointerType()
== getSubExpr()->getType()->isBlockPointerType()) ? void
(0) : __assert_fail ("getType()->isBlockPointerType() == getSubExpr()->getType()->isBlockPointerType()"
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 1786, __extension__ __PRETTY_FUNCTION__))
1786 getSubExpr()->getType()->isBlockPointerType())(static_cast <bool> (getType()->isBlockPointerType()
== getSubExpr()->getType()->isBlockPointerType()) ? void
(0) : __assert_fail ("getType()->isBlockPointerType() == getSubExpr()->getType()->isBlockPointerType()"
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 1786, __extension__ __PRETTY_FUNCTION__))
;
1787 }
1788 goto CheckNoBasePath;
1789
1790 case CK_AnyPointerToBlockPointerCast:
1791 assert(getType()->isBlockPointerType())(static_cast <bool> (getType()->isBlockPointerType()
) ? void (0) : __assert_fail ("getType()->isBlockPointerType()"
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 1791, __extension__ __PRETTY_FUNCTION__))
;
1792 assert(getSubExpr()->getType()->isAnyPointerType() &&(static_cast <bool> (getSubExpr()->getType()->isAnyPointerType
() && !getSubExpr()->getType()->isBlockPointerType
()) ? void (0) : __assert_fail ("getSubExpr()->getType()->isAnyPointerType() && !getSubExpr()->getType()->isBlockPointerType()"
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 1793, __extension__ __PRETTY_FUNCTION__))
1793 !getSubExpr()->getType()->isBlockPointerType())(static_cast <bool> (getSubExpr()->getType()->isAnyPointerType
() && !getSubExpr()->getType()->isBlockPointerType
()) ? void (0) : __assert_fail ("getSubExpr()->getType()->isAnyPointerType() && !getSubExpr()->getType()->isBlockPointerType()"
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 1793, __extension__ __PRETTY_FUNCTION__))
;
1794 goto CheckNoBasePath;
1795
1796 case CK_CopyAndAutoreleaseBlockObject:
1797 assert(getType()->isBlockPointerType())(static_cast <bool> (getType()->isBlockPointerType()
) ? void (0) : __assert_fail ("getType()->isBlockPointerType()"
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 1797, __extension__ __PRETTY_FUNCTION__))
;
1798 assert(getSubExpr()->getType()->isBlockPointerType())(static_cast <bool> (getSubExpr()->getType()->isBlockPointerType
()) ? void (0) : __assert_fail ("getSubExpr()->getType()->isBlockPointerType()"
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 1798, __extension__ __PRETTY_FUNCTION__))
;
1799 goto CheckNoBasePath;
1800
1801 case CK_FunctionToPointerDecay:
1802 assert(getType()->isPointerType())(static_cast <bool> (getType()->isPointerType()) ? void
(0) : __assert_fail ("getType()->isPointerType()", "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 1802, __extension__ __PRETTY_FUNCTION__))
;
1803 assert(getSubExpr()->getType()->isFunctionType())(static_cast <bool> (getSubExpr()->getType()->isFunctionType
()) ? void (0) : __assert_fail ("getSubExpr()->getType()->isFunctionType()"
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 1803, __extension__ __PRETTY_FUNCTION__))
;
1804 goto CheckNoBasePath;
1805
1806 case CK_AddressSpaceConversion: {
1807 auto Ty = getType();
1808 auto SETy = getSubExpr()->getType();
1809 assert(getValueKindForType(Ty) == Expr::getValueKindForType(SETy))(static_cast <bool> (getValueKindForType(Ty) == Expr::getValueKindForType
(SETy)) ? void (0) : __assert_fail ("getValueKindForType(Ty) == Expr::getValueKindForType(SETy)"
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 1809, __extension__ __PRETTY_FUNCTION__))
;
1810 if (isPRValue() && !Ty->isDependentType() && !SETy->isDependentType()) {
1811 Ty = Ty->getPointeeType();
1812 SETy = SETy->getPointeeType();
1813 }
1814 assert((Ty->isDependentType() || SETy->isDependentType()) ||(static_cast <bool> ((Ty->isDependentType() || SETy->
isDependentType()) || (!Ty.isNull() && !SETy.isNull()
&& Ty.getAddressSpace() != SETy.getAddressSpace())) ?
void (0) : __assert_fail ("(Ty->isDependentType() || SETy->isDependentType()) || (!Ty.isNull() && !SETy.isNull() && Ty.getAddressSpace() != SETy.getAddressSpace())"
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 1816, __extension__ __PRETTY_FUNCTION__))
1815 (!Ty.isNull() && !SETy.isNull() &&(static_cast <bool> ((Ty->isDependentType() || SETy->
isDependentType()) || (!Ty.isNull() && !SETy.isNull()
&& Ty.getAddressSpace() != SETy.getAddressSpace())) ?
void (0) : __assert_fail ("(Ty->isDependentType() || SETy->isDependentType()) || (!Ty.isNull() && !SETy.isNull() && Ty.getAddressSpace() != SETy.getAddressSpace())"
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 1816, __extension__ __PRETTY_FUNCTION__))
1816 Ty.getAddressSpace() != SETy.getAddressSpace()))(static_cast <bool> ((Ty->isDependentType() || SETy->
isDependentType()) || (!Ty.isNull() && !SETy.isNull()
&& Ty.getAddressSpace() != SETy.getAddressSpace())) ?
void (0) : __assert_fail ("(Ty->isDependentType() || SETy->isDependentType()) || (!Ty.isNull() && !SETy.isNull() && Ty.getAddressSpace() != SETy.getAddressSpace())"
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 1816, __extension__ __PRETTY_FUNCTION__))
;
1817 goto CheckNoBasePath;
1818 }
1819 // These should not have an inheritance path.
1820 case CK_Dynamic:
1821 case CK_ToUnion:
1822 case CK_ArrayToPointerDecay:
1823 case CK_NullToMemberPointer:
1824 case CK_NullToPointer:
1825 case CK_ConstructorConversion:
1826 case CK_IntegralToPointer:
1827 case CK_PointerToIntegral:
1828 case CK_ToVoid:
1829 case CK_VectorSplat:
1830 case CK_IntegralCast:
1831 case CK_BooleanToSignedIntegral:
1832 case CK_IntegralToFloating:
1833 case CK_FloatingToIntegral:
1834 case CK_FloatingCast:
1835 case CK_ObjCObjectLValueCast:
1836 case CK_FloatingRealToComplex:
1837 case CK_FloatingComplexToReal:
1838 case CK_FloatingComplexCast:
1839 case CK_FloatingComplexToIntegralComplex:
1840 case CK_IntegralRealToComplex:
1841 case CK_IntegralComplexToReal:
1842 case CK_IntegralComplexCast:
1843 case CK_IntegralComplexToFloatingComplex:
1844 case CK_ARCProduceObject:
1845 case CK_ARCConsumeObject:
1846 case CK_ARCReclaimReturnedObject:
1847 case CK_ARCExtendBlockObject:
1848 case CK_ZeroToOCLOpaqueType:
1849 case CK_IntToOCLSampler:
1850 case CK_FloatingToFixedPoint:
1851 case CK_FixedPointToFloating:
1852 case CK_FixedPointCast:
1853 case CK_FixedPointToIntegral:
1854 case CK_IntegralToFixedPoint:
1855 case CK_MatrixCast:
1856 assert(!getType()->isBooleanType() && "unheralded conversion to bool")(static_cast <bool> (!getType()->isBooleanType() &&
"unheralded conversion to bool") ? void (0) : __assert_fail (
"!getType()->isBooleanType() && \"unheralded conversion to bool\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 1856, __extension__ __PRETTY_FUNCTION__))
;
1857 goto CheckNoBasePath;
1858
1859 case CK_Dependent:
1860 case CK_LValueToRValue:
1861 case CK_NoOp:
1862 case CK_AtomicToNonAtomic:
1863 case CK_NonAtomicToAtomic:
1864 case CK_PointerToBoolean:
1865 case CK_IntegralToBoolean:
1866 case CK_FloatingToBoolean:
1867 case CK_MemberPointerToBoolean:
1868 case CK_FloatingComplexToBoolean:
1869 case CK_IntegralComplexToBoolean:
1870 case CK_LValueBitCast: // -> bool&
1871 case CK_LValueToRValueBitCast:
1872 case CK_UserDefinedConversion: // operator bool()
1873 case CK_BuiltinFnToFnPtr:
1874 case CK_FixedPointToBoolean:
1875 CheckNoBasePath:
1876 assert(path_empty() && "Cast kind should not have a base path!")(static_cast <bool> (path_empty() && "Cast kind should not have a base path!"
) ? void (0) : __assert_fail ("path_empty() && \"Cast kind should not have a base path!\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 1876, __extension__ __PRETTY_FUNCTION__))
;
1877 break;
1878 }
1879 return true;
1880}
1881
1882const char *CastExpr::getCastKindName(CastKind CK) {
1883 switch (CK) {
1884#define CAST_OPERATION(Name) case CK_##Name: return #Name;
1885#include "clang/AST/OperationKinds.def"
1886 }
1887 llvm_unreachable("Unhandled cast kind!")::llvm::llvm_unreachable_internal("Unhandled cast kind!", "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 1887)
;
1888}
1889
1890namespace {
1891 const Expr *skipImplicitTemporary(const Expr *E) {
1892 // Skip through reference binding to temporary.
1893 if (auto *Materialize = dyn_cast<MaterializeTemporaryExpr>(E))
1894 E = Materialize->getSubExpr();
1895
1896 // Skip any temporary bindings; they're implicit.
1897 if (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
1898 E = Binder->getSubExpr();
1899
1900 return E;
1901 }
1902}
1903
1904Expr *CastExpr::getSubExprAsWritten() {
1905 const Expr *SubExpr = nullptr;
1906 const CastExpr *E = this;
1907 do {
1908 SubExpr = skipImplicitTemporary(E->getSubExpr());
1909
1910 // Conversions by constructor and conversion functions have a
1911 // subexpression describing the call; strip it off.
1912 if (E->getCastKind() == CK_ConstructorConversion)
1913 SubExpr =
1914 skipImplicitTemporary(cast<CXXConstructExpr>(SubExpr->IgnoreImplicit())->getArg(0));
1915 else if (E->getCastKind() == CK_UserDefinedConversion) {
1916 assert((isa<CXXMemberCallExpr>(SubExpr) ||(static_cast <bool> ((isa<CXXMemberCallExpr>(SubExpr
) || isa<BlockExpr>(SubExpr)) && "Unexpected SubExpr for CK_UserDefinedConversion."
) ? void (0) : __assert_fail ("(isa<CXXMemberCallExpr>(SubExpr) || isa<BlockExpr>(SubExpr)) && \"Unexpected SubExpr for CK_UserDefinedConversion.\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 1918, __extension__ __PRETTY_FUNCTION__))
1917 isa<BlockExpr>(SubExpr)) &&(static_cast <bool> ((isa<CXXMemberCallExpr>(SubExpr
) || isa<BlockExpr>(SubExpr)) && "Unexpected SubExpr for CK_UserDefinedConversion."
) ? void (0) : __assert_fail ("(isa<CXXMemberCallExpr>(SubExpr) || isa<BlockExpr>(SubExpr)) && \"Unexpected SubExpr for CK_UserDefinedConversion.\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 1918, __extension__ __PRETTY_FUNCTION__))
1918 "Unexpected SubExpr for CK_UserDefinedConversion.")(static_cast <bool> ((isa<CXXMemberCallExpr>(SubExpr
) || isa<BlockExpr>(SubExpr)) && "Unexpected SubExpr for CK_UserDefinedConversion."
) ? void (0) : __assert_fail ("(isa<CXXMemberCallExpr>(SubExpr) || isa<BlockExpr>(SubExpr)) && \"Unexpected SubExpr for CK_UserDefinedConversion.\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 1918, __extension__ __PRETTY_FUNCTION__))
;
1919 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SubExpr))
1920 SubExpr = MCE->getImplicitObjectArgument();
1921 }
1922
1923 // If the subexpression we're left with is an implicit cast, look
1924 // through that, too.
1925 } while ((E = dyn_cast<ImplicitCastExpr>(SubExpr)));
1926
1927 return const_cast<Expr*>(SubExpr);
1928}
1929
1930NamedDecl *CastExpr::getConversionFunction() const {
1931 const Expr *SubExpr = nullptr;
1932
1933 for (const CastExpr *E = this; E; E = dyn_cast<ImplicitCastExpr>(SubExpr)) {
1934 SubExpr = skipImplicitTemporary(E->getSubExpr());
1935
1936 if (E->getCastKind() == CK_ConstructorConversion)
1937 return cast<CXXConstructExpr>(SubExpr)->getConstructor();
1938
1939 if (E->getCastKind() == CK_UserDefinedConversion) {
1940 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SubExpr))
1941 return MCE->getMethodDecl();
1942 }
1943 }
1944
1945 return nullptr;
1946}
1947
1948CXXBaseSpecifier **CastExpr::path_buffer() {
1949 switch (getStmtClass()) {
1950#define ABSTRACT_STMT(x)
1951#define CASTEXPR(Type, Base) \
1952 case Stmt::Type##Class: \
1953 return static_cast<Type *>(this)->getTrailingObjects<CXXBaseSpecifier *>();
1954#define STMT(Type, Base)
1955#include "clang/AST/StmtNodes.inc"
1956 default:
1957 llvm_unreachable("non-cast expressions not possible here")::llvm::llvm_unreachable_internal("non-cast expressions not possible here"
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 1957)
;
1958 }
1959}
1960
1961const FieldDecl *CastExpr::getTargetFieldForToUnionCast(QualType unionType,
1962 QualType opType) {
1963 auto RD = unionType->castAs<RecordType>()->getDecl();
1964 return getTargetFieldForToUnionCast(RD, opType);
1965}
1966
1967const FieldDecl *CastExpr::getTargetFieldForToUnionCast(const RecordDecl *RD,
1968 QualType OpType) {
1969 auto &Ctx = RD->getASTContext();
1970 RecordDecl::field_iterator Field, FieldEnd;
1971 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
1972 Field != FieldEnd; ++Field) {
1973 if (Ctx.hasSameUnqualifiedType(Field->getType(), OpType) &&
1974 !Field->isUnnamedBitfield()) {
1975 return *Field;
1976 }
1977 }
1978 return nullptr;
1979}
1980
1981FPOptionsOverride *CastExpr::getTrailingFPFeatures() {
1982 assert(hasStoredFPFeatures())(static_cast <bool> (hasStoredFPFeatures()) ? void (0) :
__assert_fail ("hasStoredFPFeatures()", "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 1982, __extension__ __PRETTY_FUNCTION__))
;
1983 switch (getStmtClass()) {
1984 case ImplicitCastExprClass:
1985 return static_cast<ImplicitCastExpr *>(this)
1986 ->getTrailingObjects<FPOptionsOverride>();
1987 case CStyleCastExprClass:
1988 return static_cast<CStyleCastExpr *>(this)
1989 ->getTrailingObjects<FPOptionsOverride>();
1990 case CXXFunctionalCastExprClass:
1991 return static_cast<CXXFunctionalCastExpr *>(this)
1992 ->getTrailingObjects<FPOptionsOverride>();
1993 case CXXStaticCastExprClass:
1994 return static_cast<CXXStaticCastExpr *>(this)
1995 ->getTrailingObjects<FPOptionsOverride>();
1996 default:
1997 llvm_unreachable("Cast does not have FPFeatures")::llvm::llvm_unreachable_internal("Cast does not have FPFeatures"
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 1997)
;
1998 }
1999}
2000
2001ImplicitCastExpr *ImplicitCastExpr::Create(const ASTContext &C, QualType T,
2002 CastKind Kind, Expr *Operand,
2003 const CXXCastPath *BasePath,
2004 ExprValueKind VK,
2005 FPOptionsOverride FPO) {
2006 unsigned PathSize = (BasePath ? BasePath->size() : 0);
2007 void *Buffer =
2008 C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *, FPOptionsOverride>(
2009 PathSize, FPO.requiresTrailingStorage()));
2010 // Per C++ [conv.lval]p3, lvalue-to-rvalue conversions on class and
2011 // std::nullptr_t have special semantics not captured by CK_LValueToRValue.
2012 assert((Kind != CK_LValueToRValue ||(static_cast <bool> ((Kind != CK_LValueToRValue || !(T->
isNullPtrType() || T->getAsCXXRecordDecl())) && "invalid type for lvalue-to-rvalue conversion"
) ? void (0) : __assert_fail ("(Kind != CK_LValueToRValue || !(T->isNullPtrType() || T->getAsCXXRecordDecl())) && \"invalid type for lvalue-to-rvalue conversion\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 2014, __extension__ __PRETTY_FUNCTION__))
2013 !(T->isNullPtrType() || T->getAsCXXRecordDecl())) &&(static_cast <bool> ((Kind != CK_LValueToRValue || !(T->
isNullPtrType() || T->getAsCXXRecordDecl())) && "invalid type for lvalue-to-rvalue conversion"
) ? void (0) : __assert_fail ("(Kind != CK_LValueToRValue || !(T->isNullPtrType() || T->getAsCXXRecordDecl())) && \"invalid type for lvalue-to-rvalue conversion\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 2014, __extension__ __PRETTY_FUNCTION__))
2014 "invalid type for lvalue-to-rvalue conversion")(static_cast <bool> ((Kind != CK_LValueToRValue || !(T->
isNullPtrType() || T->getAsCXXRecordDecl())) && "invalid type for lvalue-to-rvalue conversion"
) ? void (0) : __assert_fail ("(Kind != CK_LValueToRValue || !(T->isNullPtrType() || T->getAsCXXRecordDecl())) && \"invalid type for lvalue-to-rvalue conversion\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 2014, __extension__ __PRETTY_FUNCTION__))
;
2015 ImplicitCastExpr *E =
2016 new (Buffer) ImplicitCastExpr(T, Kind, Operand, PathSize, FPO, VK);
2017 if (PathSize)
2018 std::uninitialized_copy_n(BasePath->data(), BasePath->size(),
2019 E->getTrailingObjects<CXXBaseSpecifier *>());
2020 return E;
2021}
2022
2023ImplicitCastExpr *ImplicitCastExpr::CreateEmpty(const ASTContext &C,
2024 unsigned PathSize,
2025 bool HasFPFeatures) {
2026 void *Buffer =
2027 C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *, FPOptionsOverride>(
2028 PathSize, HasFPFeatures));
2029 return new (Buffer) ImplicitCastExpr(EmptyShell(), PathSize, HasFPFeatures);
2030}
2031
2032CStyleCastExpr *CStyleCastExpr::Create(const ASTContext &C, QualType T,
2033 ExprValueKind VK, CastKind K, Expr *Op,
2034 const CXXCastPath *BasePath,
2035 FPOptionsOverride FPO,
2036 TypeSourceInfo *WrittenTy,
2037 SourceLocation L, SourceLocation R) {
2038 unsigned PathSize = (BasePath ? BasePath->size() : 0);
2039 void *Buffer =
2040 C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *, FPOptionsOverride>(
2041 PathSize, FPO.requiresTrailingStorage()));
2042 CStyleCastExpr *E =
2043 new (Buffer) CStyleCastExpr(T, VK, K, Op, PathSize, FPO, WrittenTy, L, R);
2044 if (PathSize)
2045 std::uninitialized_copy_n(BasePath->data(), BasePath->size(),
2046 E->getTrailingObjects<CXXBaseSpecifier *>());
2047 return E;
2048}
2049
2050CStyleCastExpr *CStyleCastExpr::CreateEmpty(const ASTContext &C,
2051 unsigned PathSize,
2052 bool HasFPFeatures) {
2053 void *Buffer =
2054 C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *, FPOptionsOverride>(
2055 PathSize, HasFPFeatures));
2056 return new (Buffer) CStyleCastExpr(EmptyShell(), PathSize, HasFPFeatures);
2057}
2058
2059/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
2060/// corresponds to, e.g. "<<=".
2061StringRef BinaryOperator::getOpcodeStr(Opcode Op) {
2062 switch (Op) {
2063#define BINARY_OPERATION(Name, Spelling) case BO_##Name: return Spelling;
2064#include "clang/AST/OperationKinds.def"
2065 }
2066 llvm_unreachable("Invalid OpCode!")::llvm::llvm_unreachable_internal("Invalid OpCode!", "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 2066)
;
2067}
2068
2069BinaryOperatorKind
2070BinaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO) {
2071 switch (OO) {
2072 default: llvm_unreachable("Not an overloadable binary operator")::llvm::llvm_unreachable_internal("Not an overloadable binary operator"
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 2072)
;
2073 case OO_Plus: return BO_Add;
2074 case OO_Minus: return BO_Sub;
2075 case OO_Star: return BO_Mul;
2076 case OO_Slash: return BO_Div;
2077 case OO_Percent: return BO_Rem;
2078 case OO_Caret: return BO_Xor;
2079 case OO_Amp: return BO_And;
2080 case OO_Pipe: return BO_Or;
2081 case OO_Equal: return BO_Assign;
2082 case OO_Spaceship: return BO_Cmp;
2083 case OO_Less: return BO_LT;
2084 case OO_Greater: return BO_GT;
2085 case OO_PlusEqual: return BO_AddAssign;
2086 case OO_MinusEqual: return BO_SubAssign;
2087 case OO_StarEqual: return BO_MulAssign;
2088 case OO_SlashEqual: return BO_DivAssign;
2089 case OO_PercentEqual: return BO_RemAssign;
2090 case OO_CaretEqual: return BO_XorAssign;
2091 case OO_AmpEqual: return BO_AndAssign;
2092 case OO_PipeEqual: return BO_OrAssign;
2093 case OO_LessLess: return BO_Shl;
2094 case OO_GreaterGreater: return BO_Shr;
2095 case OO_LessLessEqual: return BO_ShlAssign;
2096 case OO_GreaterGreaterEqual: return BO_ShrAssign;
2097 case OO_EqualEqual: return BO_EQ;
2098 case OO_ExclaimEqual: return BO_NE;
2099 case OO_LessEqual: return BO_LE;
2100 case OO_GreaterEqual: return BO_GE;
2101 case OO_AmpAmp: return BO_LAnd;
2102 case OO_PipePipe: return BO_LOr;
2103 case OO_Comma: return BO_Comma;
2104 case OO_ArrowStar: return BO_PtrMemI;
2105 }
2106}
2107
2108OverloadedOperatorKind BinaryOperator::getOverloadedOperator(Opcode Opc) {
2109 static const OverloadedOperatorKind OverOps[] = {
2110 /* .* Cannot be overloaded */OO_None, OO_ArrowStar,
2111 OO_Star, OO_Slash, OO_Percent,
2112 OO_Plus, OO_Minus,
2113 OO_LessLess, OO_GreaterGreater,
2114 OO_Spaceship,
2115 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
2116 OO_EqualEqual, OO_ExclaimEqual,
2117 OO_Amp,
2118 OO_Caret,
2119 OO_Pipe,
2120 OO_AmpAmp,
2121 OO_PipePipe,
2122 OO_Equal, OO_StarEqual,
2123 OO_SlashEqual, OO_PercentEqual,
2124 OO_PlusEqual, OO_MinusEqual,
2125 OO_LessLessEqual, OO_GreaterGreaterEqual,
2126 OO_AmpEqual, OO_CaretEqual,
2127 OO_PipeEqual,
2128 OO_Comma
2129 };
2130 return OverOps[Opc];
2131}
2132
2133bool BinaryOperator::isNullPointerArithmeticExtension(ASTContext &Ctx,
2134 Opcode Opc,
2135 Expr *LHS, Expr *RHS) {
2136 if (Opc != BO_Add)
2137 return false;
2138
2139 // Check that we have one pointer and one integer operand.
2140 Expr *PExp;
2141 if (LHS->getType()->isPointerType()) {
2142 if (!RHS->getType()->isIntegerType())
2143 return false;
2144 PExp = LHS;
2145 } else if (RHS->getType()->isPointerType()) {
2146 if (!LHS->getType()->isIntegerType())
2147 return false;
2148 PExp = RHS;
2149 } else {
2150 return false;
2151 }
2152
2153 // Check that the pointer is a nullptr.
2154 if (!PExp->IgnoreParenCasts()
2155 ->isNullPointerConstant(Ctx, Expr::NPC_ValueDependentIsNotNull))
2156 return false;
2157
2158 // Check that the pointee type is char-sized.
2159 const PointerType *PTy = PExp->getType()->getAs<PointerType>();
2160 if (!PTy || !PTy->getPointeeType()->isCharType())
2161 return false;
2162
2163 return true;
2164}
2165
2166static QualType getDecayedSourceLocExprType(const ASTContext &Ctx,
2167 SourceLocExpr::IdentKind Kind) {
2168 switch (Kind) {
2169 case SourceLocExpr::File:
2170 case SourceLocExpr::Function: {
2171 QualType ArrTy = Ctx.getStringLiteralArrayType(Ctx.CharTy, 0);
2172 return Ctx.getPointerType(ArrTy->getAsArrayTypeUnsafe()->getElementType());
2173 }
2174 case SourceLocExpr::Line:
2175 case SourceLocExpr::Column:
2176 return Ctx.UnsignedIntTy;
2177 }
2178 llvm_unreachable("unhandled case")::llvm::llvm_unreachable_internal("unhandled case", "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 2178)
;
2179}
2180
2181SourceLocExpr::SourceLocExpr(const ASTContext &Ctx, IdentKind Kind,
2182 SourceLocation BLoc, SourceLocation RParenLoc,
2183 DeclContext *ParentContext)
2184 : Expr(SourceLocExprClass, getDecayedSourceLocExprType(Ctx, Kind),
2185 VK_PRValue, OK_Ordinary),
2186 BuiltinLoc(BLoc), RParenLoc(RParenLoc), ParentContext(ParentContext) {
2187 SourceLocExprBits.Kind = Kind;
2188 setDependence(ExprDependence::None);
2189}
2190
2191StringRef SourceLocExpr::getBuiltinStr() const {
2192 switch (getIdentKind()) {
2193 case File:
2194 return "__builtin_FILE";
2195 case Function:
2196 return "__builtin_FUNCTION";
2197 case Line:
2198 return "__builtin_LINE";
2199 case Column:
2200 return "__builtin_COLUMN";
2201 }
2202 llvm_unreachable("unexpected IdentKind!")::llvm::llvm_unreachable_internal("unexpected IdentKind!", "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 2202)
;
2203}
2204
2205APValue SourceLocExpr::EvaluateInContext(const ASTContext &Ctx,
2206 const Expr *DefaultExpr) const {
2207 SourceLocation Loc;
2208 const DeclContext *Context;
2209
2210 std::tie(Loc,
2211 Context) = [&]() -> std::pair<SourceLocation, const DeclContext *> {
2212 if (auto *DIE = dyn_cast_or_null<CXXDefaultInitExpr>(DefaultExpr))
2213 return {DIE->getUsedLocation(), DIE->getUsedContext()};
2214 if (auto *DAE = dyn_cast_or_null<CXXDefaultArgExpr>(DefaultExpr))
2215 return {DAE->getUsedLocation(), DAE->getUsedContext()};
2216 return {this->getLocation(), this->getParentContext()};
2217 }();
2218
2219 PresumedLoc PLoc = Ctx.getSourceManager().getPresumedLoc(
2220 Ctx.getSourceManager().getExpansionRange(Loc).getEnd());
2221
2222 auto MakeStringLiteral = [&](StringRef Tmp) {
2223 using LValuePathEntry = APValue::LValuePathEntry;
2224 StringLiteral *Res = Ctx.getPredefinedStringLiteralFromCache(Tmp);
2225 // Decay the string to a pointer to the first character.
2226 LValuePathEntry Path[1] = {LValuePathEntry::ArrayIndex(0)};
2227 return APValue(Res, CharUnits::Zero(), Path, /*OnePastTheEnd=*/false);
2228 };
2229
2230 switch (getIdentKind()) {
2231 case SourceLocExpr::File:
2232 return MakeStringLiteral(PLoc.getFilename());
2233 case SourceLocExpr::Function: {
2234 const Decl *CurDecl = dyn_cast_or_null<Decl>(Context);
2235 return MakeStringLiteral(
2236 CurDecl ? PredefinedExpr::ComputeName(PredefinedExpr::Function, CurDecl)
2237 : std::string(""));
2238 }
2239 case SourceLocExpr::Line:
2240 case SourceLocExpr::Column: {
2241 llvm::APSInt IntVal(Ctx.getIntWidth(Ctx.UnsignedIntTy),
2242 /*isUnsigned=*/true);
2243 IntVal = getIdentKind() == SourceLocExpr::Line ? PLoc.getLine()
2244 : PLoc.getColumn();
2245 return APValue(IntVal);
2246 }
2247 }
2248 llvm_unreachable("unhandled case")::llvm::llvm_unreachable_internal("unhandled case", "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 2248)
;
2249}
2250
2251InitListExpr::InitListExpr(const ASTContext &C, SourceLocation lbraceloc,
2252 ArrayRef<Expr *> initExprs, SourceLocation rbraceloc)
2253 : Expr(InitListExprClass, QualType(), VK_PRValue, OK_Ordinary),
2254 InitExprs(C, initExprs.size()), LBraceLoc(lbraceloc),
2255 RBraceLoc(rbraceloc), AltForm(nullptr, true) {
2256 sawArrayRangeDesignator(false);
2257 InitExprs.insert(C, InitExprs.end(), initExprs.begin(), initExprs.end());
2258
2259 setDependence(computeDependence(this));
2260}
2261
2262void InitListExpr::reserveInits(const ASTContext &C, unsigned NumInits) {
2263 if (NumInits > InitExprs.size())
2264 InitExprs.reserve(C, NumInits);
2265}
2266
2267void InitListExpr::resizeInits(const ASTContext &C, unsigned NumInits) {
2268 InitExprs.resize(C, NumInits, nullptr);
2269}
2270
2271Expr *InitListExpr::updateInit(const ASTContext &C, unsigned Init, Expr *expr) {
2272 if (Init >= InitExprs.size()) {
2273 InitExprs.insert(C, InitExprs.end(), Init - InitExprs.size() + 1, nullptr);
2274 setInit(Init, expr);
2275 return nullptr;
2276 }
2277
2278 Expr *Result = cast_or_null<Expr>(InitExprs[Init]);
2279 setInit(Init, expr);
2280 return Result;
2281}
2282
2283void InitListExpr::setArrayFiller(Expr *filler) {
2284 assert(!hasArrayFiller() && "Filler already set!")(static_cast <bool> (!hasArrayFiller() && "Filler already set!"
) ? void (0) : __assert_fail ("!hasArrayFiller() && \"Filler already set!\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 2284, __extension__ __PRETTY_FUNCTION__))
;
2285 ArrayFillerOrUnionFieldInit = filler;
2286 // Fill out any "holes" in the array due to designated initializers.
2287 Expr **inits = getInits();
2288 for (unsigned i = 0, e = getNumInits(); i != e; ++i)
2289 if (inits[i] == nullptr)
2290 inits[i] = filler;
2291}
2292
2293bool InitListExpr::isStringLiteralInit() const {
2294 if (getNumInits() != 1)
2295 return false;
2296 const ArrayType *AT = getType()->getAsArrayTypeUnsafe();
2297 if (!AT || !AT->getElementType()->isIntegerType())
2298 return false;
2299 // It is possible for getInit() to return null.
2300 const Expr *Init = getInit(0);
2301 if (!Init)
2302 return false;
2303 Init = Init->IgnoreParens();
2304 return isa<StringLiteral>(Init) || isa<ObjCEncodeExpr>(Init);
2305}
2306
2307bool InitListExpr::isTransparent() const {
2308 assert(isSemanticForm() && "syntactic form never semantically transparent")(static_cast <bool> (isSemanticForm() && "syntactic form never semantically transparent"
) ? void (0) : __assert_fail ("isSemanticForm() && \"syntactic form never semantically transparent\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 2308, __extension__ __PRETTY_FUNCTION__))
;
2309
2310 // A glvalue InitListExpr is always just sugar.
2311 if (isGLValue()) {
2312 assert(getNumInits() == 1 && "multiple inits in glvalue init list")(static_cast <bool> (getNumInits() == 1 && "multiple inits in glvalue init list"
) ? void (0) : __assert_fail ("getNumInits() == 1 && \"multiple inits in glvalue init list\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 2312, __extension__ __PRETTY_FUNCTION__))
;
2313 return true;
2314 }
2315
2316 // Otherwise, we're sugar if and only if we have exactly one initializer that
2317 // is of the same type.
2318 if (getNumInits() != 1 || !getInit(0))
2319 return false;
2320
2321 // Don't confuse aggregate initialization of a struct X { X &x; }; with a
2322 // transparent struct copy.
2323 if (!getInit(0)->isPRValue() && getType()->isRecordType())
2324 return false;
2325
2326 return getType().getCanonicalType() ==
2327 getInit(0)->getType().getCanonicalType();
2328}
2329
2330bool InitListExpr::isIdiomaticZeroInitializer(const LangOptions &LangOpts) const {
2331 assert(isSyntacticForm() && "only test syntactic form as zero initializer")(static_cast <bool> (isSyntacticForm() && "only test syntactic form as zero initializer"
) ? void (0) : __assert_fail ("isSyntacticForm() && \"only test syntactic form as zero initializer\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 2331, __extension__ __PRETTY_FUNCTION__))
;
2332
2333 if (LangOpts.CPlusPlus || getNumInits() != 1 || !getInit(0)) {
2334 return false;
2335 }
2336
2337 const IntegerLiteral *Lit = dyn_cast<IntegerLiteral>(getInit(0)->IgnoreImplicit());
2338 return Lit && Lit->getValue() == 0;
2339}
2340
2341SourceLocation InitListExpr::getBeginLoc() const {
2342 if (InitListExpr *SyntacticForm = getSyntacticForm())
2343 return SyntacticForm->getBeginLoc();
2344 SourceLocation Beg = LBraceLoc;
2345 if (Beg.isInvalid()) {
2346 // Find the first non-null initializer.
2347 for (InitExprsTy::const_iterator I = InitExprs.begin(),
2348 E = InitExprs.end();
2349 I != E; ++I) {
2350 if (Stmt *S = *I) {
2351 Beg = S->getBeginLoc();
2352 break;
2353 }
2354 }
2355 }
2356 return Beg;
2357}
2358
2359SourceLocation InitListExpr::getEndLoc() const {
2360 if (InitListExpr *SyntacticForm = getSyntacticForm())
2361 return SyntacticForm->getEndLoc();
2362 SourceLocation End = RBraceLoc;
2363 if (End.isInvalid()) {
2364 // Find the first non-null initializer from the end.
2365 for (InitExprsTy::const_reverse_iterator I = InitExprs.rbegin(),
2366 E = InitExprs.rend();
2367 I != E; ++I) {
2368 if (Stmt *S = *I) {
2369 End = S->getEndLoc();
2370 break;
2371 }
2372 }
2373 }
2374 return End;
2375}
2376
2377/// getFunctionType - Return the underlying function type for this block.
2378///
2379const FunctionProtoType *BlockExpr::getFunctionType() const {
2380 // The block pointer is never sugared, but the function type might be.
2381 return cast<BlockPointerType>(getType())
2382 ->getPointeeType()->castAs<FunctionProtoType>();
2383}
2384
2385SourceLocation BlockExpr::getCaretLocation() const {
2386 return TheBlock->getCaretLocation();
2387}
2388const Stmt *BlockExpr::getBody() const {
2389 return TheBlock->getBody();
2390}
2391Stmt *BlockExpr::getBody() {
2392 return TheBlock->getBody();
2393}
2394
2395
2396//===----------------------------------------------------------------------===//
2397// Generic Expression Routines
2398//===----------------------------------------------------------------------===//
2399
2400bool Expr::isReadIfDiscardedInCPlusPlus11() const {
2401 // In C++11, discarded-value expressions of a certain form are special,
2402 // according to [expr]p10:
2403 // The lvalue-to-rvalue conversion (4.1) is applied only if the
2404 // expression is an lvalue of volatile-qualified type and it has
2405 // one of the following forms:
2406 if (!isGLValue() || !getType().isVolatileQualified())
2407 return false;
2408
2409 const Expr *E = IgnoreParens();
2410
2411 // - id-expression (5.1.1),
2412 if (isa<DeclRefExpr>(E))
2413 return true;
2414
2415 // - subscripting (5.2.1),
2416 if (isa<ArraySubscriptExpr>(E))
2417 return true;
2418
2419 // - class member access (5.2.5),
2420 if (isa<MemberExpr>(E))
2421 return true;
2422
2423 // - indirection (5.3.1),
2424 if (auto *UO = dyn_cast<UnaryOperator>(E))
2425 if (UO->getOpcode() == UO_Deref)
2426 return true;
2427
2428 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
2429 // - pointer-to-member operation (5.5),
2430 if (BO->isPtrMemOp())
2431 return true;
2432
2433 // - comma expression (5.18) where the right operand is one of the above.
2434 if (BO->getOpcode() == BO_Comma)
2435 return BO->getRHS()->isReadIfDiscardedInCPlusPlus11();
2436 }
2437
2438 // - conditional expression (5.16) where both the second and the third
2439 // operands are one of the above, or
2440 if (auto *CO = dyn_cast<ConditionalOperator>(E))
2441 return CO->getTrueExpr()->isReadIfDiscardedInCPlusPlus11() &&
2442 CO->getFalseExpr()->isReadIfDiscardedInCPlusPlus11();
2443 // The related edge case of "*x ?: *x".
2444 if (auto *BCO =
2445 dyn_cast<BinaryConditionalOperator>(E)) {
2446 if (auto *OVE = dyn_cast<OpaqueValueExpr>(BCO->getTrueExpr()))
2447 return OVE->getSourceExpr()->isReadIfDiscardedInCPlusPlus11() &&
2448 BCO->getFalseExpr()->isReadIfDiscardedInCPlusPlus11();
2449 }
2450
2451 // Objective-C++ extensions to the rule.
2452 if (isa<PseudoObjectExpr>(E) || isa<ObjCIvarRefExpr>(E))
2453 return true;
2454
2455 return false;
2456}
2457
2458/// isUnusedResultAWarning - Return true if this immediate expression should
2459/// be warned about if the result is unused. If so, fill in Loc and Ranges
2460/// with location to warn on and the source range[s] to report with the
2461/// warning.
2462bool Expr::isUnusedResultAWarning(const Expr *&WarnE, SourceLocation &Loc,
2463 SourceRange &R1, SourceRange &R2,
2464 ASTContext &Ctx) const {
2465 // Don't warn if the expr is type dependent. The type could end up
2466 // instantiating to void.
2467 if (isTypeDependent())
2468 return false;
2469
2470 switch (getStmtClass()) {
2471 default:
2472 if (getType()->isVoidType())
2473 return false;
2474 WarnE = this;
2475 Loc = getExprLoc();
2476 R1 = getSourceRange();
2477 return true;
2478 case ParenExprClass:
2479 return cast<ParenExpr>(this)->getSubExpr()->
2480 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2481 case GenericSelectionExprClass:
2482 return cast<GenericSelectionExpr>(this)->getResultExpr()->
2483 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2484 case CoawaitExprClass:
2485 case CoyieldExprClass:
2486 return cast<CoroutineSuspendExpr>(this)->getResumeExpr()->
2487 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2488 case ChooseExprClass:
2489 return cast<ChooseExpr>(this)->getChosenSubExpr()->
2490 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2491 case UnaryOperatorClass: {
2492 const UnaryOperator *UO = cast<UnaryOperator>(this);
2493
2494 switch (UO->getOpcode()) {
2495 case UO_Plus:
2496 case UO_Minus:
2497 case UO_AddrOf:
2498 case UO_Not:
2499 case UO_LNot:
2500 case UO_Deref:
2501 break;
2502 case UO_Coawait:
2503 // This is just the 'operator co_await' call inside the guts of a
2504 // dependent co_await call.
2505 case UO_PostInc:
2506 case UO_PostDec:
2507 case UO_PreInc:
2508 case UO_PreDec: // ++/--
2509 return false; // Not a warning.
2510 case UO_Real:
2511 case UO_Imag:
2512 // accessing a piece of a volatile complex is a side-effect.
2513 if (Ctx.getCanonicalType(UO->getSubExpr()->getType())
2514 .isVolatileQualified())
2515 return false;
2516 break;
2517 case UO_Extension:
2518 return UO->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2519 }
2520 WarnE = this;
2521 Loc = UO->getOperatorLoc();
2522 R1 = UO->getSubExpr()->getSourceRange();
2523 return true;
2524 }
2525 case BinaryOperatorClass: {
2526 const BinaryOperator *BO = cast<BinaryOperator>(this);
2527 switch (BO->getOpcode()) {
2528 default:
2529 break;
2530 // Consider the RHS of comma for side effects. LHS was checked by
2531 // Sema::CheckCommaOperands.
2532 case BO_Comma:
2533 // ((foo = <blah>), 0) is an idiom for hiding the result (and
2534 // lvalue-ness) of an assignment written in a macro.
2535 if (IntegerLiteral *IE =
2536 dyn_cast<IntegerLiteral>(BO->getRHS()->IgnoreParens()))
2537 if (IE->getValue() == 0)
2538 return false;
2539 return BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2540 // Consider '||', '&&' to have side effects if the LHS or RHS does.
2541 case BO_LAnd:
2542 case BO_LOr:
2543 if (!BO->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx) ||
2544 !BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx))
2545 return false;
2546 break;
2547 }
2548 if (BO->isAssignmentOp())
2549 return false;
2550 WarnE = this;
2551 Loc = BO->getOperatorLoc();
2552 R1 = BO->getLHS()->getSourceRange();
2553 R2 = BO->getRHS()->getSourceRange();
2554 return true;
2555 }
2556 case CompoundAssignOperatorClass:
2557 case VAArgExprClass:
2558 case AtomicExprClass:
2559 return false;
2560
2561 case ConditionalOperatorClass: {
2562 // If only one of the LHS or RHS is a warning, the operator might
2563 // be being used for control flow. Only warn if both the LHS and
2564 // RHS are warnings.
2565 const auto *Exp = cast<ConditionalOperator>(this);
2566 return Exp->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx) &&
2567 Exp->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2568 }
2569 case BinaryConditionalOperatorClass: {
2570 const auto *Exp = cast<BinaryConditionalOperator>(this);
2571 return Exp->getFalseExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2572 }
2573
2574 case MemberExprClass:
2575 WarnE = this;
2576 Loc = cast<MemberExpr>(this)->getMemberLoc();
2577 R1 = SourceRange(Loc, Loc);
2578 R2 = cast<MemberExpr>(this)->getBase()->getSourceRange();
2579 return true;
2580
2581 case ArraySubscriptExprClass:
2582 WarnE = this;
2583 Loc = cast<ArraySubscriptExpr>(this)->getRBracketLoc();
2584 R1 = cast<ArraySubscriptExpr>(this)->getLHS()->getSourceRange();
2585 R2 = cast<ArraySubscriptExpr>(this)->getRHS()->getSourceRange();
2586 return true;
2587
2588 case CXXOperatorCallExprClass: {
2589 // Warn about operator ==,!=,<,>,<=, and >= even when user-defined operator
2590 // overloads as there is no reasonable way to define these such that they
2591 // have non-trivial, desirable side-effects. See the -Wunused-comparison
2592 // warning: operators == and != are commonly typo'ed, and so warning on them
2593 // provides additional value as well. If this list is updated,
2594 // DiagnoseUnusedComparison should be as well.
2595 const CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(this);
2596 switch (Op->getOperator()) {
2597 default:
2598 break;
2599 case OO_EqualEqual:
2600 case OO_ExclaimEqual:
2601 case OO_Less:
2602 case OO_Greater:
2603 case OO_GreaterEqual:
2604 case OO_LessEqual:
2605 if (Op->getCallReturnType(Ctx)->isReferenceType() ||
2606 Op->getCallReturnType(Ctx)->isVoidType())
2607 break;
2608 WarnE = this;
2609 Loc = Op->getOperatorLoc();
2610 R1 = Op->getSourceRange();
2611 return true;
2612 }
2613
2614 // Fallthrough for generic call handling.
2615 LLVM_FALLTHROUGH[[gnu::fallthrough]];
2616 }
2617 case CallExprClass:
2618 case CXXMemberCallExprClass:
2619 case UserDefinedLiteralClass: {
2620 // If this is a direct call, get the callee.
2621 const CallExpr *CE = cast<CallExpr>(this);
2622 if (const Decl *FD = CE->getCalleeDecl()) {
2623 // If the callee has attribute pure, const, or warn_unused_result, warn
2624 // about it. void foo() { strlen("bar"); } should warn.
2625 //
2626 // Note: If new cases are added here, DiagnoseUnusedExprResult should be
2627 // updated to match for QoI.
2628 if (CE->hasUnusedResultAttr(Ctx) ||
2629 FD->hasAttr<PureAttr>() || FD->hasAttr<ConstAttr>()) {
2630 WarnE = this;
2631 Loc = CE->getCallee()->getBeginLoc();
2632 R1 = CE->getCallee()->getSourceRange();
2633
2634 if (unsigned NumArgs = CE->getNumArgs())
2635 R2 = SourceRange(CE->getArg(0)->getBeginLoc(),
2636 CE->getArg(NumArgs - 1)->getEndLoc());
2637 return true;
2638 }
2639 }
2640 return false;
2641 }
2642
2643 // If we don't know precisely what we're looking at, let's not warn.
2644 case UnresolvedLookupExprClass:
2645 case CXXUnresolvedConstructExprClass:
2646 case RecoveryExprClass:
2647 return false;
2648
2649 case CXXTemporaryObjectExprClass:
2650 case CXXConstructExprClass: {
2651 if (const CXXRecordDecl *Type = getType()->getAsCXXRecordDecl()) {
2652 const auto *WarnURAttr = Type->getAttr<WarnUnusedResultAttr>();
2653 if (Type->hasAttr<WarnUnusedAttr>() ||
2654 (WarnURAttr && WarnURAttr->IsCXX11NoDiscard())) {
2655 WarnE = this;
2656 Loc = getBeginLoc();
2657 R1 = getSourceRange();
2658 return true;
2659 }
2660 }
2661
2662 const auto *CE = cast<CXXConstructExpr>(this);
2663 if (const CXXConstructorDecl *Ctor = CE->getConstructor()) {
2664 const auto *WarnURAttr = Ctor->getAttr<WarnUnusedResultAttr>();
2665 if (WarnURAttr && WarnURAttr->IsCXX11NoDiscard()) {
2666 WarnE = this;
2667 Loc = getBeginLoc();
2668 R1 = getSourceRange();
2669
2670 if (unsigned NumArgs = CE->getNumArgs())
2671 R2 = SourceRange(CE->getArg(0)->getBeginLoc(),
2672 CE->getArg(NumArgs - 1)->getEndLoc());
2673 return true;
2674 }
2675 }
2676
2677 return false;
2678 }
2679
2680 case ObjCMessageExprClass: {
2681 const ObjCMessageExpr *ME = cast<ObjCMessageExpr>(this);
2682 if (Ctx.getLangOpts().ObjCAutoRefCount &&
2683 ME->isInstanceMessage() &&
2684 !ME->getType()->isVoidType() &&
2685 ME->getMethodFamily() == OMF_init) {
2686 WarnE = this;
2687 Loc = getExprLoc();
2688 R1 = ME->getSourceRange();
2689 return true;
2690 }
2691
2692 if (const ObjCMethodDecl *MD = ME->getMethodDecl())
2693 if (MD->hasAttr<WarnUnusedResultAttr>()) {
2694 WarnE = this;
2695 Loc = getExprLoc();
2696 return true;
2697 }
2698
2699 return false;
2700 }
2701
2702 case ObjCPropertyRefExprClass:
2703 WarnE = this;
2704 Loc = getExprLoc();
2705 R1 = getSourceRange();
2706 return true;
2707
2708 case PseudoObjectExprClass: {
2709 const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this);
2710
2711 // Only complain about things that have the form of a getter.
2712 if (isa<UnaryOperator>(PO->getSyntacticForm()) ||
2713 isa<BinaryOperator>(PO->getSyntacticForm()))
2714 return false;
2715
2716 WarnE = this;
2717 Loc = getExprLoc();
2718 R1 = getSourceRange();
2719 return true;
2720 }
2721
2722 case StmtExprClass: {
2723 // Statement exprs don't logically have side effects themselves, but are
2724 // sometimes used in macros in ways that give them a type that is unused.
2725 // For example ({ blah; foo(); }) will end up with a type if foo has a type.
2726 // however, if the result of the stmt expr is dead, we don't want to emit a
2727 // warning.
2728 const CompoundStmt *CS = cast<StmtExpr>(this)->getSubStmt();
2729 if (!CS->body_empty()) {
2730 if (const Expr *E = dyn_cast<Expr>(CS->body_back()))
2731 return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2732 if (const LabelStmt *Label = dyn_cast<LabelStmt>(CS->body_back()))
2733 if (const Expr *E = dyn_cast<Expr>(Label->getSubStmt()))
2734 return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2735 }
2736
2737 if (getType()->isVoidType())
2738 return false;
2739 WarnE = this;
2740 Loc = cast<StmtExpr>(this)->getLParenLoc();
2741 R1 = getSourceRange();
2742 return true;
2743 }
2744 case CXXFunctionalCastExprClass:
2745 case CStyleCastExprClass: {
2746 // Ignore an explicit cast to void, except in C++98 if the operand is a
2747 // volatile glvalue for which we would trigger an implicit read in any
2748 // other language mode. (Such an implicit read always happens as part of
2749 // the lvalue conversion in C, and happens in C++ for expressions of all
2750 // forms where it seems likely the user intended to trigger a volatile
2751 // load.)
2752 const CastExpr *CE = cast<CastExpr>(this);
2753 const Expr *SubE = CE->getSubExpr()->IgnoreParens();
2754 if (CE->getCastKind() == CK_ToVoid) {
2755 if (Ctx.getLangOpts().CPlusPlus && !Ctx.getLangOpts().CPlusPlus11 &&
2756 SubE->isReadIfDiscardedInCPlusPlus11()) {
2757 // Suppress the "unused value" warning for idiomatic usage of
2758 // '(void)var;' used to suppress "unused variable" warnings.
2759 if (auto *DRE = dyn_cast<DeclRefExpr>(SubE))
2760 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
2761 if (!VD->isExternallyVisible())
2762 return false;
2763
2764 // The lvalue-to-rvalue conversion would have no effect for an array.
2765 // It's implausible that the programmer expected this to result in a
2766 // volatile array load, so don't warn.
2767 if (SubE->getType()->isArrayType())
2768 return false;
2769
2770 return SubE->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2771 }
2772 return false;
2773 }
2774
2775 // If this is a cast to a constructor conversion, check the operand.
2776 // Otherwise, the result of the cast is unused.
2777 if (CE->getCastKind() == CK_ConstructorConversion)
2778 return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2779 if (CE->getCastKind() == CK_Dependent)
2780 return false;
2781
2782 WarnE = this;
2783 if (const CXXFunctionalCastExpr *CXXCE =
2784 dyn_cast<CXXFunctionalCastExpr>(this)) {
2785 Loc = CXXCE->getBeginLoc();
2786 R1 = CXXCE->getSubExpr()->getSourceRange();
2787 } else {
2788 const CStyleCastExpr *CStyleCE = cast<CStyleCastExpr>(this);
2789 Loc = CStyleCE->getLParenLoc();
2790 R1 = CStyleCE->getSubExpr()->getSourceRange();
2791 }
2792 return true;
2793 }
2794 case ImplicitCastExprClass: {
2795 const CastExpr *ICE = cast<ImplicitCastExpr>(this);
2796
2797 // lvalue-to-rvalue conversion on a volatile lvalue is a side-effect.
2798 if (ICE->getCastKind() == CK_LValueToRValue &&
2799 ICE->getSubExpr()->getType().isVolatileQualified())
2800 return false;
2801
2802 return ICE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2803 }
2804 case CXXDefaultArgExprClass:
2805 return (cast<CXXDefaultArgExpr>(this)
2806 ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
2807 case CXXDefaultInitExprClass:
2808 return (cast<CXXDefaultInitExpr>(this)
2809 ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
2810
2811 case CXXNewExprClass:
2812 // FIXME: In theory, there might be new expressions that don't have side
2813 // effects (e.g. a placement new with an uninitialized POD).
2814 case CXXDeleteExprClass:
2815 return false;
2816 case MaterializeTemporaryExprClass:
2817 return cast<MaterializeTemporaryExpr>(this)
2818 ->getSubExpr()
2819 ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2820 case CXXBindTemporaryExprClass:
2821 return cast<CXXBindTemporaryExpr>(this)->getSubExpr()
2822 ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2823 case ExprWithCleanupsClass:
2824 return cast<ExprWithCleanups>(this)->getSubExpr()
2825 ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2826 }
2827}
2828
2829/// isOBJCGCCandidate - Check if an expression is objc gc'able.
2830/// returns true, if it is; false otherwise.
2831bool Expr::isOBJCGCCandidate(ASTContext &Ctx) const {
2832 const Expr *E = IgnoreParens();
2833 switch (E->getStmtClass()) {
2834 default:
2835 return false;
2836 case ObjCIvarRefExprClass:
2837 return true;
2838 case Expr::UnaryOperatorClass:
2839 return cast<UnaryOperator>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
2840 case ImplicitCastExprClass:
2841 return cast<ImplicitCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
2842 case MaterializeTemporaryExprClass:
2843 return cast<MaterializeTemporaryExpr>(E)->getSubExpr()->isOBJCGCCandidate(
2844 Ctx);
2845 case CStyleCastExprClass:
2846 return cast<CStyleCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
2847 case DeclRefExprClass: {
2848 const Decl *D = cast<DeclRefExpr>(E)->getDecl();
2849
2850 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2851 if (VD->hasGlobalStorage())
2852 return true;
2853 QualType T = VD->getType();
2854 // dereferencing to a pointer is always a gc'able candidate,
2855 // unless it is __weak.
2856 return T->isPointerType() &&
2857 (Ctx.getObjCGCAttrKind(T) != Qualifiers::Weak);
2858 }
2859 return false;
2860 }
2861 case MemberExprClass: {
2862 const MemberExpr *M = cast<MemberExpr>(E);
2863 return M->getBase()->isOBJCGCCandidate(Ctx);
2864 }
2865 case ArraySubscriptExprClass:
2866 return cast<ArraySubscriptExpr>(E)->getBase()->isOBJCGCCandidate(Ctx);
2867 }
2868}
2869
2870bool Expr::isBoundMemberFunction(ASTContext &Ctx) const {
2871 if (isTypeDependent())
2872 return false;
2873 return ClassifyLValue(Ctx) == Expr::LV_MemberFunction;
2874}
2875
2876QualType Expr::findBoundMemberType(const Expr *expr) {
2877 assert(expr->hasPlaceholderType(BuiltinType::BoundMember))(static_cast <bool> (expr->hasPlaceholderType(BuiltinType
::BoundMember)) ? void (0) : __assert_fail ("expr->hasPlaceholderType(BuiltinType::BoundMember)"
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 2877, __extension__ __PRETTY_FUNCTION__))
;
2878
2879 // Bound member expressions are always one of these possibilities:
2880 // x->m x.m x->*y x.*y
2881 // (possibly parenthesized)
2882
2883 expr = expr->IgnoreParens();
2884 if (const MemberExpr *mem = dyn_cast<MemberExpr>(expr)) {
2885 assert(isa<CXXMethodDecl>(mem->getMemberDecl()))(static_cast <bool> (isa<CXXMethodDecl>(mem->getMemberDecl
())) ? void (0) : __assert_fail ("isa<CXXMethodDecl>(mem->getMemberDecl())"
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 2885, __extension__ __PRETTY_FUNCTION__))
;
2886 return mem->getMemberDecl()->getType();
2887 }
2888
2889 if (const BinaryOperator *op = dyn_cast<BinaryOperator>(expr)) {
2890 QualType type = op->getRHS()->getType()->castAs<MemberPointerType>()
2891 ->getPointeeType();
2892 assert(type->isFunctionType())(static_cast <bool> (type->isFunctionType()) ? void (
0) : __assert_fail ("type->isFunctionType()", "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 2892, __extension__ __PRETTY_FUNCTION__))
;
2893 return type;
2894 }
2895
2896 assert(isa<UnresolvedMemberExpr>(expr) || isa<CXXPseudoDestructorExpr>(expr))(static_cast <bool> (isa<UnresolvedMemberExpr>(expr
) || isa<CXXPseudoDestructorExpr>(expr)) ? void (0) : __assert_fail
("isa<UnresolvedMemberExpr>(expr) || isa<CXXPseudoDestructorExpr>(expr)"
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 2896, __extension__ __PRETTY_FUNCTION__))
;
2897 return QualType();
2898}
2899
2900Expr *Expr::IgnoreImpCasts() {
2901 return IgnoreExprNodes(this, IgnoreImplicitCastsSingleStep);
2902}
2903
2904Expr *Expr::IgnoreCasts() {
2905 return IgnoreExprNodes(this, IgnoreCastsSingleStep);
2906}
2907
2908Expr *Expr::IgnoreImplicit() {
2909 return IgnoreExprNodes(this, IgnoreImplicitSingleStep);
2910}
2911
2912Expr *Expr::IgnoreImplicitAsWritten() {
2913 return IgnoreExprNodes(this, IgnoreImplicitAsWrittenSingleStep);
2914}
2915
2916Expr *Expr::IgnoreParens() {
2917 return IgnoreExprNodes(this, IgnoreParensSingleStep);
2918}
2919
2920Expr *Expr::IgnoreParenImpCasts() {
2921 return IgnoreExprNodes(this, IgnoreParensSingleStep,
2922 IgnoreImplicitCastsExtraSingleStep);
2923}
2924
2925Expr *Expr::IgnoreParenCasts() {
2926 return IgnoreExprNodes(this, IgnoreParensSingleStep, IgnoreCastsSingleStep);
2927}
2928
2929Expr *Expr::IgnoreConversionOperatorSingleStep() {
2930 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(this)) {
2931 if (MCE->getMethodDecl() && isa<CXXConversionDecl>(MCE->getMethodDecl()))
2932 return MCE->getImplicitObjectArgument();
2933 }
2934 return this;
2935}
2936
2937Expr *Expr::IgnoreParenLValueCasts() {
2938 return IgnoreExprNodes(this, IgnoreParensSingleStep,
2939 IgnoreLValueCastsSingleStep);
2940}
2941
2942Expr *Expr::IgnoreParenBaseCasts() {
2943 return IgnoreExprNodes(this, IgnoreParensSingleStep,
2944 IgnoreBaseCastsSingleStep);
2945}
2946
2947Expr *Expr::IgnoreParenNoopCasts(const ASTContext &Ctx) {
2948 auto IgnoreNoopCastsSingleStep = [&Ctx](Expr *E) {
2949 if (auto *CE = dyn_cast<CastExpr>(E)) {
2950 // We ignore integer <-> casts that are of the same width, ptr<->ptr and
2951 // ptr<->int casts of the same width. We also ignore all identity casts.
2952 Expr *SubExpr = CE->getSubExpr();
2953 bool IsIdentityCast =
2954 Ctx.hasSameUnqualifiedType(E->getType(), SubExpr->getType());
2955 bool IsSameWidthCast = (E->getType()->isPointerType() ||
2956 E->getType()->isIntegralType(Ctx)) &&
2957 (SubExpr->getType()->isPointerType() ||
2958 SubExpr->getType()->isIntegralType(Ctx)) &&
2959 (Ctx.getTypeSize(E->getType()) ==
2960 Ctx.getTypeSize(SubExpr->getType()));
2961
2962 if (IsIdentityCast || IsSameWidthCast)
2963 return SubExpr;
2964 } else if (auto *NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E))
2965 return NTTP->getReplacement();
2966
2967 return E;
2968 };
2969 return IgnoreExprNodes(this, IgnoreParensSingleStep,
2970 IgnoreNoopCastsSingleStep);
2971}
2972
2973Expr *Expr::IgnoreUnlessSpelledInSource() {
2974 auto IgnoreImplicitConstructorSingleStep = [](Expr *E) {
2975 if (auto *Cast = dyn_cast<CXXFunctionalCastExpr>(E)) {
2976 auto *SE = Cast->getSubExpr();
2977 if (SE->getSourceRange() == E->getSourceRange())
2978 return SE;
2979 }
2980
2981 if (auto *C = dyn_cast<CXXConstructExpr>(E)) {
2982 auto NumArgs = C->getNumArgs();
2983 if (NumArgs == 1 ||
2984 (NumArgs > 1 && isa<CXXDefaultArgExpr>(C->getArg(1)))) {
2985 Expr *A = C->getArg(0);
2986 if (A->getSourceRange() == E->getSourceRange() || C->isElidable())
2987 return A;
2988 }
2989 }
2990 return E;
2991 };
2992 auto IgnoreImplicitMemberCallSingleStep = [](Expr *E) {
2993 if (auto *C = dyn_cast<CXXMemberCallExpr>(E)) {
2994 Expr *ExprNode = C->getImplicitObjectArgument();
2995 if (ExprNode->getSourceRange() == E->getSourceRange()) {
2996 return ExprNode;
2997 }
2998 if (auto *PE = dyn_cast<ParenExpr>(ExprNode)) {
2999 if (PE->getSourceRange() == C->getSourceRange()) {
3000 return cast<Expr>(PE);
3001 }
3002 }
3003 ExprNode = ExprNode->IgnoreParenImpCasts();
3004 if (ExprNode->getSourceRange() == E->getSourceRange())
3005 return ExprNode;
3006 }
3007 return E;
3008 };
3009 return IgnoreExprNodes(
3010 this, IgnoreImplicitSingleStep, IgnoreImplicitCastsExtraSingleStep,
3011 IgnoreParensOnlySingleStep, IgnoreImplicitConstructorSingleStep,
3012 IgnoreImplicitMemberCallSingleStep);
3013}
3014
3015bool Expr::isDefaultArgument() const {
3016 const Expr *E = this;
3017 if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
3018 E = M->getSubExpr();
3019
3020 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3021 E = ICE->getSubExprAsWritten();
3022
3023 return isa<CXXDefaultArgExpr>(E);
3024}
3025
3026/// Skip over any no-op casts and any temporary-binding
3027/// expressions.
3028static const Expr *skipTemporaryBindingsNoOpCastsAndParens(const Expr *E) {
3029 if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
3030 E = M->getSubExpr();
3031
3032 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3033 if (ICE->getCastKind() == CK_NoOp)
3034 E = ICE->getSubExpr();
3035 else
3036 break;
3037 }
3038
3039 while (const CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
3040 E = BE->getSubExpr();
3041
3042 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3043 if (ICE->getCastKind() == CK_NoOp)
3044 E = ICE->getSubExpr();
3045 else
3046 break;
3047 }
3048
3049 return E->IgnoreParens();
3050}
3051
3052/// isTemporaryObject - Determines if this expression produces a
3053/// temporary of the given class type.
3054bool Expr::isTemporaryObject(ASTContext &C, const CXXRecordDecl *TempTy) const {
3055 if (!C.hasSameUnqualifiedType(getType(), C.getTypeDeclType(TempTy)))
3056 return false;
3057
3058 const Expr *E = skipTemporaryBindingsNoOpCastsAndParens(this);
3059
3060 // Temporaries are by definition pr-values of class type.
3061 if (!E->Classify(C).isPRValue()) {
3062 // In this context, property reference is a message call and is pr-value.
3063 if (!isa<ObjCPropertyRefExpr>(E))
3064 return false;
3065 }
3066
3067 // Black-list a few cases which yield pr-values of class type that don't
3068 // refer to temporaries of that type:
3069
3070 // - implicit derived-to-base conversions
3071 if (isa<ImplicitCastExpr>(E)) {
3072 switch (cast<ImplicitCastExpr>(E)->getCastKind()) {
3073 case CK_DerivedToBase:
3074 case CK_UncheckedDerivedToBase:
3075 return false;
3076 default:
3077 break;
3078 }
3079 }
3080
3081 // - member expressions (all)
3082 if (isa<MemberExpr>(E))
3083 return false;
3084
3085 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E))
3086 if (BO->isPtrMemOp())
3087 return false;
3088
3089 // - opaque values (all)
3090 if (isa<OpaqueValueExpr>(E))
3091 return false;
3092
3093 return true;
3094}
3095
3096bool Expr::isImplicitCXXThis() const {
3097 const Expr *E = this;
3098
3099 // Strip away parentheses and casts we don't care about.
3100 while (true) {
3101 if (const ParenExpr *Paren = dyn_cast<ParenExpr>(E)) {
3102 E = Paren->getSubExpr();
3103 continue;
3104 }
3105
3106 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3107 if (ICE->getCastKind() == CK_NoOp ||
3108 ICE->getCastKind() == CK_LValueToRValue ||
3109 ICE->getCastKind() == CK_DerivedToBase ||
3110 ICE->getCastKind() == CK_UncheckedDerivedToBase) {
3111 E = ICE->getSubExpr();
3112 continue;
3113 }
3114 }
3115
3116 if (const UnaryOperator* UnOp = dyn_cast<UnaryOperator>(E)) {
3117 if (UnOp->getOpcode() == UO_Extension) {
3118 E = UnOp->getSubExpr();
3119 continue;
3120 }
3121 }
3122
3123 if (const MaterializeTemporaryExpr *M
3124 = dyn_cast<MaterializeTemporaryExpr>(E)) {
3125 E = M->getSubExpr();
3126 continue;
3127 }
3128
3129 break;
3130 }
3131
3132 if (const CXXThisExpr *This = dyn_cast<CXXThisExpr>(E))
3133 return This->isImplicit();
3134
3135 return false;
3136}
3137
3138/// hasAnyTypeDependentArguments - Determines if any of the expressions
3139/// in Exprs is type-dependent.
3140bool Expr::hasAnyTypeDependentArguments(ArrayRef<Expr *> Exprs) {
3141 for (unsigned I = 0; I < Exprs.size(); ++I)
3142 if (Exprs[I]->isTypeDependent())
3143 return true;
3144
3145 return false;
3146}
3147
3148bool Expr::isConstantInitializer(ASTContext &Ctx, bool IsForRef,
3149 const Expr **Culprit) const {
3150 assert(!isValueDependent() &&(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression."
) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 3151, __extension__ __PRETTY_FUNCTION__))
3151 "Expression evaluator can't be called on a dependent expression.")(static_cast <bool> (!isValueDependent() && "Expression evaluator can't be called on a dependent expression."
) ? void (0) : __assert_fail ("!isValueDependent() && \"Expression evaluator can't be called on a dependent expression.\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 3151, __extension__ __PRETTY_FUNCTION__))
;
3152
3153 // This function is attempting whether an expression is an initializer
3154 // which can be evaluated at compile-time. It very closely parallels
3155 // ConstExprEmitter in CGExprConstant.cpp; if they don't match, it
3156 // will lead to unexpected results. Like ConstExprEmitter, it falls back
3157 // to isEvaluatable most of the time.
3158 //
3159 // If we ever capture reference-binding directly in the AST, we can
3160 // kill the second parameter.
3161
3162 if (IsForRef) {
3163 EvalResult Result;
3164 if (EvaluateAsLValue(Result, Ctx) && !Result.HasSideEffects)
3165 return true;
3166 if (Culprit)
3167 *Culprit = this;
3168 return false;
3169 }
3170
3171 switch (getStmtClass()) {
3172 default: break;
3173 case Stmt::ExprWithCleanupsClass:
3174 return cast<ExprWithCleanups>(this)->getSubExpr()->isConstantInitializer(
3175 Ctx, IsForRef, Culprit);
3176 case StringLiteralClass:
3177 case ObjCEncodeExprClass:
3178 return true;
3179 case CXXTemporaryObjectExprClass:
3180 case CXXConstructExprClass: {
3181 const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
3182
3183 if (CE->getConstructor()->isTrivial() &&
3184 CE->getConstructor()->getParent()->hasTrivialDestructor()) {
3185 // Trivial default constructor
3186 if (!CE->getNumArgs()) return true;
3187
3188 // Trivial copy constructor
3189 assert(CE->getNumArgs() == 1 && "trivial ctor with > 1 argument")(static_cast <bool> (CE->getNumArgs() == 1 &&
"trivial ctor with > 1 argument") ? void (0) : __assert_fail
("CE->getNumArgs() == 1 && \"trivial ctor with > 1 argument\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 3189, __extension__ __PRETTY_FUNCTION__))
;
3190 return CE->getArg(0)->isConstantInitializer(Ctx, false, Culprit);
3191 }
3192
3193 break;
3194 }
3195 case ConstantExprClass: {
3196 // FIXME: We should be able to return "true" here, but it can lead to extra
3197 // error messages. E.g. in Sema/array-init.c.
3198 const Expr *Exp = cast<ConstantExpr>(this)->getSubExpr();
3199 return Exp->isConstantInitializer(Ctx, false, Culprit);
3200 }
3201 case CompoundLiteralExprClass: {
3202 // This handles gcc's extension that allows global initializers like
3203 // "struct x {int x;} x = (struct x) {};".
3204 // FIXME: This accepts other cases it shouldn't!
3205 const Expr *Exp = cast<CompoundLiteralExpr>(this)->getInitializer();
3206 return Exp->isConstantInitializer(Ctx, false, Culprit);
3207 }
3208 case DesignatedInitUpdateExprClass: {
3209 const DesignatedInitUpdateExpr *DIUE = cast<DesignatedInitUpdateExpr>(this);
3210 return DIUE->getBase()->isConstantInitializer(Ctx, false, Culprit) &&
3211 DIUE->getUpdater()->isConstantInitializer(Ctx, false, Culprit);
3212 }
3213 case InitListExprClass: {
3214 const InitListExpr *ILE = cast<InitListExpr>(this);
3215 assert(ILE->isSemanticForm() && "InitListExpr must be in semantic form")(static_cast <bool> (ILE->isSemanticForm() &&
"InitListExpr must be in semantic form") ? void (0) : __assert_fail
("ILE->isSemanticForm() && \"InitListExpr must be in semantic form\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 3215, __extension__ __PRETTY_FUNCTION__))
;
3216 if (ILE->getType()->isArrayType()) {
3217 unsigned numInits = ILE->getNumInits();
3218 for (unsigned i = 0; i < numInits; i++) {
3219 if (!ILE->getInit(i)->isConstantInitializer(Ctx, false, Culprit))
3220 return false;
3221 }
3222 return true;
3223 }
3224
3225 if (ILE->getType()->isRecordType()) {
3226 unsigned ElementNo = 0;
3227 RecordDecl *RD = ILE->getType()->castAs<RecordType>()->getDecl();
3228 for (const auto *Field : RD->fields()) {
3229 // If this is a union, skip all the fields that aren't being initialized.
3230 if (RD->isUnion() && ILE->getInitializedFieldInUnion() != Field)
3231 continue;
3232
3233 // Don't emit anonymous bitfields, they just affect layout.
3234 if (Field->isUnnamedBitfield())
3235 continue;
3236
3237 if (ElementNo < ILE->getNumInits()) {
3238 const Expr *Elt = ILE->getInit(ElementNo++);
3239 if (Field->isBitField()) {
3240 // Bitfields have to evaluate to an integer.
3241 EvalResult Result;
3242 if (!Elt->EvaluateAsInt(Result, Ctx)) {
3243 if (Culprit)
3244 *Culprit = Elt;
3245 return false;
3246 }
3247 } else {
3248 bool RefType = Field->getType()->isReferenceType();
3249 if (!Elt->isConstantInitializer(Ctx, RefType, Culprit))
3250 return false;
3251 }
3252 }
3253 }
3254 return true;
3255 }
3256
3257 break;
3258 }
3259 case ImplicitValueInitExprClass:
3260 case NoInitExprClass:
3261 return true;
3262 case ParenExprClass:
3263 return cast<ParenExpr>(this)->getSubExpr()
3264 ->isConstantInitializer(Ctx, IsForRef, Culprit);
3265 case GenericSelectionExprClass:
3266 return cast<GenericSelectionExpr>(this)->getResultExpr()
3267 ->isConstantInitializer(Ctx, IsForRef, Culprit);
3268 case ChooseExprClass:
3269 if (cast<ChooseExpr>(this)->isConditionDependent()) {
3270 if (Culprit)
3271 *Culprit = this;
3272 return false;
3273 }
3274 return cast<ChooseExpr>(this)->getChosenSubExpr()
3275 ->isConstantInitializer(Ctx, IsForRef, Culprit);
3276 case UnaryOperatorClass: {
3277 const UnaryOperator* Exp = cast<UnaryOperator>(this);
3278 if (Exp->getOpcode() == UO_Extension)
3279 return Exp->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
3280 break;
3281 }
3282 case CXXFunctionalCastExprClass:
3283 case CXXStaticCastExprClass:
3284 case ImplicitCastExprClass:
3285 case CStyleCastExprClass:
3286 case ObjCBridgedCastExprClass:
3287 case CXXDynamicCastExprClass:
3288 case CXXReinterpretCastExprClass:
3289 case CXXAddrspaceCastExprClass:
3290 case CXXConstCastExprClass: {
3291 const CastExpr *CE = cast<CastExpr>(this);
3292
3293 // Handle misc casts we want to ignore.
3294 if (CE->getCastKind() == CK_NoOp ||
3295 CE->getCastKind() == CK_LValueToRValue ||
3296 CE->getCastKind() == CK_ToUnion ||
3297 CE->getCastKind() == CK_ConstructorConversion ||
3298 CE->getCastKind() == CK_NonAtomicToAtomic ||
3299 CE->getCastKind() == CK_AtomicToNonAtomic ||
3300 CE->getCastKind() == CK_IntToOCLSampler)
3301 return CE->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
3302
3303 break;
3304 }
3305 case MaterializeTemporaryExprClass:
3306 return cast<MaterializeTemporaryExpr>(this)
3307 ->getSubExpr()
3308 ->isConstantInitializer(Ctx, false, Culprit);
3309
3310 case SubstNonTypeTemplateParmExprClass:
3311 return cast<SubstNonTypeTemplateParmExpr>(this)->getReplacement()
3312 ->isConstantInitializer(Ctx, false, Culprit);
3313 case CXXDefaultArgExprClass:
3314 return cast<CXXDefaultArgExpr>(this)->getExpr()
3315 ->isConstantInitializer(Ctx, false, Culprit);
3316 case CXXDefaultInitExprClass:
3317 return cast<CXXDefaultInitExpr>(this)->getExpr()
3318 ->isConstantInitializer(Ctx, false, Culprit);
3319 }
3320 // Allow certain forms of UB in constant initializers: signed integer
3321 // overflow and floating-point division by zero. We'll give a warning on
3322 // these, but they're common enough that we have to accept them.
3323 if (isEvaluatable(Ctx, SE_AllowUndefinedBehavior))
3324 return true;
3325 if (Culprit)
3326 *Culprit = this;
3327 return false;
3328}
3329
3330bool CallExpr::isBuiltinAssumeFalse(const ASTContext &Ctx) const {
3331 const FunctionDecl* FD = getDirectCallee();
3332 if (!FD || (FD->getBuiltinID() != Builtin::BI__assume &&
3333 FD->getBuiltinID() != Builtin::BI__builtin_assume))
3334 return false;
3335
3336 const Expr* Arg = getArg(0);
3337 bool ArgVal;
3338 return !Arg->isValueDependent() &&
3339 Arg->EvaluateAsBooleanCondition(ArgVal, Ctx) && !ArgVal;
3340}
3341
3342namespace {
3343 /// Look for any side effects within a Stmt.
3344 class SideEffectFinder : public ConstEvaluatedExprVisitor<SideEffectFinder> {
3345 typedef ConstEvaluatedExprVisitor<SideEffectFinder> Inherited;
3346 const bool IncludePossibleEffects;
3347 bool HasSideEffects;
3348
3349 public:
3350 explicit SideEffectFinder(const ASTContext &Context, bool IncludePossible)
3351 : Inherited(Context),
3352 IncludePossibleEffects(IncludePossible), HasSideEffects(false) { }
3353
3354 bool hasSideEffects() const { return HasSideEffects; }
3355
3356 void VisitDecl(const Decl *D) {
3357 if (!D)
3358 return;
3359
3360 // We assume the caller checks subexpressions (eg, the initializer, VLA
3361 // bounds) for side-effects on our behalf.
3362 if (auto *VD = dyn_cast<VarDecl>(D)) {
3363 // Registering a destructor is a side-effect.
3364 if (IncludePossibleEffects && VD->isThisDeclarationADefinition() &&
3365 VD->needsDestruction(Context))
3366 HasSideEffects = true;
3367 }
3368 }
3369
3370 void VisitDeclStmt(const DeclStmt *DS) {
3371 for (auto *D : DS->decls())
3372 VisitDecl(D);
3373 Inherited::VisitDeclStmt(DS);
3374 }
3375
3376 void VisitExpr(const Expr *E) {
3377 if (!HasSideEffects &&
3378 E->HasSideEffects(Context, IncludePossibleEffects))
3379 HasSideEffects = true;
3380 }
3381 };
3382}
3383
3384bool Expr::HasSideEffects(const ASTContext &Ctx,
3385 bool IncludePossibleEffects) const {
3386 // In circumstances where we care about definite side effects instead of
3387 // potential side effects, we want to ignore expressions that are part of a
3388 // macro expansion as a potential side effect.
3389 if (!IncludePossibleEffects && getExprLoc().isMacroID())
3390 return false;
3391
3392 switch (getStmtClass()) {
3393 case NoStmtClass:
3394 #define ABSTRACT_STMT(Type)
3395 #define STMT(Type, Base) case Type##Class:
3396 #define EXPR(Type, Base)
3397 #include "clang/AST/StmtNodes.inc"
3398 llvm_unreachable("unexpected Expr kind")::llvm::llvm_unreachable_internal("unexpected Expr kind", "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 3398)
;
3399
3400 case DependentScopeDeclRefExprClass:
3401 case CXXUnresolvedConstructExprClass:
3402 case CXXDependentScopeMemberExprClass:
3403 case UnresolvedLookupExprClass:
3404 case UnresolvedMemberExprClass:
3405 case PackExpansionExprClass:
3406 case SubstNonTypeTemplateParmPackExprClass:
3407 case FunctionParmPackExprClass:
3408 case TypoExprClass:
3409 case RecoveryExprClass:
3410 case CXXFoldExprClass:
3411 // Make a conservative assumption for dependent nodes.
3412 return IncludePossibleEffects;
3413
3414 case DeclRefExprClass:
3415 case ObjCIvarRefExprClass:
3416 case PredefinedExprClass:
3417 case IntegerLiteralClass:
3418 case FixedPointLiteralClass:
3419 case FloatingLiteralClass:
3420 case ImaginaryLiteralClass:
3421 case StringLiteralClass:
3422 case CharacterLiteralClass:
3423 case OffsetOfExprClass:
3424 case ImplicitValueInitExprClass:
3425 case UnaryExprOrTypeTraitExprClass:
3426 case AddrLabelExprClass:
3427 case GNUNullExprClass:
3428 case ArrayInitIndexExprClass:
3429 case NoInitExprClass:
3430 case CXXBoolLiteralExprClass:
3431 case CXXNullPtrLiteralExprClass:
3432 case CXXThisExprClass:
3433 case CXXScalarValueInitExprClass:
3434 case TypeTraitExprClass:
3435 case ArrayTypeTraitExprClass:
3436 case ExpressionTraitExprClass:
3437 case CXXNoexceptExprClass:
3438 case SizeOfPackExprClass:
3439 case ObjCStringLiteralClass:
3440 case ObjCEncodeExprClass:
3441 case ObjCBoolLiteralExprClass:
3442 case ObjCAvailabilityCheckExprClass:
3443 case CXXUuidofExprClass:
3444 case OpaqueValueExprClass:
3445 case SourceLocExprClass:
3446 case ConceptSpecializationExprClass:
3447 case RequiresExprClass:
3448 case SYCLUniqueStableNameExprClass:
3449 // These never have a side-effect.
3450 return false;
3451
3452 case ConstantExprClass:
3453 // FIXME: Move this into the "return false;" block above.
3454 return cast<ConstantExpr>(this)->getSubExpr()->HasSideEffects(
3455 Ctx, IncludePossibleEffects);
3456
3457 case CallExprClass:
3458 case CXXOperatorCallExprClass:
3459 case CXXMemberCallExprClass:
3460 case CUDAKernelCallExprClass:
3461 case UserDefinedLiteralClass: {
3462 // We don't know a call definitely has side effects, except for calls
3463 // to pure/const functions that definitely don't.
3464 // If the call itself is considered side-effect free, check the operands.
3465 const Decl *FD = cast<CallExpr>(this)->getCalleeDecl();
3466 bool IsPure = FD && (FD->hasAttr<ConstAttr>() || FD->hasAttr<PureAttr>());
3467 if (IsPure || !IncludePossibleEffects)
3468 break;
3469 return true;
3470 }
3471
3472 case BlockExprClass:
3473 case CXXBindTemporaryExprClass:
3474 if (!IncludePossibleEffects)
3475 break;
3476 return true;
3477
3478 case MSPropertyRefExprClass:
3479 case MSPropertySubscriptExprClass:
3480 case CompoundAssignOperatorClass:
3481 case VAArgExprClass:
3482 case AtomicExprClass:
3483 case CXXThrowExprClass:
3484 case CXXNewExprClass:
3485 case CXXDeleteExprClass:
3486 case CoawaitExprClass:
3487 case DependentCoawaitExprClass:
3488 case CoyieldExprClass:
3489 // These always have a side-effect.
3490 return true;
3491
3492 case StmtExprClass: {
3493 // StmtExprs have a side-effect if any substatement does.
3494 SideEffectFinder Finder(Ctx, IncludePossibleEffects);
3495 Finder.Visit(cast<StmtExpr>(this)->getSubStmt());
3496 return Finder.hasSideEffects();
3497 }
3498
3499 case ExprWithCleanupsClass:
3500 if (IncludePossibleEffects)
3501 if (cast<ExprWithCleanups>(this)->cleanupsHaveSideEffects())
3502 return true;
3503 break;
3504
3505 case ParenExprClass:
3506 case ArraySubscriptExprClass:
3507 case MatrixSubscriptExprClass:
3508 case OMPArraySectionExprClass:
3509 case OMPArrayShapingExprClass:
3510 case OMPIteratorExprClass:
3511 case MemberExprClass:
3512 case ConditionalOperatorClass:
3513 case BinaryConditionalOperatorClass:
3514 case CompoundLiteralExprClass:
3515 case ExtVectorElementExprClass:
3516 case DesignatedInitExprClass:
3517 case DesignatedInitUpdateExprClass:
3518 case ArrayInitLoopExprClass:
3519 case ParenListExprClass:
3520 case CXXPseudoDestructorExprClass:
3521 case CXXRewrittenBinaryOperatorClass:
3522 case CXXStdInitializerListExprClass:
3523 case SubstNonTypeTemplateParmExprClass:
3524 case MaterializeTemporaryExprClass:
3525 case ShuffleVectorExprClass:
3526 case ConvertVectorExprClass:
3527 case AsTypeExprClass:
3528 // These have a side-effect if any subexpression does.
3529 break;
3530
3531 case UnaryOperatorClass:
3532 if (cast<UnaryOperator>(this)->isIncrementDecrementOp())
3533 return true;
3534 break;
3535
3536 case BinaryOperatorClass:
3537 if (cast<BinaryOperator>(this)->isAssignmentOp())
3538 return true;
3539 break;
3540
3541 case InitListExprClass:
3542 // FIXME: The children for an InitListExpr doesn't include the array filler.
3543 if (const Expr *E = cast<InitListExpr>(this)->getArrayFiller())
3544 if (E->HasSideEffects(Ctx, IncludePossibleEffects))
3545 return true;
3546 break;
3547
3548 case GenericSelectionExprClass:
3549 return cast<GenericSelectionExpr>(this)->getResultExpr()->
3550 HasSideEffects(Ctx, IncludePossibleEffects);
3551
3552 case ChooseExprClass:
3553 return cast<ChooseExpr>(this)->getChosenSubExpr()->HasSideEffects(
3554 Ctx, IncludePossibleEffects);
3555
3556 case CXXDefaultArgExprClass:
3557 return cast<CXXDefaultArgExpr>(this)->getExpr()->HasSideEffects(
3558 Ctx, IncludePossibleEffects);
3559
3560 case CXXDefaultInitExprClass: {
3561 const FieldDecl *FD = cast<CXXDefaultInitExpr>(this)->getField();
3562 if (const Expr *E = FD->getInClassInitializer())
3563 return E->HasSideEffects(Ctx, IncludePossibleEffects);
3564 // If we've not yet parsed the initializer, assume it has side-effects.
3565 return true;
3566 }
3567
3568 case CXXDynamicCastExprClass: {
3569 // A dynamic_cast expression has side-effects if it can throw.
3570 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(this);
3571 if (DCE->getTypeAsWritten()->isReferenceType() &&
3572 DCE->getCastKind() == CK_Dynamic)
3573 return true;
3574 }
3575 LLVM_FALLTHROUGH[[gnu::fallthrough]];
3576 case ImplicitCastExprClass:
3577 case CStyleCastExprClass:
3578 case CXXStaticCastExprClass:
3579 case CXXReinterpretCastExprClass:
3580 case CXXConstCastExprClass:
3581 case CXXAddrspaceCastExprClass:
3582 case CXXFunctionalCastExprClass:
3583 case BuiltinBitCastExprClass: {
3584 // While volatile reads are side-effecting in both C and C++, we treat them
3585 // as having possible (not definite) side-effects. This allows idiomatic
3586 // code to behave without warning, such as sizeof(*v) for a volatile-
3587 // qualified pointer.
3588 if (!IncludePossibleEffects)
3589 break;
3590
3591 const CastExpr *CE = cast<CastExpr>(this);
3592 if (CE->getCastKind() == CK_LValueToRValue &&
3593 CE->getSubExpr()->getType().isVolatileQualified())
3594 return true;
3595 break;
3596 }
3597
3598 case CXXTypeidExprClass:
3599 // typeid might throw if its subexpression is potentially-evaluated, so has
3600 // side-effects in that case whether or not its subexpression does.
3601 return cast<CXXTypeidExpr>(this)->isPotentiallyEvaluated();
3602
3603 case CXXConstructExprClass:
3604 case CXXTemporaryObjectExprClass: {
3605 const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
3606 if (!CE->getConstructor()->isTrivial() && IncludePossibleEffects)
3607 return true;
3608 // A trivial constructor does not add any side-effects of its own. Just look
3609 // at its arguments.
3610 break;
3611 }
3612
3613 case CXXInheritedCtorInitExprClass: {
3614 const auto *ICIE = cast<CXXInheritedCtorInitExpr>(this);
3615 if (!ICIE->getConstructor()->isTrivial() && IncludePossibleEffects)
3616 return true;
3617 break;
3618 }
3619
3620 case LambdaExprClass: {
3621 const LambdaExpr *LE = cast<LambdaExpr>(this);
3622 for (Expr *E : LE->capture_inits())
3623 if (E && E->HasSideEffects(Ctx, IncludePossibleEffects))
3624 return true;
3625 return false;
3626 }
3627
3628 case PseudoObjectExprClass: {
3629 // Only look for side-effects in the semantic form, and look past
3630 // OpaqueValueExpr bindings in that form.
3631 const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this);
3632 for (PseudoObjectExpr::const_semantics_iterator I = PO->semantics_begin(),
3633 E = PO->semantics_end();
3634 I != E; ++I) {
3635 const Expr *Subexpr = *I;
3636 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Subexpr))
3637 Subexpr = OVE->getSourceExpr();
3638 if (Subexpr->HasSideEffects(Ctx, IncludePossibleEffects))
3639 return true;
3640 }
3641 return false;
3642 }
3643
3644 case ObjCBoxedExprClass:
3645 case ObjCArrayLiteralClass:
3646 case ObjCDictionaryLiteralClass:
3647 case ObjCSelectorExprClass:
3648 case ObjCProtocolExprClass:
3649 case ObjCIsaExprClass:
3650 case ObjCIndirectCopyRestoreExprClass:
3651 case ObjCSubscriptRefExprClass:
3652 case ObjCBridgedCastExprClass:
3653 case ObjCMessageExprClass:
3654 case ObjCPropertyRefExprClass:
3655 // FIXME: Classify these cases better.
3656 if (IncludePossibleEffects)
3657 return true;
3658 break;
3659 }
3660
3661 // Recurse to children.
3662 for (const Stmt *SubStmt : children())
3663 if (SubStmt &&
3664 cast<Expr>(SubStmt)->HasSideEffects(Ctx, IncludePossibleEffects))
3665 return true;
3666
3667 return false;
3668}
3669
3670FPOptions Expr::getFPFeaturesInEffect(const LangOptions &LO) const {
3671 if (auto Call = dyn_cast<CallExpr>(this))
3672 return Call->getFPFeaturesInEffect(LO);
3673 if (auto UO = dyn_cast<UnaryOperator>(this))
3674 return UO->getFPFeaturesInEffect(LO);
3675 if (auto BO = dyn_cast<BinaryOperator>(this))
3676 return BO->getFPFeaturesInEffect(LO);
3677 if (auto Cast = dyn_cast<CastExpr>(this))
3678 return Cast->getFPFeaturesInEffect(LO);
3679 return FPOptions::defaultWithoutTrailingStorage(LO);
3680}
3681
3682namespace {
3683 /// Look for a call to a non-trivial function within an expression.
3684 class NonTrivialCallFinder : public ConstEvaluatedExprVisitor<NonTrivialCallFinder>
3685 {
3686 typedef ConstEvaluatedExprVisitor<NonTrivialCallFinder> Inherited;
3687
3688 bool NonTrivial;
3689
3690 public:
3691 explicit NonTrivialCallFinder(const ASTContext &Context)
3692 : Inherited(Context), NonTrivial(false) { }
3693
3694 bool hasNonTrivialCall() const { return NonTrivial; }
3695
3696 void VisitCallExpr(const CallExpr *E) {
3697 if (const CXXMethodDecl *Method
3698 = dyn_cast_or_null<const CXXMethodDecl>(E->getCalleeDecl())) {
3699 if (Method->isTrivial()) {
3700 // Recurse to children of the call.
3701 Inherited::VisitStmt(E);
3702 return;
3703 }
3704 }
3705
3706 NonTrivial = true;
3707 }
3708
3709 void VisitCXXConstructExpr(const CXXConstructExpr *E) {
3710 if (E->getConstructor()->isTrivial()) {
3711 // Recurse to children of the call.
3712 Inherited::VisitStmt(E);
3713 return;
3714 }
3715
3716 NonTrivial = true;
3717 }
3718
3719 void VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
3720 if (E->getTemporary()->getDestructor()->isTrivial()) {
3721 Inherited::VisitStmt(E);
3722 return;
3723 }
3724
3725 NonTrivial = true;
3726 }
3727 };
3728}
3729
3730bool Expr::hasNonTrivialCall(const ASTContext &Ctx) const {
3731 NonTrivialCallFinder Finder(Ctx);
3732 Finder.Visit(this);
3733 return Finder.hasNonTrivialCall();
3734}
3735
3736/// isNullPointerConstant - C99 6.3.2.3p3 - Return whether this is a null
3737/// pointer constant or not, as well as the specific kind of constant detected.
3738/// Null pointer constants can be integer constant expressions with the
3739/// value zero, casts of zero to void*, nullptr (C++0X), or __null
3740/// (a GNU extension).
3741Expr::NullPointerConstantKind
3742Expr::isNullPointerConstant(ASTContext &Ctx,
3743 NullPointerConstantValueDependence NPC) const {
3744 if (isValueDependent() &&
3745 (!Ctx.getLangOpts().CPlusPlus11 || Ctx.getLangOpts().MSVCCompat)) {
3746 // Error-dependent expr should never be a null pointer.
3747 if (containsErrors())
3748 return NPCK_NotNull;
3749 switch (NPC) {
3750 case NPC_NeverValueDependent:
3751 llvm_unreachable("Unexpected value dependent expression!")::llvm::llvm_unreachable_internal("Unexpected value dependent expression!"
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 3751)
;
3752 case NPC_ValueDependentIsNull:
3753 if (isTypeDependent() || getType()->isIntegralType(Ctx))
3754 return NPCK_ZeroExpression;
3755 else
3756 return NPCK_NotNull;
3757
3758 case NPC_ValueDependentIsNotNull:
3759 return NPCK_NotNull;
3760 }
3761 }
3762
3763 // Strip off a cast to void*, if it exists. Except in C++.
3764 if (const ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(this)) {
3765 if (!Ctx.getLangOpts().CPlusPlus) {
3766 // Check that it is a cast to void*.
3767 if (const PointerType *PT = CE->getType()->getAs<PointerType>()) {
3768 QualType Pointee = PT->getPointeeType();
3769 Qualifiers Qs = Pointee.getQualifiers();
3770 // Only (void*)0 or equivalent are treated as nullptr. If pointee type
3771 // has non-default address space it is not treated as nullptr.
3772 // (__generic void*)0 in OpenCL 2.0 should not be treated as nullptr
3773 // since it cannot be assigned to a pointer to constant address space.
3774 if ((Ctx.getLangOpts().OpenCLVersion >= 200 &&
3775 Pointee.getAddressSpace() == LangAS::opencl_generic) ||
3776 (Ctx.getLangOpts().OpenCL &&
3777 Ctx.getLangOpts().OpenCLVersion < 200 &&
3778 Pointee.getAddressSpace() == LangAS::opencl_private))
3779 Qs.removeAddressSpace();
3780
3781 if (Pointee->isVoidType() && Qs.empty() && // to void*
3782 CE->getSubExpr()->getType()->isIntegerType()) // from int
3783 return CE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
3784 }
3785 }
3786 } else if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(this)) {
3787 // Ignore the ImplicitCastExpr type entirely.
3788 return ICE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
3789 } else if (const ParenExpr *PE = dyn_cast<ParenExpr>(this)) {
3790 // Accept ((void*)0) as a null pointer constant, as many other
3791 // implementations do.
3792 return PE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
3793 } else if (const GenericSelectionExpr *GE =
3794 dyn_cast<GenericSelectionExpr>(this)) {
3795 if (GE->isResultDependent())
3796 return NPCK_NotNull;
3797 return GE->getResultExpr()->isNullPointerConstant(Ctx, NPC);
3798 } else if (const ChooseExpr *CE = dyn_cast<ChooseExpr>(this)) {
3799 if (CE->isConditionDependent())
3800 return NPCK_NotNull;
3801 return CE->getChosenSubExpr()->isNullPointerConstant(Ctx, NPC);
3802 } else if (const CXXDefaultArgExpr *DefaultArg
3803 = dyn_cast<CXXDefaultArgExpr>(this)) {
3804 // See through default argument expressions.
3805 return DefaultArg->getExpr()->isNullPointerConstant(Ctx, NPC);
3806 } else if (const CXXDefaultInitExpr *DefaultInit
3807 = dyn_cast<CXXDefaultInitExpr>(this)) {
3808 // See through default initializer expressions.
3809 return DefaultInit->getExpr()->isNullPointerConstant(Ctx, NPC);
3810 } else if (isa<GNUNullExpr>(this)) {
3811 // The GNU __null extension is always a null pointer constant.
3812 return NPCK_GNUNull;
3813 } else if (const MaterializeTemporaryExpr *M
3814 = dyn_cast<MaterializeTemporaryExpr>(this)) {
3815 return M->getSubExpr()->isNullPointerConstant(Ctx, NPC);
3816 } else if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(this)) {
3817 if (const Expr *Source = OVE->getSourceExpr())
3818 return Source->isNullPointerConstant(Ctx, NPC);
3819 }
3820
3821 // If the expression has no type information, it cannot be a null pointer
3822 // constant.
3823 if (getType().isNull())
3824 return NPCK_NotNull;
3825
3826 // C++11 nullptr_t is always a null pointer constant.
3827 if (getType()->isNullPtrType())
3828 return NPCK_CXX11_nullptr;
3829
3830 if (const RecordType *UT = getType()->getAsUnionType())
3831 if (!Ctx.getLangOpts().CPlusPlus11 &&
3832 UT && UT->getDecl()->hasAttr<TransparentUnionAttr>())
3833 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(this)){
3834 const Expr *InitExpr = CLE->getInitializer();
3835 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(InitExpr))
3836 return ILE->getInit(0)->isNullPointerConstant(Ctx, NPC);
3837 }
3838 // This expression must be an integer type.
3839 if (!getType()->isIntegerType() ||
3840 (Ctx.getLangOpts().CPlusPlus && getType()->isEnumeralType()))
3841 return NPCK_NotNull;
3842
3843 if (Ctx.getLangOpts().CPlusPlus11) {
3844 // C++11 [conv.ptr]p1: A null pointer constant is an integer literal with
3845 // value zero or a prvalue of type std::nullptr_t.
3846 // Microsoft mode permits C++98 rules reflecting MSVC behavior.
3847 const IntegerLiteral *Lit = dyn_cast<IntegerLiteral>(this);
3848 if (Lit && !Lit->getValue())
3849 return NPCK_ZeroLiteral;
3850 if (!Ctx.getLangOpts().MSVCCompat || !isCXX98IntegralConstantExpr(Ctx))
3851 return NPCK_NotNull;
3852 } else {
3853 // If we have an integer constant expression, we need to *evaluate* it and
3854 // test for the value 0.
3855 if (!isIntegerConstantExpr(Ctx))
3856 return NPCK_NotNull;
3857 }
3858
3859 if (EvaluateKnownConstInt(Ctx) != 0)
3860 return NPCK_NotNull;
3861
3862 if (isa<IntegerLiteral>(this))
3863 return NPCK_ZeroLiteral;
3864 return NPCK_ZeroExpression;
3865}
3866
3867/// If this expression is an l-value for an Objective C
3868/// property, find the underlying property reference expression.
3869const ObjCPropertyRefExpr *Expr::getObjCProperty() const {
3870 const Expr *E = this;
3871 while (true) {
3872 assert((E->getValueKind() == VK_LValue &&(static_cast <bool> ((E->getValueKind() == VK_LValue
&& E->getObjectKind() == OK_ObjCProperty) &&
"expression is not a property reference") ? void (0) : __assert_fail
("(E->getValueKind() == VK_LValue && E->getObjectKind() == OK_ObjCProperty) && \"expression is not a property reference\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 3874, __extension__ __PRETTY_FUNCTION__))
3873 E->getObjectKind() == OK_ObjCProperty) &&(static_cast <bool> ((E->getValueKind() == VK_LValue
&& E->getObjectKind() == OK_ObjCProperty) &&
"expression is not a property reference") ? void (0) : __assert_fail
("(E->getValueKind() == VK_LValue && E->getObjectKind() == OK_ObjCProperty) && \"expression is not a property reference\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 3874, __extension__ __PRETTY_FUNCTION__))
3874 "expression is not a property reference")(static_cast <bool> ((E->getValueKind() == VK_LValue
&& E->getObjectKind() == OK_ObjCProperty) &&
"expression is not a property reference") ? void (0) : __assert_fail
("(E->getValueKind() == VK_LValue && E->getObjectKind() == OK_ObjCProperty) && \"expression is not a property reference\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 3874, __extension__ __PRETTY_FUNCTION__))
;
3875 E = E->IgnoreParenCasts();
3876 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3877 if (BO->getOpcode() == BO_Comma) {
3878 E = BO->getRHS();
3879 continue;
3880 }
3881 }
3882
3883 break;
3884 }
3885
3886 return cast<ObjCPropertyRefExpr>(E);
3887}
3888
3889bool Expr::isObjCSelfExpr() const {
3890 const Expr *E = IgnoreParenImpCasts();
3891
3892 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
3893 if (!DRE)
3894 return false;
3895
3896 const ImplicitParamDecl *Param = dyn_cast<ImplicitParamDecl>(DRE->getDecl());
3897 if (!Param)
3898 return false;
3899
3900 const ObjCMethodDecl *M = dyn_cast<ObjCMethodDecl>(Param->getDeclContext());
3901 if (!M)
3902 return false;
3903
3904 return M->getSelfDecl() == Param;
3905}
3906
3907FieldDecl *Expr::getSourceBitField() {
3908 Expr *E = this->IgnoreParens();
3909
3910 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3911 if (ICE->getCastKind() == CK_LValueToRValue ||
3912 (ICE->getValueKind() != VK_PRValue && ICE->getCastKind() == CK_NoOp))
3913 E = ICE->getSubExpr()->IgnoreParens();
3914 else
3915 break;
3916 }
3917
3918 if (MemberExpr *MemRef = dyn_cast<MemberExpr>(E))
3919 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemRef->getMemberDecl()))
3920 if (Field->isBitField())
3921 return Field;
3922
3923 if (ObjCIvarRefExpr *IvarRef = dyn_cast<ObjCIvarRefExpr>(E)) {
3924 FieldDecl *Ivar = IvarRef->getDecl();
3925 if (Ivar->isBitField())
3926 return Ivar;
3927 }
3928
3929 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E)) {
3930 if (FieldDecl *Field = dyn_cast<FieldDecl>(DeclRef->getDecl()))
3931 if (Field->isBitField())
3932 return Field;
3933
3934 if (BindingDecl *BD = dyn_cast<BindingDecl>(DeclRef->getDecl()))
3935 if (Expr *E = BD->getBinding())
3936 return E->getSourceBitField();
3937 }
3938
3939 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(E)) {
3940 if (BinOp->isAssignmentOp() && BinOp->getLHS())
3941 return BinOp->getLHS()->getSourceBitField();
3942
3943 if (BinOp->getOpcode() == BO_Comma && BinOp->getRHS())
3944 return BinOp->getRHS()->getSourceBitField();
3945 }
3946
3947 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E))
3948 if (UnOp->isPrefix() && UnOp->isIncrementDecrementOp())
3949 return UnOp->getSubExpr()->getSourceBitField();
3950
3951 return nullptr;
3952}
3953
3954bool Expr::refersToVectorElement() const {
3955 // FIXME: Why do we not just look at the ObjectKind here?
3956 const Expr *E = this->IgnoreParens();
3957
3958 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3959 if (ICE->getValueKind() != VK_PRValue && ICE->getCastKind() == CK_NoOp)
3960 E = ICE->getSubExpr()->IgnoreParens();
3961 else
3962 break;
3963 }
3964
3965 if (const ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(E))
3966 return ASE->getBase()->getType()->isVectorType();
3967
3968 if (isa<ExtVectorElementExpr>(E))
3969 return true;
3970
3971 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3972 if (auto *BD = dyn_cast<BindingDecl>(DRE->getDecl()))
3973 if (auto *E = BD->getBinding())
3974 return E->refersToVectorElement();
3975
3976 return false;
3977}
3978
3979bool Expr::refersToGlobalRegisterVar() const {
3980 const Expr *E = this->IgnoreParenImpCasts();
3981
3982 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
3983 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
3984 if (VD->getStorageClass() == SC_Register &&
3985 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
3986 return true;
3987
3988 return false;
3989}
3990
3991bool Expr::isSameComparisonOperand(const Expr* E1, const Expr* E2) {
3992 E1 = E1->IgnoreParens();
3993 E2 = E2->IgnoreParens();
3994
3995 if (E1->getStmtClass() != E2->getStmtClass())
3996 return false;
3997
3998 switch (E1->getStmtClass()) {
3999 default:
4000 return false;
4001 case CXXThisExprClass:
4002 return true;
4003 case DeclRefExprClass: {
4004 // DeclRefExpr without an ImplicitCastExpr can happen for integral
4005 // template parameters.
4006 const auto *DRE1 = cast<DeclRefExpr>(E1);
4007 const auto *DRE2 = cast<DeclRefExpr>(E2);
4008 return DRE1->isPRValue() && DRE2->isPRValue() &&
4009 DRE1->getDecl() == DRE2->getDecl();
4010 }
4011 case ImplicitCastExprClass: {
4012 // Peel off implicit casts.
4013 while (true) {
4014 const auto *ICE1 = dyn_cast<ImplicitCastExpr>(E1);
4015 const auto *ICE2 = dyn_cast<ImplicitCastExpr>(E2);
4016 if (!ICE1 || !ICE2)
4017 return false;
4018 if (ICE1->getCastKind() != ICE2->getCastKind())
4019 return false;
4020 E1 = ICE1->getSubExpr()->IgnoreParens();
4021 E2 = ICE2->getSubExpr()->IgnoreParens();
4022 // The final cast must be one of these types.
4023 if (ICE1->getCastKind() == CK_LValueToRValue ||
4024 ICE1->getCastKind() == CK_ArrayToPointerDecay ||
4025 ICE1->getCastKind() == CK_FunctionToPointerDecay) {
4026 break;
4027 }
4028 }
4029
4030 const auto *DRE1 = dyn_cast<DeclRefExpr>(E1);
4031 const auto *DRE2 = dyn_cast<DeclRefExpr>(E2);
4032 if (DRE1 && DRE2)
4033 return declaresSameEntity(DRE1->getDecl(), DRE2->getDecl());
4034
4035 const auto *Ivar1 = dyn_cast<ObjCIvarRefExpr>(E1);
4036 const auto *Ivar2 = dyn_cast<ObjCIvarRefExpr>(E2);
4037 if (Ivar1 && Ivar2) {
4038 return Ivar1->isFreeIvar() && Ivar2->isFreeIvar() &&
4039 declaresSameEntity(Ivar1->getDecl(), Ivar2->getDecl());
4040 }
4041
4042 const auto *Array1 = dyn_cast<ArraySubscriptExpr>(E1);
4043 const auto *Array2 = dyn_cast<ArraySubscriptExpr>(E2);
4044 if (Array1 && Array2) {
4045 if (!isSameComparisonOperand(Array1->getBase(), Array2->getBase()))
4046 return false;
4047
4048 auto Idx1 = Array1->getIdx();
4049 auto Idx2 = Array2->getIdx();
4050 const auto Integer1 = dyn_cast<IntegerLiteral>(Idx1);
4051 const auto Integer2 = dyn_cast<IntegerLiteral>(Idx2);
4052 if (Integer1 && Integer2) {
4053 if (!llvm::APInt::isSameValue(Integer1->getValue(),
4054 Integer2->getValue()))
4055 return false;
4056 } else {
4057 if (!isSameComparisonOperand(Idx1, Idx2))
4058 return false;
4059 }
4060
4061 return true;
4062 }
4063
4064 // Walk the MemberExpr chain.
4065 while (isa<MemberExpr>(E1) && isa<MemberExpr>(E2)) {
4066 const auto *ME1 = cast<MemberExpr>(E1);
4067 const auto *ME2 = cast<MemberExpr>(E2);
4068 if (!declaresSameEntity(ME1->getMemberDecl(), ME2->getMemberDecl()))
4069 return false;
4070 if (const auto *D = dyn_cast<VarDecl>(ME1->getMemberDecl()))
4071 if (D->isStaticDataMember())
4072 return true;
4073 E1 = ME1->getBase()->IgnoreParenImpCasts();
4074 E2 = ME2->getBase()->IgnoreParenImpCasts();
4075 }
4076
4077 if (isa<CXXThisExpr>(E1) && isa<CXXThisExpr>(E2))
4078 return true;
4079
4080 // A static member variable can end the MemberExpr chain with either
4081 // a MemberExpr or a DeclRefExpr.
4082 auto getAnyDecl = [](const Expr *E) -> const ValueDecl * {
4083 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
4084 return DRE->getDecl();
4085 if (const auto *ME = dyn_cast<MemberExpr>(E))
4086 return ME->getMemberDecl();
4087 return nullptr;
4088 };
4089
4090 const ValueDecl *VD1 = getAnyDecl(E1);
4091 const ValueDecl *VD2 = getAnyDecl(E2);
4092 return declaresSameEntity(VD1, VD2);
4093 }
4094 }
4095}
4096
4097/// isArrow - Return true if the base expression is a pointer to vector,
4098/// return false if the base expression is a vector.
4099bool ExtVectorElementExpr::isArrow() const {
4100 return getBase()->getType()->isPointerType();
4101}
4102
4103unsigned ExtVectorElementExpr::getNumElements() const {
4104 if (const VectorType *VT = getType()->getAs<VectorType>())
4105 return VT->getNumElements();
4106 return 1;
4107}
4108
4109/// containsDuplicateElements - Return true if any element access is repeated.
4110bool ExtVectorElementExpr::containsDuplicateElements() const {
4111 // FIXME: Refactor this code to an accessor on the AST node which returns the
4112 // "type" of component access, and share with code below and in Sema.
4113 StringRef Comp = Accessor->getName();
4114
4115 // Halving swizzles do not contain duplicate elements.
4116 if (Comp == "hi" || Comp == "lo" || Comp == "even" || Comp == "odd")
4117 return false;
4118
4119 // Advance past s-char prefix on hex swizzles.
4120 if (Comp[0] == 's' || Comp[0] == 'S')
4121 Comp = Comp.substr(1);
4122
4123 for (unsigned i = 0, e = Comp.size(); i != e; ++i)
4124 if (Comp.substr(i + 1).find(Comp[i]) != StringRef::npos)
4125 return true;
4126
4127 return false;
4128}
4129
4130/// getEncodedElementAccess - We encode the fields as a llvm ConstantArray.
4131void ExtVectorElementExpr::getEncodedElementAccess(
4132 SmallVectorImpl<uint32_t> &Elts) const {
4133 StringRef Comp = Accessor->getName();
4134 bool isNumericAccessor = false;
4135 if (Comp[0] == 's' || Comp[0] == 'S') {
4136 Comp = Comp.substr(1);
4137 isNumericAccessor = true;
4138 }
4139
4140 bool isHi = Comp == "hi";
4141 bool isLo = Comp == "lo";
4142 bool isEven = Comp == "even";
4143 bool isOdd = Comp == "odd";
4144
4145 for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
4146 uint64_t Index;
4147
4148 if (isHi)
4149 Index = e + i;
4150 else if (isLo)
4151 Index = i;
4152 else if (isEven)
4153 Index = 2 * i;
4154 else if (isOdd)
4155 Index = 2 * i + 1;
4156 else
4157 Index = ExtVectorType::getAccessorIdx(Comp[i], isNumericAccessor);
4158
4159 Elts.push_back(Index);
4160 }
4161}
4162
4163ShuffleVectorExpr::ShuffleVectorExpr(const ASTContext &C, ArrayRef<Expr *> args,
4164 QualType Type, SourceLocation BLoc,
4165 SourceLocation RP)
4166 : Expr(ShuffleVectorExprClass, Type, VK_PRValue, OK_Ordinary),
4167 BuiltinLoc(BLoc), RParenLoc(RP), NumExprs(args.size()) {
4168 SubExprs = new (C) Stmt*[args.size()];
4169 for (unsigned i = 0; i != args.size(); i++)
4170 SubExprs[i] = args[i];
4171
4172 setDependence(computeDependence(this));
4173}
4174
4175void ShuffleVectorExpr::setExprs(const ASTContext &C, ArrayRef<Expr *> Exprs) {
4176 if (SubExprs) C.Deallocate(SubExprs);
4177
4178 this->NumExprs = Exprs.size();
4179 SubExprs = new (C) Stmt*[NumExprs];
4180 memcpy(SubExprs, Exprs.data(), sizeof(Expr *) * Exprs.size());
4181}
4182
4183GenericSelectionExpr::GenericSelectionExpr(
4184 const ASTContext &, SourceLocation GenericLoc, Expr *ControllingExpr,
4185 ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
4186 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4187 bool ContainsUnexpandedParameterPack, unsigned ResultIndex)
4188 : Expr(GenericSelectionExprClass, AssocExprs[ResultIndex]->getType(),
4189 AssocExprs[ResultIndex]->getValueKind(),
4190 AssocExprs[ResultIndex]->getObjectKind()),
4191 NumAssocs(AssocExprs.size()), ResultIndex(ResultIndex),
4192 DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
4193 assert(AssocTypes.size() == AssocExprs.size() &&(static_cast <bool> (AssocTypes.size() == AssocExprs.size
() && "Must have the same number of association expressions"
" and TypeSourceInfo!") ? void (0) : __assert_fail ("AssocTypes.size() == AssocExprs.size() && \"Must have the same number of association expressions\" \" and TypeSourceInfo!\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 4195, __extension__ __PRETTY_FUNCTION__))
4194 "Must have the same number of association expressions"(static_cast <bool> (AssocTypes.size() == AssocExprs.size
() && "Must have the same number of association expressions"
" and TypeSourceInfo!") ? void (0) : __assert_fail ("AssocTypes.size() == AssocExprs.size() && \"Must have the same number of association expressions\" \" and TypeSourceInfo!\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 4195, __extension__ __PRETTY_FUNCTION__))
4195 " and TypeSourceInfo!")(static_cast <bool> (AssocTypes.size() == AssocExprs.size
() && "Must have the same number of association expressions"
" and TypeSourceInfo!") ? void (0) : __assert_fail ("AssocTypes.size() == AssocExprs.size() && \"Must have the same number of association expressions\" \" and TypeSourceInfo!\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 4195, __extension__ __PRETTY_FUNCTION__))
;
4196 assert(ResultIndex < NumAssocs && "ResultIndex is out-of-bounds!")(static_cast <bool> (ResultIndex < NumAssocs &&
"ResultIndex is out-of-bounds!") ? void (0) : __assert_fail (
"ResultIndex < NumAssocs && \"ResultIndex is out-of-bounds!\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 4196, __extension__ __PRETTY_FUNCTION__))
;
4197
4198 GenericSelectionExprBits.GenericLoc = GenericLoc;
4199 getTrailingObjects<Stmt *>()[ControllingIndex] = ControllingExpr;
4200 std::copy(AssocExprs.begin(), AssocExprs.end(),
4201 getTrailingObjects<Stmt *>() + AssocExprStartIndex);
4202 std::copy(AssocTypes.begin(), AssocTypes.end(),
4203 getTrailingObjects<TypeSourceInfo *>());
4204
4205 setDependence(computeDependence(this, ContainsUnexpandedParameterPack));
4206}
4207
4208GenericSelectionExpr::GenericSelectionExpr(
4209 const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,
4210 ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
4211 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4212 bool ContainsUnexpandedParameterPack)
4213 : Expr(GenericSelectionExprClass, Context.DependentTy, VK_PRValue,
4214 OK_Ordinary),
4215 NumAssocs(AssocExprs.size()), ResultIndex(ResultDependentIndex),
4216 DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
4217 assert(AssocTypes.size() == AssocExprs.size() &&(static_cast <bool> (AssocTypes.size() == AssocExprs.size
() && "Must have the same number of association expressions"
" and TypeSourceInfo!") ? void (0) : __assert_fail ("AssocTypes.size() == AssocExprs.size() && \"Must have the same number of association expressions\" \" and TypeSourceInfo!\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 4219, __extension__ __PRETTY_FUNCTION__))
4218 "Must have the same number of association expressions"(static_cast <bool> (AssocTypes.size() == AssocExprs.size
() && "Must have the same number of association expressions"
" and TypeSourceInfo!") ? void (0) : __assert_fail ("AssocTypes.size() == AssocExprs.size() && \"Must have the same number of association expressions\" \" and TypeSourceInfo!\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 4219, __extension__ __PRETTY_FUNCTION__))
4219 " and TypeSourceInfo!")(static_cast <bool> (AssocTypes.size() == AssocExprs.size
() && "Must have the same number of association expressions"
" and TypeSourceInfo!") ? void (0) : __assert_fail ("AssocTypes.size() == AssocExprs.size() && \"Must have the same number of association expressions\" \" and TypeSourceInfo!\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 4219, __extension__ __PRETTY_FUNCTION__))
;
4220
4221 GenericSelectionExprBits.GenericLoc = GenericLoc;
4222 getTrailingObjects<Stmt *>()[ControllingIndex] = ControllingExpr;
4223 std::copy(AssocExprs.begin(), AssocExprs.end(),
4224 getTrailingObjects<Stmt *>() + AssocExprStartIndex);
4225 std::copy(AssocTypes.begin(), AssocTypes.end(),
4226 getTrailingObjects<TypeSourceInfo *>());
4227
4228 setDependence(computeDependence(this, ContainsUnexpandedParameterPack));
4229}
4230
4231GenericSelectionExpr::GenericSelectionExpr(EmptyShell Empty, unsigned NumAssocs)
4232 : Expr(GenericSelectionExprClass, Empty), NumAssocs(NumAssocs) {}
4233
4234GenericSelectionExpr *GenericSelectionExpr::Create(
4235 const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,
4236 ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
4237 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4238 bool ContainsUnexpandedParameterPack, unsigned ResultIndex) {
4239 unsigned NumAssocs = AssocExprs.size();
4240 void *Mem = Context.Allocate(
4241 totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
4242 alignof(GenericSelectionExpr));
4243 return new (Mem) GenericSelectionExpr(
4244 Context, GenericLoc, ControllingExpr, AssocTypes, AssocExprs, DefaultLoc,
4245 RParenLoc, ContainsUnexpandedParameterPack, ResultIndex);
4246}
4247
4248GenericSelectionExpr *GenericSelectionExpr::Create(
4249 const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,
4250 ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
4251 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4252 bool ContainsUnexpandedParameterPack) {
4253 unsigned NumAssocs = AssocExprs.size();
4254 void *Mem = Context.Allocate(
4255 totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
4256 alignof(GenericSelectionExpr));
4257 return new (Mem) GenericSelectionExpr(
4258 Context, GenericLoc, ControllingExpr, AssocTypes, AssocExprs, DefaultLoc,
4259 RParenLoc, ContainsUnexpandedParameterPack);
4260}
4261
4262GenericSelectionExpr *
4263GenericSelectionExpr::CreateEmpty(const ASTContext &Context,
4264 unsigned NumAssocs) {
4265 void *Mem = Context.Allocate(
4266 totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
4267 alignof(GenericSelectionExpr));
4268 return new (Mem) GenericSelectionExpr(EmptyShell(), NumAssocs);
4269}
4270
4271//===----------------------------------------------------------------------===//
4272// DesignatedInitExpr
4273//===----------------------------------------------------------------------===//
4274
4275IdentifierInfo *DesignatedInitExpr::Designator::getFieldName() const {
4276 assert(Kind == FieldDesignator && "Only valid on a field designator")(static_cast <bool> (Kind == FieldDesignator &&
"Only valid on a field designator") ? void (0) : __assert_fail
("Kind == FieldDesignator && \"Only valid on a field designator\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 4276, __extension__ __PRETTY_FUNCTION__))
;
4277 if (Field.NameOrField & 0x01)
4278 return reinterpret_cast<IdentifierInfo *>(Field.NameOrField & ~0x01);
4279 return getField()->getIdentifier();
4280}
4281
4282DesignatedInitExpr::DesignatedInitExpr(const ASTContext &C, QualType Ty,
4283 llvm::ArrayRef<Designator> Designators,
4284 SourceLocation EqualOrColonLoc,
4285 bool GNUSyntax,
4286 ArrayRef<Expr *> IndexExprs, Expr *Init)
4287 : Expr(DesignatedInitExprClass, Ty, Init->getValueKind(),
4288 Init->getObjectKind()),
4289 EqualOrColonLoc(EqualOrColonLoc), GNUSyntax(GNUSyntax),
4290 NumDesignators(Designators.size()), NumSubExprs(IndexExprs.size() + 1) {
4291 this->Designators = new (C) Designator[NumDesignators];
4292
4293 // Record the initializer itself.
4294 child_iterator Child = child_begin();
4295 *Child++ = Init;
4296
4297 // Copy the designators and their subexpressions, computing
4298 // value-dependence along the way.
4299 unsigned IndexIdx = 0;
4300 for (unsigned I = 0; I != NumDesignators; ++I) {
4301 this->Designators[I] = Designators[I];
4302 if (this->Designators[I].isArrayDesignator()) {
4303 // Copy the index expressions into permanent storage.
4304 *Child++ = IndexExprs[IndexIdx++];
4305 } else if (this->Designators[I].isArrayRangeDesignator()) {
4306 // Copy the start/end expressions into permanent storage.
4307 *Child++ = IndexExprs[IndexIdx++];
4308 *Child++ = IndexExprs[IndexIdx++];
4309 }
4310 }
4311
4312 assert(IndexIdx == IndexExprs.size() && "Wrong number of index expressions")(static_cast <bool> (IndexIdx == IndexExprs.size() &&
"Wrong number of index expressions") ? void (0) : __assert_fail
("IndexIdx == IndexExprs.size() && \"Wrong number of index expressions\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 4312, __extension__ __PRETTY_FUNCTION__))
;
4313 setDependence(computeDependence(this));
4314}
4315
4316DesignatedInitExpr *
4317DesignatedInitExpr::Create(const ASTContext &C,
4318 llvm::ArrayRef<Designator> Designators,
4319 ArrayRef<Expr*> IndexExprs,
4320 SourceLocation ColonOrEqualLoc,
4321 bool UsesColonSyntax, Expr *Init) {
4322 void *Mem = C.Allocate(totalSizeToAlloc<Stmt *>(IndexExprs.size() + 1),
4323 alignof(DesignatedInitExpr));
4324 return new (Mem) DesignatedInitExpr(C, C.VoidTy, Designators,
4325 ColonOrEqualLoc, UsesColonSyntax,
4326 IndexExprs, Init);
4327}
4328
4329DesignatedInitExpr *DesignatedInitExpr::CreateEmpty(const ASTContext &C,
4330 unsigned NumIndexExprs) {
4331 void *Mem = C.Allocate(totalSizeToAlloc<Stmt *>(NumIndexExprs + 1),
4332 alignof(DesignatedInitExpr));
4333 return new (Mem) DesignatedInitExpr(NumIndexExprs + 1);
4334}
4335
4336void DesignatedInitExpr::setDesignators(const ASTContext &C,
4337 const Designator *Desigs,
4338 unsigned NumDesigs) {
4339 Designators = new (C) Designator[NumDesigs];
4340 NumDesignators = NumDesigs;
4341 for (unsigned I = 0; I != NumDesigs; ++I)
4342 Designators[I] = Desigs[I];
4343}
4344
4345SourceRange DesignatedInitExpr::getDesignatorsSourceRange() const {
4346 DesignatedInitExpr *DIE = const_cast<DesignatedInitExpr*>(this);
4347 if (size() == 1)
4348 return DIE->getDesignator(0)->getSourceRange();
4349 return SourceRange(DIE->getDesignator(0)->getBeginLoc(),
4350 DIE->getDesignator(size() - 1)->getEndLoc());
4351}
4352
4353SourceLocation DesignatedInitExpr::getBeginLoc() const {
4354 SourceLocation StartLoc;
4355 auto *DIE = const_cast<DesignatedInitExpr *>(this);
4356 Designator &First = *DIE->getDesignator(0);
4357 if (First.isFieldDesignator())
4358 StartLoc = GNUSyntax ? First.Field.FieldLoc : First.Field.DotLoc;
4359 else
4360 StartLoc = First.ArrayOrRange.LBracketLoc;
4361 return StartLoc;
4362}
4363
4364SourceLocation DesignatedInitExpr::getEndLoc() const {
4365 return getInit()->getEndLoc();
4366}
4367
4368Expr *DesignatedInitExpr::getArrayIndex(const Designator& D) const {
4369 assert(D.Kind == Designator::ArrayDesignator && "Requires array designator")(static_cast <bool> (D.Kind == Designator::ArrayDesignator
&& "Requires array designator") ? void (0) : __assert_fail
("D.Kind == Designator::ArrayDesignator && \"Requires array designator\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 4369, __extension__ __PRETTY_FUNCTION__))
;
4370 return getSubExpr(D.ArrayOrRange.Index + 1);
4371}
4372
4373Expr *DesignatedInitExpr::getArrayRangeStart(const Designator &D) const {
4374 assert(D.Kind == Designator::ArrayRangeDesignator &&(static_cast <bool> (D.Kind == Designator::ArrayRangeDesignator
&& "Requires array range designator") ? void (0) : __assert_fail
("D.Kind == Designator::ArrayRangeDesignator && \"Requires array range designator\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 4375, __extension__ __PRETTY_FUNCTION__))
4375 "Requires array range designator")(static_cast <bool> (D.Kind == Designator::ArrayRangeDesignator
&& "Requires array range designator") ? void (0) : __assert_fail
("D.Kind == Designator::ArrayRangeDesignator && \"Requires array range designator\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 4375, __extension__ __PRETTY_FUNCTION__))
;
4376 return getSubExpr(D.ArrayOrRange.Index + 1);
4377}
4378
4379Expr *DesignatedInitExpr::getArrayRangeEnd(const Designator &D) const {
4380 assert(D.Kind == Designator::ArrayRangeDesignator &&(static_cast <bool> (D.Kind == Designator::ArrayRangeDesignator
&& "Requires array range designator") ? void (0) : __assert_fail
("D.Kind == Designator::ArrayRangeDesignator && \"Requires array range designator\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 4381, __extension__ __PRETTY_FUNCTION__))
4381 "Requires array range designator")(static_cast <bool> (D.Kind == Designator::ArrayRangeDesignator
&& "Requires array range designator") ? void (0) : __assert_fail
("D.Kind == Designator::ArrayRangeDesignator && \"Requires array range designator\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 4381, __extension__ __PRETTY_FUNCTION__))
;
4382 return getSubExpr(D.ArrayOrRange.Index + 2);
4383}
4384
4385/// Replaces the designator at index @p Idx with the series
4386/// of designators in [First, Last).
4387void DesignatedInitExpr::ExpandDesignator(const ASTContext &C, unsigned Idx,
4388 const Designator *First,
4389 const Designator *Last) {
4390 unsigned NumNewDesignators = Last - First;
4391 if (NumNewDesignators == 0) {
4392 std::copy_backward(Designators + Idx + 1,
4393 Designators + NumDesignators,
4394 Designators + Idx);
4395 --NumNewDesignators;
4396 return;
4397 }
4398 if (NumNewDesignators == 1) {
4399 Designators[Idx] = *First;
4400 return;
4401 }
4402
4403 Designator *NewDesignators
4404 = new (C) Designator[NumDesignators - 1 + NumNewDesignators];
4405 std::copy(Designators, Designators + Idx, NewDesignators);
4406 std::copy(First, Last, NewDesignators + Idx);
4407 std::copy(Designators + Idx + 1, Designators + NumDesignators,
4408 NewDesignators + Idx + NumNewDesignators);
4409 Designators = NewDesignators;
4410 NumDesignators = NumDesignators - 1 + NumNewDesignators;
4411}
4412
4413DesignatedInitUpdateExpr::DesignatedInitUpdateExpr(const ASTContext &C,
4414 SourceLocation lBraceLoc,
4415 Expr *baseExpr,
4416 SourceLocation rBraceLoc)
4417 : Expr(DesignatedInitUpdateExprClass, baseExpr->getType(), VK_PRValue,
4418 OK_Ordinary) {
4419 BaseAndUpdaterExprs[0] = baseExpr;
4420
4421 InitListExpr *ILE = new (C) InitListExpr(C, lBraceLoc, None, rBraceLoc);
4422 ILE->setType(baseExpr->getType());
4423 BaseAndUpdaterExprs[1] = ILE;
4424
4425 // FIXME: this is wrong, set it correctly.
4426 setDependence(ExprDependence::None);
4427}
4428
4429SourceLocation DesignatedInitUpdateExpr::getBeginLoc() const {
4430 return getBase()->getBeginLoc();
4431}
4432
4433SourceLocation DesignatedInitUpdateExpr::getEndLoc() const {
4434 return getBase()->getEndLoc();
4435}
4436
4437ParenListExpr::ParenListExpr(SourceLocation LParenLoc, ArrayRef<Expr *> Exprs,
4438 SourceLocation RParenLoc)
4439 : Expr(ParenListExprClass, QualType(), VK_PRValue, OK_Ordinary),
4440 LParenLoc(LParenLoc), RParenLoc(RParenLoc) {
4441 ParenListExprBits.NumExprs = Exprs.size();
4442
4443 for (unsigned I = 0, N = Exprs.size(); I != N; ++I)
4444 getTrailingObjects<Stmt *>()[I] = Exprs[I];
4445 setDependence(computeDependence(this));
4446}
4447
4448ParenListExpr::ParenListExpr(EmptyShell Empty, unsigned NumExprs)
4449 : Expr(ParenListExprClass, Empty) {
4450 ParenListExprBits.NumExprs = NumExprs;
4451}
4452
4453ParenListExpr *ParenListExpr::Create(const ASTContext &Ctx,
4454 SourceLocation LParenLoc,
4455 ArrayRef<Expr *> Exprs,
4456 SourceLocation RParenLoc) {
4457 void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *>(Exprs.size()),
4458 alignof(ParenListExpr));
4459 return new (Mem) ParenListExpr(LParenLoc, Exprs, RParenLoc);
4460}
4461
4462ParenListExpr *ParenListExpr::CreateEmpty(const ASTContext &Ctx,
4463 unsigned NumExprs) {
4464 void *Mem =
4465 Ctx.Allocate(totalSizeToAlloc<Stmt *>(NumExprs), alignof(ParenListExpr));
4466 return new (Mem) ParenListExpr(EmptyShell(), NumExprs);
4467}
4468
4469BinaryOperator::BinaryOperator(const ASTContext &Ctx, Expr *lhs, Expr *rhs,
4470 Opcode opc, QualType ResTy, ExprValueKind VK,
4471 ExprObjectKind OK, SourceLocation opLoc,
4472 FPOptionsOverride FPFeatures)
4473 : Expr(BinaryOperatorClass, ResTy, VK, OK) {
4474 BinaryOperatorBits.Opc = opc;
4475 assert(!isCompoundAssignmentOp() &&(static_cast <bool> (!isCompoundAssignmentOp() &&
"Use CompoundAssignOperator for compound assignments") ? void
(0) : __assert_fail ("!isCompoundAssignmentOp() && \"Use CompoundAssignOperator for compound assignments\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 4476, __extension__ __PRETTY_FUNCTION__))
4476 "Use CompoundAssignOperator for compound assignments")(static_cast <bool> (!isCompoundAssignmentOp() &&
"Use CompoundAssignOperator for compound assignments") ? void
(0) : __assert_fail ("!isCompoundAssignmentOp() && \"Use CompoundAssignOperator for compound assignments\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 4476, __extension__ __PRETTY_FUNCTION__))
;
4477 BinaryOperatorBits.OpLoc = opLoc;
4478 SubExprs[LHS] = lhs;
4479 SubExprs[RHS] = rhs;
4480 BinaryOperatorBits.HasFPFeatures = FPFeatures.requiresTrailingStorage();
4481 if (hasStoredFPFeatures())
4482 setStoredFPFeatures(FPFeatures);
4483 setDependence(computeDependence(this));
4484}
4485
4486BinaryOperator::BinaryOperator(const ASTContext &Ctx, Expr *lhs, Expr *rhs,
4487 Opcode opc, QualType ResTy, ExprValueKind VK,
4488 ExprObjectKind OK, SourceLocation opLoc,
4489 FPOptionsOverride FPFeatures, bool dead2)
4490 : Expr(CompoundAssignOperatorClass, ResTy, VK, OK) {
4491 BinaryOperatorBits.Opc = opc;
4492 assert(isCompoundAssignmentOp() &&(static_cast <bool> (isCompoundAssignmentOp() &&
"Use CompoundAssignOperator for compound assignments") ? void
(0) : __assert_fail ("isCompoundAssignmentOp() && \"Use CompoundAssignOperator for compound assignments\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 4493, __extension__ __PRETTY_FUNCTION__))
4493 "Use CompoundAssignOperator for compound assignments")(static_cast <bool> (isCompoundAssignmentOp() &&
"Use CompoundAssignOperator for compound assignments") ? void
(0) : __assert_fail ("isCompoundAssignmentOp() && \"Use CompoundAssignOperator for compound assignments\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 4493, __extension__ __PRETTY_FUNCTION__))
;
4494 BinaryOperatorBits.OpLoc = opLoc;
4495 SubExprs[LHS] = lhs;
4496 SubExprs[RHS] = rhs;
4497 BinaryOperatorBits.HasFPFeatures = FPFeatures.requiresTrailingStorage();
4498 if (hasStoredFPFeatures())
4499 setStoredFPFeatures(FPFeatures);
4500 setDependence(computeDependence(this));
4501}
4502
4503BinaryOperator *BinaryOperator::CreateEmpty(const ASTContext &C,
4504 bool HasFPFeatures) {
4505 unsigned Extra = sizeOfTrailingObjects(HasFPFeatures);
4506 void *Mem =
4507 C.Allocate(sizeof(BinaryOperator) + Extra, alignof(BinaryOperator));
4508 return new (Mem) BinaryOperator(EmptyShell());
4509}
4510
4511BinaryOperator *BinaryOperator::Create(const ASTContext &C, Expr *lhs,
4512 Expr *rhs, Opcode opc, QualType ResTy,
4513 ExprValueKind VK, ExprObjectKind OK,
4514 SourceLocation opLoc,
4515 FPOptionsOverride FPFeatures) {
4516 bool HasFPFeatures = FPFeatures.requiresTrailingStorage();
4517 unsigned Extra = sizeOfTrailingObjects(HasFPFeatures);
4518 void *Mem =
4519 C.Allocate(sizeof(BinaryOperator) + Extra, alignof(BinaryOperator));
4520 return new (Mem)
4521 BinaryOperator(C, lhs, rhs, opc, ResTy, VK, OK, opLoc, FPFeatures);
4522}
4523
4524CompoundAssignOperator *
4525CompoundAssignOperator::CreateEmpty(const ASTContext &C, bool HasFPFeatures) {
4526 unsigned Extra = sizeOfTrailingObjects(HasFPFeatures);
4527 void *Mem = C.Allocate(sizeof(CompoundAssignOperator) + Extra,
4528 alignof(CompoundAssignOperator));
4529 return new (Mem) CompoundAssignOperator(C, EmptyShell(), HasFPFeatures);
4530}
4531
4532CompoundAssignOperator *
4533CompoundAssignOperator::Create(const ASTContext &C, Expr *lhs, Expr *rhs,
4534 Opcode opc, QualType ResTy, ExprValueKind VK,
4535 ExprObjectKind OK, SourceLocation opLoc,
4536 FPOptionsOverride FPFeatures,
4537 QualType CompLHSType, QualType CompResultType) {
4538 bool HasFPFeatures = FPFeatures.requiresTrailingStorage();
4539 unsigned Extra = sizeOfTrailingObjects(HasFPFeatures);
4540 void *Mem = C.Allocate(sizeof(CompoundAssignOperator) + Extra,
4541 alignof(CompoundAssignOperator));
4542 return new (Mem)
4543 CompoundAssignOperator(C, lhs, rhs, opc, ResTy, VK, OK, opLoc, FPFeatures,
4544 CompLHSType, CompResultType);
4545}
4546
4547UnaryOperator *UnaryOperator::CreateEmpty(const ASTContext &C,
4548 bool hasFPFeatures) {
4549 void *Mem = C.Allocate(totalSizeToAlloc<FPOptionsOverride>(hasFPFeatures),
4550 alignof(UnaryOperator));
4551 return new (Mem) UnaryOperator(hasFPFeatures, EmptyShell());
4552}
4553
4554UnaryOperator::UnaryOperator(const ASTContext &Ctx, Expr *input, Opcode opc,
4555 QualType type, ExprValueKind VK, ExprObjectKind OK,
4556 SourceLocation l, bool CanOverflow,
4557 FPOptionsOverride FPFeatures)
4558 : Expr(UnaryOperatorClass, type, VK, OK), Val(input) {
4559 UnaryOperatorBits.Opc = opc;
4560 UnaryOperatorBits.CanOverflow = CanOverflow;
4561 UnaryOperatorBits.Loc = l;
4562 UnaryOperatorBits.HasFPFeatures = FPFeatures.requiresTrailingStorage();
4563 if (hasStoredFPFeatures())
4564 setStoredFPFeatures(FPFeatures);
4565 setDependence(computeDependence(this, Ctx));
4566}
4567
4568UnaryOperator *UnaryOperator::Create(const ASTContext &C, Expr *input,
4569 Opcode opc, QualType type,
4570 ExprValueKind VK, ExprObjectKind OK,
4571 SourceLocation l, bool CanOverflow,
4572 FPOptionsOverride FPFeatures) {
4573 bool HasFPFeatures = FPFeatures.requiresTrailingStorage();
4574 unsigned Size = totalSizeToAlloc<FPOptionsOverride>(HasFPFeatures);
4575 void *Mem = C.Allocate(Size, alignof(UnaryOperator));
4576 return new (Mem)
4577 UnaryOperator(C, input, opc, type, VK, OK, l, CanOverflow, FPFeatures);
4578}
4579
4580const OpaqueValueExpr *OpaqueValueExpr::findInCopyConstruct(const Expr *e) {
4581 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(e))
4582 e = ewc->getSubExpr();
4583 if (const MaterializeTemporaryExpr *m = dyn_cast<MaterializeTemporaryExpr>(e))
4584 e = m->getSubExpr();
4585 e = cast<CXXConstructExpr>(e)->getArg(0);
4586 while (const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
4587 e = ice->getSubExpr();
4588 return cast<OpaqueValueExpr>(e);
4589}
4590
4591PseudoObjectExpr *PseudoObjectExpr::Create(const ASTContext &Context,
4592 EmptyShell sh,
4593 unsigned numSemanticExprs) {
4594 void *buffer =
4595 Context.Allocate(totalSizeToAlloc<Expr *>(1 + numSemanticExprs),
4596 alignof(PseudoObjectExpr));
4597 return new(buffer) PseudoObjectExpr(sh, numSemanticExprs);
4598}
4599
4600PseudoObjectExpr::PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs)
4601 : Expr(PseudoObjectExprClass, shell) {
4602 PseudoObjectExprBits.NumSubExprs = numSemanticExprs + 1;
4603}
4604
4605PseudoObjectExpr *PseudoObjectExpr::Create(const ASTContext &C, Expr *syntax,
4606 ArrayRef<Expr*> semantics,
4607 unsigned resultIndex) {
4608 assert(syntax && "no syntactic expression!")(static_cast <bool> (syntax && "no syntactic expression!"
) ? void (0) : __assert_fail ("syntax && \"no syntactic expression!\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 4608, __extension__ __PRETTY_FUNCTION__))
;
4609 assert(semantics.size() && "no semantic expressions!")(static_cast <bool> (semantics.size() && "no semantic expressions!"
) ? void (0) : __assert_fail ("semantics.size() && \"no semantic expressions!\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 4609, __extension__ __PRETTY_FUNCTION__))
;
4610
4611 QualType type;
4612 ExprValueKind VK;
4613 if (resultIndex == NoResult) {
4614 type = C.VoidTy;
4615 VK = VK_PRValue;
4616 } else {
4617 assert(resultIndex < semantics.size())(static_cast <bool> (resultIndex < semantics.size())
? void (0) : __assert_fail ("resultIndex < semantics.size()"
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 4617, __extension__ __PRETTY_FUNCTION__))
;
4618 type = semantics[resultIndex]->getType();
4619 VK = semantics[resultIndex]->getValueKind();
4620 assert(semantics[resultIndex]->getObjectKind() == OK_Ordinary)(static_cast <bool> (semantics[resultIndex]->getObjectKind
() == OK_Ordinary) ? void (0) : __assert_fail ("semantics[resultIndex]->getObjectKind() == OK_Ordinary"
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 4620, __extension__ __PRETTY_FUNCTION__))
;
4621 }
4622
4623 void *buffer = C.Allocate(totalSizeToAlloc<Expr *>(semantics.size() + 1),
4624 alignof(PseudoObjectExpr));
4625 return new(buffer) PseudoObjectExpr(type, VK, syntax, semantics,
4626 resultIndex);
4627}
4628
4629PseudoObjectExpr::PseudoObjectExpr(QualType type, ExprValueKind VK,
4630 Expr *syntax, ArrayRef<Expr *> semantics,
4631 unsigned resultIndex)
4632 : Expr(PseudoObjectExprClass, type, VK, OK_Ordinary) {
4633 PseudoObjectExprBits.NumSubExprs = semantics.size() + 1;
4634 PseudoObjectExprBits.ResultIndex = resultIndex + 1;
4635
4636 for (unsigned i = 0, e = semantics.size() + 1; i != e; ++i) {
4637 Expr *E = (i == 0 ? syntax : semantics[i-1]);
4638 getSubExprsBuffer()[i] = E;
4639
4640 if (isa<OpaqueValueExpr>(E))
4641 assert(cast<OpaqueValueExpr>(E)->getSourceExpr() != nullptr &&(static_cast <bool> (cast<OpaqueValueExpr>(E)->
getSourceExpr() != nullptr && "opaque-value semantic expressions for pseudo-object "
"operations must have sources") ? void (0) : __assert_fail (
"cast<OpaqueValueExpr>(E)->getSourceExpr() != nullptr && \"opaque-value semantic expressions for pseudo-object \" \"operations must have sources\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 4643, __extension__ __PRETTY_FUNCTION__))
4642 "opaque-value semantic expressions for pseudo-object "(static_cast <bool> (cast<OpaqueValueExpr>(E)->
getSourceExpr() != nullptr && "opaque-value semantic expressions for pseudo-object "
"operations must have sources") ? void (0) : __assert_fail (
"cast<OpaqueValueExpr>(E)->getSourceExpr() != nullptr && \"opaque-value semantic expressions for pseudo-object \" \"operations must have sources\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 4643, __extension__ __PRETTY_FUNCTION__))
4643 "operations must have sources")(static_cast <bool> (cast<OpaqueValueExpr>(E)->
getSourceExpr() != nullptr && "opaque-value semantic expressions for pseudo-object "
"operations must have sources") ? void (0) : __assert_fail (
"cast<OpaqueValueExpr>(E)->getSourceExpr() != nullptr && \"opaque-value semantic expressions for pseudo-object \" \"operations must have sources\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 4643, __extension__ __PRETTY_FUNCTION__))
;
4644 }
4645
4646 setDependence(computeDependence(this));
4647}
4648
4649//===----------------------------------------------------------------------===//
4650// Child Iterators for iterating over subexpressions/substatements
4651//===----------------------------------------------------------------------===//
4652
4653// UnaryExprOrTypeTraitExpr
4654Stmt::child_range UnaryExprOrTypeTraitExpr::children() {
4655 const_child_range CCR =
4656 const_cast<const UnaryExprOrTypeTraitExpr *>(this)->children();
4657 return child_range(cast_away_const(CCR.begin()), cast_away_const(CCR.end()));
4658}
4659
4660Stmt::const_child_range UnaryExprOrTypeTraitExpr::children() const {
4661 // If this is of a type and the type is a VLA type (and not a typedef), the
4662 // size expression of the VLA needs to be treated as an executable expression.
4663 // Why isn't this weirdness documented better in StmtIterator?
4664 if (isArgumentType()) {
4665 if (const VariableArrayType *T =
4666 dyn_cast<VariableArrayType>(getArgumentType().getTypePtr()))
4667 return const_child_range(const_child_iterator(T), const_child_iterator());
4668 return const_child_range(const_child_iterator(), const_child_iterator());
4669 }
4670 return const_child_range(&Argument.Ex, &Argument.Ex + 1);
4671}
4672
4673AtomicExpr::AtomicExpr(SourceLocation BLoc, ArrayRef<Expr *> args, QualType t,
4674 AtomicOp op, SourceLocation RP)
4675 : Expr(AtomicExprClass, t, VK_PRValue, OK_Ordinary),
4676 NumSubExprs(args.size()), BuiltinLoc(BLoc), RParenLoc(RP), Op(op) {
4677 assert(args.size() == getNumSubExprs(op) && "wrong number of subexpressions")(static_cast <bool> (args.size() == getNumSubExprs(op) &&
"wrong number of subexpressions") ? void (0) : __assert_fail
("args.size() == getNumSubExprs(op) && \"wrong number of subexpressions\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 4677, __extension__ __PRETTY_FUNCTION__))
;
4678 for (unsigned i = 0; i != args.size(); i++)
4679 SubExprs[i] = args[i];
4680 setDependence(computeDependence(this));
4681}
4682
4683unsigned AtomicExpr::getNumSubExprs(AtomicOp Op) {
4684 switch (Op) {
4685 case AO__c11_atomic_init:
4686 case AO__opencl_atomic_init:
4687 case AO__c11_atomic_load:
4688 case AO__atomic_load_n:
4689 return 2;
4690
4691 case AO__opencl_atomic_load:
4692 case AO__c11_atomic_store:
4693 case AO__c11_atomic_exchange:
4694 case AO__atomic_load:
4695 case AO__atomic_store:
4696 case AO__atomic_store_n:
4697 case AO__atomic_exchange_n:
4698 case AO__c11_atomic_fetch_add:
4699 case AO__c11_atomic_fetch_sub:
4700 case AO__c11_atomic_fetch_and:
4701 case AO__c11_atomic_fetch_or:
4702 case AO__c11_atomic_fetch_xor:
4703 case AO__c11_atomic_fetch_max:
4704 case AO__c11_atomic_fetch_min:
4705 case AO__atomic_fetch_add:
4706 case AO__atomic_fetch_sub:
4707 case AO__atomic_fetch_and:
4708 case AO__atomic_fetch_or:
4709 case AO__atomic_fetch_xor:
4710 case AO__atomic_fetch_nand:
4711 case AO__atomic_add_fetch:
4712 case AO__atomic_sub_fetch:
4713 case AO__atomic_and_fetch:
4714 case AO__atomic_or_fetch:
4715 case AO__atomic_xor_fetch:
4716 case AO__atomic_nand_fetch:
4717 case AO__atomic_min_fetch:
4718 case AO__atomic_max_fetch:
4719 case AO__atomic_fetch_min:
4720 case AO__atomic_fetch_max:
4721 return 3;
4722
4723 case AO__opencl_atomic_store:
4724 case AO__opencl_atomic_exchange:
4725 case AO__opencl_atomic_fetch_add:
4726 case AO__opencl_atomic_fetch_sub:
4727 case AO__opencl_atomic_fetch_and:
4728 case AO__opencl_atomic_fetch_or:
4729 case AO__opencl_atomic_fetch_xor:
4730 case AO__opencl_atomic_fetch_min:
4731 case AO__opencl_atomic_fetch_max:
4732 case AO__atomic_exchange:
4733 return 4;
4734
4735 case AO__c11_atomic_compare_exchange_strong:
4736 case AO__c11_atomic_compare_exchange_weak:
4737 return 5;
4738
4739 case AO__opencl_atomic_compare_exchange_strong:
4740 case AO__opencl_atomic_compare_exchange_weak:
4741 case AO__atomic_compare_exchange:
4742 case AO__atomic_compare_exchange_n:
4743 return 6;
4744 }
4745 llvm_unreachable("unknown atomic op")::llvm::llvm_unreachable_internal("unknown atomic op", "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 4745)
;
4746}
4747
4748QualType AtomicExpr::getValueType() const {
4749 auto T = getPtr()->getType()->castAs<PointerType>()->getPointeeType();
4750 if (auto AT = T->getAs<AtomicType>())
4751 return AT->getValueType();
4752 return T;
4753}
4754
4755QualType OMPArraySectionExpr::getBaseOriginalType(const Expr *Base) {
4756 unsigned ArraySectionCount = 0;
4757 while (auto *OASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParens())) {
4758 Base = OASE->getBase();
4759 ++ArraySectionCount;
4760 }
4761 while (auto *ASE =
4762 dyn_cast<ArraySubscriptExpr>(Base->IgnoreParenImpCasts())) {
4763 Base = ASE->getBase();
4764 ++ArraySectionCount;
4765 }
4766 Base = Base->IgnoreParenImpCasts();
4767 auto OriginalTy = Base->getType();
4768 if (auto *DRE = dyn_cast<DeclRefExpr>(Base))
4769 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
4770 OriginalTy = PVD->getOriginalType().getNonReferenceType();
4771
4772 for (unsigned Cnt = 0; Cnt < ArraySectionCount; ++Cnt) {
4773 if (OriginalTy->isAnyPointerType())
4774 OriginalTy = OriginalTy->getPointeeType();
4775 else {
4776 assert (OriginalTy->isArrayType())(static_cast <bool> (OriginalTy->isArrayType()) ? void
(0) : __assert_fail ("OriginalTy->isArrayType()", "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 4776, __extension__ __PRETTY_FUNCTION__))
;
4777 OriginalTy = OriginalTy->castAsArrayTypeUnsafe()->getElementType();
4778 }
4779 }
4780 return OriginalTy;
4781}
4782
4783RecoveryExpr::RecoveryExpr(ASTContext &Ctx, QualType T, SourceLocation BeginLoc,
4784 SourceLocation EndLoc, ArrayRef<Expr *> SubExprs)
4785 : Expr(RecoveryExprClass, T.getNonReferenceType(),
4786 T->isDependentType() ? VK_LValue : getValueKindForType(T),
4787 OK_Ordinary),
4788 BeginLoc(BeginLoc), EndLoc(EndLoc), NumExprs(SubExprs.size()) {
4789 assert(!T.isNull())(static_cast <bool> (!T.isNull()) ? void (0) : __assert_fail
("!T.isNull()", "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 4789, __extension__ __PRETTY_FUNCTION__))
;
4790 assert(llvm::all_of(SubExprs, [](Expr* E) { return E != nullptr; }))(static_cast <bool> (llvm::all_of(SubExprs, [](Expr* E)
{ return E != nullptr; })) ? void (0) : __assert_fail ("llvm::all_of(SubExprs, [](Expr* E) { return E != nullptr; })"
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 4790, __extension__ __PRETTY_FUNCTION__))
;
4791
4792 llvm::copy(SubExprs, getTrailingObjects<Expr *>());
4793 setDependence(computeDependence(this));
4794}
4795
4796RecoveryExpr *RecoveryExpr::Create(ASTContext &Ctx, QualType T,
4797 SourceLocation BeginLoc,
4798 SourceLocation EndLoc,
4799 ArrayRef<Expr *> SubExprs) {
4800 void *Mem = Ctx.Allocate(totalSizeToAlloc<Expr *>(SubExprs.size()),
4801 alignof(RecoveryExpr));
4802 return new (Mem) RecoveryExpr(Ctx, T, BeginLoc, EndLoc, SubExprs);
4803}
4804
4805RecoveryExpr *RecoveryExpr::CreateEmpty(ASTContext &Ctx, unsigned NumSubExprs) {
4806 void *Mem = Ctx.Allocate(totalSizeToAlloc<Expr *>(NumSubExprs),
4807 alignof(RecoveryExpr));
4808 return new (Mem) RecoveryExpr(EmptyShell(), NumSubExprs);
4809}
4810
4811void OMPArrayShapingExpr::setDimensions(ArrayRef<Expr *> Dims) {
4812 assert((static_cast <bool> (NumDims == Dims.size() && "Preallocated number of dimensions is different from the provided one."
) ? void (0) : __assert_fail ("NumDims == Dims.size() && \"Preallocated number of dimensions is different from the provided one.\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 4814, __extension__ __PRETTY_FUNCTION__))
4813 NumDims == Dims.size() &&(static_cast <bool> (NumDims == Dims.size() && "Preallocated number of dimensions is different from the provided one."
) ? void (0) : __assert_fail ("NumDims == Dims.size() && \"Preallocated number of dimensions is different from the provided one.\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 4814, __extension__ __PRETTY_FUNCTION__))
4814 "Preallocated number of dimensions is different from the provided one.")(static_cast <bool> (NumDims == Dims.size() && "Preallocated number of dimensions is different from the provided one."
) ? void (0) : __assert_fail ("NumDims == Dims.size() && \"Preallocated number of dimensions is different from the provided one.\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 4814, __extension__ __PRETTY_FUNCTION__))
;
4815 llvm::copy(Dims, getTrailingObjects<Expr *>());
4816}
4817
4818void OMPArrayShapingExpr::setBracketsRanges(ArrayRef<SourceRange> BR) {
4819 assert((static_cast <bool> (NumDims == BR.size() && "Preallocated number of dimensions is different from the provided one."
) ? void (0) : __assert_fail ("NumDims == BR.size() && \"Preallocated number of dimensions is different from the provided one.\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 4821, __extension__ __PRETTY_FUNCTION__))
4820 NumDims == BR.size() &&(static_cast <bool> (NumDims == BR.size() && "Preallocated number of dimensions is different from the provided one."
) ? void (0) : __assert_fail ("NumDims == BR.size() && \"Preallocated number of dimensions is different from the provided one.\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 4821, __extension__ __PRETTY_FUNCTION__))
4821 "Preallocated number of dimensions is different from the provided one.")(static_cast <bool> (NumDims == BR.size() && "Preallocated number of dimensions is different from the provided one."
) ? void (0) : __assert_fail ("NumDims == BR.size() && \"Preallocated number of dimensions is different from the provided one.\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 4821, __extension__ __PRETTY_FUNCTION__))
;
4822 llvm::copy(BR, getTrailingObjects<SourceRange>());
4823}
4824
4825OMPArrayShapingExpr::OMPArrayShapingExpr(QualType ExprTy, Expr *Op,
4826 SourceLocation L, SourceLocation R,
4827 ArrayRef<Expr *> Dims)
4828 : Expr(OMPArrayShapingExprClass, ExprTy, VK_LValue, OK_Ordinary), LPLoc(L),
4829 RPLoc(R), NumDims(Dims.size()) {
4830 setBase(Op);
4831 setDimensions(Dims);
4832 setDependence(computeDependence(this));
4833}
4834
4835OMPArrayShapingExpr *
4836OMPArrayShapingExpr::Create(const ASTContext &Context, QualType T, Expr *Op,
4837 SourceLocation L, SourceLocation R,
4838 ArrayRef<Expr *> Dims,
4839 ArrayRef<SourceRange> BracketRanges) {
4840 assert(Dims.size() == BracketRanges.size() &&(static_cast <bool> (Dims.size() == BracketRanges.size(
) && "Different number of dimensions and brackets ranges."
) ? void (0) : __assert_fail ("Dims.size() == BracketRanges.size() && \"Different number of dimensions and brackets ranges.\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 4841, __extension__ __PRETTY_FUNCTION__))
4841 "Different number of dimensions and brackets ranges.")(static_cast <bool> (Dims.size() == BracketRanges.size(
) && "Different number of dimensions and brackets ranges."
) ? void (0) : __assert_fail ("Dims.size() == BracketRanges.size() && \"Different number of dimensions and brackets ranges.\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 4841, __extension__ __PRETTY_FUNCTION__))
;
4842 void *Mem = Context.Allocate(
4843 totalSizeToAlloc<Expr *, SourceRange>(Dims.size() + 1, Dims.size()),
4844 alignof(OMPArrayShapingExpr));
4845 auto *E = new (Mem) OMPArrayShapingExpr(T, Op, L, R, Dims);
4846 E->setBracketsRanges(BracketRanges);
4847 return E;
4848}
4849
4850OMPArrayShapingExpr *OMPArrayShapingExpr::CreateEmpty(const ASTContext &Context,
4851 unsigned NumDims) {
4852 void *Mem = Context.Allocate(
4853 totalSizeToAlloc<Expr *, SourceRange>(NumDims + 1, NumDims),
4854 alignof(OMPArrayShapingExpr));
4855 return new (Mem) OMPArrayShapingExpr(EmptyShell(), NumDims);
4856}
4857
4858void OMPIteratorExpr::setIteratorDeclaration(unsigned I, Decl *D) {
4859 assert(I < NumIterators &&(static_cast <bool> (I < NumIterators && "Idx is greater or equal the number of iterators definitions."
) ? void (0) : __assert_fail ("I < NumIterators && \"Idx is greater or equal the number of iterators definitions.\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 4860, __extension__ __PRETTY_FUNCTION__))
4860 "Idx is greater or equal the number of iterators definitions.")(static_cast <bool> (I < NumIterators && "Idx is greater or equal the number of iterators definitions."
) ? void (0) : __assert_fail ("I < NumIterators && \"Idx is greater or equal the number of iterators definitions.\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 4860, __extension__ __PRETTY_FUNCTION__))
;
4861 getTrailingObjects<Decl *>()[I] = D;
4862}
4863
4864void OMPIteratorExpr::setAssignmentLoc(unsigned I, SourceLocation Loc) {
4865 assert(I < NumIterators &&(static_cast <bool> (I < NumIterators && "Idx is greater or equal the number of iterators definitions."
) ? void (0) : __assert_fail ("I < NumIterators && \"Idx is greater or equal the number of iterators definitions.\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 4866, __extension__ __PRETTY_FUNCTION__))
4866 "Idx is greater or equal the number of iterators definitions.")(static_cast <bool> (I < NumIterators && "Idx is greater or equal the number of iterators definitions."
) ? void (0) : __assert_fail ("I < NumIterators && \"Idx is greater or equal the number of iterators definitions.\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 4866, __extension__ __PRETTY_FUNCTION__))
;
4867 getTrailingObjects<
4868 SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +
4869 static_cast<int>(RangeLocOffset::AssignLoc)] = Loc;
4870}
4871
4872void OMPIteratorExpr::setIteratorRange(unsigned I, Expr *Begin,
4873 SourceLocation ColonLoc, Expr *End,
4874 SourceLocation SecondColonLoc,
4875 Expr *Step) {
4876 assert(I < NumIterators &&(static_cast <bool> (I < NumIterators && "Idx is greater or equal the number of iterators definitions."
) ? void (0) : __assert_fail ("I < NumIterators && \"Idx is greater or equal the number of iterators definitions.\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 4877, __extension__ __PRETTY_FUNCTION__))
4877 "Idx is greater or equal the number of iterators definitions.")(static_cast <bool> (I < NumIterators && "Idx is greater or equal the number of iterators definitions."
) ? void (0) : __assert_fail ("I < NumIterators && \"Idx is greater or equal the number of iterators definitions.\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 4877, __extension__ __PRETTY_FUNCTION__))
;
4878 getTrailingObjects<Expr *>()[I * static_cast<int>(RangeExprOffset::Total) +
4879 static_cast<int>(RangeExprOffset::Begin)] =
4880 Begin;
4881 getTrailingObjects<Expr *>()[I * static_cast<int>(RangeExprOffset::Total) +
4882 static_cast<int>(RangeExprOffset::End)] = End;
4883 getTrailingObjects<Expr *>()[I * static_cast<int>(RangeExprOffset::Total) +
4884 static_cast<int>(RangeExprOffset::Step)] = Step;
4885 getTrailingObjects<
4886 SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +
4887 static_cast<int>(RangeLocOffset::FirstColonLoc)] =
4888 ColonLoc;
4889 getTrailingObjects<
4890 SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +
4891 static_cast<int>(RangeLocOffset::SecondColonLoc)] =
4892 SecondColonLoc;
4893}
4894
4895Decl *OMPIteratorExpr::getIteratorDecl(unsigned I) {
4896 return getTrailingObjects<Decl *>()[I];
4897}
4898
4899OMPIteratorExpr::IteratorRange OMPIteratorExpr::getIteratorRange(unsigned I) {
4900 IteratorRange Res;
4901 Res.Begin =
4902 getTrailingObjects<Expr *>()[I * static_cast<int>(
4903 RangeExprOffset::Total) +
4904 static_cast<int>(RangeExprOffset::Begin)];
4905 Res.End =
4906 getTrailingObjects<Expr *>()[I * static_cast<int>(
4907 RangeExprOffset::Total) +
4908 static_cast<int>(RangeExprOffset::End)];
4909 Res.Step =
4910 getTrailingObjects<Expr *>()[I * static_cast<int>(
4911 RangeExprOffset::Total) +
4912 static_cast<int>(RangeExprOffset::Step)];
4913 return Res;
4914}
4915
4916SourceLocation OMPIteratorExpr::getAssignLoc(unsigned I) const {
4917 return getTrailingObjects<
4918 SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +
4919 static_cast<int>(RangeLocOffset::AssignLoc)];
4920}
4921
4922SourceLocation OMPIteratorExpr::getColonLoc(unsigned I) const {
4923 return getTrailingObjects<
4924 SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +
4925 static_cast<int>(RangeLocOffset::FirstColonLoc)];
4926}
4927
4928SourceLocation OMPIteratorExpr::getSecondColonLoc(unsigned I) const {
4929 return getTrailingObjects<
4930 SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +
4931 static_cast<int>(RangeLocOffset::SecondColonLoc)];
4932}
4933
4934void OMPIteratorExpr::setHelper(unsigned I, const OMPIteratorHelperData &D) {
4935 getTrailingObjects<OMPIteratorHelperData>()[I] = D;
4936}
4937
4938OMPIteratorHelperData &OMPIteratorExpr::getHelper(unsigned I) {
4939 return getTrailingObjects<OMPIteratorHelperData>()[I];
4940}
4941
4942const OMPIteratorHelperData &OMPIteratorExpr::getHelper(unsigned I) const {
4943 return getTrailingObjects<OMPIteratorHelperData>()[I];
4944}
4945
4946OMPIteratorExpr::OMPIteratorExpr(
4947 QualType ExprTy, SourceLocation IteratorKwLoc, SourceLocation L,
4948 SourceLocation R, ArrayRef<OMPIteratorExpr::IteratorDefinition> Data,
4949 ArrayRef<OMPIteratorHelperData> Helpers)
4950 : Expr(OMPIteratorExprClass, ExprTy, VK_LValue, OK_Ordinary),
4951 IteratorKwLoc(IteratorKwLoc), LPLoc(L), RPLoc(R),
4952 NumIterators(Data.size()) {
4953 for (unsigned I = 0, E = Data.size(); I < E; ++I) {
4954 const IteratorDefinition &D = Data[I];
4955 setIteratorDeclaration(I, D.IteratorDecl);
4956 setAssignmentLoc(I, D.AssignmentLoc);
4957 setIteratorRange(I, D.Range.Begin, D.ColonLoc, D.Range.End,
4958 D.SecondColonLoc, D.Range.Step);
4959 setHelper(I, Helpers[I]);
4960 }
4961 setDependence(computeDependence(this));
4962}
4963
4964OMPIteratorExpr *
4965OMPIteratorExpr::Create(const ASTContext &Context, QualType T,
4966 SourceLocation IteratorKwLoc, SourceLocation L,
4967 SourceLocation R,
4968 ArrayRef<OMPIteratorExpr::IteratorDefinition> Data,
4969 ArrayRef<OMPIteratorHelperData> Helpers) {
4970 assert(Data.size() == Helpers.size() &&(static_cast <bool> (Data.size() == Helpers.size() &&
"Data and helpers must have the same size.") ? void (0) : __assert_fail
("Data.size() == Helpers.size() && \"Data and helpers must have the same size.\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 4971, __extension__ __PRETTY_FUNCTION__))
4971 "Data and helpers must have the same size.")(static_cast <bool> (Data.size() == Helpers.size() &&
"Data and helpers must have the same size.") ? void (0) : __assert_fail
("Data.size() == Helpers.size() && \"Data and helpers must have the same size.\""
, "/build/llvm-toolchain-snapshot-13~++20210613111130+5be314f79ba7/clang/lib/AST/Expr.cpp"
, 4971, __extension__ __PRETTY_FUNCTION__))
;
4972 void *Mem = Context.Allocate(
4973 totalSizeToAlloc<Decl *, Expr *, SourceLocation, OMPIteratorHelperData>(
4974 Data.size(), Data.size() * static_cast<int>(RangeExprOffset::Total),
4975 Data.size() * static_cast<int>(RangeLocOffset::Total),
4976 Helpers.size()),
4977 alignof(OMPIteratorExpr));
4978 return new (Mem) OMPIteratorExpr(T, IteratorKwLoc, L, R, Data, Helpers);
4979}
4980
4981OMPIteratorExpr *OMPIteratorExpr::CreateEmpty(const ASTContext &Context,
4982 unsigned NumIterators) {
4983 void *Mem = Context.Allocate(
4984 totalSizeToAlloc<Decl *, Expr *, SourceLocation, OMPIteratorHelperData>(
4985 NumIterators, NumIterators * static_cast<int>(RangeExprOffset::Total),
4986 NumIterators * static_cast<int>(RangeLocOffset::Total), NumIterators),
4987 alignof(OMPIteratorExpr));
4988 return new (Mem) OMPIteratorExpr(EmptyShell(), NumIterators);
4989}

/usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/bits/stl_iterator.h

1// Iterators -*- C++ -*-
2
3// Copyright (C) 2001-2020 Free Software Foundation, Inc.
4//
5// This file is part of the GNU ISO C++ Library. This library is free
6// software; you can redistribute it and/or modify it under the
7// terms of the GNU General Public License as published by the
8// Free Software Foundation; either version 3, or (at your option)
9// any later version.
10
11// This library is distributed in the hope that it will be useful,
12// but WITHOUT ANY WARRANTY; without even the implied warranty of
13// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14// GNU General Public License for more details.
15
16// Under Section 7 of GPL version 3, you are granted additional
17// permissions described in the GCC Runtime Library Exception, version
18// 3.1, as published by the Free Software Foundation.
19
20// You should have received a copy of the GNU General Public License and
21// a copy of the GCC Runtime Library Exception along with this program;
22// see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
23// <http://www.gnu.org/licenses/>.
24
25/*
26 *
27 * Copyright (c) 1994
28 * Hewlett-Packard Company
29 *
30 * Permission to use, copy, modify, distribute and sell this software
31 * and its documentation for any purpose is hereby granted without fee,
32 * provided that the above copyright notice appear in all copies and
33 * that both that copyright notice and this permission notice appear
34 * in supporting documentation. Hewlett-Packard Company makes no
35 * representations about the suitability of this software for any
36 * purpose. It is provided "as is" without express or implied warranty.
37 *
38 *
39 * Copyright (c) 1996-1998
40 * Silicon Graphics Computer Systems, Inc.
41 *
42 * Permission to use, copy, modify, distribute and sell this software
43 * and its documentation for any purpose is hereby granted without fee,
44 * provided that the above copyright notice appear in all copies and
45 * that both that copyright notice and this permission notice appear
46 * in supporting documentation. Silicon Graphics makes no
47 * representations about the suitability of this software for any
48 * purpose. It is provided "as is" without express or implied warranty.
49 */
50
51/** @file bits/stl_iterator.h
52 * This is an internal header file, included by other library headers.
53 * Do not attempt to use it directly. @headername{iterator}
54 *
55 * This file implements reverse_iterator, back_insert_iterator,
56 * front_insert_iterator, insert_iterator, __normal_iterator, and their
57 * supporting functions and overloaded operators.
58 */
59
60#ifndef _STL_ITERATOR_H1
61#define _STL_ITERATOR_H1 1
62
63#include <bits/cpp_type_traits.h>
64#include <ext/type_traits.h>
65#include <bits/move.h>
66#include <bits/ptr_traits.h>
67
68#if __cplusplus201402L >= 201103L
69# include <type_traits>
70#endif
71
72#if __cplusplus201402L > 201703L
73# define __cpp_lib_array_constexpr 201811L
74# define __cpp_lib_constexpr_iterator 201811L
75#elif __cplusplus201402L == 201703L
76# define __cpp_lib_array_constexpr 201803L
77#endif
78
79#if __cplusplus201402L > 201703L
80# include <compare>
81# include <new>
82# include <bits/iterator_concepts.h>
83#endif
84
85namespace std _GLIBCXX_VISIBILITY(default)__attribute__ ((__visibility__ ("default")))
86{
87_GLIBCXX_BEGIN_NAMESPACE_VERSION
88
89 /**
90 * @addtogroup iterators
91 * @{
92 */
93
94#if __cplusplus201402L > 201703L && __cpp_lib_concepts
95 namespace __detail
96 {
97 // Weaken iterator_category _Cat to _Limit if it is derived from that,
98 // otherwise use _Otherwise.
99 template<typename _Cat, typename _Limit, typename _Otherwise = _Cat>
100 using __clamp_iter_cat
101 = conditional_t<derived_from<_Cat, _Limit>, _Limit, _Otherwise>;
102 }
103#endif
104
105 // 24.4.1 Reverse iterators
106 /**
107 * Bidirectional and random access iterators have corresponding reverse
108 * %iterator adaptors that iterate through the data structure in the
109 * opposite direction. They have the same signatures as the corresponding
110 * iterators. The fundamental relation between a reverse %iterator and its
111 * corresponding %iterator @c i is established by the identity:
112 * @code
113 * &*(reverse_iterator(i)) == &*(i - 1)
114 * @endcode
115 *
116 * <em>This mapping is dictated by the fact that while there is always a
117 * pointer past the end of an array, there might not be a valid pointer
118 * before the beginning of an array.</em> [24.4.1]/1,2
119 *
120 * Reverse iterators can be tricky and surprising at first. Their
121 * semantics make sense, however, and the trickiness is a side effect of
122 * the requirement that the iterators must be safe.
123 */
124 template<typename _Iterator>
125 class reverse_iterator
126 : public iterator<typename iterator_traits<_Iterator>::iterator_category,
127 typename iterator_traits<_Iterator>::value_type,
128 typename iterator_traits<_Iterator>::difference_type,
129 typename iterator_traits<_Iterator>::pointer,
130 typename iterator_traits<_Iterator>::reference>
131 {
132 protected:
133 _Iterator current;
134
135 typedef iterator_traits<_Iterator> __traits_type;
136
137 public:
138 typedef _Iterator iterator_type;
139 typedef typename __traits_type::difference_type difference_type;
140 typedef typename __traits_type::pointer pointer;
141 typedef typename __traits_type::reference reference;
142
143#if __cplusplus201402L > 201703L && __cpp_lib_concepts
144 using iterator_concept
145 = conditional_t<random_access_iterator<_Iterator>,
146 random_access_iterator_tag,
147 bidirectional_iterator_tag>;
148 using iterator_category
149 = __detail::__clamp_iter_cat<typename __traits_type::iterator_category,
150 random_access_iterator_tag>;
151#endif
152
153 /**
154 * The default constructor value-initializes member @p current.
155 * If it is a pointer, that means it is zero-initialized.
156 */
157 // _GLIBCXX_RESOLVE_LIB_DEFECTS
158 // 235 No specification of default ctor for reverse_iterator
159 // 1012. reverse_iterator default ctor should value initialize
160 _GLIBCXX17_CONSTEXPR
161 reverse_iterator() : current() { }
162
163 /**
164 * This %iterator will move in the opposite direction that @p x does.
165 */
166 explicit _GLIBCXX17_CONSTEXPR
167 reverse_iterator(iterator_type __x) : current(__x) { }
168
169 /**
170 * The copy constructor is normal.
171 */
172 _GLIBCXX17_CONSTEXPR
173 reverse_iterator(const reverse_iterator& __x)
174 : current(__x.current) { }
175
176#if __cplusplus201402L >= 201103L
177 reverse_iterator& operator=(const reverse_iterator&) = default;
178#endif
179
180 /**
181 * A %reverse_iterator across other types can be copied if the
182 * underlying %iterator can be converted to the type of @c current.
183 */
184 template<typename _Iter>
185 _GLIBCXX17_CONSTEXPR
186 reverse_iterator(const reverse_iterator<_Iter>& __x)
187 : current(__x.base()) { }
188
189 /**
190 * @return @c current, the %iterator used for underlying work.
191 */
192 _GLIBCXX17_CONSTEXPR iterator_type
193 base() const
194 { return current; }
195
196 /**
197 * @return A reference to the value at @c --current
198 *
199 * This requires that @c --current is dereferenceable.
200 *
201 * @warning This implementation requires that for an iterator of the
202 * underlying iterator type, @c x, a reference obtained by
203 * @c *x remains valid after @c x has been modified or
204 * destroyed. This is a bug: http://gcc.gnu.org/PR51823
205 */
206 _GLIBCXX17_CONSTEXPR reference
207 operator*() const
208 {
209 _Iterator __tmp = current;
210 return *--__tmp;
211 }
212
213 /**
214 * @return A pointer to the value at @c --current
215 *
216 * This requires that @c --current is dereferenceable.
217 */
218 _GLIBCXX17_CONSTEXPR pointer
219 operator->() const
220#if __cplusplus201402L > 201703L && __cpp_concepts >= 201907L
221 requires is_pointer_v<_Iterator>
222 || requires(const _Iterator __i) { __i.operator->(); }
223#endif
224 {
225 // _GLIBCXX_RESOLVE_LIB_DEFECTS
226 // 1052. operator-> should also support smart pointers
227 _Iterator __tmp = current;
228 --__tmp;
229 return _S_to_pointer(__tmp);
230 }
231
232 /**
233 * @return @c *this
234 *
235 * Decrements the underlying iterator.
236 */
237 _GLIBCXX17_CONSTEXPR reverse_iterator&
238 operator++()
239 {
240 --current;
241 return *this;
242 }
243
244 /**
245 * @return The original value of @c *this
246 *
247 * Decrements the underlying iterator.
248 */
249 _GLIBCXX17_CONSTEXPR reverse_iterator
250 operator++(int)
251 {
252 reverse_iterator __tmp = *this;
253 --current;
254 return __tmp;
255 }
256
257 /**
258 * @return @c *this
259 *
260 * Increments the underlying iterator.
261 */
262 _GLIBCXX17_CONSTEXPR reverse_iterator&
263 operator--()
264 {
265 ++current;
266 return *this;
267 }
268
269 /**
270 * @return A reverse_iterator with the previous value of @c *this
271 *
272 * Increments the underlying iterator.
273 */
274 _GLIBCXX17_CONSTEXPR reverse_iterator
275 operator--(int)
276 {
277 reverse_iterator __tmp = *this;
278 ++current;
279 return __tmp;
280 }
281
282 /**
283 * @return A reverse_iterator that refers to @c current - @a __n
284 *
285 * The underlying iterator must be a Random Access Iterator.
286 */
287 _GLIBCXX17_CONSTEXPR reverse_iterator
288 operator+(difference_type __n) const
289 { return reverse_iterator(current - __n); }
290
291 /**
292 * @return *this
293 *
294 * Moves the underlying iterator backwards @a __n steps.
295 * The underlying iterator must be a Random Access Iterator.
296 */
297 _GLIBCXX17_CONSTEXPR reverse_iterator&
298 operator+=(difference_type __n)
299 {
300 current -= __n;
301 return *this;
302 }
303
304 /**
305 * @return A reverse_iterator that refers to @c current - @a __n
306 *
307 * The underlying iterator must be a Random Access Iterator.
308 */
309 _GLIBCXX17_CONSTEXPR reverse_iterator
310 operator-(difference_type __n) const
311 { return reverse_iterator(current + __n); }
312
313 /**
314 * @return *this
315 *
316 * Moves the underlying iterator forwards @a __n steps.
317 * The underlying iterator must be a Random Access Iterator.
318 */
319 _GLIBCXX17_CONSTEXPR reverse_iterator&
320 operator-=(difference_type __n)
321 {
322 current += __n;
323 return *this;
324 }
325
326 /**
327 * @return The value at @c current - @a __n - 1
328 *
329 * The underlying iterator must be a Random Access Iterator.
330 */
331 _GLIBCXX17_CONSTEXPR reference
332 operator[](difference_type __n) const
333 { return *(*this + __n); }
334
335#if __cplusplus201402L > 201703L && __cpp_lib_concepts
336 friend constexpr iter_rvalue_reference_t<_Iterator>
337 iter_move(const reverse_iterator& __i)
338 noexcept(is_nothrow_copy_constructible_v<_Iterator>
339 && noexcept(ranges::iter_move(--std::declval<_Iterator&>())))
340 {
341 auto __tmp = __i.base();
342 return ranges::iter_move(--__tmp);
343 }
344
345 template<indirectly_swappable<_Iterator> _Iter2>
346 friend constexpr void
347 iter_swap(const reverse_iterator& __x,
348 const reverse_iterator<_Iter2>& __y)
349 noexcept(is_nothrow_copy_constructible_v<_Iterator>
350 && is_nothrow_copy_constructible_v<_Iter2>
351 && noexcept(ranges::iter_swap(--std::declval<_Iterator&>(),
352 --std::declval<_Iter2&>())))
353 {
354 auto __xtmp = __x.base();
355 auto __ytmp = __y.base();
356 ranges::iter_swap(--__xtmp, --__ytmp);
357 }
358#endif
359
360 private:
361 template<typename _Tp>
362 static _GLIBCXX17_CONSTEXPR _Tp*
363 _S_to_pointer(_Tp* __p)
364 { return __p; }
365
366 template<typename _Tp>
367 static _GLIBCXX17_CONSTEXPR pointer
368 _S_to_pointer(_Tp __t)
369 { return __t.operator->(); }
370 };
371
372 //@{
373 /**
374 * @param __x A %reverse_iterator.
375 * @param __y A %reverse_iterator.
376 * @return A simple bool.
377 *
378 * Reverse iterators forward comparisons to their underlying base()
379 * iterators.
380 *
381 */
382#if __cplusplus201402L <= 201703L || ! defined __cpp_lib_concepts
383 template<typename _Iterator>
384 inline _GLIBCXX17_CONSTEXPR bool
385 operator==(const reverse_iterator<_Iterator>& __x,
386 const reverse_iterator<_Iterator>& __y)
387 { return __x.base() == __y.base(); }
23
Assuming the condition is true
24
Returning the value 1, which participates in a condition later
388
389 template<typename _Iterator>
390 inline _GLIBCXX17_CONSTEXPR bool
391 operator<(const reverse_iterator<_Iterator>& __x,
392 const reverse_iterator<_Iterator>& __y)
393 { return __y.base() < __x.base(); }
394
395 template<typename _Iterator>
396 inline _GLIBCXX17_CONSTEXPR bool
397 operator!=(const reverse_iterator<_Iterator>& __x,
398 const reverse_iterator<_Iterator>& __y)
399 { return !(__x == __y); }
22
Calling 'operator==<const clang::ClassTemplateSpecializationDecl **>'
25
Returning from 'operator==<const clang::ClassTemplateSpecializationDecl **>'
26
Returning zero, which participates in a condition later
400
401 template<typename _Iterator>
402 inline _GLIBCXX17_CONSTEXPR bool
403 operator>(const reverse_iterator<_Iterator>& __x,
404 const reverse_iterator<_Iterator>& __y)
405 { return __y < __x; }
406
407 template<typename _Iterator>
408 inline _GLIBCXX17_CONSTEXPR bool
409 operator<=(const reverse_iterator<_Iterator>& __x,
410 const reverse_iterator<_Iterator>& __y)
411 { return !(__y < __x); }
412
413 template<typename _Iterator>
414 inline _GLIBCXX17_CONSTEXPR bool
415 operator>=(const reverse_iterator<_Iterator>& __x,
416 const reverse_iterator<_Iterator>& __y)
417 { return !(__x < __y); }
418
419 // _GLIBCXX_RESOLVE_LIB_DEFECTS
420 // DR 280. Comparison of reverse_iterator to const reverse_iterator.
421 template<typename _IteratorL, typename _IteratorR>
422 inline _GLIBCXX17_CONSTEXPR bool
423 operator==(const reverse_iterator<_IteratorL>& __x,
424 const reverse_iterator<_IteratorR>& __y)
425 { return __x.base() == __y.base(); }
426
427 template<typename _IteratorL, typename _IteratorR>
428 inline _GLIBCXX17_CONSTEXPR bool
429 operator<(const reverse_iterator<_IteratorL>& __x,
430 const reverse_iterator<_IteratorR>& __y)
431 { return __y.base() < __x.base(); }
432
433 template<typename _IteratorL, typename _IteratorR>
434 inline _GLIBCXX17_CONSTEXPR bool
435 operator!=(const reverse_iterator<_IteratorL>& __x,
436 const reverse_iterator<_IteratorR>& __y)
437 { return !(__x == __y); }
438
439 template<typename _IteratorL, typename _IteratorR>
440 inline _GLIBCXX17_CONSTEXPR bool
441 operator>(const reverse_iterator<_IteratorL>& __x,
442 const reverse_iterator<_IteratorR>& __y)
443 { return __y < __x; }
444
445 template<typename _IteratorL, typename _IteratorR>
446 inline _GLIBCXX17_CONSTEXPR bool
447 operator<=(const reverse_iterator<_IteratorL>& __x,
448 const reverse_iterator<_IteratorR>& __y)
449 { return !(__y < __x); }
450
451 template<typename _IteratorL, typename _IteratorR>
452 inline _GLIBCXX17_CONSTEXPR bool
453 operator>=(const reverse_iterator<_IteratorL>& __x,
454 const reverse_iterator<_IteratorR>& __y)
455 { return !(__x < __y); }
456#else // C++20
457 template<typename _IteratorL, typename _IteratorR>
458 constexpr bool
459 operator==(const reverse_iterator<_IteratorL>& __x,
460 const reverse_iterator<_IteratorR>& __y)
461 requires requires { { __x.base() == __y.base() } -> convertible_to<bool>; }
462 { return __x.base() == __y.base(); }
463
464 template<typename _IteratorL, typename _IteratorR>
465 constexpr bool
466 operator!=(const reverse_iterator<_IteratorL>& __x,
467 const reverse_iterator<_IteratorR>& __y)
468 requires requires { { __x.base() != __y.base() } -> convertible_to<bool>; }
469 { return __x.base() != __y.base(); }
470
471 template<typename _IteratorL, typename _IteratorR>
472 constexpr bool
473 operator<(const reverse_iterator<_IteratorL>& __x,
474 const reverse_iterator<_IteratorR>& __y)
475 requires requires { { __x.base() > __y.base() } -> convertible_to<bool>; }
476 { return __x.base() > __y.base(); }
477
478 template<typename _IteratorL, typename _IteratorR>
479 constexpr bool
480 operator>(const reverse_iterator<_IteratorL>& __x,
481 const reverse_iterator<_IteratorR>& __y)
482 requires requires { { __x.base() < __y.base() } -> convertible_to<bool>; }
483 { return __x.base() < __y.base(); }
484
485 template<typename _IteratorL, typename _IteratorR>
486 constexpr bool
487 operator<=(const reverse_iterator<_IteratorL>& __x,
488 const reverse_iterator<_IteratorR>& __y)
489 requires requires { { __x.base() >= __y.base() } -> convertible_to<bool>; }
490 { return __x.base() >= __y.base(); }
491
492 template<typename _IteratorL, typename _IteratorR>
493 constexpr bool
494 operator>=(const reverse_iterator<_IteratorL>& __x,
495 const reverse_iterator<_IteratorR>& __y)
496 requires requires { { __x.base() <= __y.base() } -> convertible_to<bool>; }
497 { return __x.base() <= __y.base(); }
498
499 template<typename _IteratorL,
500 three_way_comparable_with<_IteratorL> _IteratorR>
501 constexpr compare_three_way_result_t<_IteratorL, _IteratorR>
502 operator<=>(const reverse_iterator<_IteratorL>& __x,
503 const reverse_iterator<_IteratorR>& __y)
504 { return __y.base() <=> __x.base(); }
505#endif // C++20
506 //@}
507
508#if __cplusplus201402L < 201103L
509 template<typename _Iterator>
510 inline typename reverse_iterator<_Iterator>::difference_type
511 operator-(const reverse_iterator<_Iterator>& __x,
512 const reverse_iterator<_Iterator>& __y)
513 { return __y.base() - __x.base(); }
514
515 template<typename _IteratorL, typename _IteratorR>
516 inline typename reverse_iterator<_IteratorL>::difference_type
517 operator-(const reverse_iterator<_IteratorL>& __x,
518 const reverse_iterator<_IteratorR>& __y)
519 { return __y.base() - __x.base(); }
520#else
521 // _GLIBCXX_RESOLVE_LIB_DEFECTS
522 // DR 685. reverse_iterator/move_iterator difference has invalid signatures
523 template<typename _IteratorL, typename _IteratorR>
524 inline _GLIBCXX17_CONSTEXPR auto
525 operator-(const reverse_iterator<_IteratorL>& __x,
526 const reverse_iterator<_IteratorR>& __y)
527 -> decltype(__y.base() - __x.base())
528 { return __y.base() - __x.base(); }
529#endif
530
531 template<typename _Iterator>
532 inline _GLIBCXX17_CONSTEXPR reverse_iterator<_Iterator>
533 operator+(typename reverse_iterator<_Iterator>::difference_type __n,
534 const reverse_iterator<_Iterator>& __x)
535 { return reverse_iterator<_Iterator>(__x.base() - __n); }
536
537#if __cplusplus201402L >= 201103L
538 // Same as C++14 make_reverse_iterator but used in C++11 mode too.
539 template<typename _Iterator>
540 inline _GLIBCXX17_CONSTEXPR reverse_iterator<_Iterator>
541 __make_reverse_iterator(_Iterator __i)
542 { return reverse_iterator<_Iterator>(__i); }
543
544# if __cplusplus201402L >= 201402L
545# define __cpp_lib_make_reverse_iterator201402 201402
546
547 // _GLIBCXX_RESOLVE_LIB_DEFECTS
548 // DR 2285. make_reverse_iterator
549 /// Generator function for reverse_iterator.
550 template<typename _Iterator>
551 inline _GLIBCXX17_CONSTEXPR reverse_iterator<_Iterator>
552 make_reverse_iterator(_Iterator __i)
553 { return reverse_iterator<_Iterator>(__i); }
554
555# if __cplusplus201402L > 201703L && defined __cpp_lib_concepts
556 template<typename _Iterator1, typename _Iterator2>
557 requires (!sized_sentinel_for<_Iterator1, _Iterator2>)
558 inline constexpr bool
559 disable_sized_sentinel_for<reverse_iterator<_Iterator1>,
560 reverse_iterator<_Iterator2>> = true;
561# endif // C++20
562# endif // C++14
563
564 template<typename _Iterator>
565 _GLIBCXX20_CONSTEXPR
566 auto
567 __niter_base(reverse_iterator<_Iterator> __it)
568 -> decltype(__make_reverse_iterator(__niter_base(__it.base())))
569 { return __make_reverse_iterator(__niter_base(__it.base())); }
570
571 template<typename _Iterator>
572 struct __is_move_iterator<reverse_iterator<_Iterator> >
573 : __is_move_iterator<_Iterator>
574 { };
575
576 template<typename _Iterator>
577 _GLIBCXX20_CONSTEXPR
578 auto
579 __miter_base(reverse_iterator<_Iterator> __it)
580 -> decltype(__make_reverse_iterator(__miter_base(__it.base())))
581 { return __make_reverse_iterator(__miter_base(__it.base())); }
582#endif // C++11
583
584 // 24.4.2.2.1 back_insert_iterator
585 /**
586 * @brief Turns assignment into insertion.
587 *
588 * These are output iterators, constructed from a container-of-T.
589 * Assigning a T to the iterator appends it to the container using
590 * push_back.
591 *
592 * Tip: Using the back_inserter function to create these iterators can
593 * save typing.
594 */
595 template<typename _Container>
596 class back_insert_iterator
597 : public iterator<output_iterator_tag, void, void, void, void>
598 {
599 protected:
600 _Container* container;
601
602 public:
603 /// A nested typedef for the type of whatever container you used.
604 typedef _Container container_type;
605#if __cplusplus201402L > 201703L
606 using difference_type = ptrdiff_t;
607
608 constexpr back_insert_iterator() noexcept : container(nullptr) { }
609#endif
610
611 /// The only way to create this %iterator is with a container.
612 explicit _GLIBCXX20_CONSTEXPR
613 back_insert_iterator(_Container& __x)
614 : container(std::__addressof(__x)) { }
615
616 /**
617 * @param __value An instance of whatever type
618 * container_type::const_reference is; presumably a
619 * reference-to-const T for container<T>.
620 * @return This %iterator, for chained operations.
621 *
622 * This kind of %iterator doesn't really have a @a position in the
623 * container (you can think of the position as being permanently at
624 * the end, if you like). Assigning a value to the %iterator will