Bug Summary

File:tools/clang/lib/AST/Expr.cpp
Warning:line 3776, column 25
Array access (via field 'SubExprs') results in a null pointer dereference

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