Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name Expr.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-12/lib/clang/12.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-12~++20200917111122+b03c2b8395b/build-llvm/tools/clang/lib/AST -I /build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/AST -I /build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/include -I /build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/build-llvm/include -I /build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/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-12/lib/clang/12.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-12~++20200917111122+b03c2b8395b/build-llvm/tools/clang/lib/AST -fdebug-prefix-map=/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2020-09-17-195756-12974-1 -x c++ /build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/AST/Expr.cpp

/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/AST/Expr.cpp

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

/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,