Bug Summary

File:clang/lib/AST/Expr.cpp
Warning:line 855, 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 -target-cpu x86-64 -dwarf-column-info -fno-split-dwarf-inlining -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~++20200112100611+7fa5290d5bd/build-llvm/tools/clang/lib/AST -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/build-llvm/include -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/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~++20200112100611+7fa5290d5bd/build-llvm/tools/clang/lib/AST -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2020-01-13-084841-49055-1 -x c++ /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/Expr.cpp

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

/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