Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

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