Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name 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 -mthread-model posix -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-10/lib/clang/10.0.0 -D CLANG_VENDOR="Debian " -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/build-llvm/tools/clang/lib/AST -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/build-llvm/include -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-10/lib/clang/10.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/build-llvm/tools/clang/lib/AST -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2019-12-07-102640-14763-1 -x c++ /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/Expr.cpp

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

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

1// Iterators -*- C++ -*-
2
3// Copyright (C) 2001-2016 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
68namespace std _GLIBCXX_VISIBILITY(default)__attribute__ ((__visibility__ ("default")))
69{
70_GLIBCXX_BEGIN_NAMESPACE_VERSION
71
72 /**
73 * @addtogroup iterators
74 * @{
75 */
76
77 // 24.4.1 Reverse iterators
78 /**
79 * Bidirectional and random access iterators have corresponding reverse
80 * %iterator adaptors that iterate through the data structure in the
81 * opposite direction. They have the same signatures as the corresponding
82 * iterators. The fundamental relation between a reverse %iterator and its
83 * corresponding %iterator @c i is established by the identity:
84 * @code
85 * &*(reverse_iterator(i)) == &*(i - 1)
86 * @endcode
87 *
88 * <em>This mapping is dictated by the fact that while there is always a
89 * pointer past the end of an array, there might not be a valid pointer
90 * before the beginning of an array.</em> [24.4.1]/1,2
91 *
92 * Reverse iterators can be tricky and surprising at first. Their
93 * semantics make sense, however, and the trickiness is a side effect of
94 * the requirement that the iterators must be safe.
95 */
96 template<typename _Iterator>
97 class reverse_iterator
98 : public iterator<typename iterator_traits<_Iterator>::iterator_category,
99 typename iterator_traits<_Iterator>::value_type,
100 typename iterator_traits<_Iterator>::difference_type,
101 typename iterator_traits<_Iterator>::pointer,
102 typename iterator_traits<_Iterator>::reference>
103 {
104 protected:
105 _Iterator current;
106
107 typedef iterator_traits<_Iterator> __traits_type;
108
109 public:
110 typedef _Iterator iterator_type;
111 typedef typename __traits_type::difference_type difference_type;
112 typedef typename __traits_type::pointer pointer;
113 typedef typename __traits_type::reference reference;
114
115 /**
116 * The default constructor value-initializes member @p current.
117 * If it is a pointer, that means it is zero-initialized.
118 */
119 // _GLIBCXX_RESOLVE_LIB_DEFECTS
120 // 235 No specification of default ctor for reverse_iterator
121 reverse_iterator() : current() { }
122
123 /**
124 * This %iterator will move in the opposite direction that @p x does.
125 */
126 explicit
127 reverse_iterator(iterator_type __x) : current(__x) { }
128
129 /**
130 * The copy constructor is normal.
131 */
132 reverse_iterator(const reverse_iterator& __x)
133 : current(__x.current) { }
134
135 /**
136 * A %reverse_iterator across other types can be copied if the
137 * underlying %iterator can be converted to the type of @c current.
138 */
139 template<typename _Iter>
140 reverse_iterator(const reverse_iterator<_Iter>& __x)
141 : current(__x.base()) { }
142
143 /**
144 * @return @c current, the %iterator used for underlying work.
145 */
146 iterator_type
147 base() const
148 { return current; }
149
150 /**
151 * @return A reference to the value at @c --current
152 *
153 * This requires that @c --current is dereferenceable.
154 *
155 * @warning This implementation requires that for an iterator of the
156 * underlying iterator type, @c x, a reference obtained by
157 * @c *x remains valid after @c x has been modified or
158 * destroyed. This is a bug: http://gcc.gnu.org/PR51823
159 */
160 reference
161 operator*() const
162 {
163 _Iterator __tmp = current;
164 return *--__tmp;
165 }
166
167 /**
168 * @return A pointer to the value at @c --current
169 *
170 * This requires that @c --current is dereferenceable.
171 */
172 pointer
173 operator->() const
174 { return &(operator*()); }
175
176 /**
177 * @return @c *this
178 *
179 * Decrements the underlying iterator.
180 */
181 reverse_iterator&
182 operator++()
183 {
184 --current;
185 return *this;
186 }
187
188 /**
189 * @return The original value of @c *this
190 *
191 * Decrements the underlying iterator.
192 */
193 reverse_iterator
194 operator++(int)
195 {
196 reverse_iterator __tmp = *this;
197 --current;
198 return __tmp;
199 }
200
201 /**
202 * @return @c *this
203 *
204 * Increments the underlying iterator.
205 */
206 reverse_iterator&
207 operator--()
208 {
209 ++current;
210 return *this;
211 }
212
213 /**
214 * @return A reverse_iterator with the previous value of @c *this
215 *
216 * Increments the underlying iterator.
217 */
218 reverse_iterator
219 operator--(int)
220 {
221 reverse_iterator __tmp = *this;
222 ++current;
223 return __tmp;
224 }
225
226 /**
227 * @return A reverse_iterator that refers to @c current - @a __n
228 *
229 * The underlying iterator must be a Random Access Iterator.
230 */
231 reverse_iterator
232 operator+(difference_type __n) const
233 { return reverse_iterator(current - __n); }
234
235 /**
236 * @return *this
237 *
238 * Moves the underlying iterator backwards @a __n steps.
239 * The underlying iterator must be a Random Access Iterator.
240 */
241 reverse_iterator&
242 operator+=(difference_type __n)
243 {
244 current -= __n;
245 return *this;
246 }
247
248 /**
249 * @return A reverse_iterator that refers to @c current - @a __n
250 *
251 * The underlying iterator must be a Random Access Iterator.
252 */
253 reverse_iterator
254 operator-(difference_type __n) const
255 { return reverse_iterator(current + __n); }
256
257 /**
258 * @return *this
259 *
260 * Moves the underlying iterator forwards @a __n steps.
261 * The underlying iterator must be a Random Access Iterator.
262 */
263 reverse_iterator&
264 operator-=(difference_type __n)
265 {
266 current += __n;
267 return *this;
268 }
269
270 /**
271 * @return The value at @c current - @a __n - 1
272 *
273 * The underlying iterator must be a Random Access Iterator.
274 */
275 reference
276 operator[](difference_type __n) const
277 { return *(*this + __n); }
278 };
279
280 //@{
281 /**
282 * @param __x A %reverse_iterator.
283 * @param __y A %reverse_iterator.
284 * @return A simple bool.
285 *
286 * Reverse iterators forward many operations to their underlying base()
287 * iterators. Others are implemented in terms of one another.
288 *
289 */
290 template<typename _Iterator>
291 inline bool
292 operator==(const reverse_iterator<_Iterator>& __x,
293 const reverse_iterator<_Iterator>& __y)
294 { return __x.base() == __y.base(); }
23
Assuming the condition is true
24
Returning the value 1, which participates in a condition later
295
296 template<typename _Iterator>
297 inline bool
298 operator<(const reverse_iterator<_Iterator>& __x,
299 const reverse_iterator<_Iterator>& __y)
300 { return __y.base() < __x.base(); }
301
302 template<typename _Iterator>
303 inline bool
304 operator!=(const reverse_iterator<_Iterator>& __x,
305 const reverse_iterator<_Iterator>& __y)
306 { 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
307
308 template<typename _Iterator>
309 inline bool
310 operator>(const reverse_iterator<_Iterator>& __x,
311 const reverse_iterator<_Iterator>& __y)
312 { return __y < __x; }
313
314 template<typename _Iterator>
315 inline bool
316 operator<=(const reverse_iterator<_Iterator>& __x,
317 const reverse_iterator<_Iterator>& __y)
318 { return !(__y < __x); }
319
320 template<typename _Iterator>
321 inline bool
322 operator>=(const reverse_iterator<_Iterator>& __x,
323 const reverse_iterator<_Iterator>& __y)
324 { return !(__x < __y); }
325
326 template<typename _Iterator>
327#if __cplusplus201402L < 201103L
328 inline typename reverse_iterator<_Iterator>::difference_type
329 operator-(const reverse_iterator<_Iterator>& __x,
330 const reverse_iterator<_Iterator>& __y)
331#else
332 inline auto
333 operator-(const reverse_iterator<_Iterator>& __x,
334 const reverse_iterator<_Iterator>& __y)
335 -> decltype(__x.base() - __y.base())
336#endif
337 { return __y.base() - __x.base(); }
338
339 template<typename _Iterator>
340 inline reverse_iterator<_Iterator>
341 operator+(typename reverse_iterator<_Iterator>::difference_type __n,
342 const reverse_iterator<_Iterator>& __x)
343 { return reverse_iterator<_Iterator>(__x.base() - __n); }
344
345 // _GLIBCXX_RESOLVE_LIB_DEFECTS
346 // DR 280. Comparison of reverse_iterator to const reverse_iterator.
347 template<typename _IteratorL, typename _IteratorR>
348 inline bool
349 operator==(const reverse_iterator<_IteratorL>& __x,
350 const reverse_iterator<_IteratorR>& __y)
351 { return __x.base() == __y.base(); }
352
353 template<typename _IteratorL, typename _IteratorR>
354 inline bool
355 operator<(const reverse_iterator<_IteratorL>& __x,
356 const reverse_iterator<_IteratorR>& __y)
357 { return __y.base() < __x.base(); }
358
359 template<typename _IteratorL, typename _IteratorR>
360 inline bool
361 operator!=(const reverse_iterator<_IteratorL>& __x,
362 const reverse_iterator<_IteratorR>& __y)
363 { return !(__x == __y); }
364
365 template<typename _IteratorL, typename _IteratorR>
366 inline bool
367 operator>(const reverse_iterator<_IteratorL>& __x,
368 const reverse_iterator<_IteratorR>& __y)
369 { return __y < __x; }
370
371 template<typename _IteratorL, typename _IteratorR>
372 inline bool
373 operator<=(const reverse_iterator<_IteratorL>& __x,
374 const reverse_iterator<_IteratorR>& __y)
375 { return !(__y < __x); }
376
377 template<typename _IteratorL, typename _IteratorR>
378 inline bool
379 operator>=(const reverse_iterator<_IteratorL>& __x,
380 const reverse_iterator<_IteratorR>& __y)
381 { return !(__x < __y); }
382
383 template<typename _IteratorL, typename _IteratorR>
384#if __cplusplus201402L >= 201103L
385 // DR 685.
386 inline auto
387 operator-(const reverse_iterator<_IteratorL>& __x,
388 const reverse_iterator<_IteratorR>& __y)
389 -> decltype(__y.base() - __x.base())
390#else
391 inline typename reverse_iterator<_IteratorL>::difference_type
392 operator-(const reverse_iterator<_IteratorL>& __x,
393 const reverse_iterator<_IteratorR>& __y)
394#endif
395 { return __y.base() - __x.base(); }
396 //@}
397
398#if __cplusplus201402L >= 201103L
399 // Same as C++14 make_reverse_iterator but used in C++03 mode too.
400 template<typename _Iterator>
401 inline reverse_iterator<_Iterator>
402 __make_reverse_iterator(_Iterator __i)
403 { return reverse_iterator<_Iterator>(__i); }
404
405# if __cplusplus201402L > 201103L
406# define __cpp_lib_make_reverse_iterator201402 201402
407
408 // _GLIBCXX_RESOLVE_LIB_DEFECTS
409 // DR 2285. make_reverse_iterator
410 /// Generator function for reverse_iterator.
411 template<typename _Iterator>
412 inline reverse_iterator<_Iterator>
413 make_reverse_iterator(_Iterator __i)
414 { return reverse_iterator<_Iterator>(__i); }
415# endif
416#endif
417
418#if __cplusplus201402L >= 201103L
419 template<typename _Iterator>
420 auto
421 __niter_base(reverse_iterator<_Iterator> __it)
422 -> decltype(__make_reverse_iterator(__niter_base(__it.base())))
423 { return __make_reverse_iterator(__niter_base(__it.base())); }
424
425 template<typename _Iterator>
426 struct __is_move_iterator<reverse_iterator<_Iterator> >
427 : __is_move_iterator<_Iterator>
428 { };
429
430 template<typename _Iterator>
431 auto
432 __miter_base(reverse_iterator<_Iterator> __it)
433 -> decltype(__make_reverse_iterator(__miter_base(__it.base())))
434 { return __make_reverse_iterator(__miter_base(__it.base())); }
435#endif
436
437 // 24.4.2.2.1 back_insert_iterator
438 /**
439 * @brief Turns assignment into insertion.
440 *
441 * These are output iterators, constructed from a container-of-T.
442 * Assigning a T to the iterator appends it to the container using
443 * push_back.
444 *
445 * Tip: Using the back_inserter function to create these iterators can
446 * save typing.
447 */
448 template<typename _Container>
449 class back_insert_iterator
450 : public iterator<output_iterator_tag, void, void, void, void>
451 {
452 protected:
453 _Container* container;
454
455 public:
456 /// A nested typedef for the type of whatever container you used.
457 typedef _Container container_type;
458
459 /// The only way to create this %iterator is with a container.
460 explicit
461 back_insert_iterator(_Container& __x)
462 : container(std::__addressof(__x)) { }
463
464 /**
465 * @param __value An instance of whatever type
466 * container_type::const_reference is; presumably a
467 * reference-to-const T for container<T>.
468 * @return This %iterator, for chained operations.
469 *
470 * This kind of %iterator doesn't really have a @a position in the
471 * container (you can think of the position as being permanently at
472 * the end, if you like). Assigning a value to the %iterator will
473 * always append the value to the end of the container.
474 */
475#if __cplusplus201402L < 201103L
476 back_insert_iterator&
477 operator=(typename _Container::const_reference __value)
478 {
479 container->push_back(__value);
480 return *this;
481 }
482#else
483 back_insert_iterator&
484 operator=(const typename _Container::value_type& __value)
485 {
486 container->push_back(__value);
487 return *this;
488 }
489
490 back_insert_iterator&
491 operator=(typename _Container::value_type&& __value)
492 {
493 container->push_back(std::move(__value));
494 return *this;
495 }
496#endif
497
498 /// Simply returns *this.
499 back_insert_iterator&
500 operator*()
501 { return *this; }
502
503 /// Simply returns *this. (This %iterator does not @a move.)
504 back_insert_iterator&
505 operator++()
506 { return *this; }
507
508 /// Simply returns *this. (This %iterator does not @a move.)
509 back_insert_iterator
510 operator++(int)
511 { return *this; }
512 };
513
514 /**
515 * @param __x A container of arbitrary type.
516 * @return An instance of back_insert_iterator working on @p __x.
517 *
518 * This wrapper function helps in creating back_insert_iterator instances.
519 * Typing the name of the %iterator requires knowing the precise full
520 * type of the container, which can be tedious and impedes generic
521 * programming. Using this function lets you take advantage of automatic
522 * template parameter deduction, making the compiler match the correct
523 * types for you.
524 */
525 template<typename _Container>
526 inline back_insert_iterator<_Container>
527 back_inserter(_Container& __x)
528 { return back_insert_iterator<_Container>(__x); }
529
530 /**
531 * @brief Turns assignment into insertion.
532 *
533 * These are output iterators, constructed from a container-of-T.
534 * Assigning a T to the iterator prepends it to the container using
535 * push_front.
536 *
537 * Tip: Using the front_inserter function to create these iterators can
538 * save typing.
539 */
540 template<typename _Container>
541 class front_insert_iterator
542 : public iterator<output_iterator_tag, void, void, void, void>
543 {
544 protected:
545 _Container* container;
546
547 public:
548 /// A nested typedef for the type of whatever container you used.
549 typedef _Container container_type;
550
551 /// The only way to create this %iterator is with a container.
552 explicit front_insert_iterator(_Container& __x)
553 : container(std::__addressof(__x)) { }
554
555 /**
556 * @param __value An instance of whatever type
557 * container_type::const_reference is; presumably a
558 * reference-to-const T for container<T>.
559 * @return This %iterator, for chained operations.
560 *
561 * This kind of %iterator doesn't really have a @a position in the
562 * container (you can think of the position as being permanently at
563 * the front, if you like). Assigning a value to the %iterator will
564 * always prepend the value to the front of the container.
565 */
566#if __cplusplus201402L < 201103L
567 front_insert_iterator&
568 operator=(typename _Container::const_reference __value)
569 {
570 container->push_front(__value);
571 return *this;
572 }
573#else
574 front_insert_iterator&
575 operator=(const typename _Container::value_type& __value)
576 {
577 container->push_front(__value);
578 return *this;
579 }
580
581 front_insert_iterator&
582 operator=(typename _Container::value_type&& __value)
583 {
584 container->push_front(std::move(__value));
585 return *this;
586 }
587#endif
588
589 /// Simply returns *this.
590 front_insert_iterator&
591 operator*()
592 { return *this; }
593
594 /// Simply returns *this. (This %iterator does not @a move.)
595 front_insert_iterator&
596 operator++()
597 { return *this; }
598
599 /// Simply returns *this. (This %iterator does not @a move.)
600 front_insert_iterator
601 operator++(int)
602 { return *this; }
603 };
604
605 /**
606 * @param __x A container of arbitrary type.
607 * @return An instance of front_insert_iterator working on @p x.
608 *
609 * This wrapper function helps in creating front_insert_iterator instances.
610 * Typing the name of the %iterator requires knowing the precise full
611 * type of the container, which can be tedious and impedes generic
612 * programming. Using this function lets you take advantage of automatic
613 * template parameter deduction, making the compiler match the correct
614 * types for you.
615 */
616 template<typename _Container>
617 inline front_insert_iterator<_Container>
618 front_inserter(_Container& __x)
619 { return front_insert_iterator<_Container>(__x); }
620
621 /**
622 * @brief Turns assignment into insertion.
623 *
624 * These are output iterators, constructed from a container-of-T.
625 * Assigning a T to the iterator inserts it in the container at the
626 * %iterator's position, rather than overwriting the value at that
627 * position.
628 *
629 * (Sequences will actually insert a @e copy of the value before the
630 * %iterator's position.)
631 *
632 * Tip: Using the inserter function to create these iterators can
633 * save typing.
634 */
635 template<typename _Container>
636 class insert_iterator
637 : public iterator<output_iterator_tag, void, void, void, void>
638 {
639 protected:
640 _Container* container;
641 typename _Container::iterator iter;
642
643 public:
644 /// A nested typedef for the type of whatever container you used.
645 typedef _Container container_type;
646
647 /**
648 * The only way to create this %iterator is with a container and an
649 * initial position (a normal %iterator into the container).
650 */
651 insert_iterator(_Container& __x, typename _Container::iterator __i)
652 : container(std::__addressof(__x)), iter(__i) {}
653
654 /**
655 * @param __value An instance of whatever type
656 * container_type::const_reference is; presumably a
657 * reference-to-const T for container<T>.
658 * @return This %iterator, for chained operations.
659 *
660 * This kind of %iterator maintains its own position in the
661 * container. Assigning a value to the %iterator will insert the
662 * value into the container at the place before the %iterator.
663 *
664 * The position is maintained such that subsequent assignments will
665 * insert values immediately after one another. For example,
666 * @code
667 * // vector v contains A and Z
668 *
669 * insert_iterator i (v, ++v.begin());
670 * i = 1;
671 * i = 2;
672 * i = 3;
673 *
674 * // vector v contains A, 1, 2, 3, and Z
675 * @endcode
676 */
677#if __cplusplus201402L < 201103L
678 insert_iterator&
679 operator=(typename _Container::const_reference __value)
680 {
681 iter = container->insert(iter, __value);
682 ++iter;
683 return *this;
684 }
685#else
686 insert_iterator&
687 operator=(const typename _Container::value_type& __value)
688 {
689 iter = container->insert(iter, __value);
690 ++iter;
691 return *this;
692 }
693
694 insert_iterator&
695 operator=(typename _Container::value_type&& __value)
696 {
697 iter = container->insert(iter, std::move(__value));
698 ++iter;
699 return *this;
700 }
701#endif
702
703 /// Simply returns *this.
704 insert_iterator&
705 operator*()
706 { return *this; }
707
708 /// Simply returns *this. (This %iterator does not @a move.)
709 insert_iterator&
710 operator++()
711 { return *this; }
712
713 /// Simply returns *this. (This %iterator does not @a move.)
714 insert_iterator&
715 operator++(int)
716 { return *this; }
717 };
718
719 /**
720 * @param __x A container of arbitrary type.
721 * @return An instance of insert_iterator working on @p __x.
722 *
723 * This wrapper function helps in creating insert_iterator instances.
724 * Typing the name of the %iterator requires knowing the precise full
725 * type of the container, which can be tedious and impedes generic
726 * programming. Using this function lets you take advantage of automatic
727 * template parameter deduction, making the compiler match the correct
728 * types for you.
729 */
730 template<typename _Container, typename _Iterator>
731 inline insert_iterator<_Container>
732 inserter(_Container& __x, _Iterator __i)
733 {
734 return insert_iterator<_Container>(__x,
735 typename _Container::iterator(__i));
736 }
737
738 // @} group iterators
739
740_GLIBCXX_END_NAMESPACE_VERSION
741} // namespace
742
743namespace __gnu_cxx _GLIBCXX_VISIBILITY(default)__attribute__ ((__visibility__ ("default")))
744{
745_GLIBCXX_BEGIN_NAMESPACE_VERSION
746
747 // This iterator adapter is @a normal in the sense that it does not
748 // change the semantics of any of the operators of its iterator
749 // parameter. Its primary purpose is to convert an iterator that is
750 // not a class, e.g. a pointer, into an iterator that is a class.
751 // The _Container parameter exists solely so that different containers
752 // using this template can instantiate different types, even if the
753 // _Iterator parameter is the same.
754 using std::iterator_traits;
755 using std::iterator;
756 template<typename _Iterator, typename _Container>
757 class __normal_iterator
758 {
759 protected:
760 _Iterator _M_current;
761
762 typedef iterator_traits<_Iterator> __traits_type;
763
764 public:
765 typedef _Iterator iterator_type;
766 typedef typename __traits_type::iterator_category iterator_category;
767 typedef typename __traits_type::value_type value_type;
768 typedef typename __traits_type::difference_type difference_type;
769 typedef typename __traits_type::reference reference;
770 typedef typename __traits_type::pointer pointer;
771
772 _GLIBCXX_CONSTEXPRconstexpr __normal_iterator() _GLIBCXX_NOEXCEPTnoexcept
773 : _M_current(_Iterator()) { }
774
775 explicit
776 __normal_iterator(const _Iterator& __i) _GLIBCXX_NOEXCEPTnoexcept
777 : _M_current(__i) { }
778
779 // Allow iterator to const_iterator conversion
780 template<typename _Iter>
781 __normal_iterator(const __normal_iterator<_Iter,
782 typename __enable_if<
783 (std::__are_same<_Iter, typename _Container::pointer>::__value),
784 _Container>::__type>& __i) _GLIBCXX_NOEXCEPTnoexcept
785 : _M_current(__i.base()) { }
786
787 // Forward iterator requirements
788 reference
789 operator*() const _GLIBCXX_NOEXCEPTnoexcept
790 { return *_M_current; }
791
792 pointer
793 operator->() const _GLIBCXX_NOEXCEPTnoexcept
794 { return _M_current; }
795
796 __normal_iterator&
797 operator++() _GLIBCXX_NOEXCEPTnoexcept
798 {
799 ++_M_current;
800 return *this;
801 }
802
803 __normal_iterator
804 operator++(int) _GLIBCXX_NOEXCEPTnoexcept
805 { return __normal_iterator(_M_current++); }
806
807 // Bidirectional iterator requirements
808 __normal_iterator&
809 operator--() _GLIBCXX_NOEXCEPTnoexcept
810 {
811 --_M_current;
812 return *this;
813 }
814
815 __normal_iterator
816 operator--(int) _GLIBCXX_NOEXCEPTnoexcept
817 { return __normal_iterator(_M_current--); }
818
819 // Random access iterator requirements
820 reference
821 operator[](difference_type __n) const _GLIBCXX_NOEXCEPTnoexcept
822 { return _M_current[__n]; }
823
824 __normal_iterator&
825 operator+=(difference_type __n) _GLIBCXX_NOEXCEPTnoexcept
826 { _M_current += __n; return *this; }
827
828 __normal_iterator
829 operator+(difference_type __n) const _GLIBCXX_NOEXCEPTnoexcept
830 { return __normal_iterator(_M_current + __n); }
831
832 __normal_iterator&
833 operator-=(difference_type __n) _GLIBCXX_NOEXCEPTnoexcept
834 { _M_current -= __n; return *this; }
835
836 __normal_iterator
837 operator-(difference_type __n) const _GLIBCXX_NOEXCEPTnoexcept
838 { return __normal_iterator(_M_current - __n); }
839
840 const _Iterator&
841 base() const _GLIBCXX_NOEXCEPTnoexcept
842 { return _M_current; }
843 };
844
845 // Note: In what follows, the left- and right-hand-side iterators are
846 // allowed to vary in types (conceptually in cv-qualification) so that
847 // comparison between cv-qualified and non-cv-qualified iterators be
848 // valid. However, the greedy and unfriendly operators in std::rel_ops
849 // will make overload resolution ambiguous (when in scope) if we don't
850 // provide overloads whose operands are of the same type. Can someone
851 // remind me what generic programming is about? -- Gaby
852
853 // Forward iterator requirements
854 template<typename _IteratorL, typename _IteratorR, typename _Container>
855 inline bool
856 operator==(const __normal_iterator<_IteratorL, _Container>& __lhs,
857 const __normal_iterator<_IteratorR, _Container>& __rhs)
858 _GLIBCXX_NOEXCEPTnoexcept
859 { return __lhs.base() == __rhs.base(); }
860
861 template<typename _Iterator, typename _Container>
862 inline bool
863 operator==(const __normal_iterator<_Iterator, _Container>& __lhs,
864 const __normal_iterator<_Iterator, _Container>& __rhs)
865 _GLIBCXX_NOEXCEPTnoexcept
866 { return __lhs.base() == __rhs.base(); }
867
868 template<typename _IteratorL, typename _IteratorR, typename _Container>
869 inline bool
870 operator!=(const __normal_iterator<_IteratorL, _Container>& __lhs,
871 const __normal_iterator<_IteratorR, _Container>& __rhs)
872 _GLIBCXX_NOEXCEPTnoexcept
873 { return __lhs.base() != __rhs.base(); }
874
875 template<typename _Iterator, typename _Container>
876 inline bool
877 operator!=(const __normal_iterator<_Iterator, _Container>& __lhs,
878 const __normal_iterator<_Iterator, _Container>& __rhs)
879 _GLIBCXX_NOEXCEPTnoexcept
880 { return __lhs.base() != __rhs.base(); }
881
882 // Random access iterator requirements
883 template<typename _IteratorL, typename _IteratorR, typename _Container>
884 inline bool
885 operator<(const __normal_iterator<_IteratorL, _Container>& __lhs,
886 const __normal_iterator<_IteratorR, _Container>& __rhs)
887 _GLIBCXX_NOEXCEPTnoexcept
888 { return __lhs.base() < __rhs.base(); }
889
890 template<typename _Iterator, typename _Container>
891 inline bool
892 operator<(const __normal_iterator<_Iterator, _Container>& __lhs,
893 const __normal_iterator<_Iterator, _Container>& __rhs)
894 _GLIBCXX_NOEXCEPTnoexcept
895 { return __lhs.base() < __rhs.base(); }
896
897 template<typename _IteratorL, typename _IteratorR, typename _Container>
898 inline bool
899 operator>(const __normal_iterator<_IteratorL, _Container>& __lhs,
900 const __normal_iterator<_IteratorR, _Container>& __rhs)
901 _GLIBCXX_NOEXCEPTnoexcept
902 { return __lhs.base() > __rhs.base(); }
903
904 template<typename _Iterator, typename _Container>
905 inline bool
906 operator>(const __normal_iterator<_Iterator, _Container>& __lhs,
907 const __normal_iterator<_Iterator, _Container>& __rhs)
908 _GLIBCXX_NOEXCEPTnoexcept
909 { return __lhs.base() > __rhs.base(); }
910
911 template<typename _IteratorL, typename _IteratorR, typename _Container>
912 inline bool
913 operator<=(const __normal_iterator<_IteratorL, _Container>& __lhs,
914 const __normal_iterator<_IteratorR, _Container>& __rhs)
915 _GLIBCXX_NOEXCEPTnoexcept
916 { return __lhs.base() <= __rhs.base(); }
917
918 template<typename _Iterator, typename _Container>
919 inline bool
920 operator<=(const __normal_iterator<_Iterator, _Container>& __lhs,
921 const __normal_iterator<_Iterator, _Container>& __rhs)
922 _GLIBCXX_NOEXCEPTnoexcept
923 { return __lhs.base() <= __rhs.base(); }
924
925 template<typename _IteratorL, typename _IteratorR, typename _Container>
926 inline bool
927 operator>=(const __normal_iterator<_IteratorL, _Container>& __lhs,
928 const __normal_iterator<_IteratorR, _Container>& __rhs)
929 _GLIBCXX_NOEXCEPTnoexcept
930 { return __lhs.base() >= __rhs.base(); }
931
932 template<typename _Iterator, typename _Container>
933 inline bool
934 operator>=(const __normal_iterator<_Iterator, _Container>& __lhs,
935 const __normal_iterator<_Iterator, _Container>& __rhs)
936 _GLIBCXX_NOEXCEPTnoexcept
937 { return __lhs.base() >= __rhs.base(); }
938
939 // _GLIBCXX_RESOLVE_LIB_DEFECTS
940 // According to the resolution of DR179 not only the various comparison
941 // operators but also operator- must accept mixed iterator/const_iterator
942 // parameters.
943 template<typename _IteratorL, typename _IteratorR, typename _Container>
944#if __cplusplus201402L >= 201103L
945 // DR 685.
946 inline auto
947 operator-(const __normal_iterator<_IteratorL, _Container>& __lhs,
948 const __normal_iterator<_IteratorR, _Container>& __rhs) noexcept
949 -> decltype(__lhs.base() - __rhs.base())
950#else
951 inline typename __normal_iterator<_IteratorL, _Container>::difference_type
952 operator-(const __normal_iterator<_IteratorL, _Container>& __lhs,
953 const __normal_iterator<_IteratorR, _Container>& __rhs)
954#endif
955 { return __lhs.base() - __rhs.base(); }
956
957 template<typename _Iterator, typename _Container>
958 inline typename __normal_iterator<_Iterator, _Container>::difference_type
959 operator-(const __normal_iterator<_Iterator, _Container>& __lhs,
960 const __normal_iterator<_Iterator, _Container>& __rhs)
961 _GLIBCXX_NOEXCEPTnoexcept
962 { return __lhs.base() - __rhs.base(); }
963
964 template<typename _Iterator, typename _Container>
965 inline __normal_iterator<_Iterator, _Container>
966 operator+(typename __normal_iterator<_Iterator, _Container>::difference_type
967 __n, const __normal_iterator<_Iterator, _Container>& __i)
968 _GLIBCXX_NOEXCEPTnoexcept
969 { return __normal_iterator<_Iterator, _Container>(__i.base() + __n); }
970
971_GLIBCXX_END_NAMESPACE_VERSION
972} // namespace
973
974namespace std _GLIBCXX_VISIBILITY(default)__attribute__ ((__visibility__ ("default")))
975{
976_GLIBCXX_BEGIN_NAMESPACE_VERSION
977
978 template<typename _Iterator, typename _Container>
979 _Iterator
980 __niter_base(__gnu_cxx::__normal_iterator<_Iterator, _Container> __it)
981 { return __it.base(); }
982
983_GLIBCXX_END_NAMESPACE_VERSION
984} // namespace
985
986#if __cplusplus201402L >= 201103L
987
988namespace std _GLIBCXX_VISIBILITY(default)__attribute__ ((__visibility__ ("default")))
989{
990_GLIBCXX_BEGIN_NAMESPACE_VERSION
991
992 /**
993 * @addtogroup iterators
994 * @{
995 */
996
997 // 24.4.3 Move iterators
998 /**
999 * Class template move_iterator is an iterator adapter with the same
1000 * behavior as the underlying iterator except that its dereference
1001 * operator implicitly converts the value returned by the underlying
1002 * iterator's dereference operator to an rvalue reference. Some
1003 * generic algorithms can be called with move iterators to replace
1004 * copying with moving.
1005 */
1006 template<typename _Iterator>
1007 class move_iterator
1008 {
1009 protected:
1010 _Iterator _M_current;
1011
1012 typedef iterator_traits<_Iterator> __traits_type;
1013 typedef typename __traits_type::reference __base_ref;
1014
1015 public:
1016 typedef _Iterator iterator_type;
1017 typedef typename __traits_type::iterator_category iterator_category;
1018 typedef typename __traits_type::value_type value_type;
1019 typedef typename __traits_type::difference_type difference_type;
1020 // NB: DR 680.
1021 typedef _Iterator pointer;
1022 // _GLIBCXX_RESOLVE_LIB_DEFECTS
1023 // 2106. move_iterator wrapping iterators returning prvalues
1024 typedef typename conditional<is_reference<__base_ref>::value,
1025 typename remove_reference<__base_ref>::type&&,
1026 __base_ref>::type reference;
1027
1028 move_iterator()
1029 : _M_current() { }
1030
1031 explicit
1032 move_iterator(iterator_type __i)
1033 : _M_current(__i) { }
1034
1035 template<typename _Iter>
1036 move_iterator(const move_iterator<_Iter>& __i)
1037 : _M_current(__i.base()) { }
1038