blob: 4793b114ef47fd2e63541709b2fc309b39d7d18a [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- Expr.cpp - Expression AST Node Implementation --------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expr class and subclasses.
11//
12//===----------------------------------------------------------------------===//
13
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000014#include "clang/AST/Expr.h"
Douglas Gregor0979c802009-08-31 21:41:48 +000015#include "clang/AST/ExprCXX.h"
Chris Lattnera4d55d82008-10-06 06:40:35 +000016#include "clang/AST/APValue.h"
Chris Lattner2eadfb62007-07-15 23:32:58 +000017#include "clang/AST/ASTContext.h"
Chris Lattnera4d55d82008-10-06 06:40:35 +000018#include "clang/AST/DeclObjC.h"
Douglas Gregor98cd5992008-10-21 23:43:52 +000019#include "clang/AST/DeclCXX.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000020#include "clang/AST/DeclTemplate.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000021#include "clang/AST/RecordLayout.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022#include "clang/AST/StmtVisitor.h"
Chris Lattner08f92e32010-11-17 07:37:15 +000023#include "clang/Lex/LiteralSupport.h"
24#include "clang/Lex/Lexer.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000025#include "clang/Basic/Builtins.h"
Chris Lattner08f92e32010-11-17 07:37:15 +000026#include "clang/Basic/SourceManager.h"
Chris Lattnerda5a6b62007-11-27 18:22:04 +000027#include "clang/Basic/TargetInfo.h"
Douglas Gregorcf3293e2009-11-01 20:32:48 +000028#include "llvm/Support/ErrorHandling.h"
Anders Carlsson3a082d82009-09-08 18:24:21 +000029#include "llvm/Support/raw_ostream.h"
Douglas Gregorffb4b6e2009-04-15 06:41:24 +000030#include <algorithm>
Reid Spencer5f016e22007-07-11 17:01:13 +000031using namespace clang;
32
Chris Lattner2b334bb2010-04-16 23:34:13 +000033/// isKnownToHaveBooleanValue - Return true if this is an integer expression
34/// that is known to return 0 or 1. This happens for _Bool/bool expressions
35/// but also int expressions which are produced by things like comparisons in
36/// C.
37bool Expr::isKnownToHaveBooleanValue() const {
38 // If this value has _Bool type, it is obvious 0/1.
39 if (getType()->isBooleanType()) return true;
Sean Huntc3021132010-05-05 15:23:54 +000040 // If this is a non-scalar-integer type, we don't care enough to try.
Douglas Gregor2ade35e2010-06-16 00:17:44 +000041 if (!getType()->isIntegralOrEnumerationType()) return false;
Sean Huntc3021132010-05-05 15:23:54 +000042
Chris Lattner2b334bb2010-04-16 23:34:13 +000043 if (const ParenExpr *PE = dyn_cast<ParenExpr>(this))
44 return PE->getSubExpr()->isKnownToHaveBooleanValue();
Sean Huntc3021132010-05-05 15:23:54 +000045
Chris Lattner2b334bb2010-04-16 23:34:13 +000046 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(this)) {
47 switch (UO->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +000048 case UO_Plus:
49 case UO_Extension:
Chris Lattner2b334bb2010-04-16 23:34:13 +000050 return UO->getSubExpr()->isKnownToHaveBooleanValue();
51 default:
52 return false;
53 }
54 }
Sean Huntc3021132010-05-05 15:23:54 +000055
John McCall6907fbe2010-06-12 01:56:02 +000056 // Only look through implicit casts. If the user writes
57 // '(int) (a && b)' treat it as an arbitrary int.
58 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(this))
Chris Lattner2b334bb2010-04-16 23:34:13 +000059 return CE->getSubExpr()->isKnownToHaveBooleanValue();
Sean Huntc3021132010-05-05 15:23:54 +000060
Chris Lattner2b334bb2010-04-16 23:34:13 +000061 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(this)) {
62 switch (BO->getOpcode()) {
63 default: return false;
John McCall2de56d12010-08-25 11:45:40 +000064 case BO_LT: // Relational operators.
65 case BO_GT:
66 case BO_LE:
67 case BO_GE:
68 case BO_EQ: // Equality operators.
69 case BO_NE:
70 case BO_LAnd: // AND operator.
71 case BO_LOr: // Logical OR operator.
Chris Lattner2b334bb2010-04-16 23:34:13 +000072 return true;
Sean Huntc3021132010-05-05 15:23:54 +000073
John McCall2de56d12010-08-25 11:45:40 +000074 case BO_And: // Bitwise AND operator.
75 case BO_Xor: // Bitwise XOR operator.
76 case BO_Or: // Bitwise OR operator.
Chris Lattner2b334bb2010-04-16 23:34:13 +000077 // Handle things like (x==2)|(y==12).
78 return BO->getLHS()->isKnownToHaveBooleanValue() &&
79 BO->getRHS()->isKnownToHaveBooleanValue();
Sean Huntc3021132010-05-05 15:23:54 +000080
John McCall2de56d12010-08-25 11:45:40 +000081 case BO_Comma:
82 case BO_Assign:
Chris Lattner2b334bb2010-04-16 23:34:13 +000083 return BO->getRHS()->isKnownToHaveBooleanValue();
84 }
85 }
Sean Huntc3021132010-05-05 15:23:54 +000086
Chris Lattner2b334bb2010-04-16 23:34:13 +000087 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(this))
88 return CO->getTrueExpr()->isKnownToHaveBooleanValue() &&
89 CO->getFalseExpr()->isKnownToHaveBooleanValue();
Sean Huntc3021132010-05-05 15:23:54 +000090
Chris Lattner2b334bb2010-04-16 23:34:13 +000091 return false;
92}
93
John McCall63c00d72011-02-09 08:16:59 +000094// Amusing macro metaprogramming hack: check whether a class provides
95// a more specific implementation of getExprLoc().
96namespace {
97 /// This implementation is used when a class provides a custom
98 /// implementation of getExprLoc.
99 template <class E, class T>
100 SourceLocation getExprLocImpl(const Expr *expr,
101 SourceLocation (T::*v)() const) {
102 return static_cast<const E*>(expr)->getExprLoc();
103 }
104
105 /// This implementation is used when a class doesn't provide
106 /// a custom implementation of getExprLoc. Overload resolution
107 /// should pick it over the implementation above because it's
108 /// more specialized according to function template partial ordering.
109 template <class E>
110 SourceLocation getExprLocImpl(const Expr *expr,
111 SourceLocation (Expr::*v)() const) {
112 return static_cast<const E*>(expr)->getSourceRange().getBegin();
113 }
114}
115
116SourceLocation Expr::getExprLoc() const {
117 switch (getStmtClass()) {
118 case Stmt::NoStmtClass: llvm_unreachable("statement without class");
119#define ABSTRACT_STMT(type)
120#define STMT(type, base) \
121 case Stmt::type##Class: llvm_unreachable(#type " is not an Expr"); break;
122#define EXPR(type, base) \
123 case Stmt::type##Class: return getExprLocImpl<type>(this, &type::getExprLoc);
124#include "clang/AST/StmtNodes.inc"
125 }
126 llvm_unreachable("unknown statement kind");
127 return SourceLocation();
128}
129
Reid Spencer5f016e22007-07-11 17:01:13 +0000130//===----------------------------------------------------------------------===//
131// Primary Expressions.
132//===----------------------------------------------------------------------===//
133
John McCalld5532b62009-11-23 01:53:49 +0000134void ExplicitTemplateArgumentList::initializeFrom(
135 const TemplateArgumentListInfo &Info) {
136 LAngleLoc = Info.getLAngleLoc();
137 RAngleLoc = Info.getRAngleLoc();
138 NumTemplateArgs = Info.size();
139
140 TemplateArgumentLoc *ArgBuffer = getTemplateArgs();
141 for (unsigned i = 0; i != NumTemplateArgs; ++i)
142 new (&ArgBuffer[i]) TemplateArgumentLoc(Info[i]);
143}
144
Douglas Gregorbebbe0d2010-12-15 01:34:56 +0000145void ExplicitTemplateArgumentList::initializeFrom(
146 const TemplateArgumentListInfo &Info,
147 bool &Dependent,
148 bool &ContainsUnexpandedParameterPack) {
149 LAngleLoc = Info.getLAngleLoc();
150 RAngleLoc = Info.getRAngleLoc();
151 NumTemplateArgs = Info.size();
152
153 TemplateArgumentLoc *ArgBuffer = getTemplateArgs();
154 for (unsigned i = 0; i != NumTemplateArgs; ++i) {
155 Dependent = Dependent || Info[i].getArgument().isDependent();
156 ContainsUnexpandedParameterPack
157 = ContainsUnexpandedParameterPack ||
158 Info[i].getArgument().containsUnexpandedParameterPack();
159
160 new (&ArgBuffer[i]) TemplateArgumentLoc(Info[i]);
161 }
162}
163
John McCalld5532b62009-11-23 01:53:49 +0000164void ExplicitTemplateArgumentList::copyInto(
165 TemplateArgumentListInfo &Info) const {
166 Info.setLAngleLoc(LAngleLoc);
167 Info.setRAngleLoc(RAngleLoc);
168 for (unsigned I = 0; I != NumTemplateArgs; ++I)
169 Info.addArgument(getTemplateArgs()[I]);
170}
171
Argyrios Kyrtzidis8dfbd8b2010-06-24 08:57:31 +0000172std::size_t ExplicitTemplateArgumentList::sizeFor(unsigned NumTemplateArgs) {
173 return sizeof(ExplicitTemplateArgumentList) +
174 sizeof(TemplateArgumentLoc) * NumTemplateArgs;
175}
176
John McCalld5532b62009-11-23 01:53:49 +0000177std::size_t ExplicitTemplateArgumentList::sizeFor(
178 const TemplateArgumentListInfo &Info) {
Argyrios Kyrtzidis8dfbd8b2010-06-24 08:57:31 +0000179 return sizeFor(Info.size());
John McCalld5532b62009-11-23 01:53:49 +0000180}
181
Douglas Gregord967e312011-01-19 21:52:31 +0000182/// \brief Compute the type- and value-dependence of a declaration reference
183/// based on the declaration being referenced.
184static void computeDeclRefDependence(NamedDecl *D, QualType T,
185 bool &TypeDependent,
186 bool &ValueDependent) {
187 TypeDependent = false;
188 ValueDependent = false;
Sean Huntc3021132010-05-05 15:23:54 +0000189
Douglas Gregor0da76df2009-11-23 11:41:28 +0000190
191 // (TD) C++ [temp.dep.expr]p3:
192 // An id-expression is type-dependent if it contains:
193 //
Sean Huntc3021132010-05-05 15:23:54 +0000194 // and
Douglas Gregor0da76df2009-11-23 11:41:28 +0000195 //
196 // (VD) C++ [temp.dep.constexpr]p2:
197 // An identifier is value-dependent if it is:
Douglas Gregord967e312011-01-19 21:52:31 +0000198
Douglas Gregor0da76df2009-11-23 11:41:28 +0000199 // (TD) - an identifier that was declared with dependent type
200 // (VD) - a name declared with a dependent type,
Douglas Gregord967e312011-01-19 21:52:31 +0000201 if (T->isDependentType()) {
202 TypeDependent = true;
203 ValueDependent = true;
204 return;
Douglas Gregor0da76df2009-11-23 11:41:28 +0000205 }
Douglas Gregord967e312011-01-19 21:52:31 +0000206
Douglas Gregor0da76df2009-11-23 11:41:28 +0000207 // (TD) - a conversion-function-id that specifies a dependent type
Douglas Gregord967e312011-01-19 21:52:31 +0000208 if (D->getDeclName().getNameKind()
209 == DeclarationName::CXXConversionFunctionName &&
Douglas Gregor0da76df2009-11-23 11:41:28 +0000210 D->getDeclName().getCXXNameType()->isDependentType()) {
Douglas Gregord967e312011-01-19 21:52:31 +0000211 TypeDependent = true;
212 ValueDependent = true;
213 return;
Douglas Gregor0da76df2009-11-23 11:41:28 +0000214 }
215 // (VD) - the name of a non-type template parameter,
Douglas Gregord967e312011-01-19 21:52:31 +0000216 if (isa<NonTypeTemplateParmDecl>(D)) {
217 ValueDependent = true;
218 return;
219 }
220
Douglas Gregor0da76df2009-11-23 11:41:28 +0000221 // (VD) - a constant with integral or enumeration type and is
222 // initialized with an expression that is value-dependent.
Douglas Gregord967e312011-01-19 21:52:31 +0000223 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000224 if (Var->getType()->isIntegralOrEnumerationType() &&
Douglas Gregor501edb62010-01-15 16:21:02 +0000225 Var->getType().getCVRQualifiers() == Qualifiers::Const) {
Sebastian Redl31310a22010-02-01 20:16:42 +0000226 if (const Expr *Init = Var->getAnyInitializer())
Douglas Gregor501edb62010-01-15 16:21:02 +0000227 if (Init->isValueDependent())
Douglas Gregord967e312011-01-19 21:52:31 +0000228 ValueDependent = true;
Douglas Gregorbb6e73f2010-05-11 08:41:30 +0000229 }
Douglas Gregord967e312011-01-19 21:52:31 +0000230
Douglas Gregorbb6e73f2010-05-11 08:41:30 +0000231 // (VD) - FIXME: Missing from the standard:
232 // - a member function or a static data member of the current
233 // instantiation
234 else if (Var->isStaticDataMember() &&
Douglas Gregor7ed5bd32010-05-11 08:44:04 +0000235 Var->getDeclContext()->isDependentContext())
Douglas Gregord967e312011-01-19 21:52:31 +0000236 ValueDependent = true;
237
238 return;
239 }
240
Douglas Gregorbb6e73f2010-05-11 08:41:30 +0000241 // (VD) - FIXME: Missing from the standard:
242 // - a member function or a static data member of the current
243 // instantiation
Douglas Gregord967e312011-01-19 21:52:31 +0000244 if (isa<CXXMethodDecl>(D) && D->getDeclContext()->isDependentContext()) {
245 ValueDependent = true;
246 return;
247 }
248}
Douglas Gregorbebbe0d2010-12-15 01:34:56 +0000249
Douglas Gregord967e312011-01-19 21:52:31 +0000250void DeclRefExpr::computeDependence() {
251 bool TypeDependent = false;
252 bool ValueDependent = false;
253 computeDeclRefDependence(getDecl(), getType(), TypeDependent, ValueDependent);
254
255 // (TD) C++ [temp.dep.expr]p3:
256 // An id-expression is type-dependent if it contains:
257 //
258 // and
259 //
260 // (VD) C++ [temp.dep.constexpr]p2:
261 // An identifier is value-dependent if it is:
262 if (!TypeDependent && !ValueDependent &&
263 hasExplicitTemplateArgs() &&
264 TemplateSpecializationType::anyDependentTemplateArguments(
265 getTemplateArgs(),
266 getNumTemplateArgs())) {
267 TypeDependent = true;
268 ValueDependent = true;
269 }
270
271 ExprBits.TypeDependent = TypeDependent;
272 ExprBits.ValueDependent = ValueDependent;
273
Douglas Gregor10738d32010-12-23 23:51:58 +0000274 // Is the declaration a parameter pack?
Douglas Gregord967e312011-01-19 21:52:31 +0000275 if (getDecl()->isParameterPack())
Douglas Gregor1fe85ea2011-01-05 21:11:38 +0000276 ExprBits.ContainsUnexpandedParameterPack = true;
Douglas Gregor0da76df2009-11-23 11:41:28 +0000277}
278
Douglas Gregor40d96a62011-02-28 21:54:11 +0000279DeclRefExpr::DeclRefExpr(NestedNameSpecifierLoc QualifierLoc,
John McCalldbd872f2009-12-08 09:08:17 +0000280 ValueDecl *D, SourceLocation NameLoc,
John McCalld5532b62009-11-23 01:53:49 +0000281 const TemplateArgumentListInfo *TemplateArgs,
John McCallf89e55a2010-11-18 06:31:45 +0000282 QualType T, ExprValueKind VK)
Douglas Gregorbebbe0d2010-12-15 01:34:56 +0000283 : Expr(DeclRefExprClass, T, VK, OK_Ordinary, false, false, false),
Douglas Gregora2813ce2009-10-23 18:54:35 +0000284 DecoratedD(D,
Douglas Gregor40d96a62011-02-28 21:54:11 +0000285 (QualifierLoc? HasQualifierFlag : 0) |
John McCalld5532b62009-11-23 01:53:49 +0000286 (TemplateArgs ? HasExplicitTemplateArgumentListFlag : 0)),
Douglas Gregora2813ce2009-10-23 18:54:35 +0000287 Loc(NameLoc) {
Douglas Gregor40d96a62011-02-28 21:54:11 +0000288 if (QualifierLoc) {
Douglas Gregora2813ce2009-10-23 18:54:35 +0000289 NameQualifier *NQ = getNameQualifier();
Douglas Gregor40d96a62011-02-28 21:54:11 +0000290 NQ->QualifierLoc = QualifierLoc;
Douglas Gregora2813ce2009-10-23 18:54:35 +0000291 }
Sean Huntc3021132010-05-05 15:23:54 +0000292
John McCalld5532b62009-11-23 01:53:49 +0000293 if (TemplateArgs)
John McCall096832c2010-08-19 23:49:38 +0000294 getExplicitTemplateArgs().initializeFrom(*TemplateArgs);
Douglas Gregor0da76df2009-11-23 11:41:28 +0000295
296 computeDependence();
Douglas Gregora2813ce2009-10-23 18:54:35 +0000297}
298
Douglas Gregor40d96a62011-02-28 21:54:11 +0000299DeclRefExpr::DeclRefExpr(NestedNameSpecifierLoc QualifierLoc,
Abramo Bagnara25777432010-08-11 22:01:17 +0000300 ValueDecl *D, const DeclarationNameInfo &NameInfo,
301 const TemplateArgumentListInfo *TemplateArgs,
John McCallf89e55a2010-11-18 06:31:45 +0000302 QualType T, ExprValueKind VK)
Douglas Gregorbebbe0d2010-12-15 01:34:56 +0000303 : Expr(DeclRefExprClass, T, VK, OK_Ordinary, false, false, false),
Abramo Bagnara25777432010-08-11 22:01:17 +0000304 DecoratedD(D,
Douglas Gregor40d96a62011-02-28 21:54:11 +0000305 (QualifierLoc? HasQualifierFlag : 0) |
Abramo Bagnara25777432010-08-11 22:01:17 +0000306 (TemplateArgs ? HasExplicitTemplateArgumentListFlag : 0)),
307 Loc(NameInfo.getLoc()), DNLoc(NameInfo.getInfo()) {
Douglas Gregor40d96a62011-02-28 21:54:11 +0000308 if (QualifierLoc) {
Abramo Bagnara25777432010-08-11 22:01:17 +0000309 NameQualifier *NQ = getNameQualifier();
Douglas Gregor40d96a62011-02-28 21:54:11 +0000310 NQ->QualifierLoc = QualifierLoc;
Abramo Bagnara25777432010-08-11 22:01:17 +0000311 }
312
313 if (TemplateArgs)
John McCall096832c2010-08-19 23:49:38 +0000314 getExplicitTemplateArgs().initializeFrom(*TemplateArgs);
Abramo Bagnara25777432010-08-11 22:01:17 +0000315
316 computeDependence();
317}
318
Douglas Gregora2813ce2009-10-23 18:54:35 +0000319DeclRefExpr *DeclRefExpr::Create(ASTContext &Context,
Douglas Gregor40d96a62011-02-28 21:54:11 +0000320 NestedNameSpecifierLoc QualifierLoc,
John McCalldbd872f2009-12-08 09:08:17 +0000321 ValueDecl *D,
Douglas Gregora2813ce2009-10-23 18:54:35 +0000322 SourceLocation NameLoc,
Douglas Gregor0da76df2009-11-23 11:41:28 +0000323 QualType T,
John McCallf89e55a2010-11-18 06:31:45 +0000324 ExprValueKind VK,
Douglas Gregor0da76df2009-11-23 11:41:28 +0000325 const TemplateArgumentListInfo *TemplateArgs) {
Douglas Gregor40d96a62011-02-28 21:54:11 +0000326 return Create(Context, QualifierLoc, D,
Abramo Bagnara25777432010-08-11 22:01:17 +0000327 DeclarationNameInfo(D->getDeclName(), NameLoc),
John McCallf89e55a2010-11-18 06:31:45 +0000328 T, VK, TemplateArgs);
Abramo Bagnara25777432010-08-11 22:01:17 +0000329}
330
331DeclRefExpr *DeclRefExpr::Create(ASTContext &Context,
Douglas Gregor40d96a62011-02-28 21:54:11 +0000332 NestedNameSpecifierLoc QualifierLoc,
Abramo Bagnara25777432010-08-11 22:01:17 +0000333 ValueDecl *D,
334 const DeclarationNameInfo &NameInfo,
335 QualType T,
John McCallf89e55a2010-11-18 06:31:45 +0000336 ExprValueKind VK,
Abramo Bagnara25777432010-08-11 22:01:17 +0000337 const TemplateArgumentListInfo *TemplateArgs) {
Douglas Gregora2813ce2009-10-23 18:54:35 +0000338 std::size_t Size = sizeof(DeclRefExpr);
Douglas Gregor40d96a62011-02-28 21:54:11 +0000339 if (QualifierLoc != 0)
Douglas Gregora2813ce2009-10-23 18:54:35 +0000340 Size += sizeof(NameQualifier);
Sean Huntc3021132010-05-05 15:23:54 +0000341
John McCalld5532b62009-11-23 01:53:49 +0000342 if (TemplateArgs)
343 Size += ExplicitTemplateArgumentList::sizeFor(*TemplateArgs);
Sean Huntc3021132010-05-05 15:23:54 +0000344
Chris Lattner32488542010-10-30 05:14:06 +0000345 void *Mem = Context.Allocate(Size, llvm::alignOf<DeclRefExpr>());
Douglas Gregor40d96a62011-02-28 21:54:11 +0000346 return new (Mem) DeclRefExpr(QualifierLoc, D, NameInfo, TemplateArgs, T, VK);
Douglas Gregora2813ce2009-10-23 18:54:35 +0000347}
348
Douglas Gregordef03542011-02-04 12:01:24 +0000349DeclRefExpr *DeclRefExpr::CreateEmpty(ASTContext &Context,
350 bool HasQualifier,
351 bool HasExplicitTemplateArgs,
Argyrios Kyrtzidis663e3802010-07-08 13:09:47 +0000352 unsigned NumTemplateArgs) {
353 std::size_t Size = sizeof(DeclRefExpr);
354 if (HasQualifier)
355 Size += sizeof(NameQualifier);
356
Douglas Gregordef03542011-02-04 12:01:24 +0000357 if (HasExplicitTemplateArgs)
Argyrios Kyrtzidis663e3802010-07-08 13:09:47 +0000358 Size += ExplicitTemplateArgumentList::sizeFor(NumTemplateArgs);
359
Chris Lattner32488542010-10-30 05:14:06 +0000360 void *Mem = Context.Allocate(Size, llvm::alignOf<DeclRefExpr>());
Argyrios Kyrtzidis663e3802010-07-08 13:09:47 +0000361 return new (Mem) DeclRefExpr(EmptyShell());
362}
363
Douglas Gregora2813ce2009-10-23 18:54:35 +0000364SourceRange DeclRefExpr::getSourceRange() const {
Abramo Bagnara25777432010-08-11 22:01:17 +0000365 SourceRange R = getNameInfo().getSourceRange();
Douglas Gregora2813ce2009-10-23 18:54:35 +0000366 if (hasQualifier())
Douglas Gregor40d96a62011-02-28 21:54:11 +0000367 R.setBegin(getQualifierLoc().getBeginLoc());
John McCall096832c2010-08-19 23:49:38 +0000368 if (hasExplicitTemplateArgs())
Douglas Gregora2813ce2009-10-23 18:54:35 +0000369 R.setEnd(getRAngleLoc());
370 return R;
371}
372
Anders Carlsson3a082d82009-09-08 18:24:21 +0000373// FIXME: Maybe this should use DeclPrinter with a special "print predefined
374// expr" policy instead.
Anders Carlsson848fa642010-02-11 18:20:28 +0000375std::string PredefinedExpr::ComputeName(IdentType IT, const Decl *CurrentDecl) {
376 ASTContext &Context = CurrentDecl->getASTContext();
377
Anders Carlsson3a082d82009-09-08 18:24:21 +0000378 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CurrentDecl)) {
Anders Carlsson848fa642010-02-11 18:20:28 +0000379 if (IT != PrettyFunction && IT != PrettyFunctionNoVirtual)
Anders Carlsson3a082d82009-09-08 18:24:21 +0000380 return FD->getNameAsString();
381
382 llvm::SmallString<256> Name;
383 llvm::raw_svector_ostream Out(Name);
384
385 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
Anders Carlsson848fa642010-02-11 18:20:28 +0000386 if (MD->isVirtual() && IT != PrettyFunctionNoVirtual)
Anders Carlsson3a082d82009-09-08 18:24:21 +0000387 Out << "virtual ";
Sam Weinig4eadcc52009-12-27 01:38:20 +0000388 if (MD->isStatic())
389 Out << "static ";
Anders Carlsson3a082d82009-09-08 18:24:21 +0000390 }
391
392 PrintingPolicy Policy(Context.getLangOptions());
Anders Carlsson3a082d82009-09-08 18:24:21 +0000393
394 std::string Proto = FD->getQualifiedNameAsString(Policy);
395
John McCall183700f2009-09-21 23:43:11 +0000396 const FunctionType *AFT = FD->getType()->getAs<FunctionType>();
Anders Carlsson3a082d82009-09-08 18:24:21 +0000397 const FunctionProtoType *FT = 0;
398 if (FD->hasWrittenPrototype())
399 FT = dyn_cast<FunctionProtoType>(AFT);
400
401 Proto += "(";
402 if (FT) {
403 llvm::raw_string_ostream POut(Proto);
404 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) {
405 if (i) POut << ", ";
406 std::string Param;
407 FD->getParamDecl(i)->getType().getAsStringInternal(Param, Policy);
408 POut << Param;
409 }
410
411 if (FT->isVariadic()) {
412 if (FD->getNumParams()) POut << ", ";
413 POut << "...";
414 }
415 }
416 Proto += ")";
417
Sam Weinig4eadcc52009-12-27 01:38:20 +0000418 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
419 Qualifiers ThisQuals = Qualifiers::fromCVRMask(MD->getTypeQualifiers());
420 if (ThisQuals.hasConst())
421 Proto += " const";
422 if (ThisQuals.hasVolatile())
423 Proto += " volatile";
424 }
425
Sam Weinig3a1ce1e2009-12-06 23:55:13 +0000426 if (!isa<CXXConstructorDecl>(FD) && !isa<CXXDestructorDecl>(FD))
427 AFT->getResultType().getAsStringInternal(Proto, Policy);
Anders Carlsson3a082d82009-09-08 18:24:21 +0000428
429 Out << Proto;
430
431 Out.flush();
432 return Name.str().str();
433 }
434 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurrentDecl)) {
435 llvm::SmallString<256> Name;
436 llvm::raw_svector_ostream Out(Name);
437 Out << (MD->isInstanceMethod() ? '-' : '+');
438 Out << '[';
Ted Kremenekb03d33e2010-03-18 21:23:08 +0000439
440 // For incorrect code, there might not be an ObjCInterfaceDecl. Do
441 // a null check to avoid a crash.
442 if (const ObjCInterfaceDecl *ID = MD->getClassInterface())
Benjamin Kramer900fc632010-04-17 09:33:03 +0000443 Out << ID;
Ted Kremenekb03d33e2010-03-18 21:23:08 +0000444
Anders Carlsson3a082d82009-09-08 18:24:21 +0000445 if (const ObjCCategoryImplDecl *CID =
Benjamin Kramer900fc632010-04-17 09:33:03 +0000446 dyn_cast<ObjCCategoryImplDecl>(MD->getDeclContext()))
447 Out << '(' << CID << ')';
448
Anders Carlsson3a082d82009-09-08 18:24:21 +0000449 Out << ' ';
450 Out << MD->getSelector().getAsString();
451 Out << ']';
452
453 Out.flush();
454 return Name.str().str();
455 }
456 if (isa<TranslationUnitDecl>(CurrentDecl) && IT == PrettyFunction) {
457 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
458 return "top level";
459 }
460 return "";
461}
462
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +0000463void APNumericStorage::setIntValue(ASTContext &C, const llvm::APInt &Val) {
464 if (hasAllocation())
465 C.Deallocate(pVal);
466
467 BitWidth = Val.getBitWidth();
468 unsigned NumWords = Val.getNumWords();
469 const uint64_t* Words = Val.getRawData();
470 if (NumWords > 1) {
471 pVal = new (C) uint64_t[NumWords];
472 std::copy(Words, Words + NumWords, pVal);
473 } else if (NumWords == 1)
474 VAL = Words[0];
475 else
476 VAL = 0;
477}
478
479IntegerLiteral *
480IntegerLiteral::Create(ASTContext &C, const llvm::APInt &V,
481 QualType type, SourceLocation l) {
482 return new (C) IntegerLiteral(C, V, type, l);
483}
484
485IntegerLiteral *
486IntegerLiteral::Create(ASTContext &C, EmptyShell Empty) {
487 return new (C) IntegerLiteral(Empty);
488}
489
490FloatingLiteral *
491FloatingLiteral::Create(ASTContext &C, const llvm::APFloat &V,
492 bool isexact, QualType Type, SourceLocation L) {
493 return new (C) FloatingLiteral(C, V, isexact, Type, L);
494}
495
496FloatingLiteral *
497FloatingLiteral::Create(ASTContext &C, EmptyShell Empty) {
498 return new (C) FloatingLiteral(Empty);
499}
500
Chris Lattnerda8249e2008-06-07 22:13:43 +0000501/// getValueAsApproximateDouble - This returns the value as an inaccurate
502/// double. Note that this may cause loss of precision, but is useful for
503/// debugging dumps, etc.
504double FloatingLiteral::getValueAsApproximateDouble() const {
505 llvm::APFloat V = getValue();
Dale Johannesenee5a7002008-10-09 23:02:32 +0000506 bool ignored;
507 V.convert(llvm::APFloat::IEEEdouble, llvm::APFloat::rmNearestTiesToEven,
508 &ignored);
Chris Lattnerda8249e2008-06-07 22:13:43 +0000509 return V.convertToDouble();
510}
511
Chris Lattner2085fd62009-02-18 06:40:38 +0000512StringLiteral *StringLiteral::Create(ASTContext &C, const char *StrData,
513 unsigned ByteLength, bool Wide,
514 QualType Ty,
Mike Stump1eb44332009-09-09 15:08:12 +0000515 const SourceLocation *Loc,
Anders Carlssona135fb42009-03-15 18:34:13 +0000516 unsigned NumStrs) {
Chris Lattner2085fd62009-02-18 06:40:38 +0000517 // Allocate enough space for the StringLiteral plus an array of locations for
518 // any concatenated string tokens.
519 void *Mem = C.Allocate(sizeof(StringLiteral)+
520 sizeof(SourceLocation)*(NumStrs-1),
Chris Lattner32488542010-10-30 05:14:06 +0000521 llvm::alignOf<StringLiteral>());
Chris Lattner2085fd62009-02-18 06:40:38 +0000522 StringLiteral *SL = new (Mem) StringLiteral(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +0000523
Reid Spencer5f016e22007-07-11 17:01:13 +0000524 // OPTIMIZE: could allocate this appended to the StringLiteral.
Chris Lattner2085fd62009-02-18 06:40:38 +0000525 char *AStrData = new (C, 1) char[ByteLength];
526 memcpy(AStrData, StrData, ByteLength);
527 SL->StrData = AStrData;
528 SL->ByteLength = ByteLength;
529 SL->IsWide = Wide;
530 SL->TokLocs[0] = Loc[0];
531 SL->NumConcatenated = NumStrs;
Reid Spencer5f016e22007-07-11 17:01:13 +0000532
Chris Lattner726e1682009-02-18 05:49:11 +0000533 if (NumStrs != 1)
Chris Lattner2085fd62009-02-18 06:40:38 +0000534 memcpy(&SL->TokLocs[1], Loc+1, sizeof(SourceLocation)*(NumStrs-1));
535 return SL;
Chris Lattner726e1682009-02-18 05:49:11 +0000536}
537
Douglas Gregor673ecd62009-04-15 16:35:07 +0000538StringLiteral *StringLiteral::CreateEmpty(ASTContext &C, unsigned NumStrs) {
539 void *Mem = C.Allocate(sizeof(StringLiteral)+
540 sizeof(SourceLocation)*(NumStrs-1),
Chris Lattner32488542010-10-30 05:14:06 +0000541 llvm::alignOf<StringLiteral>());
Douglas Gregor673ecd62009-04-15 16:35:07 +0000542 StringLiteral *SL = new (Mem) StringLiteral(QualType());
543 SL->StrData = 0;
544 SL->ByteLength = 0;
545 SL->NumConcatenated = NumStrs;
546 return SL;
547}
548
Daniel Dunbarb6480232009-09-22 03:27:33 +0000549void StringLiteral::setString(ASTContext &C, llvm::StringRef Str) {
Daniel Dunbarb6480232009-09-22 03:27:33 +0000550 char *AStrData = new (C, 1) char[Str.size()];
551 memcpy(AStrData, Str.data(), Str.size());
Douglas Gregor673ecd62009-04-15 16:35:07 +0000552 StrData = AStrData;
Daniel Dunbarb6480232009-09-22 03:27:33 +0000553 ByteLength = Str.size();
Douglas Gregor673ecd62009-04-15 16:35:07 +0000554}
555
Chris Lattner08f92e32010-11-17 07:37:15 +0000556/// getLocationOfByte - Return a source location that points to the specified
557/// byte of this string literal.
558///
559/// Strings are amazingly complex. They can be formed from multiple tokens and
560/// can have escape sequences in them in addition to the usual trigraph and
561/// escaped newline business. This routine handles this complexity.
562///
563SourceLocation StringLiteral::
564getLocationOfByte(unsigned ByteNo, const SourceManager &SM,
565 const LangOptions &Features, const TargetInfo &Target) const {
566 assert(!isWide() && "This doesn't work for wide strings yet");
567
568 // Loop over all of the tokens in this string until we find the one that
569 // contains the byte we're looking for.
570 unsigned TokNo = 0;
571 while (1) {
572 assert(TokNo < getNumConcatenated() && "Invalid byte number!");
573 SourceLocation StrTokLoc = getStrTokenLoc(TokNo);
574
575 // Get the spelling of the string so that we can get the data that makes up
576 // the string literal, not the identifier for the macro it is potentially
577 // expanded through.
578 SourceLocation StrTokSpellingLoc = SM.getSpellingLoc(StrTokLoc);
579
580 // Re-lex the token to get its length and original spelling.
581 std::pair<FileID, unsigned> LocInfo =SM.getDecomposedLoc(StrTokSpellingLoc);
582 bool Invalid = false;
583 llvm::StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
584 if (Invalid)
585 return StrTokSpellingLoc;
586
587 const char *StrData = Buffer.data()+LocInfo.second;
588
589 // Create a langops struct and enable trigraphs. This is sufficient for
590 // relexing tokens.
591 LangOptions LangOpts;
592 LangOpts.Trigraphs = true;
593
594 // Create a lexer starting at the beginning of this token.
595 Lexer TheLexer(StrTokSpellingLoc, Features, Buffer.begin(), StrData,
596 Buffer.end());
597 Token TheTok;
598 TheLexer.LexFromRawLexer(TheTok);
599
600 // Use the StringLiteralParser to compute the length of the string in bytes.
601 StringLiteralParser SLP(&TheTok, 1, SM, Features, Target);
602 unsigned TokNumBytes = SLP.GetStringLength();
603
604 // If the byte is in this token, return the location of the byte.
605 if (ByteNo < TokNumBytes ||
606 (ByteNo == TokNumBytes && TokNo == getNumConcatenated())) {
607 unsigned Offset = SLP.getOffsetOfStringByte(TheTok, ByteNo);
608
609 // Now that we know the offset of the token in the spelling, use the
610 // preprocessor to get the offset in the original source.
611 return Lexer::AdvanceToTokenCharacter(StrTokLoc, Offset, SM, Features);
612 }
613
614 // Move to the next string token.
615 ++TokNo;
616 ByteNo -= TokNumBytes;
617 }
618}
619
620
621
Reid Spencer5f016e22007-07-11 17:01:13 +0000622/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
623/// corresponds to, e.g. "sizeof" or "[pre]++".
624const char *UnaryOperator::getOpcodeStr(Opcode Op) {
625 switch (Op) {
626 default: assert(0 && "Unknown unary operator");
John McCall2de56d12010-08-25 11:45:40 +0000627 case UO_PostInc: return "++";
628 case UO_PostDec: return "--";
629 case UO_PreInc: return "++";
630 case UO_PreDec: return "--";
631 case UO_AddrOf: return "&";
632 case UO_Deref: return "*";
633 case UO_Plus: return "+";
634 case UO_Minus: return "-";
635 case UO_Not: return "~";
636 case UO_LNot: return "!";
637 case UO_Real: return "__real";
638 case UO_Imag: return "__imag";
639 case UO_Extension: return "__extension__";
Reid Spencer5f016e22007-07-11 17:01:13 +0000640 }
641}
642
John McCall2de56d12010-08-25 11:45:40 +0000643UnaryOperatorKind
Douglas Gregorbc736fc2009-03-13 23:49:33 +0000644UnaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix) {
645 switch (OO) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +0000646 default: assert(false && "No unary operator for overloaded function");
John McCall2de56d12010-08-25 11:45:40 +0000647 case OO_PlusPlus: return Postfix ? UO_PostInc : UO_PreInc;
648 case OO_MinusMinus: return Postfix ? UO_PostDec : UO_PreDec;
649 case OO_Amp: return UO_AddrOf;
650 case OO_Star: return UO_Deref;
651 case OO_Plus: return UO_Plus;
652 case OO_Minus: return UO_Minus;
653 case OO_Tilde: return UO_Not;
654 case OO_Exclaim: return UO_LNot;
Douglas Gregorbc736fc2009-03-13 23:49:33 +0000655 }
656}
657
658OverloadedOperatorKind UnaryOperator::getOverloadedOperator(Opcode Opc) {
659 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +0000660 case UO_PostInc: case UO_PreInc: return OO_PlusPlus;
661 case UO_PostDec: case UO_PreDec: return OO_MinusMinus;
662 case UO_AddrOf: return OO_Amp;
663 case UO_Deref: return OO_Star;
664 case UO_Plus: return OO_Plus;
665 case UO_Minus: return OO_Minus;
666 case UO_Not: return OO_Tilde;
667 case UO_LNot: return OO_Exclaim;
Douglas Gregorbc736fc2009-03-13 23:49:33 +0000668 default: return OO_None;
669 }
670}
671
672
Reid Spencer5f016e22007-07-11 17:01:13 +0000673//===----------------------------------------------------------------------===//
674// Postfix Operators.
675//===----------------------------------------------------------------------===//
676
Peter Collingbournecc324ad2011-02-08 21:18:02 +0000677CallExpr::CallExpr(ASTContext& C, StmtClass SC, Expr *fn, unsigned NumPreArgs,
678 Expr **args, unsigned numargs, QualType t, ExprValueKind VK,
John McCallf89e55a2010-11-18 06:31:45 +0000679 SourceLocation rparenloc)
680 : Expr(SC, t, VK, OK_Ordinary,
Douglas Gregorbebbe0d2010-12-15 01:34:56 +0000681 fn->isTypeDependent(),
682 fn->isValueDependent(),
683 fn->containsUnexpandedParameterPack()),
Douglas Gregor898574e2008-12-05 23:32:09 +0000684 NumArgs(numargs) {
Mike Stump1eb44332009-09-09 15:08:12 +0000685
Peter Collingbournecc324ad2011-02-08 21:18:02 +0000686 SubExprs = new (C) Stmt*[numargs+PREARGS_START+NumPreArgs];
Douglas Gregorb4609802008-11-14 16:09:21 +0000687 SubExprs[FN] = fn;
Douglas Gregorbebbe0d2010-12-15 01:34:56 +0000688 for (unsigned i = 0; i != numargs; ++i) {
689 if (args[i]->isTypeDependent())
690 ExprBits.TypeDependent = true;
691 if (args[i]->isValueDependent())
692 ExprBits.ValueDependent = true;
693 if (args[i]->containsUnexpandedParameterPack())
694 ExprBits.ContainsUnexpandedParameterPack = true;
695
Peter Collingbournecc324ad2011-02-08 21:18:02 +0000696 SubExprs[i+PREARGS_START+NumPreArgs] = args[i];
Douglas Gregorbebbe0d2010-12-15 01:34:56 +0000697 }
Ted Kremenek668bf912009-02-09 20:51:47 +0000698
Peter Collingbournecc324ad2011-02-08 21:18:02 +0000699 CallExprBits.NumPreArgs = NumPreArgs;
Douglas Gregorb4609802008-11-14 16:09:21 +0000700 RParenLoc = rparenloc;
701}
Nate Begemane2ce1d92008-01-17 17:46:27 +0000702
Ted Kremenek668bf912009-02-09 20:51:47 +0000703CallExpr::CallExpr(ASTContext& C, Expr *fn, Expr **args, unsigned numargs,
John McCallf89e55a2010-11-18 06:31:45 +0000704 QualType t, ExprValueKind VK, SourceLocation rparenloc)
705 : Expr(CallExprClass, t, VK, OK_Ordinary,
Douglas Gregorbebbe0d2010-12-15 01:34:56 +0000706 fn->isTypeDependent(),
707 fn->isValueDependent(),
708 fn->containsUnexpandedParameterPack()),
Douglas Gregor898574e2008-12-05 23:32:09 +0000709 NumArgs(numargs) {
Ted Kremenek668bf912009-02-09 20:51:47 +0000710
Peter Collingbournecc324ad2011-02-08 21:18:02 +0000711 SubExprs = new (C) Stmt*[numargs+PREARGS_START];
Ted Kremenek77ed8e42007-08-24 18:13:47 +0000712 SubExprs[FN] = fn;
Douglas Gregorbebbe0d2010-12-15 01:34:56 +0000713 for (unsigned i = 0; i != numargs; ++i) {
714 if (args[i]->isTypeDependent())
715 ExprBits.TypeDependent = true;
716 if (args[i]->isValueDependent())
717 ExprBits.ValueDependent = true;
718 if (args[i]->containsUnexpandedParameterPack())
719 ExprBits.ContainsUnexpandedParameterPack = true;
720
Peter Collingbournecc324ad2011-02-08 21:18:02 +0000721 SubExprs[i+PREARGS_START] = args[i];
Douglas Gregorbebbe0d2010-12-15 01:34:56 +0000722 }
Ted Kremenek668bf912009-02-09 20:51:47 +0000723
Peter Collingbournecc324ad2011-02-08 21:18:02 +0000724 CallExprBits.NumPreArgs = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +0000725 RParenLoc = rparenloc;
726}
727
Mike Stump1eb44332009-09-09 15:08:12 +0000728CallExpr::CallExpr(ASTContext &C, StmtClass SC, EmptyShell Empty)
729 : Expr(SC, Empty), SubExprs(0), NumArgs(0) {
Douglas Gregorbebbe0d2010-12-15 01:34:56 +0000730 // FIXME: Why do we allocate this?
Peter Collingbournecc324ad2011-02-08 21:18:02 +0000731 SubExprs = new (C) Stmt*[PREARGS_START];
732 CallExprBits.NumPreArgs = 0;
733}
734
735CallExpr::CallExpr(ASTContext &C, StmtClass SC, unsigned NumPreArgs,
736 EmptyShell Empty)
737 : Expr(SC, Empty), SubExprs(0), NumArgs(0) {
738 // FIXME: Why do we allocate this?
739 SubExprs = new (C) Stmt*[PREARGS_START+NumPreArgs];
740 CallExprBits.NumPreArgs = NumPreArgs;
Douglas Gregor1f0d0132009-04-15 17:43:59 +0000741}
742
Nuno Lopesd20254f2009-12-20 23:11:08 +0000743Decl *CallExpr::getCalleeDecl() {
Zhongxing Xua0042542009-07-17 07:29:51 +0000744 Expr *CEE = getCallee()->IgnoreParenCasts();
Sebastian Redl20012152010-09-10 20:55:30 +0000745 // If we're calling a dereference, look at the pointer instead.
746 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CEE)) {
747 if (BO->isPtrMemOp())
748 CEE = BO->getRHS()->IgnoreParenCasts();
749 } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(CEE)) {
750 if (UO->getOpcode() == UO_Deref)
751 CEE = UO->getSubExpr()->IgnoreParenCasts();
752 }
Chris Lattner6346f962009-07-17 15:46:27 +0000753 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CEE))
Nuno Lopesd20254f2009-12-20 23:11:08 +0000754 return DRE->getDecl();
Nuno Lopescb1c77f2009-12-24 00:28:18 +0000755 if (MemberExpr *ME = dyn_cast<MemberExpr>(CEE))
756 return ME->getMemberDecl();
Zhongxing Xua0042542009-07-17 07:29:51 +0000757
758 return 0;
759}
760
Nuno Lopesd20254f2009-12-20 23:11:08 +0000761FunctionDecl *CallExpr::getDirectCallee() {
Chris Lattnercaabf9b2009-12-21 01:10:56 +0000762 return dyn_cast_or_null<FunctionDecl>(getCalleeDecl());
Nuno Lopesd20254f2009-12-20 23:11:08 +0000763}
764
Chris Lattnerd18b3292007-12-28 05:25:02 +0000765/// setNumArgs - This changes the number of arguments present in this call.
766/// Any orphaned expressions are deleted by this, and any new operands are set
767/// to null.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000768void CallExpr::setNumArgs(ASTContext& C, unsigned NumArgs) {
Chris Lattnerd18b3292007-12-28 05:25:02 +0000769 // No change, just return.
770 if (NumArgs == getNumArgs()) return;
Mike Stump1eb44332009-09-09 15:08:12 +0000771
Chris Lattnerd18b3292007-12-28 05:25:02 +0000772 // If shrinking # arguments, just delete the extras and forgot them.
773 if (NumArgs < getNumArgs()) {
Chris Lattnerd18b3292007-12-28 05:25:02 +0000774 this->NumArgs = NumArgs;
775 return;
776 }
777
778 // Otherwise, we are growing the # arguments. New an bigger argument array.
Peter Collingbournecc324ad2011-02-08 21:18:02 +0000779 unsigned NumPreArgs = getNumPreArgs();
780 Stmt **NewSubExprs = new (C) Stmt*[NumArgs+PREARGS_START+NumPreArgs];
Chris Lattnerd18b3292007-12-28 05:25:02 +0000781 // Copy over args.
Peter Collingbournecc324ad2011-02-08 21:18:02 +0000782 for (unsigned i = 0; i != getNumArgs()+PREARGS_START+NumPreArgs; ++i)
Chris Lattnerd18b3292007-12-28 05:25:02 +0000783 NewSubExprs[i] = SubExprs[i];
784 // Null out new args.
Peter Collingbournecc324ad2011-02-08 21:18:02 +0000785 for (unsigned i = getNumArgs()+PREARGS_START+NumPreArgs;
786 i != NumArgs+PREARGS_START+NumPreArgs; ++i)
Chris Lattnerd18b3292007-12-28 05:25:02 +0000787 NewSubExprs[i] = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000788
Douglas Gregor88c9a462009-04-17 21:46:47 +0000789 if (SubExprs) C.Deallocate(SubExprs);
Chris Lattnerd18b3292007-12-28 05:25:02 +0000790 SubExprs = NewSubExprs;
791 this->NumArgs = NumArgs;
792}
793
Chris Lattnercb888962008-10-06 05:00:53 +0000794/// isBuiltinCall - If this is a call to a builtin, return the builtin ID. If
795/// not, return 0.
Jay Foad4ba2a172011-01-12 09:06:06 +0000796unsigned CallExpr::isBuiltinCall(const ASTContext &Context) const {
Steve Naroffc4f8e8b2008-01-31 01:07:12 +0000797 // All simple function calls (e.g. func()) are implicitly cast to pointer to
Mike Stump1eb44332009-09-09 15:08:12 +0000798 // function. As a result, we try and obtain the DeclRefExpr from the
Steve Naroffc4f8e8b2008-01-31 01:07:12 +0000799 // ImplicitCastExpr.
800 const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(getCallee());
801 if (!ICE) // FIXME: deal with more complex calls (e.g. (func)(), (*func)()).
Chris Lattnercb888962008-10-06 05:00:53 +0000802 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000803
Steve Naroffc4f8e8b2008-01-31 01:07:12 +0000804 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr());
805 if (!DRE)
Chris Lattnercb888962008-10-06 05:00:53 +0000806 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000807
Anders Carlssonbcba2012008-01-31 02:13:57 +0000808 const FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
809 if (!FDecl)
Chris Lattnercb888962008-10-06 05:00:53 +0000810 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000811
Douglas Gregor4fcd3992008-11-21 15:30:19 +0000812 if (!FDecl->getIdentifier())
813 return 0;
814
Douglas Gregor7814e6d2009-09-12 00:22:50 +0000815 return FDecl->getBuiltinID();
Chris Lattnercb888962008-10-06 05:00:53 +0000816}
Anders Carlssonbcba2012008-01-31 02:13:57 +0000817
Anders Carlsson6dde78f2009-05-26 04:57:27 +0000818QualType CallExpr::getCallReturnType() const {
819 QualType CalleeType = getCallee()->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000820 if (const PointerType *FnTypePtr = CalleeType->getAs<PointerType>())
Anders Carlsson6dde78f2009-05-26 04:57:27 +0000821 CalleeType = FnTypePtr->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000822 else if (const BlockPointerType *BPT = CalleeType->getAs<BlockPointerType>())
Anders Carlsson6dde78f2009-05-26 04:57:27 +0000823 CalleeType = BPT->getPointeeType();
Douglas Gregor5291c3c2010-07-13 08:18:22 +0000824 else if (const MemberPointerType *MPT
825 = CalleeType->getAs<MemberPointerType>())
826 CalleeType = MPT->getPointeeType();
827
John McCall183700f2009-09-21 23:43:11 +0000828 const FunctionType *FnType = CalleeType->getAs<FunctionType>();
Anders Carlsson6dde78f2009-05-26 04:57:27 +0000829 return FnType->getResultType();
830}
Chris Lattnercb888962008-10-06 05:00:53 +0000831
John McCall2882eca2011-02-21 06:23:05 +0000832SourceRange CallExpr::getSourceRange() const {
833 if (isa<CXXOperatorCallExpr>(this))
834 return cast<CXXOperatorCallExpr>(this)->getSourceRange();
835
836 SourceLocation begin = getCallee()->getLocStart();
837 if (begin.isInvalid() && getNumArgs() > 0)
838 begin = getArg(0)->getLocStart();
839 SourceLocation end = getRParenLoc();
840 if (end.isInvalid() && getNumArgs() > 0)
841 end = getArg(getNumArgs() - 1)->getLocEnd();
842 return SourceRange(begin, end);
843}
844
Sean Huntc3021132010-05-05 15:23:54 +0000845OffsetOfExpr *OffsetOfExpr::Create(ASTContext &C, QualType type,
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000846 SourceLocation OperatorLoc,
Sean Huntc3021132010-05-05 15:23:54 +0000847 TypeSourceInfo *tsi,
848 OffsetOfNode* compsPtr, unsigned numComps,
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000849 Expr** exprsPtr, unsigned numExprs,
850 SourceLocation RParenLoc) {
851 void *Mem = C.Allocate(sizeof(OffsetOfExpr) +
Sean Huntc3021132010-05-05 15:23:54 +0000852 sizeof(OffsetOfNode) * numComps +
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000853 sizeof(Expr*) * numExprs);
854
855 return new (Mem) OffsetOfExpr(C, type, OperatorLoc, tsi, compsPtr, numComps,
856 exprsPtr, numExprs, RParenLoc);
857}
858
859OffsetOfExpr *OffsetOfExpr::CreateEmpty(ASTContext &C,
860 unsigned numComps, unsigned numExprs) {
861 void *Mem = C.Allocate(sizeof(OffsetOfExpr) +
862 sizeof(OffsetOfNode) * numComps +
863 sizeof(Expr*) * numExprs);
864 return new (Mem) OffsetOfExpr(numComps, numExprs);
865}
866
Sean Huntc3021132010-05-05 15:23:54 +0000867OffsetOfExpr::OffsetOfExpr(ASTContext &C, QualType type,
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000868 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
Sean Huntc3021132010-05-05 15:23:54 +0000869 OffsetOfNode* compsPtr, unsigned numComps,
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000870 Expr** exprsPtr, unsigned numExprs,
871 SourceLocation RParenLoc)
John McCallf89e55a2010-11-18 06:31:45 +0000872 : Expr(OffsetOfExprClass, type, VK_RValue, OK_Ordinary,
873 /*TypeDependent=*/false,
Douglas Gregorbebbe0d2010-12-15 01:34:56 +0000874 /*ValueDependent=*/tsi->getType()->isDependentType(),
875 tsi->getType()->containsUnexpandedParameterPack()),
Sean Huntc3021132010-05-05 15:23:54 +0000876 OperatorLoc(OperatorLoc), RParenLoc(RParenLoc), TSInfo(tsi),
877 NumComps(numComps), NumExprs(numExprs)
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000878{
879 for(unsigned i = 0; i < numComps; ++i) {
880 setComponent(i, compsPtr[i]);
881 }
Sean Huntc3021132010-05-05 15:23:54 +0000882
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000883 for(unsigned i = 0; i < numExprs; ++i) {
Douglas Gregorbebbe0d2010-12-15 01:34:56 +0000884 if (exprsPtr[i]->isTypeDependent() || exprsPtr[i]->isValueDependent())
885 ExprBits.ValueDependent = true;
886 if (exprsPtr[i]->containsUnexpandedParameterPack())
887 ExprBits.ContainsUnexpandedParameterPack = true;
888
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000889 setIndexExpr(i, exprsPtr[i]);
890 }
891}
892
893IdentifierInfo *OffsetOfExpr::OffsetOfNode::getFieldName() const {
894 assert(getKind() == Field || getKind() == Identifier);
895 if (getKind() == Field)
896 return getField()->getIdentifier();
Sean Huntc3021132010-05-05 15:23:54 +0000897
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000898 return reinterpret_cast<IdentifierInfo *> (Data & ~(uintptr_t)Mask);
899}
900
Mike Stump1eb44332009-09-09 15:08:12 +0000901MemberExpr *MemberExpr::Create(ASTContext &C, Expr *base, bool isarrow,
Douglas Gregor40d96a62011-02-28 21:54:11 +0000902 NestedNameSpecifierLoc QualifierLoc,
Eli Friedmanf595cc42009-12-04 06:40:45 +0000903 ValueDecl *memberdecl,
John McCall161755a2010-04-06 21:38:20 +0000904 DeclAccessPair founddecl,
Abramo Bagnara25777432010-08-11 22:01:17 +0000905 DeclarationNameInfo nameinfo,
John McCalld5532b62009-11-23 01:53:49 +0000906 const TemplateArgumentListInfo *targs,
John McCallf89e55a2010-11-18 06:31:45 +0000907 QualType ty,
908 ExprValueKind vk,
909 ExprObjectKind ok) {
Douglas Gregor83f6faf2009-08-31 23:41:50 +0000910 std::size_t Size = sizeof(MemberExpr);
John McCall6bb80172010-03-30 21:47:33 +0000911
Douglas Gregor40d96a62011-02-28 21:54:11 +0000912 bool hasQualOrFound = (QualifierLoc ||
John McCall161755a2010-04-06 21:38:20 +0000913 founddecl.getDecl() != memberdecl ||
914 founddecl.getAccess() != memberdecl->getAccess());
John McCall6bb80172010-03-30 21:47:33 +0000915 if (hasQualOrFound)
916 Size += sizeof(MemberNameQualifier);
Mike Stump1eb44332009-09-09 15:08:12 +0000917
John McCalld5532b62009-11-23 01:53:49 +0000918 if (targs)
919 Size += ExplicitTemplateArgumentList::sizeFor(*targs);
Mike Stump1eb44332009-09-09 15:08:12 +0000920
Chris Lattner32488542010-10-30 05:14:06 +0000921 void *Mem = C.Allocate(Size, llvm::alignOf<MemberExpr>());
John McCallf89e55a2010-11-18 06:31:45 +0000922 MemberExpr *E = new (Mem) MemberExpr(base, isarrow, memberdecl, nameinfo,
923 ty, vk, ok);
John McCall6bb80172010-03-30 21:47:33 +0000924
925 if (hasQualOrFound) {
Douglas Gregor40d96a62011-02-28 21:54:11 +0000926 // FIXME: Wrong. We should be looking at the member declaration we found.
927 if (QualifierLoc && QualifierLoc.getNestedNameSpecifier()->isDependent()) {
John McCall6bb80172010-03-30 21:47:33 +0000928 E->setValueDependent(true);
929 E->setTypeDependent(true);
930 }
931 E->HasQualifierOrFoundDecl = true;
932
933 MemberNameQualifier *NQ = E->getMemberQualifier();
Douglas Gregor40d96a62011-02-28 21:54:11 +0000934 NQ->QualifierLoc = QualifierLoc;
John McCall6bb80172010-03-30 21:47:33 +0000935 NQ->FoundDecl = founddecl;
936 }
937
938 if (targs) {
939 E->HasExplicitTemplateArgumentList = true;
John McCall096832c2010-08-19 23:49:38 +0000940 E->getExplicitTemplateArgs().initializeFrom(*targs);
John McCall6bb80172010-03-30 21:47:33 +0000941 }
942
943 return E;
Douglas Gregor83f6faf2009-08-31 23:41:50 +0000944}
945
Douglas Gregor75e85042011-03-02 21:06:53 +0000946SourceRange MemberExpr::getSourceRange() const {
947 SourceLocation StartLoc;
948 if (isImplicitAccess()) {
949 if (hasQualifier())
950 StartLoc = getQualifierLoc().getBeginLoc();
951 else
952 StartLoc = MemberLoc;
953 } else {
954 // FIXME: We don't want this to happen. Rather, we should be able to
955 // detect all kinds of implicit accesses more cleanly.
956 StartLoc = getBase()->getLocStart();
957 if (StartLoc.isInvalid())
958 StartLoc = MemberLoc;
959 }
960
961 SourceLocation EndLoc =
962 HasExplicitTemplateArgumentList? getRAngleLoc()
963 : getMemberNameInfo().getEndLoc();
964
965 return SourceRange(StartLoc, EndLoc);
966}
967
Anders Carlssonf8ec55a2009-09-03 00:59:21 +0000968const char *CastExpr::getCastKindName() const {
969 switch (getCastKind()) {
John McCalldaa8e4e2010-11-15 09:13:47 +0000970 case CK_Dependent:
971 return "Dependent";
John McCall2de56d12010-08-25 11:45:40 +0000972 case CK_BitCast:
Anders Carlssonf8ec55a2009-09-03 00:59:21 +0000973 return "BitCast";
John McCall2de56d12010-08-25 11:45:40 +0000974 case CK_LValueBitCast:
Douglas Gregore39a3892010-07-13 23:17:26 +0000975 return "LValueBitCast";
John McCall0ae287a2010-12-01 04:43:34 +0000976 case CK_LValueToRValue:
977 return "LValueToRValue";
John McCallf6a16482010-12-04 03:47:34 +0000978 case CK_GetObjCProperty:
979 return "GetObjCProperty";
John McCall2de56d12010-08-25 11:45:40 +0000980 case CK_NoOp:
Anders Carlssonf8ec55a2009-09-03 00:59:21 +0000981 return "NoOp";
John McCall2de56d12010-08-25 11:45:40 +0000982 case CK_BaseToDerived:
Anders Carlsson11de6de2009-11-12 16:43:42 +0000983 return "BaseToDerived";
John McCall2de56d12010-08-25 11:45:40 +0000984 case CK_DerivedToBase:
Anders Carlssonf8ec55a2009-09-03 00:59:21 +0000985 return "DerivedToBase";
John McCall2de56d12010-08-25 11:45:40 +0000986 case CK_UncheckedDerivedToBase:
John McCall23cba802010-03-30 23:58:03 +0000987 return "UncheckedDerivedToBase";
John McCall2de56d12010-08-25 11:45:40 +0000988 case CK_Dynamic:
Anders Carlssonf8ec55a2009-09-03 00:59:21 +0000989 return "Dynamic";
John McCall2de56d12010-08-25 11:45:40 +0000990 case CK_ToUnion:
Anders Carlssonf8ec55a2009-09-03 00:59:21 +0000991 return "ToUnion";
John McCall2de56d12010-08-25 11:45:40 +0000992 case CK_ArrayToPointerDecay:
Anders Carlssonf8ec55a2009-09-03 00:59:21 +0000993 return "ArrayToPointerDecay";
John McCall2de56d12010-08-25 11:45:40 +0000994 case CK_FunctionToPointerDecay:
Anders Carlssonf8ec55a2009-09-03 00:59:21 +0000995 return "FunctionToPointerDecay";
John McCall2de56d12010-08-25 11:45:40 +0000996 case CK_NullToMemberPointer:
Anders Carlssonf8ec55a2009-09-03 00:59:21 +0000997 return "NullToMemberPointer";
John McCall404cd162010-11-13 01:35:44 +0000998 case CK_NullToPointer:
999 return "NullToPointer";
John McCall2de56d12010-08-25 11:45:40 +00001000 case CK_BaseToDerivedMemberPointer:
Anders Carlssonf8ec55a2009-09-03 00:59:21 +00001001 return "BaseToDerivedMemberPointer";
John McCall2de56d12010-08-25 11:45:40 +00001002 case CK_DerivedToBaseMemberPointer:
Anders Carlsson1a31a182009-10-30 00:46:35 +00001003 return "DerivedToBaseMemberPointer";
John McCall2de56d12010-08-25 11:45:40 +00001004 case CK_UserDefinedConversion:
Anders Carlssonf8ec55a2009-09-03 00:59:21 +00001005 return "UserDefinedConversion";
John McCall2de56d12010-08-25 11:45:40 +00001006 case CK_ConstructorConversion:
Anders Carlssonf8ec55a2009-09-03 00:59:21 +00001007 return "ConstructorConversion";
John McCall2de56d12010-08-25 11:45:40 +00001008 case CK_IntegralToPointer:
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001009 return "IntegralToPointer";
John McCall2de56d12010-08-25 11:45:40 +00001010 case CK_PointerToIntegral:
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001011 return "PointerToIntegral";
John McCalldaa8e4e2010-11-15 09:13:47 +00001012 case CK_PointerToBoolean:
1013 return "PointerToBoolean";
John McCall2de56d12010-08-25 11:45:40 +00001014 case CK_ToVoid:
Anders Carlssonebeaf202009-10-16 02:35:04 +00001015 return "ToVoid";
John McCall2de56d12010-08-25 11:45:40 +00001016 case CK_VectorSplat:
Anders Carlsson16a89042009-10-16 05:23:41 +00001017 return "VectorSplat";
John McCall2de56d12010-08-25 11:45:40 +00001018 case CK_IntegralCast:
Anders Carlsson82debc72009-10-18 18:12:03 +00001019 return "IntegralCast";
John McCalldaa8e4e2010-11-15 09:13:47 +00001020 case CK_IntegralToBoolean:
1021 return "IntegralToBoolean";
John McCall2de56d12010-08-25 11:45:40 +00001022 case CK_IntegralToFloating:
Anders Carlsson82debc72009-10-18 18:12:03 +00001023 return "IntegralToFloating";
John McCall2de56d12010-08-25 11:45:40 +00001024 case CK_FloatingToIntegral:
Anders Carlsson82debc72009-10-18 18:12:03 +00001025 return "FloatingToIntegral";
John McCall2de56d12010-08-25 11:45:40 +00001026 case CK_FloatingCast:
Benjamin Kramerc6b29162009-10-18 19:02:15 +00001027 return "FloatingCast";
John McCalldaa8e4e2010-11-15 09:13:47 +00001028 case CK_FloatingToBoolean:
1029 return "FloatingToBoolean";
John McCall2de56d12010-08-25 11:45:40 +00001030 case CK_MemberPointerToBoolean:
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001031 return "MemberPointerToBoolean";
John McCall2de56d12010-08-25 11:45:40 +00001032 case CK_AnyPointerToObjCPointerCast:
Fariborz Jahanian4cbf9d42009-12-08 23:46:15 +00001033 return "AnyPointerToObjCPointerCast";
John McCall2de56d12010-08-25 11:45:40 +00001034 case CK_AnyPointerToBlockPointerCast:
Fariborz Jahanian3b27f1a2009-12-11 22:40:48 +00001035 return "AnyPointerToBlockPointerCast";
John McCall2de56d12010-08-25 11:45:40 +00001036 case CK_ObjCObjectLValueCast:
Douglas Gregor569c3162010-08-07 11:51:51 +00001037 return "ObjCObjectLValueCast";
John McCall2bb5d002010-11-13 09:02:35 +00001038 case CK_FloatingRealToComplex:
1039 return "FloatingRealToComplex";
John McCallf3ea8cf2010-11-14 08:17:51 +00001040 case CK_FloatingComplexToReal:
1041 return "FloatingComplexToReal";
1042 case CK_FloatingComplexToBoolean:
1043 return "FloatingComplexToBoolean";
John McCall2bb5d002010-11-13 09:02:35 +00001044 case CK_FloatingComplexCast:
1045 return "FloatingComplexCast";
John McCallf3ea8cf2010-11-14 08:17:51 +00001046 case CK_FloatingComplexToIntegralComplex:
1047 return "FloatingComplexToIntegralComplex";
John McCall2bb5d002010-11-13 09:02:35 +00001048 case CK_IntegralRealToComplex:
1049 return "IntegralRealToComplex";
John McCallf3ea8cf2010-11-14 08:17:51 +00001050 case CK_IntegralComplexToReal:
1051 return "IntegralComplexToReal";
1052 case CK_IntegralComplexToBoolean:
1053 return "IntegralComplexToBoolean";
John McCall2bb5d002010-11-13 09:02:35 +00001054 case CK_IntegralComplexCast:
1055 return "IntegralComplexCast";
John McCallf3ea8cf2010-11-14 08:17:51 +00001056 case CK_IntegralComplexToFloatingComplex:
1057 return "IntegralComplexToFloatingComplex";
Anders Carlssonf8ec55a2009-09-03 00:59:21 +00001058 }
Mike Stump1eb44332009-09-09 15:08:12 +00001059
John McCall2bb5d002010-11-13 09:02:35 +00001060 llvm_unreachable("Unhandled cast kind!");
Anders Carlssonf8ec55a2009-09-03 00:59:21 +00001061 return 0;
1062}
1063
Douglas Gregor6eef5192009-12-14 19:27:10 +00001064Expr *CastExpr::getSubExprAsWritten() {
1065 Expr *SubExpr = 0;
1066 CastExpr *E = this;
1067 do {
1068 SubExpr = E->getSubExpr();
Sean Huntc3021132010-05-05 15:23:54 +00001069
Douglas Gregor6eef5192009-12-14 19:27:10 +00001070 // Skip any temporary bindings; they're implicit.
1071 if (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(SubExpr))
1072 SubExpr = Binder->getSubExpr();
Sean Huntc3021132010-05-05 15:23:54 +00001073
Douglas Gregor6eef5192009-12-14 19:27:10 +00001074 // Conversions by constructor and conversion functions have a
1075 // subexpression describing the call; strip it off.
John McCall2de56d12010-08-25 11:45:40 +00001076 if (E->getCastKind() == CK_ConstructorConversion)
Douglas Gregor6eef5192009-12-14 19:27:10 +00001077 SubExpr = cast<CXXConstructExpr>(SubExpr)->getArg(0);
John McCall2de56d12010-08-25 11:45:40 +00001078 else if (E->getCastKind() == CK_UserDefinedConversion)
Douglas Gregor6eef5192009-12-14 19:27:10 +00001079 SubExpr = cast<CXXMemberCallExpr>(SubExpr)->getImplicitObjectArgument();
Sean Huntc3021132010-05-05 15:23:54 +00001080
Douglas Gregor6eef5192009-12-14 19:27:10 +00001081 // If the subexpression we're left with is an implicit cast, look
1082 // through that, too.
Sean Huntc3021132010-05-05 15:23:54 +00001083 } while ((E = dyn_cast<ImplicitCastExpr>(SubExpr)));
1084
Douglas Gregor6eef5192009-12-14 19:27:10 +00001085 return SubExpr;
1086}
1087
John McCallf871d0c2010-08-07 06:22:56 +00001088CXXBaseSpecifier **CastExpr::path_buffer() {
1089 switch (getStmtClass()) {
1090#define ABSTRACT_STMT(x)
1091#define CASTEXPR(Type, Base) \
1092 case Stmt::Type##Class: \
1093 return reinterpret_cast<CXXBaseSpecifier**>(static_cast<Type*>(this)+1);
1094#define STMT(Type, Base)
1095#include "clang/AST/StmtNodes.inc"
1096 default:
1097 llvm_unreachable("non-cast expressions not possible here");
1098 return 0;
1099 }
1100}
1101
1102void CastExpr::setCastPath(const CXXCastPath &Path) {
1103 assert(Path.size() == path_size());
1104 memcpy(path_buffer(), Path.data(), Path.size() * sizeof(CXXBaseSpecifier*));
1105}
1106
1107ImplicitCastExpr *ImplicitCastExpr::Create(ASTContext &C, QualType T,
1108 CastKind Kind, Expr *Operand,
1109 const CXXCastPath *BasePath,
John McCall5baba9d2010-08-25 10:28:54 +00001110 ExprValueKind VK) {
John McCallf871d0c2010-08-07 06:22:56 +00001111 unsigned PathSize = (BasePath ? BasePath->size() : 0);
1112 void *Buffer =
1113 C.Allocate(sizeof(ImplicitCastExpr) + PathSize * sizeof(CXXBaseSpecifier*));
1114 ImplicitCastExpr *E =
John McCall5baba9d2010-08-25 10:28:54 +00001115 new (Buffer) ImplicitCastExpr(T, Kind, Operand, PathSize, VK);
John McCallf871d0c2010-08-07 06:22:56 +00001116 if (PathSize) E->setCastPath(*BasePath);
1117 return E;
1118}
1119
1120ImplicitCastExpr *ImplicitCastExpr::CreateEmpty(ASTContext &C,
1121 unsigned PathSize) {
1122 void *Buffer =
1123 C.Allocate(sizeof(ImplicitCastExpr) + PathSize * sizeof(CXXBaseSpecifier*));
1124 return new (Buffer) ImplicitCastExpr(EmptyShell(), PathSize);
1125}
1126
1127
1128CStyleCastExpr *CStyleCastExpr::Create(ASTContext &C, QualType T,
John McCallf89e55a2010-11-18 06:31:45 +00001129 ExprValueKind VK, CastKind K, Expr *Op,
John McCallf871d0c2010-08-07 06:22:56 +00001130 const CXXCastPath *BasePath,
1131 TypeSourceInfo *WrittenTy,
1132 SourceLocation L, SourceLocation R) {
1133 unsigned PathSize = (BasePath ? BasePath->size() : 0);
1134 void *Buffer =
1135 C.Allocate(sizeof(CStyleCastExpr) + PathSize * sizeof(CXXBaseSpecifier*));
1136 CStyleCastExpr *E =
John McCallf89e55a2010-11-18 06:31:45 +00001137 new (Buffer) CStyleCastExpr(T, VK, K, Op, PathSize, WrittenTy, L, R);
John McCallf871d0c2010-08-07 06:22:56 +00001138 if (PathSize) E->setCastPath(*BasePath);
1139 return E;
1140}
1141
1142CStyleCastExpr *CStyleCastExpr::CreateEmpty(ASTContext &C, unsigned PathSize) {
1143 void *Buffer =
1144 C.Allocate(sizeof(CStyleCastExpr) + PathSize * sizeof(CXXBaseSpecifier*));
1145 return new (Buffer) CStyleCastExpr(EmptyShell(), PathSize);
1146}
1147
Reid Spencer5f016e22007-07-11 17:01:13 +00001148/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1149/// corresponds to, e.g. "<<=".
1150const char *BinaryOperator::getOpcodeStr(Opcode Op) {
1151 switch (Op) {
John McCall2de56d12010-08-25 11:45:40 +00001152 case BO_PtrMemD: return ".*";
1153 case BO_PtrMemI: return "->*";
1154 case BO_Mul: return "*";
1155 case BO_Div: return "/";
1156 case BO_Rem: return "%";
1157 case BO_Add: return "+";
1158 case BO_Sub: return "-";
1159 case BO_Shl: return "<<";
1160 case BO_Shr: return ">>";
1161 case BO_LT: return "<";
1162 case BO_GT: return ">";
1163 case BO_LE: return "<=";
1164 case BO_GE: return ">=";
1165 case BO_EQ: return "==";
1166 case BO_NE: return "!=";
1167 case BO_And: return "&";
1168 case BO_Xor: return "^";
1169 case BO_Or: return "|";
1170 case BO_LAnd: return "&&";
1171 case BO_LOr: return "||";
1172 case BO_Assign: return "=";
1173 case BO_MulAssign: return "*=";
1174 case BO_DivAssign: return "/=";
1175 case BO_RemAssign: return "%=";
1176 case BO_AddAssign: return "+=";
1177 case BO_SubAssign: return "-=";
1178 case BO_ShlAssign: return "<<=";
1179 case BO_ShrAssign: return ">>=";
1180 case BO_AndAssign: return "&=";
1181 case BO_XorAssign: return "^=";
1182 case BO_OrAssign: return "|=";
1183 case BO_Comma: return ",";
Reid Spencer5f016e22007-07-11 17:01:13 +00001184 }
Douglas Gregorbaf53482009-03-12 22:51:37 +00001185
1186 return "";
Reid Spencer5f016e22007-07-11 17:01:13 +00001187}
1188
John McCall2de56d12010-08-25 11:45:40 +00001189BinaryOperatorKind
Douglas Gregor063daf62009-03-13 18:40:31 +00001190BinaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO) {
1191 switch (OO) {
Chris Lattnerb7beee92009-03-22 00:10:22 +00001192 default: assert(false && "Not an overloadable binary operator");
John McCall2de56d12010-08-25 11:45:40 +00001193 case OO_Plus: return BO_Add;
1194 case OO_Minus: return BO_Sub;
1195 case OO_Star: return BO_Mul;
1196 case OO_Slash: return BO_Div;
1197 case OO_Percent: return BO_Rem;
1198 case OO_Caret: return BO_Xor;
1199 case OO_Amp: return BO_And;
1200 case OO_Pipe: return BO_Or;
1201 case OO_Equal: return BO_Assign;
1202 case OO_Less: return BO_LT;
1203 case OO_Greater: return BO_GT;
1204 case OO_PlusEqual: return BO_AddAssign;
1205 case OO_MinusEqual: return BO_SubAssign;
1206 case OO_StarEqual: return BO_MulAssign;
1207 case OO_SlashEqual: return BO_DivAssign;
1208 case OO_PercentEqual: return BO_RemAssign;
1209 case OO_CaretEqual: return BO_XorAssign;
1210 case OO_AmpEqual: return BO_AndAssign;
1211 case OO_PipeEqual: return BO_OrAssign;
1212 case OO_LessLess: return BO_Shl;
1213 case OO_GreaterGreater: return BO_Shr;
1214 case OO_LessLessEqual: return BO_ShlAssign;
1215 case OO_GreaterGreaterEqual: return BO_ShrAssign;
1216 case OO_EqualEqual: return BO_EQ;
1217 case OO_ExclaimEqual: return BO_NE;
1218 case OO_LessEqual: return BO_LE;
1219 case OO_GreaterEqual: return BO_GE;
1220 case OO_AmpAmp: return BO_LAnd;
1221 case OO_PipePipe: return BO_LOr;
1222 case OO_Comma: return BO_Comma;
1223 case OO_ArrowStar: return BO_PtrMemI;
Douglas Gregor063daf62009-03-13 18:40:31 +00001224 }
1225}
1226
1227OverloadedOperatorKind BinaryOperator::getOverloadedOperator(Opcode Opc) {
1228 static const OverloadedOperatorKind OverOps[] = {
1229 /* .* Cannot be overloaded */OO_None, OO_ArrowStar,
1230 OO_Star, OO_Slash, OO_Percent,
1231 OO_Plus, OO_Minus,
1232 OO_LessLess, OO_GreaterGreater,
1233 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
1234 OO_EqualEqual, OO_ExclaimEqual,
1235 OO_Amp,
1236 OO_Caret,
1237 OO_Pipe,
1238 OO_AmpAmp,
1239 OO_PipePipe,
1240 OO_Equal, OO_StarEqual,
1241 OO_SlashEqual, OO_PercentEqual,
1242 OO_PlusEqual, OO_MinusEqual,
1243 OO_LessLessEqual, OO_GreaterGreaterEqual,
1244 OO_AmpEqual, OO_CaretEqual,
1245 OO_PipeEqual,
1246 OO_Comma
1247 };
1248 return OverOps[Opc];
1249}
1250
Ted Kremenek709210f2010-04-13 23:39:13 +00001251InitListExpr::InitListExpr(ASTContext &C, SourceLocation lbraceloc,
Chris Lattner418f6c72008-10-26 23:43:26 +00001252 Expr **initExprs, unsigned numInits,
Douglas Gregor4c678342009-01-28 21:54:33 +00001253 SourceLocation rbraceloc)
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00001254 : Expr(InitListExprClass, QualType(), VK_RValue, OK_Ordinary, false, false,
1255 false),
Ted Kremenek709210f2010-04-13 23:39:13 +00001256 InitExprs(C, numInits),
Mike Stump1eb44332009-09-09 15:08:12 +00001257 LBraceLoc(lbraceloc), RBraceLoc(rbraceloc), SyntacticForm(0),
Sean Huntc3021132010-05-05 15:23:54 +00001258 UnionFieldInit(0), HadArrayRangeDesignator(false)
1259{
Ted Kremenekba7bc552010-02-19 01:50:18 +00001260 for (unsigned I = 0; I != numInits; ++I) {
1261 if (initExprs[I]->isTypeDependent())
John McCall8e6285a2010-10-26 08:39:16 +00001262 ExprBits.TypeDependent = true;
Ted Kremenekba7bc552010-02-19 01:50:18 +00001263 if (initExprs[I]->isValueDependent())
John McCall8e6285a2010-10-26 08:39:16 +00001264 ExprBits.ValueDependent = true;
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00001265 if (initExprs[I]->containsUnexpandedParameterPack())
1266 ExprBits.ContainsUnexpandedParameterPack = true;
Douglas Gregor73460a32009-11-19 23:25:22 +00001267 }
Sean Huntc3021132010-05-05 15:23:54 +00001268
Ted Kremenek709210f2010-04-13 23:39:13 +00001269 InitExprs.insert(C, InitExprs.end(), initExprs, initExprs+numInits);
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00001270}
Reid Spencer5f016e22007-07-11 17:01:13 +00001271
Ted Kremenek709210f2010-04-13 23:39:13 +00001272void InitListExpr::reserveInits(ASTContext &C, unsigned NumInits) {
Ted Kremenekba7bc552010-02-19 01:50:18 +00001273 if (NumInits > InitExprs.size())
Ted Kremenek709210f2010-04-13 23:39:13 +00001274 InitExprs.reserve(C, NumInits);
Douglas Gregorfa219202009-03-20 23:58:33 +00001275}
1276
Ted Kremenek709210f2010-04-13 23:39:13 +00001277void InitListExpr::resizeInits(ASTContext &C, unsigned NumInits) {
Ted Kremenek709210f2010-04-13 23:39:13 +00001278 InitExprs.resize(C, NumInits, 0);
Douglas Gregor4c678342009-01-28 21:54:33 +00001279}
1280
Ted Kremenek709210f2010-04-13 23:39:13 +00001281Expr *InitListExpr::updateInit(ASTContext &C, unsigned Init, Expr *expr) {
Ted Kremenekba7bc552010-02-19 01:50:18 +00001282 if (Init >= InitExprs.size()) {
Ted Kremenek709210f2010-04-13 23:39:13 +00001283 InitExprs.insert(C, InitExprs.end(), Init - InitExprs.size() + 1, 0);
Ted Kremenekba7bc552010-02-19 01:50:18 +00001284 InitExprs.back() = expr;
1285 return 0;
Douglas Gregor4c678342009-01-28 21:54:33 +00001286 }
Mike Stump1eb44332009-09-09 15:08:12 +00001287
Douglas Gregor4c678342009-01-28 21:54:33 +00001288 Expr *Result = cast_or_null<Expr>(InitExprs[Init]);
1289 InitExprs[Init] = expr;
1290 return Result;
1291}
1292
Ted Kremenekc4ba51f2010-11-09 02:11:40 +00001293SourceRange InitListExpr::getSourceRange() const {
1294 if (SyntacticForm)
1295 return SyntacticForm->getSourceRange();
1296 SourceLocation Beg = LBraceLoc, End = RBraceLoc;
1297 if (Beg.isInvalid()) {
1298 // Find the first non-null initializer.
1299 for (InitExprsTy::const_iterator I = InitExprs.begin(),
1300 E = InitExprs.end();
1301 I != E; ++I) {
1302 if (Stmt *S = *I) {
1303 Beg = S->getLocStart();
1304 break;
1305 }
1306 }
1307 }
1308 if (End.isInvalid()) {
1309 // Find the first non-null initializer from the end.
1310 for (InitExprsTy::const_reverse_iterator I = InitExprs.rbegin(),
1311 E = InitExprs.rend();
1312 I != E; ++I) {
1313 if (Stmt *S = *I) {
1314 End = S->getSourceRange().getEnd();
1315 break;
1316 }
1317 }
1318 }
1319 return SourceRange(Beg, End);
1320}
1321
Steve Naroffbfdcae62008-09-04 15:31:07 +00001322/// getFunctionType - Return the underlying function type for this block.
Steve Naroff4eb206b2008-09-03 18:15:37 +00001323///
1324const FunctionType *BlockExpr::getFunctionType() const {
Ted Kremenek6217b802009-07-29 21:53:49 +00001325 return getType()->getAs<BlockPointerType>()->
John McCall183700f2009-09-21 23:43:11 +00001326 getPointeeType()->getAs<FunctionType>();
Steve Naroff4eb206b2008-09-03 18:15:37 +00001327}
1328
Mike Stump1eb44332009-09-09 15:08:12 +00001329SourceLocation BlockExpr::getCaretLocation() const {
1330 return TheBlock->getCaretLocation();
Steve Naroff56ee6892008-10-08 17:01:13 +00001331}
Mike Stump1eb44332009-09-09 15:08:12 +00001332const Stmt *BlockExpr::getBody() const {
Douglas Gregor72971342009-04-18 00:02:19 +00001333 return TheBlock->getBody();
1334}
Mike Stump1eb44332009-09-09 15:08:12 +00001335Stmt *BlockExpr::getBody() {
1336 return TheBlock->getBody();
Douglas Gregor72971342009-04-18 00:02:19 +00001337}
Steve Naroff56ee6892008-10-08 17:01:13 +00001338
1339
Reid Spencer5f016e22007-07-11 17:01:13 +00001340//===----------------------------------------------------------------------===//
1341// Generic Expression Routines
1342//===----------------------------------------------------------------------===//
1343
Chris Lattner026dc962009-02-14 07:37:35 +00001344/// isUnusedResultAWarning - Return true if this immediate expression should
1345/// be warned about if the result is unused. If so, fill in Loc and Ranges
1346/// with location to warn on and the source range[s] to report with the
1347/// warning.
1348bool Expr::isUnusedResultAWarning(SourceLocation &Loc, SourceRange &R1,
Mike Stumpdf317bf2009-11-03 23:25:48 +00001349 SourceRange &R2, ASTContext &Ctx) const {
Anders Carlssonffce2df2009-05-15 23:10:19 +00001350 // Don't warn if the expr is type dependent. The type could end up
1351 // instantiating to void.
1352 if (isTypeDependent())
1353 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001354
Reid Spencer5f016e22007-07-11 17:01:13 +00001355 switch (getStmtClass()) {
1356 default:
John McCall0faede62010-03-12 07:11:26 +00001357 if (getType()->isVoidType())
1358 return false;
Chris Lattner026dc962009-02-14 07:37:35 +00001359 Loc = getExprLoc();
1360 R1 = getSourceRange();
1361 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001362 case ParenExprClass:
Chris Lattner026dc962009-02-14 07:37:35 +00001363 return cast<ParenExpr>(this)->getSubExpr()->
Mike Stumpdf317bf2009-11-03 23:25:48 +00001364 isUnusedResultAWarning(Loc, R1, R2, Ctx);
Reid Spencer5f016e22007-07-11 17:01:13 +00001365 case UnaryOperatorClass: {
1366 const UnaryOperator *UO = cast<UnaryOperator>(this);
Mike Stump1eb44332009-09-09 15:08:12 +00001367
Reid Spencer5f016e22007-07-11 17:01:13 +00001368 switch (UO->getOpcode()) {
Chris Lattner026dc962009-02-14 07:37:35 +00001369 default: break;
John McCall2de56d12010-08-25 11:45:40 +00001370 case UO_PostInc:
1371 case UO_PostDec:
1372 case UO_PreInc:
1373 case UO_PreDec: // ++/--
Chris Lattner026dc962009-02-14 07:37:35 +00001374 return false; // Not a warning.
John McCall2de56d12010-08-25 11:45:40 +00001375 case UO_Deref:
Reid Spencer5f016e22007-07-11 17:01:13 +00001376 // Dereferencing a volatile pointer is a side-effect.
Mike Stumpdf317bf2009-11-03 23:25:48 +00001377 if (Ctx.getCanonicalType(getType()).isVolatileQualified())
Chris Lattner026dc962009-02-14 07:37:35 +00001378 return false;
1379 break;
John McCall2de56d12010-08-25 11:45:40 +00001380 case UO_Real:
1381 case UO_Imag:
Reid Spencer5f016e22007-07-11 17:01:13 +00001382 // accessing a piece of a volatile complex is a side-effect.
Mike Stumpdf317bf2009-11-03 23:25:48 +00001383 if (Ctx.getCanonicalType(UO->getSubExpr()->getType())
1384 .isVolatileQualified())
Chris Lattner026dc962009-02-14 07:37:35 +00001385 return false;
1386 break;
John McCall2de56d12010-08-25 11:45:40 +00001387 case UO_Extension:
Mike Stumpdf317bf2009-11-03 23:25:48 +00001388 return UO->getSubExpr()->isUnusedResultAWarning(Loc, R1, R2, Ctx);
Reid Spencer5f016e22007-07-11 17:01:13 +00001389 }
Chris Lattner026dc962009-02-14 07:37:35 +00001390 Loc = UO->getOperatorLoc();
1391 R1 = UO->getSubExpr()->getSourceRange();
1392 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001393 }
Chris Lattnere7716e62007-12-01 06:07:34 +00001394 case BinaryOperatorClass: {
Chris Lattner026dc962009-02-14 07:37:35 +00001395 const BinaryOperator *BO = cast<BinaryOperator>(this);
Ted Kremenekc46a2462010-04-07 18:49:21 +00001396 switch (BO->getOpcode()) {
1397 default:
1398 break;
Argyrios Kyrtzidis25973452010-06-30 10:53:14 +00001399 // Consider the RHS of comma for side effects. LHS was checked by
1400 // Sema::CheckCommaOperands.
John McCall2de56d12010-08-25 11:45:40 +00001401 case BO_Comma:
Ted Kremenekc46a2462010-04-07 18:49:21 +00001402 // ((foo = <blah>), 0) is an idiom for hiding the result (and
1403 // lvalue-ness) of an assignment written in a macro.
1404 if (IntegerLiteral *IE =
1405 dyn_cast<IntegerLiteral>(BO->getRHS()->IgnoreParens()))
1406 if (IE->getValue() == 0)
1407 return false;
Argyrios Kyrtzidis25973452010-06-30 10:53:14 +00001408 return BO->getRHS()->isUnusedResultAWarning(Loc, R1, R2, Ctx);
1409 // Consider '||', '&&' to have side effects if the LHS or RHS does.
John McCall2de56d12010-08-25 11:45:40 +00001410 case BO_LAnd:
1411 case BO_LOr:
Argyrios Kyrtzidis25973452010-06-30 10:53:14 +00001412 if (!BO->getLHS()->isUnusedResultAWarning(Loc, R1, R2, Ctx) ||
1413 !BO->getRHS()->isUnusedResultAWarning(Loc, R1, R2, Ctx))
1414 return false;
1415 break;
John McCallbf0ee352010-02-16 04:10:53 +00001416 }
Chris Lattner026dc962009-02-14 07:37:35 +00001417 if (BO->isAssignmentOp())
1418 return false;
1419 Loc = BO->getOperatorLoc();
1420 R1 = BO->getLHS()->getSourceRange();
1421 R2 = BO->getRHS()->getSourceRange();
1422 return true;
Chris Lattnere7716e62007-12-01 06:07:34 +00001423 }
Chris Lattnereb14fe82007-08-25 02:00:02 +00001424 case CompoundAssignOperatorClass:
Douglas Gregorc6dfe192010-05-08 22:41:50 +00001425 case VAArgExprClass:
Chris Lattner026dc962009-02-14 07:37:35 +00001426 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001427
Fariborz Jahanianab38e4b2007-12-01 19:58:28 +00001428 case ConditionalOperatorClass: {
Ted Kremenekfb7cb352011-03-01 20:34:48 +00001429 // If only one of the LHS or RHS is a warning, the operator might
1430 // be being used for control flow. Only warn if both the LHS and
1431 // RHS are warnings.
Fariborz Jahanianab38e4b2007-12-01 19:58:28 +00001432 const ConditionalOperator *Exp = cast<ConditionalOperator>(this);
Ted Kremenekfb7cb352011-03-01 20:34:48 +00001433 if (!Exp->getRHS()->isUnusedResultAWarning(Loc, R1, R2, Ctx))
1434 return false;
1435 if (!Exp->getLHS())
Chris Lattner026dc962009-02-14 07:37:35 +00001436 return true;
Ted Kremenekfb7cb352011-03-01 20:34:48 +00001437 return Exp->getLHS()->isUnusedResultAWarning(Loc, R1, R2, Ctx);
Fariborz Jahanianab38e4b2007-12-01 19:58:28 +00001438 }
1439
Reid Spencer5f016e22007-07-11 17:01:13 +00001440 case MemberExprClass:
Chris Lattner026dc962009-02-14 07:37:35 +00001441 // If the base pointer or element is to a volatile pointer/field, accessing
1442 // it is a side effect.
Mike Stumpdf317bf2009-11-03 23:25:48 +00001443 if (Ctx.getCanonicalType(getType()).isVolatileQualified())
Chris Lattner026dc962009-02-14 07:37:35 +00001444 return false;
1445 Loc = cast<MemberExpr>(this)->getMemberLoc();
1446 R1 = SourceRange(Loc, Loc);
1447 R2 = cast<MemberExpr>(this)->getBase()->getSourceRange();
1448 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001449
Reid Spencer5f016e22007-07-11 17:01:13 +00001450 case ArraySubscriptExprClass:
1451 // If the base pointer or element is to a volatile pointer/field, accessing
Chris Lattner026dc962009-02-14 07:37:35 +00001452 // it is a side effect.
Mike Stumpdf317bf2009-11-03 23:25:48 +00001453 if (Ctx.getCanonicalType(getType()).isVolatileQualified())
Chris Lattner026dc962009-02-14 07:37:35 +00001454 return false;
1455 Loc = cast<ArraySubscriptExpr>(this)->getRBracketLoc();
1456 R1 = cast<ArraySubscriptExpr>(this)->getLHS()->getSourceRange();
1457 R2 = cast<ArraySubscriptExpr>(this)->getRHS()->getSourceRange();
1458 return true;
Eli Friedman211f6ad2008-05-27 15:24:04 +00001459
Reid Spencer5f016e22007-07-11 17:01:13 +00001460 case CallExprClass:
Eli Friedman852871a2009-04-29 16:35:53 +00001461 case CXXOperatorCallExprClass:
1462 case CXXMemberCallExprClass: {
Chris Lattner026dc962009-02-14 07:37:35 +00001463 // If this is a direct call, get the callee.
1464 const CallExpr *CE = cast<CallExpr>(this);
Nuno Lopesd20254f2009-12-20 23:11:08 +00001465 if (const Decl *FD = CE->getCalleeDecl()) {
Chris Lattner026dc962009-02-14 07:37:35 +00001466 // If the callee has attribute pure, const, or warn_unused_result, warn
1467 // about it. void foo() { strlen("bar"); } should warn.
Chris Lattnerbc8d42c2009-10-13 04:53:48 +00001468 //
1469 // Note: If new cases are added here, DiagnoseUnusedExprResult should be
1470 // updated to match for QoI.
1471 if (FD->getAttr<WarnUnusedResultAttr>() ||
1472 FD->getAttr<PureAttr>() || FD->getAttr<ConstAttr>()) {
1473 Loc = CE->getCallee()->getLocStart();
1474 R1 = CE->getCallee()->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001475
Chris Lattnerbc8d42c2009-10-13 04:53:48 +00001476 if (unsigned NumArgs = CE->getNumArgs())
1477 R2 = SourceRange(CE->getArg(0)->getLocStart(),
1478 CE->getArg(NumArgs-1)->getLocEnd());
1479 return true;
1480 }
Chris Lattner026dc962009-02-14 07:37:35 +00001481 }
1482 return false;
1483 }
Anders Carlsson58beed92009-11-17 17:11:23 +00001484
1485 case CXXTemporaryObjectExprClass:
1486 case CXXConstructExprClass:
1487 return false;
1488
Fariborz Jahanianf0317742010-03-30 18:22:15 +00001489 case ObjCMessageExprClass: {
1490 const ObjCMessageExpr *ME = cast<ObjCMessageExpr>(this);
1491 const ObjCMethodDecl *MD = ME->getMethodDecl();
1492 if (MD && MD->getAttr<WarnUnusedResultAttr>()) {
1493 Loc = getExprLoc();
1494 return true;
1495 }
Chris Lattner026dc962009-02-14 07:37:35 +00001496 return false;
Fariborz Jahanianf0317742010-03-30 18:22:15 +00001497 }
Mike Stump1eb44332009-09-09 15:08:12 +00001498
John McCall12f78a62010-12-02 01:19:52 +00001499 case ObjCPropertyRefExprClass:
Chris Lattner5e94a0d2009-08-16 16:51:50 +00001500 Loc = getExprLoc();
1501 R1 = getSourceRange();
Chris Lattnera50089e2009-08-16 16:45:18 +00001502 return true;
John McCall12f78a62010-12-02 01:19:52 +00001503
Chris Lattner611b2ec2008-07-26 19:51:01 +00001504 case StmtExprClass: {
1505 // Statement exprs don't logically have side effects themselves, but are
1506 // sometimes used in macros in ways that give them a type that is unused.
1507 // For example ({ blah; foo(); }) will end up with a type if foo has a type.
1508 // however, if the result of the stmt expr is dead, we don't want to emit a
1509 // warning.
1510 const CompoundStmt *CS = cast<StmtExpr>(this)->getSubStmt();
Argyrios Kyrtzidisd2827af2010-09-19 21:21:10 +00001511 if (!CS->body_empty()) {
Chris Lattner611b2ec2008-07-26 19:51:01 +00001512 if (const Expr *E = dyn_cast<Expr>(CS->body_back()))
Mike Stumpdf317bf2009-11-03 23:25:48 +00001513 return E->isUnusedResultAWarning(Loc, R1, R2, Ctx);
Argyrios Kyrtzidisd2827af2010-09-19 21:21:10 +00001514 if (const LabelStmt *Label = dyn_cast<LabelStmt>(CS->body_back()))
1515 if (const Expr *E = dyn_cast<Expr>(Label->getSubStmt()))
1516 return E->isUnusedResultAWarning(Loc, R1, R2, Ctx);
1517 }
Mike Stump1eb44332009-09-09 15:08:12 +00001518
John McCall0faede62010-03-12 07:11:26 +00001519 if (getType()->isVoidType())
1520 return false;
Chris Lattner026dc962009-02-14 07:37:35 +00001521 Loc = cast<StmtExpr>(this)->getLParenLoc();
1522 R1 = getSourceRange();
1523 return true;
Chris Lattner611b2ec2008-07-26 19:51:01 +00001524 }
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001525 case CStyleCastExprClass:
Chris Lattnerfb846642009-07-28 18:25:28 +00001526 // If this is an explicit cast to void, allow it. People do this when they
1527 // think they know what they're doing :).
Chris Lattner026dc962009-02-14 07:37:35 +00001528 if (getType()->isVoidType())
Chris Lattnerfb846642009-07-28 18:25:28 +00001529 return false;
Chris Lattner026dc962009-02-14 07:37:35 +00001530 Loc = cast<CStyleCastExpr>(this)->getLParenLoc();
1531 R1 = cast<CStyleCastExpr>(this)->getSubExpr()->getSourceRange();
1532 return true;
Anders Carlsson58beed92009-11-17 17:11:23 +00001533 case CXXFunctionalCastExprClass: {
John McCall0faede62010-03-12 07:11:26 +00001534 if (getType()->isVoidType())
1535 return false;
Anders Carlsson58beed92009-11-17 17:11:23 +00001536 const CastExpr *CE = cast<CastExpr>(this);
Sean Huntc3021132010-05-05 15:23:54 +00001537
Anders Carlsson58beed92009-11-17 17:11:23 +00001538 // If this is a cast to void or a constructor conversion, check the operand.
1539 // Otherwise, the result of the cast is unused.
John McCall2de56d12010-08-25 11:45:40 +00001540 if (CE->getCastKind() == CK_ToVoid ||
1541 CE->getCastKind() == CK_ConstructorConversion)
Mike Stumpdf317bf2009-11-03 23:25:48 +00001542 return (cast<CastExpr>(this)->getSubExpr()
1543 ->isUnusedResultAWarning(Loc, R1, R2, Ctx));
Chris Lattner026dc962009-02-14 07:37:35 +00001544 Loc = cast<CXXFunctionalCastExpr>(this)->getTypeBeginLoc();
1545 R1 = cast<CXXFunctionalCastExpr>(this)->getSubExpr()->getSourceRange();
1546 return true;
Anders Carlsson58beed92009-11-17 17:11:23 +00001547 }
Mike Stump1eb44332009-09-09 15:08:12 +00001548
Eli Friedman4be1f472008-05-19 21:24:43 +00001549 case ImplicitCastExprClass:
1550 // Check the operand, since implicit casts are inserted by Sema
Mike Stumpdf317bf2009-11-03 23:25:48 +00001551 return (cast<ImplicitCastExpr>(this)
1552 ->getSubExpr()->isUnusedResultAWarning(Loc, R1, R2, Ctx));
Eli Friedman4be1f472008-05-19 21:24:43 +00001553
Chris Lattner04421082008-04-08 04:40:51 +00001554 case CXXDefaultArgExprClass:
Mike Stumpdf317bf2009-11-03 23:25:48 +00001555 return (cast<CXXDefaultArgExpr>(this)
1556 ->getExpr()->isUnusedResultAWarning(Loc, R1, R2, Ctx));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001557
1558 case CXXNewExprClass:
1559 // FIXME: In theory, there might be new expressions that don't have side
1560 // effects (e.g. a placement new with an uninitialized POD).
1561 case CXXDeleteExprClass:
Chris Lattner026dc962009-02-14 07:37:35 +00001562 return false;
Anders Carlsson2d46eb22009-08-16 04:11:06 +00001563 case CXXBindTemporaryExprClass:
Mike Stumpdf317bf2009-11-03 23:25:48 +00001564 return (cast<CXXBindTemporaryExpr>(this)
1565 ->getSubExpr()->isUnusedResultAWarning(Loc, R1, R2, Ctx));
John McCall4765fa02010-12-06 08:20:24 +00001566 case ExprWithCleanupsClass:
1567 return (cast<ExprWithCleanups>(this)
Mike Stumpdf317bf2009-11-03 23:25:48 +00001568 ->getSubExpr()->isUnusedResultAWarning(Loc, R1, R2, Ctx));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001569 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001570}
1571
Fariborz Jahanian44baa8a2009-02-22 18:40:18 +00001572/// isOBJCGCCandidate - Check if an expression is objc gc'able.
Fariborz Jahanian7f4f86a2009-09-08 23:38:54 +00001573/// returns true, if it is; false otherwise.
Fariborz Jahanian102e3902009-06-01 21:29:32 +00001574bool Expr::isOBJCGCCandidate(ASTContext &Ctx) const {
Fariborz Jahanian44baa8a2009-02-22 18:40:18 +00001575 switch (getStmtClass()) {
1576 default:
1577 return false;
1578 case ObjCIvarRefExprClass:
1579 return true;
Fariborz Jahanian207c5212009-02-23 18:59:50 +00001580 case Expr::UnaryOperatorClass:
Fariborz Jahanian102e3902009-06-01 21:29:32 +00001581 return cast<UnaryOperator>(this)->getSubExpr()->isOBJCGCCandidate(Ctx);
Fariborz Jahanian44baa8a2009-02-22 18:40:18 +00001582 case ParenExprClass:
Fariborz Jahanian102e3902009-06-01 21:29:32 +00001583 return cast<ParenExpr>(this)->getSubExpr()->isOBJCGCCandidate(Ctx);
Fariborz Jahanian44baa8a2009-02-22 18:40:18 +00001584 case ImplicitCastExprClass:
Fariborz Jahanian102e3902009-06-01 21:29:32 +00001585 return cast<ImplicitCastExpr>(this)->getSubExpr()->isOBJCGCCandidate(Ctx);
Fariborz Jahanian06b89122009-05-05 23:28:21 +00001586 case CStyleCastExprClass:
Fariborz Jahanian102e3902009-06-01 21:29:32 +00001587 return cast<CStyleCastExpr>(this)->getSubExpr()->isOBJCGCCandidate(Ctx);
Douglas Gregora2813ce2009-10-23 18:54:35 +00001588 case DeclRefExprClass: {
Fariborz Jahanian44baa8a2009-02-22 18:40:18 +00001589 const Decl *D = cast<DeclRefExpr>(this)->getDecl();
Fariborz Jahanian102e3902009-06-01 21:29:32 +00001590 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1591 if (VD->hasGlobalStorage())
1592 return true;
1593 QualType T = VD->getType();
Fariborz Jahanian59a53fa2009-09-16 18:09:18 +00001594 // dereferencing to a pointer is always a gc'able candidate,
1595 // unless it is __weak.
Daniel Dunbar7e88a602009-09-17 06:31:17 +00001596 return T->isPointerType() &&
John McCall0953e762009-09-24 19:53:00 +00001597 (Ctx.getObjCGCAttrKind(T) != Qualifiers::Weak);
Fariborz Jahanian102e3902009-06-01 21:29:32 +00001598 }
Fariborz Jahanian44baa8a2009-02-22 18:40:18 +00001599 return false;
1600 }
Douglas Gregor83f6faf2009-08-31 23:41:50 +00001601 case MemberExprClass: {
Fariborz Jahanian44baa8a2009-02-22 18:40:18 +00001602 const MemberExpr *M = cast<MemberExpr>(this);
Fariborz Jahanian102e3902009-06-01 21:29:32 +00001603 return M->getBase()->isOBJCGCCandidate(Ctx);
Fariborz Jahanian44baa8a2009-02-22 18:40:18 +00001604 }
1605 case ArraySubscriptExprClass:
Fariborz Jahanian102e3902009-06-01 21:29:32 +00001606 return cast<ArraySubscriptExpr>(this)->getBase()->isOBJCGCCandidate(Ctx);
Fariborz Jahanian44baa8a2009-02-22 18:40:18 +00001607 }
1608}
Sebastian Redl369e51f2010-09-10 20:55:33 +00001609
Argyrios Kyrtzidis11ab7902010-11-01 18:49:26 +00001610bool Expr::isBoundMemberFunction(ASTContext &Ctx) const {
1611 if (isTypeDependent())
1612 return false;
John McCall7eb0a9e2010-11-24 05:12:34 +00001613 return ClassifyLValue(Ctx) == Expr::LV_MemberFunction;
Argyrios Kyrtzidis11ab7902010-11-01 18:49:26 +00001614}
1615
Sebastian Redl369e51f2010-09-10 20:55:33 +00001616static Expr::CanThrowResult MergeCanThrow(Expr::CanThrowResult CT1,
1617 Expr::CanThrowResult CT2) {
1618 // CanThrowResult constants are ordered so that the maximum is the correct
1619 // merge result.
1620 return CT1 > CT2 ? CT1 : CT2;
1621}
1622
1623static Expr::CanThrowResult CanSubExprsThrow(ASTContext &C, const Expr *CE) {
1624 Expr *E = const_cast<Expr*>(CE);
1625 Expr::CanThrowResult R = Expr::CT_Cannot;
John McCall7502c1d2011-02-13 04:07:26 +00001626 for (Expr::child_range I = E->children(); I && R != Expr::CT_Can; ++I) {
Sebastian Redl369e51f2010-09-10 20:55:33 +00001627 R = MergeCanThrow(R, cast<Expr>(*I)->CanThrow(C));
1628 }
1629 return R;
1630}
1631
1632static Expr::CanThrowResult CanCalleeThrow(const Decl *D,
1633 bool NullThrows = true) {
1634 if (!D)
1635 return NullThrows ? Expr::CT_Can : Expr::CT_Cannot;
1636
1637 // See if we can get a function type from the decl somehow.
1638 const ValueDecl *VD = dyn_cast<ValueDecl>(D);
1639 if (!VD) // If we have no clue what we're calling, assume the worst.
1640 return Expr::CT_Can;
1641
Sebastian Redl5221d8f2010-09-10 22:34:40 +00001642 // As an extension, we assume that __attribute__((nothrow)) functions don't
1643 // throw.
1644 if (isa<FunctionDecl>(D) && D->hasAttr<NoThrowAttr>())
1645 return Expr::CT_Cannot;
1646
Sebastian Redl369e51f2010-09-10 20:55:33 +00001647 QualType T = VD->getType();
1648 const FunctionProtoType *FT;
1649 if ((FT = T->getAs<FunctionProtoType>())) {
1650 } else if (const PointerType *PT = T->getAs<PointerType>())
1651 FT = PT->getPointeeType()->getAs<FunctionProtoType>();
1652 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
1653 FT = RT->getPointeeType()->getAs<FunctionProtoType>();
1654 else if (const MemberPointerType *MT = T->getAs<MemberPointerType>())
1655 FT = MT->getPointeeType()->getAs<FunctionProtoType>();
1656 else if (const BlockPointerType *BT = T->getAs<BlockPointerType>())
1657 FT = BT->getPointeeType()->getAs<FunctionProtoType>();
1658
1659 if (!FT)
1660 return Expr::CT_Can;
1661
1662 return FT->hasEmptyExceptionSpec() ? Expr::CT_Cannot : Expr::CT_Can;
1663}
1664
1665static Expr::CanThrowResult CanDynamicCastThrow(const CXXDynamicCastExpr *DC) {
1666 if (DC->isTypeDependent())
1667 return Expr::CT_Dependent;
1668
Sebastian Redl295995c2010-09-10 20:55:47 +00001669 if (!DC->getTypeAsWritten()->isReferenceType())
1670 return Expr::CT_Cannot;
1671
Sebastian Redl369e51f2010-09-10 20:55:33 +00001672 return DC->getCastKind() == clang::CK_Dynamic? Expr::CT_Can : Expr::CT_Cannot;
1673}
1674
1675static Expr::CanThrowResult CanTypeidThrow(ASTContext &C,
1676 const CXXTypeidExpr *DC) {
1677 if (DC->isTypeOperand())
1678 return Expr::CT_Cannot;
1679
1680 Expr *Op = DC->getExprOperand();
1681 if (Op->isTypeDependent())
1682 return Expr::CT_Dependent;
1683
1684 const RecordType *RT = Op->getType()->getAs<RecordType>();
1685 if (!RT)
1686 return Expr::CT_Cannot;
1687
1688 if (!cast<CXXRecordDecl>(RT->getDecl())->isPolymorphic())
1689 return Expr::CT_Cannot;
1690
1691 if (Op->Classify(C).isPRValue())
1692 return Expr::CT_Cannot;
1693
1694 return Expr::CT_Can;
1695}
1696
1697Expr::CanThrowResult Expr::CanThrow(ASTContext &C) const {
1698 // C++ [expr.unary.noexcept]p3:
1699 // [Can throw] if in a potentially-evaluated context the expression would
1700 // contain:
1701 switch (getStmtClass()) {
1702 case CXXThrowExprClass:
1703 // - a potentially evaluated throw-expression
1704 return CT_Can;
1705
1706 case CXXDynamicCastExprClass: {
1707 // - a potentially evaluated dynamic_cast expression dynamic_cast<T>(v),
1708 // where T is a reference type, that requires a run-time check
1709 CanThrowResult CT = CanDynamicCastThrow(cast<CXXDynamicCastExpr>(this));
1710 if (CT == CT_Can)
1711 return CT;
1712 return MergeCanThrow(CT, CanSubExprsThrow(C, this));
1713 }
1714
1715 case CXXTypeidExprClass:
1716 // - a potentially evaluated typeid expression applied to a glvalue
1717 // expression whose type is a polymorphic class type
1718 return CanTypeidThrow(C, cast<CXXTypeidExpr>(this));
1719
1720 // - a potentially evaluated call to a function, member function, function
1721 // pointer, or member function pointer that does not have a non-throwing
1722 // exception-specification
1723 case CallExprClass:
1724 case CXXOperatorCallExprClass:
1725 case CXXMemberCallExprClass: {
1726 CanThrowResult CT = CanCalleeThrow(cast<CallExpr>(this)->getCalleeDecl());
1727 if (CT == CT_Can)
1728 return CT;
1729 return MergeCanThrow(CT, CanSubExprsThrow(C, this));
1730 }
1731
Sebastian Redl295995c2010-09-10 20:55:47 +00001732 case CXXConstructExprClass:
1733 case CXXTemporaryObjectExprClass: {
Sebastian Redl369e51f2010-09-10 20:55:33 +00001734 CanThrowResult CT = CanCalleeThrow(
1735 cast<CXXConstructExpr>(this)->getConstructor());
1736 if (CT == CT_Can)
1737 return CT;
1738 return MergeCanThrow(CT, CanSubExprsThrow(C, this));
1739 }
1740
1741 case CXXNewExprClass: {
1742 CanThrowResult CT = MergeCanThrow(
1743 CanCalleeThrow(cast<CXXNewExpr>(this)->getOperatorNew()),
1744 CanCalleeThrow(cast<CXXNewExpr>(this)->getConstructor(),
1745 /*NullThrows*/false));
1746 if (CT == CT_Can)
1747 return CT;
1748 return MergeCanThrow(CT, CanSubExprsThrow(C, this));
1749 }
1750
1751 case CXXDeleteExprClass: {
Sebastian Redl369e51f2010-09-10 20:55:33 +00001752 CanThrowResult CT = CanCalleeThrow(
1753 cast<CXXDeleteExpr>(this)->getOperatorDelete());
1754 if (CT == CT_Can)
1755 return CT;
Sebastian Redl0b34cf72010-09-10 23:27:10 +00001756 const Expr *Arg = cast<CXXDeleteExpr>(this)->getArgument();
1757 // Unwrap exactly one implicit cast, which converts all pointers to void*.
1758 if (const ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1759 Arg = Cast->getSubExpr();
1760 if (const PointerType *PT = Arg->getType()->getAs<PointerType>()) {
1761 if (const RecordType *RT = PT->getPointeeType()->getAs<RecordType>()) {
1762 CanThrowResult CT2 = CanCalleeThrow(
1763 cast<CXXRecordDecl>(RT->getDecl())->getDestructor());
1764 if (CT2 == CT_Can)
1765 return CT2;
1766 CT = MergeCanThrow(CT, CT2);
1767 }
1768 }
1769 return MergeCanThrow(CT, CanSubExprsThrow(C, this));
1770 }
1771
1772 case CXXBindTemporaryExprClass: {
1773 // The bound temporary has to be destroyed again, which might throw.
1774 CanThrowResult CT = CanCalleeThrow(
1775 cast<CXXBindTemporaryExpr>(this)->getTemporary()->getDestructor());
1776 if (CT == CT_Can)
1777 return CT;
Sebastian Redl369e51f2010-09-10 20:55:33 +00001778 return MergeCanThrow(CT, CanSubExprsThrow(C, this));
1779 }
1780
1781 // ObjC message sends are like function calls, but never have exception
1782 // specs.
1783 case ObjCMessageExprClass:
1784 case ObjCPropertyRefExprClass:
Sebastian Redl369e51f2010-09-10 20:55:33 +00001785 return CT_Can;
1786
1787 // Many other things have subexpressions, so we have to test those.
1788 // Some are simple:
1789 case ParenExprClass:
1790 case MemberExprClass:
1791 case CXXReinterpretCastExprClass:
1792 case CXXConstCastExprClass:
1793 case ConditionalOperatorClass:
1794 case CompoundLiteralExprClass:
1795 case ExtVectorElementExprClass:
1796 case InitListExprClass:
1797 case DesignatedInitExprClass:
1798 case ParenListExprClass:
1799 case VAArgExprClass:
1800 case CXXDefaultArgExprClass:
John McCall4765fa02010-12-06 08:20:24 +00001801 case ExprWithCleanupsClass:
Sebastian Redl369e51f2010-09-10 20:55:33 +00001802 case ObjCIvarRefExprClass:
1803 case ObjCIsaExprClass:
1804 case ShuffleVectorExprClass:
1805 return CanSubExprsThrow(C, this);
1806
1807 // Some might be dependent for other reasons.
1808 case UnaryOperatorClass:
1809 case ArraySubscriptExprClass:
1810 case ImplicitCastExprClass:
1811 case CStyleCastExprClass:
1812 case CXXStaticCastExprClass:
1813 case CXXFunctionalCastExprClass:
1814 case BinaryOperatorClass:
1815 case CompoundAssignOperatorClass: {
1816 CanThrowResult CT = isTypeDependent() ? CT_Dependent : CT_Cannot;
1817 return MergeCanThrow(CT, CanSubExprsThrow(C, this));
1818 }
1819
1820 // FIXME: We should handle StmtExpr, but that opens a MASSIVE can of worms.
1821 case StmtExprClass:
1822 return CT_Can;
1823
1824 case ChooseExprClass:
1825 if (isTypeDependent() || isValueDependent())
1826 return CT_Dependent;
1827 return cast<ChooseExpr>(this)->getChosenSubExpr(C)->CanThrow(C);
1828
1829 // Some expressions are always dependent.
1830 case DependentScopeDeclRefExprClass:
1831 case CXXUnresolvedConstructExprClass:
1832 case CXXDependentScopeMemberExprClass:
1833 return CT_Dependent;
1834
1835 default:
1836 // All other expressions don't have subexpressions, or else they are
1837 // unevaluated.
1838 return CT_Cannot;
1839 }
1840}
1841
Ted Kremenek4e99a5f2008-01-17 16:57:34 +00001842Expr* Expr::IgnoreParens() {
1843 Expr* E = this;
Abramo Bagnarab9eb35c2010-10-15 07:51:18 +00001844 while (true) {
1845 if (ParenExpr* P = dyn_cast<ParenExpr>(E)) {
1846 E = P->getSubExpr();
1847 continue;
1848 }
1849 if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) {
1850 if (P->getOpcode() == UO_Extension) {
1851 E = P->getSubExpr();
1852 continue;
1853 }
1854 }
1855 return E;
1856 }
Ted Kremenek4e99a5f2008-01-17 16:57:34 +00001857}
1858
Chris Lattner56f34942008-02-13 01:02:39 +00001859/// IgnoreParenCasts - Ignore parentheses and casts. Strip off any ParenExpr
1860/// or CastExprs or ImplicitCastExprs, returning their operand.
1861Expr *Expr::IgnoreParenCasts() {
1862 Expr *E = this;
1863 while (true) {
Abramo Bagnarab9eb35c2010-10-15 07:51:18 +00001864 if (ParenExpr* P = dyn_cast<ParenExpr>(E)) {
Chris Lattner56f34942008-02-13 01:02:39 +00001865 E = P->getSubExpr();
Abramo Bagnarab9eb35c2010-10-15 07:51:18 +00001866 continue;
1867 }
1868 if (CastExpr *P = dyn_cast<CastExpr>(E)) {
Chris Lattner56f34942008-02-13 01:02:39 +00001869 E = P->getSubExpr();
Abramo Bagnarab9eb35c2010-10-15 07:51:18 +00001870 continue;
1871 }
1872 if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) {
1873 if (P->getOpcode() == UO_Extension) {
1874 E = P->getSubExpr();
1875 continue;
1876 }
1877 }
1878 return E;
Chris Lattner56f34942008-02-13 01:02:39 +00001879 }
1880}
1881
John McCall9c5d70c2010-12-04 08:24:19 +00001882/// IgnoreParenLValueCasts - Ignore parentheses and lvalue-to-rvalue
1883/// casts. This is intended purely as a temporary workaround for code
1884/// that hasn't yet been rewritten to do the right thing about those
1885/// casts, and may disappear along with the last internal use.
John McCallf6a16482010-12-04 03:47:34 +00001886Expr *Expr::IgnoreParenLValueCasts() {
1887 Expr *E = this;
John McCall9c5d70c2010-12-04 08:24:19 +00001888 while (true) {
John McCallf6a16482010-12-04 03:47:34 +00001889 if (ParenExpr *P = dyn_cast<ParenExpr>(E)) {
1890 E = P->getSubExpr();
1891 continue;
John McCall9c5d70c2010-12-04 08:24:19 +00001892 } else if (CastExpr *P = dyn_cast<CastExpr>(E)) {
John McCallf6a16482010-12-04 03:47:34 +00001893 if (P->getCastKind() == CK_LValueToRValue) {
1894 E = P->getSubExpr();
1895 continue;
1896 }
John McCall9c5d70c2010-12-04 08:24:19 +00001897 } else if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) {
1898 if (P->getOpcode() == UO_Extension) {
1899 E = P->getSubExpr();
1900 continue;
1901 }
John McCallf6a16482010-12-04 03:47:34 +00001902 }
1903 break;
1904 }
1905 return E;
1906}
1907
John McCall2fc46bf2010-05-05 22:59:52 +00001908Expr *Expr::IgnoreParenImpCasts() {
1909 Expr *E = this;
1910 while (true) {
Abramo Bagnarab9eb35c2010-10-15 07:51:18 +00001911 if (ParenExpr *P = dyn_cast<ParenExpr>(E)) {
John McCall2fc46bf2010-05-05 22:59:52 +00001912 E = P->getSubExpr();
Abramo Bagnarab9eb35c2010-10-15 07:51:18 +00001913 continue;
1914 }
1915 if (ImplicitCastExpr *P = dyn_cast<ImplicitCastExpr>(E)) {
John McCall2fc46bf2010-05-05 22:59:52 +00001916 E = P->getSubExpr();
Abramo Bagnarab9eb35c2010-10-15 07:51:18 +00001917 continue;
1918 }
1919 if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) {
1920 if (P->getOpcode() == UO_Extension) {
1921 E = P->getSubExpr();
1922 continue;
1923 }
1924 }
1925 return E;
John McCall2fc46bf2010-05-05 22:59:52 +00001926 }
1927}
1928
Chris Lattnerecdd8412009-03-13 17:28:01 +00001929/// IgnoreParenNoopCasts - Ignore parentheses and casts that do not change the
1930/// value (including ptr->int casts of the same size). Strip off any
1931/// ParenExpr or CastExprs, returning their operand.
1932Expr *Expr::IgnoreParenNoopCasts(ASTContext &Ctx) {
1933 Expr *E = this;
1934 while (true) {
1935 if (ParenExpr *P = dyn_cast<ParenExpr>(E)) {
1936 E = P->getSubExpr();
1937 continue;
1938 }
Mike Stump1eb44332009-09-09 15:08:12 +00001939
Chris Lattnerecdd8412009-03-13 17:28:01 +00001940 if (CastExpr *P = dyn_cast<CastExpr>(E)) {
1941 // We ignore integer <-> casts that are of the same width, ptr<->ptr and
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001942 // ptr<->int casts of the same width. We also ignore all identity casts.
Chris Lattnerecdd8412009-03-13 17:28:01 +00001943 Expr *SE = P->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00001944
Chris Lattnerecdd8412009-03-13 17:28:01 +00001945 if (Ctx.hasSameUnqualifiedType(E->getType(), SE->getType())) {
1946 E = SE;
1947 continue;
1948 }
Mike Stump1eb44332009-09-09 15:08:12 +00001949
Abramo Bagnarab9eb35c2010-10-15 07:51:18 +00001950 if ((E->getType()->isPointerType() ||
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001951 E->getType()->isIntegralType(Ctx)) &&
Abramo Bagnarab9eb35c2010-10-15 07:51:18 +00001952 (SE->getType()->isPointerType() ||
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001953 SE->getType()->isIntegralType(Ctx)) &&
Chris Lattnerecdd8412009-03-13 17:28:01 +00001954 Ctx.getTypeSize(E->getType()) == Ctx.getTypeSize(SE->getType())) {
1955 E = SE;
1956 continue;
1957 }
1958 }
Mike Stump1eb44332009-09-09 15:08:12 +00001959
Abramo Bagnarab9eb35c2010-10-15 07:51:18 +00001960 if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) {
1961 if (P->getOpcode() == UO_Extension) {
1962 E = P->getSubExpr();
1963 continue;
1964 }
1965 }
1966
Chris Lattnerecdd8412009-03-13 17:28:01 +00001967 return E;
1968 }
1969}
1970
Douglas Gregor6eef5192009-12-14 19:27:10 +00001971bool Expr::isDefaultArgument() const {
1972 const Expr *E = this;
1973 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
1974 E = ICE->getSubExprAsWritten();
Sean Huntc3021132010-05-05 15:23:54 +00001975
Douglas Gregor6eef5192009-12-14 19:27:10 +00001976 return isa<CXXDefaultArgExpr>(E);
1977}
Chris Lattnerecdd8412009-03-13 17:28:01 +00001978
Douglas Gregor2f599792010-04-02 18:24:57 +00001979/// \brief Skip over any no-op casts and any temporary-binding
1980/// expressions.
Anders Carlssonf8b30152010-11-28 16:40:49 +00001981static const Expr *skipTemporaryBindingsNoOpCastsAndParens(const Expr *E) {
Douglas Gregor2f599792010-04-02 18:24:57 +00001982 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall2de56d12010-08-25 11:45:40 +00001983 if (ICE->getCastKind() == CK_NoOp)
Douglas Gregor2f599792010-04-02 18:24:57 +00001984 E = ICE->getSubExpr();
1985 else
1986 break;
1987 }
1988
1989 while (const CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
1990 E = BE->getSubExpr();
1991
1992 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall2de56d12010-08-25 11:45:40 +00001993 if (ICE->getCastKind() == CK_NoOp)
Douglas Gregor2f599792010-04-02 18:24:57 +00001994 E = ICE->getSubExpr();
1995 else
1996 break;
1997 }
Anders Carlssonf8b30152010-11-28 16:40:49 +00001998
1999 return E->IgnoreParens();
Douglas Gregor2f599792010-04-02 18:24:57 +00002000}
2001
John McCall558d2ab2010-09-15 10:14:12 +00002002/// isTemporaryObject - Determines if this expression produces a
2003/// temporary of the given class type.
2004bool Expr::isTemporaryObject(ASTContext &C, const CXXRecordDecl *TempTy) const {
2005 if (!C.hasSameUnqualifiedType(getType(), C.getTypeDeclType(TempTy)))
2006 return false;
2007
Anders Carlssonf8b30152010-11-28 16:40:49 +00002008 const Expr *E = skipTemporaryBindingsNoOpCastsAndParens(this);
Douglas Gregor2f599792010-04-02 18:24:57 +00002009
John McCall58277b52010-09-15 20:59:13 +00002010 // Temporaries are by definition pr-values of class type.
Fariborz Jahaniandb148be2010-09-27 17:30:38 +00002011 if (!E->Classify(C).isPRValue()) {
2012 // In this context, property reference is a message call and is pr-value.
John McCall12f78a62010-12-02 01:19:52 +00002013 if (!isa<ObjCPropertyRefExpr>(E))
Fariborz Jahaniandb148be2010-09-27 17:30:38 +00002014 return false;
2015 }
Douglas Gregor2f599792010-04-02 18:24:57 +00002016
John McCall19e60ad2010-09-16 06:57:56 +00002017 // Black-list a few cases which yield pr-values of class type that don't
2018 // refer to temporaries of that type:
2019
2020 // - implicit derived-to-base conversions
John McCall558d2ab2010-09-15 10:14:12 +00002021 if (isa<ImplicitCastExpr>(E)) {
2022 switch (cast<ImplicitCastExpr>(E)->getCastKind()) {
2023 case CK_DerivedToBase:
2024 case CK_UncheckedDerivedToBase:
2025 return false;
2026 default:
2027 break;
2028 }
Douglas Gregor2f599792010-04-02 18:24:57 +00002029 }
2030
John McCall19e60ad2010-09-16 06:57:56 +00002031 // - member expressions (all)
2032 if (isa<MemberExpr>(E))
2033 return false;
2034
John McCall56ca35d2011-02-17 10:25:35 +00002035 // - opaque values (all)
2036 if (isa<OpaqueValueExpr>(E))
2037 return false;
2038
John McCall558d2ab2010-09-15 10:14:12 +00002039 return true;
Douglas Gregor2f599792010-04-02 18:24:57 +00002040}
2041
Douglas Gregor75e85042011-03-02 21:06:53 +00002042bool Expr::isImplicitCXXThis() const {
2043 const Expr *E = this;
2044
2045 // Strip away parentheses and casts we don't care about.
2046 while (true) {
2047 if (const ParenExpr *Paren = dyn_cast<ParenExpr>(E)) {
2048 E = Paren->getSubExpr();
2049 continue;
2050 }
2051
2052 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2053 if (ICE->getCastKind() == CK_NoOp ||
2054 ICE->getCastKind() == CK_LValueToRValue ||
2055 ICE->getCastKind() == CK_DerivedToBase ||
2056 ICE->getCastKind() == CK_UncheckedDerivedToBase) {
2057 E = ICE->getSubExpr();
2058 continue;
2059 }
2060 }
2061
2062 if (const UnaryOperator* UnOp = dyn_cast<UnaryOperator>(E)) {
2063 if (UnOp->getOpcode() == UO_Extension) {
2064 E = UnOp->getSubExpr();
2065 continue;
2066 }
2067 }
2068
2069 break;
2070 }
2071
2072 if (const CXXThisExpr *This = dyn_cast<CXXThisExpr>(E))
2073 return This->isImplicit();
2074
2075 return false;
2076}
2077
Douglas Gregor898574e2008-12-05 23:32:09 +00002078/// hasAnyTypeDependentArguments - Determines if any of the expressions
2079/// in Exprs is type-dependent.
2080bool Expr::hasAnyTypeDependentArguments(Expr** Exprs, unsigned NumExprs) {
2081 for (unsigned I = 0; I < NumExprs; ++I)
2082 if (Exprs[I]->isTypeDependent())
2083 return true;
2084
2085 return false;
2086}
2087
2088/// hasAnyValueDependentArguments - Determines if any of the expressions
2089/// in Exprs is value-dependent.
2090bool Expr::hasAnyValueDependentArguments(Expr** Exprs, unsigned NumExprs) {
2091 for (unsigned I = 0; I < NumExprs; ++I)
2092 if (Exprs[I]->isValueDependent())
2093 return true;
2094
2095 return false;
2096}
2097
John McCall4204f072010-08-02 21:13:48 +00002098bool Expr::isConstantInitializer(ASTContext &Ctx, bool IsForRef) const {
Eli Friedmanc39dc9a2009-01-25 03:12:18 +00002099 // This function is attempting whether an expression is an initializer
2100 // which can be evaluated at compile-time. isEvaluatable handles most
2101 // of the cases, but it can't deal with some initializer-specific
2102 // expressions, and it can't deal with aggregates; we deal with those here,
2103 // and fall back to isEvaluatable for the other cases.
2104
John McCall4204f072010-08-02 21:13:48 +00002105 // If we ever capture reference-binding directly in the AST, we can
2106 // kill the second parameter.
2107
2108 if (IsForRef) {
2109 EvalResult Result;
2110 return EvaluateAsLValue(Result, Ctx) && !Result.HasSideEffects;
2111 }
Eli Friedman1f4a6db2009-02-20 02:36:22 +00002112
Anders Carlssone8a32b82008-11-24 05:23:59 +00002113 switch (getStmtClass()) {
Eli Friedmanc39dc9a2009-01-25 03:12:18 +00002114 default: break;
Anders Carlssone8a32b82008-11-24 05:23:59 +00002115 case StringLiteralClass:
Steve Naroff14108da2009-07-10 23:34:53 +00002116 case ObjCStringLiteralClass:
Chris Lattnereaf2bb82009-02-24 22:18:39 +00002117 case ObjCEncodeExprClass:
Anders Carlssone8a32b82008-11-24 05:23:59 +00002118 return true;
John McCallb4b9b152010-08-01 21:51:45 +00002119 case CXXTemporaryObjectExprClass:
2120 case CXXConstructExprClass: {
2121 const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
John McCall4204f072010-08-02 21:13:48 +00002122
2123 // Only if it's
2124 // 1) an application of the trivial default constructor or
John McCallb4b9b152010-08-01 21:51:45 +00002125 if (!CE->getConstructor()->isTrivial()) return false;
John McCall4204f072010-08-02 21:13:48 +00002126 if (!CE->getNumArgs()) return true;
2127
2128 // 2) an elidable trivial copy construction of an operand which is
2129 // itself a constant initializer. Note that we consider the
2130 // operand on its own, *not* as a reference binding.
2131 return CE->isElidable() &&
2132 CE->getArg(0)->isConstantInitializer(Ctx, false);
John McCallb4b9b152010-08-01 21:51:45 +00002133 }
Nate Begeman59b5da62009-01-18 03:20:47 +00002134 case CompoundLiteralExprClass: {
Eli Friedman1f4a6db2009-02-20 02:36:22 +00002135 // This handles gcc's extension that allows global initializers like
2136 // "struct x {int x;} x = (struct x) {};".
2137 // FIXME: This accepts other cases it shouldn't!
Nate Begeman59b5da62009-01-18 03:20:47 +00002138 const Expr *Exp = cast<CompoundLiteralExpr>(this)->getInitializer();
John McCall4204f072010-08-02 21:13:48 +00002139 return Exp->isConstantInitializer(Ctx, false);
Nate Begeman59b5da62009-01-18 03:20:47 +00002140 }
Anders Carlssone8a32b82008-11-24 05:23:59 +00002141 case InitListExprClass: {
Eli Friedman1f4a6db2009-02-20 02:36:22 +00002142 // FIXME: This doesn't deal with fields with reference types correctly.
2143 // FIXME: This incorrectly allows pointers cast to integers to be assigned
2144 // to bitfields.
Anders Carlssone8a32b82008-11-24 05:23:59 +00002145 const InitListExpr *Exp = cast<InitListExpr>(this);
2146 unsigned numInits = Exp->getNumInits();
2147 for (unsigned i = 0; i < numInits; i++) {
John McCall4204f072010-08-02 21:13:48 +00002148 if (!Exp->getInit(i)->isConstantInitializer(Ctx, false))
Anders Carlssone8a32b82008-11-24 05:23:59 +00002149 return false;
2150 }
Eli Friedmanc39dc9a2009-01-25 03:12:18 +00002151 return true;
Anders Carlssone8a32b82008-11-24 05:23:59 +00002152 }
Douglas Gregor3498bdb2009-01-29 17:44:32 +00002153 case ImplicitValueInitExprClass:
2154 return true;
Chris Lattner3ae9f482009-10-13 07:14:16 +00002155 case ParenExprClass:
John McCall4204f072010-08-02 21:13:48 +00002156 return cast<ParenExpr>(this)->getSubExpr()
2157 ->isConstantInitializer(Ctx, IsForRef);
Abramo Bagnara5cadfab2010-09-27 07:13:32 +00002158 case ChooseExprClass:
2159 return cast<ChooseExpr>(this)->getChosenSubExpr(Ctx)
2160 ->isConstantInitializer(Ctx, IsForRef);
Eli Friedmanc39dc9a2009-01-25 03:12:18 +00002161 case UnaryOperatorClass: {
2162 const UnaryOperator* Exp = cast<UnaryOperator>(this);
John McCall2de56d12010-08-25 11:45:40 +00002163 if (Exp->getOpcode() == UO_Extension)
John McCall4204f072010-08-02 21:13:48 +00002164 return Exp->getSubExpr()->isConstantInitializer(Ctx, false);
Eli Friedmanc39dc9a2009-01-25 03:12:18 +00002165 break;
2166 }
Chris Lattner3ae9f482009-10-13 07:14:16 +00002167 case BinaryOperatorClass: {
2168 // Special case &&foo - &&bar. It would be nice to generalize this somehow
2169 // but this handles the common case.
2170 const BinaryOperator *Exp = cast<BinaryOperator>(this);
John McCall2de56d12010-08-25 11:45:40 +00002171 if (Exp->getOpcode() == BO_Sub &&
Chris Lattner3ae9f482009-10-13 07:14:16 +00002172 isa<AddrLabelExpr>(Exp->getLHS()->IgnoreParenNoopCasts(Ctx)) &&
2173 isa<AddrLabelExpr>(Exp->getRHS()->IgnoreParenNoopCasts(Ctx)))
2174 return true;
2175 break;
2176 }
John McCall4204f072010-08-02 21:13:48 +00002177 case CXXFunctionalCastExprClass:
John McCallb4b9b152010-08-01 21:51:45 +00002178 case CXXStaticCastExprClass:
Chris Lattner81045d82009-04-21 05:19:11 +00002179 case ImplicitCastExprClass:
Eli Friedmanc39dc9a2009-01-25 03:12:18 +00002180 case CStyleCastExprClass:
2181 // Handle casts with a destination that's a struct or union; this
2182 // deals with both the gcc no-op struct cast extension and the
2183 // cast-to-union extension.
2184 if (getType()->isRecordType())
John McCall4204f072010-08-02 21:13:48 +00002185 return cast<CastExpr>(this)->getSubExpr()
2186 ->isConstantInitializer(Ctx, false);
Sean Huntc3021132010-05-05 15:23:54 +00002187
Chris Lattner430656e2009-10-13 22:12:09 +00002188 // Integer->integer casts can be handled here, which is important for
2189 // things like (int)(&&x-&&y). Scary but true.
2190 if (getType()->isIntegerType() &&
2191 cast<CastExpr>(this)->getSubExpr()->getType()->isIntegerType())
John McCall4204f072010-08-02 21:13:48 +00002192 return cast<CastExpr>(this)->getSubExpr()
2193 ->isConstantInitializer(Ctx, false);
Sean Huntc3021132010-05-05 15:23:54 +00002194
Eli Friedmanc39dc9a2009-01-25 03:12:18 +00002195 break;
Anders Carlssone8a32b82008-11-24 05:23:59 +00002196 }
Eli Friedmanc39dc9a2009-01-25 03:12:18 +00002197 return isEvaluatable(Ctx);
Steve Naroff38374b02007-09-02 20:30:18 +00002198}
2199
Chandler Carruth82214a82011-02-18 23:54:50 +00002200/// isNullPointerConstant - C99 6.3.2.3p3 - Return whether this is a null
2201/// pointer constant or not, as well as the specific kind of constant detected.
2202/// Null pointer constants can be integer constant expressions with the
2203/// value zero, casts of zero to void*, nullptr (C++0X), or __null
2204/// (a GNU extension).
2205Expr::NullPointerConstantKind
2206Expr::isNullPointerConstant(ASTContext &Ctx,
2207 NullPointerConstantValueDependence NPC) const {
Douglas Gregorce940492009-09-25 04:25:58 +00002208 if (isValueDependent()) {
2209 switch (NPC) {
2210 case NPC_NeverValueDependent:
2211 assert(false && "Unexpected value dependent expression!");
2212 // If the unthinkable happens, fall through to the safest alternative.
Sean Huntc3021132010-05-05 15:23:54 +00002213
Douglas Gregorce940492009-09-25 04:25:58 +00002214 case NPC_ValueDependentIsNull:
Chandler Carruth82214a82011-02-18 23:54:50 +00002215 if (isTypeDependent() || getType()->isIntegralType(Ctx))
2216 return NPCK_ZeroInteger;
2217 else
2218 return NPCK_NotNull;
Sean Huntc3021132010-05-05 15:23:54 +00002219
Douglas Gregorce940492009-09-25 04:25:58 +00002220 case NPC_ValueDependentIsNotNull:
Chandler Carruth82214a82011-02-18 23:54:50 +00002221 return NPCK_NotNull;
Douglas Gregorce940492009-09-25 04:25:58 +00002222 }
2223 }
Daniel Dunbarf515b222009-09-18 08:46:16 +00002224
Sebastian Redl07779722008-10-31 14:43:28 +00002225 // Strip off a cast to void*, if it exists. Except in C++.
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002226 if (const ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(this)) {
Sebastian Redl6215dee2008-11-04 11:45:54 +00002227 if (!Ctx.getLangOptions().CPlusPlus) {
Sebastian Redl07779722008-10-31 14:43:28 +00002228 // Check that it is a cast to void*.
Ted Kremenek6217b802009-07-29 21:53:49 +00002229 if (const PointerType *PT = CE->getType()->getAs<PointerType>()) {
Sebastian Redl07779722008-10-31 14:43:28 +00002230 QualType Pointee = PT->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00002231 if (!Pointee.hasQualifiers() &&
Sebastian Redl07779722008-10-31 14:43:28 +00002232 Pointee->isVoidType() && // to void*
2233 CE->getSubExpr()->getType()->isIntegerType()) // from int.
Douglas Gregorce940492009-09-25 04:25:58 +00002234 return CE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
Sebastian Redl07779722008-10-31 14:43:28 +00002235 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002236 }
Steve Naroffaa58f002008-01-14 16:10:57 +00002237 } else if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(this)) {
2238 // Ignore the ImplicitCastExpr type entirely.
Douglas Gregorce940492009-09-25 04:25:58 +00002239 return ICE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
Steve Naroffaa58f002008-01-14 16:10:57 +00002240 } else if (const ParenExpr *PE = dyn_cast<ParenExpr>(this)) {
2241 // Accept ((void*)0) as a null pointer constant, as many other
2242 // implementations do.
Douglas Gregorce940492009-09-25 04:25:58 +00002243 return PE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
Mike Stump1eb44332009-09-09 15:08:12 +00002244 } else if (const CXXDefaultArgExpr *DefaultArg
Chris Lattner8123a952008-04-10 02:22:51 +00002245 = dyn_cast<CXXDefaultArgExpr>(this)) {
Chris Lattner04421082008-04-08 04:40:51 +00002246 // See through default argument expressions
Douglas Gregorce940492009-09-25 04:25:58 +00002247 return DefaultArg->getExpr()->isNullPointerConstant(Ctx, NPC);
Douglas Gregor2d8b2732008-11-29 04:51:27 +00002248 } else if (isa<GNUNullExpr>(this)) {
2249 // The GNU __null extension is always a null pointer constant.
Chandler Carruth82214a82011-02-18 23:54:50 +00002250 return NPCK_GNUNull;
Steve Naroffaaffbf72008-01-14 02:53:34 +00002251 }
Douglas Gregor2d8b2732008-11-29 04:51:27 +00002252
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002253 // C++0x nullptr_t is always a null pointer constant.
2254 if (getType()->isNullPtrType())
Chandler Carruth82214a82011-02-18 23:54:50 +00002255 return NPCK_CXX0X_nullptr;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002256
Fariborz Jahanianff3a0782010-09-27 22:42:37 +00002257 if (const RecordType *UT = getType()->getAsUnionType())
2258 if (UT && UT->getDecl()->hasAttr<TransparentUnionAttr>())
2259 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(this)){
2260 const Expr *InitExpr = CLE->getInitializer();
2261 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(InitExpr))
2262 return ILE->getInit(0)->isNullPointerConstant(Ctx, NPC);
2263 }
Steve Naroffaa58f002008-01-14 16:10:57 +00002264 // This expression must be an integer type.
Sean Huntc3021132010-05-05 15:23:54 +00002265 if (!getType()->isIntegerType() ||
Fariborz Jahanian56fc0d12009-10-06 00:09:31 +00002266 (Ctx.getLangOptions().CPlusPlus && getType()->isEnumeralType()))
Chandler Carruth82214a82011-02-18 23:54:50 +00002267 return NPCK_NotNull;
Mike Stump1eb44332009-09-09 15:08:12 +00002268
Reid Spencer5f016e22007-07-11 17:01:13 +00002269 // If we have an integer constant expression, we need to *evaluate* it and
2270 // test for the value 0.
Eli Friedman09de1762009-04-25 22:37:12 +00002271 llvm::APSInt Result;
Chandler Carruth82214a82011-02-18 23:54:50 +00002272 bool IsNull = isIntegerConstantExpr(Result, Ctx) && Result == 0;
2273
2274 return (IsNull ? NPCK_ZeroInteger : NPCK_NotNull);
Reid Spencer5f016e22007-07-11 17:01:13 +00002275}
Steve Naroff31a45842007-07-28 23:10:27 +00002276
John McCallf6a16482010-12-04 03:47:34 +00002277/// \brief If this expression is an l-value for an Objective C
2278/// property, find the underlying property reference expression.
2279const ObjCPropertyRefExpr *Expr::getObjCProperty() const {
2280 const Expr *E = this;
2281 while (true) {
2282 assert((E->getValueKind() == VK_LValue &&
2283 E->getObjectKind() == OK_ObjCProperty) &&
2284 "expression is not a property reference");
2285 E = E->IgnoreParenCasts();
2286 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2287 if (BO->getOpcode() == BO_Comma) {
2288 E = BO->getRHS();
2289 continue;
2290 }
2291 }
2292
2293 break;
2294 }
2295
2296 return cast<ObjCPropertyRefExpr>(E);
2297}
2298
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002299FieldDecl *Expr::getBitField() {
Douglas Gregor6f4a69a2009-07-06 15:38:40 +00002300 Expr *E = this->IgnoreParens();
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002301
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002302 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCallf6a16482010-12-04 03:47:34 +00002303 if (ICE->getCastKind() == CK_LValueToRValue ||
2304 (ICE->getValueKind() != VK_RValue && ICE->getCastKind() == CK_NoOp))
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002305 E = ICE->getSubExpr()->IgnoreParens();
2306 else
2307 break;
2308 }
2309
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002310 if (MemberExpr *MemRef = dyn_cast<MemberExpr>(E))
Douglas Gregor86f19402008-12-20 23:49:58 +00002311 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemRef->getMemberDecl()))
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002312 if (Field->isBitField())
2313 return Field;
2314
Argyrios Kyrtzidis0f279e72010-10-30 19:52:22 +00002315 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E))
2316 if (FieldDecl *Field = dyn_cast<FieldDecl>(DeclRef->getDecl()))
2317 if (Field->isBitField())
2318 return Field;
2319
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002320 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(E))
2321 if (BinOp->isAssignmentOp() && BinOp->getLHS())
2322 return BinOp->getLHS()->getBitField();
2323
2324 return 0;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002325}
2326
Anders Carlsson09380262010-01-31 17:18:49 +00002327bool Expr::refersToVectorElement() const {
2328 const Expr *E = this->IgnoreParens();
Sean Huntc3021132010-05-05 15:23:54 +00002329
Anders Carlsson09380262010-01-31 17:18:49 +00002330 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall5baba9d2010-08-25 10:28:54 +00002331 if (ICE->getValueKind() != VK_RValue &&
John McCall2de56d12010-08-25 11:45:40 +00002332 ICE->getCastKind() == CK_NoOp)
Anders Carlsson09380262010-01-31 17:18:49 +00002333 E = ICE->getSubExpr()->IgnoreParens();
2334 else
2335 break;
2336 }
Sean Huntc3021132010-05-05 15:23:54 +00002337
Anders Carlsson09380262010-01-31 17:18:49 +00002338 if (const ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(E))
2339 return ASE->getBase()->getType()->isVectorType();
2340
2341 if (isa<ExtVectorElementExpr>(E))
2342 return true;
2343
2344 return false;
2345}
2346
Chris Lattner2140e902009-02-16 22:14:05 +00002347/// isArrow - Return true if the base expression is a pointer to vector,
2348/// return false if the base expression is a vector.
2349bool ExtVectorElementExpr::isArrow() const {
2350 return getBase()->getType()->isPointerType();
2351}
2352
Nate Begeman213541a2008-04-18 23:10:10 +00002353unsigned ExtVectorElementExpr::getNumElements() const {
John McCall183700f2009-09-21 23:43:11 +00002354 if (const VectorType *VT = getType()->getAs<VectorType>())
Nate Begeman8a997642008-05-09 06:41:27 +00002355 return VT->getNumElements();
2356 return 1;
Chris Lattner4d0ac882007-08-03 16:00:20 +00002357}
2358
Nate Begeman8a997642008-05-09 06:41:27 +00002359/// containsDuplicateElements - Return true if any element access is repeated.
Nate Begeman213541a2008-04-18 23:10:10 +00002360bool ExtVectorElementExpr::containsDuplicateElements() const {
Daniel Dunbara2b34eb2009-10-18 02:09:09 +00002361 // FIXME: Refactor this code to an accessor on the AST node which returns the
2362 // "type" of component access, and share with code below and in Sema.
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00002363 llvm::StringRef Comp = Accessor->getName();
Nate Begeman190d6a22009-01-18 02:01:21 +00002364
2365 // Halving swizzles do not contain duplicate elements.
Daniel Dunbar15027422009-10-17 23:53:04 +00002366 if (Comp == "hi" || Comp == "lo" || Comp == "even" || Comp == "odd")
Nate Begeman190d6a22009-01-18 02:01:21 +00002367 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002368
Nate Begeman190d6a22009-01-18 02:01:21 +00002369 // Advance past s-char prefix on hex swizzles.
Daniel Dunbar15027422009-10-17 23:53:04 +00002370 if (Comp[0] == 's' || Comp[0] == 'S')
2371 Comp = Comp.substr(1);
Mike Stump1eb44332009-09-09 15:08:12 +00002372
Daniel Dunbar15027422009-10-17 23:53:04 +00002373 for (unsigned i = 0, e = Comp.size(); i != e; ++i)
2374 if (Comp.substr(i + 1).find(Comp[i]) != llvm::StringRef::npos)
Steve Narofffec0b492007-07-30 03:29:09 +00002375 return true;
Daniel Dunbar15027422009-10-17 23:53:04 +00002376
Steve Narofffec0b492007-07-30 03:29:09 +00002377 return false;
2378}
Chris Lattnerb8f849d2007-08-02 23:36:59 +00002379
Nate Begeman8a997642008-05-09 06:41:27 +00002380/// getEncodedElementAccess - We encode the fields as a llvm ConstantArray.
Nate Begeman3b8d1162008-05-13 21:03:02 +00002381void ExtVectorElementExpr::getEncodedElementAccess(
2382 llvm::SmallVectorImpl<unsigned> &Elts) const {
Daniel Dunbar4b55b242009-10-18 02:09:31 +00002383 llvm::StringRef Comp = Accessor->getName();
2384 if (Comp[0] == 's' || Comp[0] == 'S')
2385 Comp = Comp.substr(1);
Mike Stump1eb44332009-09-09 15:08:12 +00002386
Daniel Dunbar4b55b242009-10-18 02:09:31 +00002387 bool isHi = Comp == "hi";
2388 bool isLo = Comp == "lo";
2389 bool isEven = Comp == "even";
2390 bool isOdd = Comp == "odd";
Mike Stump1eb44332009-09-09 15:08:12 +00002391
Nate Begeman8a997642008-05-09 06:41:27 +00002392 for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
2393 uint64_t Index;
Mike Stump1eb44332009-09-09 15:08:12 +00002394
Nate Begeman8a997642008-05-09 06:41:27 +00002395 if (isHi)
2396 Index = e + i;
2397 else if (isLo)
2398 Index = i;
2399 else if (isEven)
2400 Index = 2 * i;
2401 else if (isOdd)
2402 Index = 2 * i + 1;
2403 else
Daniel Dunbar4b55b242009-10-18 02:09:31 +00002404 Index = ExtVectorType::getAccessorIdx(Comp[i]);
Chris Lattnerb8f849d2007-08-02 23:36:59 +00002405
Nate Begeman3b8d1162008-05-13 21:03:02 +00002406 Elts.push_back(Index);
Chris Lattnerb8f849d2007-08-02 23:36:59 +00002407 }
Nate Begeman8a997642008-05-09 06:41:27 +00002408}
2409
Douglas Gregor04badcf2010-04-21 00:45:42 +00002410ObjCMessageExpr::ObjCMessageExpr(QualType T,
John McCallf89e55a2010-11-18 06:31:45 +00002411 ExprValueKind VK,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002412 SourceLocation LBracLoc,
2413 SourceLocation SuperLoc,
2414 bool IsInstanceSuper,
2415 QualType SuperType,
Sean Huntc3021132010-05-05 15:23:54 +00002416 Selector Sel,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00002417 SourceLocation SelLoc,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002418 ObjCMethodDecl *Method,
2419 Expr **Args, unsigned NumArgs,
2420 SourceLocation RBracLoc)
John McCallf89e55a2010-11-18 06:31:45 +00002421 : Expr(ObjCMessageExprClass, T, VK, OK_Ordinary,
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00002422 /*TypeDependent=*/false, /*ValueDependent=*/false,
2423 /*ContainsUnexpandedParameterPack=*/false),
Douglas Gregor04badcf2010-04-21 00:45:42 +00002424 NumArgs(NumArgs), Kind(IsInstanceSuper? SuperInstance : SuperClass),
2425 HasMethod(Method != 0), SuperLoc(SuperLoc),
2426 SelectorOrMethod(reinterpret_cast<uintptr_t>(Method? Method
2427 : Sel.getAsOpaquePtr())),
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00002428 SelectorLoc(SelLoc), LBracLoc(LBracLoc), RBracLoc(RBracLoc)
Douglas Gregorc2350e52010-03-08 16:40:19 +00002429{
Douglas Gregor04badcf2010-04-21 00:45:42 +00002430 setReceiverPointer(SuperType.getAsOpaquePtr());
2431 if (NumArgs)
2432 memcpy(getArgs(), Args, NumArgs * sizeof(Expr *));
Ted Kremenek4df728e2008-06-24 15:50:53 +00002433}
2434
Douglas Gregor04badcf2010-04-21 00:45:42 +00002435ObjCMessageExpr::ObjCMessageExpr(QualType T,
John McCallf89e55a2010-11-18 06:31:45 +00002436 ExprValueKind VK,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002437 SourceLocation LBracLoc,
2438 TypeSourceInfo *Receiver,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00002439 Selector Sel,
2440 SourceLocation SelLoc,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002441 ObjCMethodDecl *Method,
2442 Expr **Args, unsigned NumArgs,
2443 SourceLocation RBracLoc)
John McCallf89e55a2010-11-18 06:31:45 +00002444 : Expr(ObjCMessageExprClass, T, VK, OK_Ordinary, T->isDependentType(),
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00002445 T->isDependentType(), T->containsUnexpandedParameterPack()),
Douglas Gregor04badcf2010-04-21 00:45:42 +00002446 NumArgs(NumArgs), Kind(Class), HasMethod(Method != 0),
2447 SelectorOrMethod(reinterpret_cast<uintptr_t>(Method? Method
2448 : Sel.getAsOpaquePtr())),
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00002449 SelectorLoc(SelLoc), LBracLoc(LBracLoc), RBracLoc(RBracLoc)
Douglas Gregor04badcf2010-04-21 00:45:42 +00002450{
2451 setReceiverPointer(Receiver);
Douglas Gregoraa165f82011-01-03 19:04:46 +00002452 Expr **MyArgs = getArgs();
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00002453 for (unsigned I = 0; I != NumArgs; ++I) {
2454 if (Args[I]->isTypeDependent())
2455 ExprBits.TypeDependent = true;
2456 if (Args[I]->isValueDependent())
2457 ExprBits.ValueDependent = true;
2458 if (Args[I]->containsUnexpandedParameterPack())
2459 ExprBits.ContainsUnexpandedParameterPack = true;
2460
2461 MyArgs[I] = Args[I];
2462 }
Ted Kremenek4df728e2008-06-24 15:50:53 +00002463}
2464
Douglas Gregor04badcf2010-04-21 00:45:42 +00002465ObjCMessageExpr::ObjCMessageExpr(QualType T,
John McCallf89e55a2010-11-18 06:31:45 +00002466 ExprValueKind VK,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002467 SourceLocation LBracLoc,
2468 Expr *Receiver,
Sean Huntc3021132010-05-05 15:23:54 +00002469 Selector Sel,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00002470 SourceLocation SelLoc,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002471 ObjCMethodDecl *Method,
2472 Expr **Args, unsigned NumArgs,
2473 SourceLocation RBracLoc)
John McCallf89e55a2010-11-18 06:31:45 +00002474 : Expr(ObjCMessageExprClass, T, VK, OK_Ordinary, Receiver->isTypeDependent(),
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00002475 Receiver->isTypeDependent(),
2476 Receiver->containsUnexpandedParameterPack()),
Douglas Gregor04badcf2010-04-21 00:45:42 +00002477 NumArgs(NumArgs), Kind(Instance), HasMethod(Method != 0),
2478 SelectorOrMethod(reinterpret_cast<uintptr_t>(Method? Method
2479 : Sel.getAsOpaquePtr())),
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00002480 SelectorLoc(SelLoc), LBracLoc(LBracLoc), RBracLoc(RBracLoc)
Douglas Gregor04badcf2010-04-21 00:45:42 +00002481{
2482 setReceiverPointer(Receiver);
Douglas Gregoraa165f82011-01-03 19:04:46 +00002483 Expr **MyArgs = getArgs();
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00002484 for (unsigned I = 0; I != NumArgs; ++I) {
2485 if (Args[I]->isTypeDependent())
2486 ExprBits.TypeDependent = true;
2487 if (Args[I]->isValueDependent())
2488 ExprBits.ValueDependent = true;
2489 if (Args[I]->containsUnexpandedParameterPack())
2490 ExprBits.ContainsUnexpandedParameterPack = true;
2491
2492 MyArgs[I] = Args[I];
2493 }
Chris Lattner0389e6b2009-04-26 00:44:05 +00002494}
2495
Douglas Gregor04badcf2010-04-21 00:45:42 +00002496ObjCMessageExpr *ObjCMessageExpr::Create(ASTContext &Context, QualType T,
John McCallf89e55a2010-11-18 06:31:45 +00002497 ExprValueKind VK,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002498 SourceLocation LBracLoc,
2499 SourceLocation SuperLoc,
2500 bool IsInstanceSuper,
2501 QualType SuperType,
Sean Huntc3021132010-05-05 15:23:54 +00002502 Selector Sel,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00002503 SourceLocation SelLoc,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002504 ObjCMethodDecl *Method,
2505 Expr **Args, unsigned NumArgs,
2506 SourceLocation RBracLoc) {
Sean Huntc3021132010-05-05 15:23:54 +00002507 unsigned Size = sizeof(ObjCMessageExpr) + sizeof(void *) +
Douglas Gregor04badcf2010-04-21 00:45:42 +00002508 NumArgs * sizeof(Expr *);
2509 void *Mem = Context.Allocate(Size, llvm::AlignOf<ObjCMessageExpr>::Alignment);
John McCallf89e55a2010-11-18 06:31:45 +00002510 return new (Mem) ObjCMessageExpr(T, VK, LBracLoc, SuperLoc, IsInstanceSuper,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00002511 SuperType, Sel, SelLoc, Method, Args,NumArgs,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002512 RBracLoc);
2513}
2514
2515ObjCMessageExpr *ObjCMessageExpr::Create(ASTContext &Context, QualType T,
John McCallf89e55a2010-11-18 06:31:45 +00002516 ExprValueKind VK,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002517 SourceLocation LBracLoc,
2518 TypeSourceInfo *Receiver,
Sean Huntc3021132010-05-05 15:23:54 +00002519 Selector Sel,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00002520 SourceLocation SelLoc,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002521 ObjCMethodDecl *Method,
2522 Expr **Args, unsigned NumArgs,
2523 SourceLocation RBracLoc) {
Sean Huntc3021132010-05-05 15:23:54 +00002524 unsigned Size = sizeof(ObjCMessageExpr) + sizeof(void *) +
Douglas Gregor04badcf2010-04-21 00:45:42 +00002525 NumArgs * sizeof(Expr *);
2526 void *Mem = Context.Allocate(Size, llvm::AlignOf<ObjCMessageExpr>::Alignment);
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00002527 return new (Mem) ObjCMessageExpr(T, VK, LBracLoc, Receiver, Sel, SelLoc,
2528 Method, Args, NumArgs, RBracLoc);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002529}
2530
2531ObjCMessageExpr *ObjCMessageExpr::Create(ASTContext &Context, QualType T,
John McCallf89e55a2010-11-18 06:31:45 +00002532 ExprValueKind VK,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002533 SourceLocation LBracLoc,
2534 Expr *Receiver,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00002535 Selector Sel,
2536 SourceLocation SelLoc,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002537 ObjCMethodDecl *Method,
2538 Expr **Args, unsigned NumArgs,
2539 SourceLocation RBracLoc) {
Sean Huntc3021132010-05-05 15:23:54 +00002540 unsigned Size = sizeof(ObjCMessageExpr) + sizeof(void *) +
Douglas Gregor04badcf2010-04-21 00:45:42 +00002541 NumArgs * sizeof(Expr *);
2542 void *Mem = Context.Allocate(Size, llvm::AlignOf<ObjCMessageExpr>::Alignment);
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00002543 return new (Mem) ObjCMessageExpr(T, VK, LBracLoc, Receiver, Sel, SelLoc,
2544 Method, Args, NumArgs, RBracLoc);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002545}
2546
Sean Huntc3021132010-05-05 15:23:54 +00002547ObjCMessageExpr *ObjCMessageExpr::CreateEmpty(ASTContext &Context,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002548 unsigned NumArgs) {
Sean Huntc3021132010-05-05 15:23:54 +00002549 unsigned Size = sizeof(ObjCMessageExpr) + sizeof(void *) +
Douglas Gregor04badcf2010-04-21 00:45:42 +00002550 NumArgs * sizeof(Expr *);
2551 void *Mem = Context.Allocate(Size, llvm::AlignOf<ObjCMessageExpr>::Alignment);
2552 return new (Mem) ObjCMessageExpr(EmptyShell(), NumArgs);
2553}
Argyrios Kyrtzidise005d192010-12-10 20:08:30 +00002554
2555SourceRange ObjCMessageExpr::getReceiverRange() const {
2556 switch (getReceiverKind()) {
2557 case Instance:
2558 return getInstanceReceiver()->getSourceRange();
2559
2560 case Class:
2561 return getClassReceiverTypeInfo()->getTypeLoc().getSourceRange();
2562
2563 case SuperInstance:
2564 case SuperClass:
2565 return getSuperLoc();
2566 }
2567
2568 return SourceLocation();
2569}
2570
Douglas Gregor04badcf2010-04-21 00:45:42 +00002571Selector ObjCMessageExpr::getSelector() const {
2572 if (HasMethod)
2573 return reinterpret_cast<const ObjCMethodDecl *>(SelectorOrMethod)
2574 ->getSelector();
Sean Huntc3021132010-05-05 15:23:54 +00002575 return Selector(SelectorOrMethod);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002576}
2577
2578ObjCInterfaceDecl *ObjCMessageExpr::getReceiverInterface() const {
2579 switch (getReceiverKind()) {
2580 case Instance:
2581 if (const ObjCObjectPointerType *Ptr
2582 = getInstanceReceiver()->getType()->getAs<ObjCObjectPointerType>())
2583 return Ptr->getInterfaceDecl();
2584 break;
2585
2586 case Class:
John McCallc12c5bb2010-05-15 11:32:37 +00002587 if (const ObjCObjectType *Ty
2588 = getClassReceiver()->getAs<ObjCObjectType>())
2589 return Ty->getInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00002590 break;
2591
2592 case SuperInstance:
2593 if (const ObjCObjectPointerType *Ptr
2594 = getSuperType()->getAs<ObjCObjectPointerType>())
2595 return Ptr->getInterfaceDecl();
2596 break;
2597
2598 case SuperClass:
Argyrios Kyrtzidisee8a6ca2011-01-25 00:03:48 +00002599 if (const ObjCObjectType *Iface
2600 = getSuperType()->getAs<ObjCObjectType>())
2601 return Iface->getInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00002602 break;
2603 }
2604
2605 return 0;
Ted Kremenekeb3b3242010-02-11 22:41:21 +00002606}
Chris Lattner0389e6b2009-04-26 00:44:05 +00002607
Jay Foad4ba2a172011-01-12 09:06:06 +00002608bool ChooseExpr::isConditionTrue(const ASTContext &C) const {
Eli Friedman9a901bb2009-04-26 19:19:15 +00002609 return getCond()->EvaluateAsInt(C) != 0;
Chris Lattner27437ca2007-10-25 00:29:32 +00002610}
2611
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00002612ShuffleVectorExpr::ShuffleVectorExpr(ASTContext &C, Expr **args, unsigned nexpr,
2613 QualType Type, SourceLocation BLoc,
2614 SourceLocation RP)
2615 : Expr(ShuffleVectorExprClass, Type, VK_RValue, OK_Ordinary,
2616 Type->isDependentType(), Type->isDependentType(),
2617 Type->containsUnexpandedParameterPack()),
2618 BuiltinLoc(BLoc), RParenLoc(RP), NumExprs(nexpr)
2619{
2620 SubExprs = new (C) Stmt*[nexpr];
2621 for (unsigned i = 0; i < nexpr; i++) {
2622 if (args[i]->isTypeDependent())
2623 ExprBits.TypeDependent = true;
2624 if (args[i]->isValueDependent())
2625 ExprBits.ValueDependent = true;
2626 if (args[i]->containsUnexpandedParameterPack())
2627 ExprBits.ContainsUnexpandedParameterPack = true;
2628
2629 SubExprs[i] = args[i];
2630 }
2631}
2632
Nate Begeman888376a2009-08-12 02:28:50 +00002633void ShuffleVectorExpr::setExprs(ASTContext &C, Expr ** Exprs,
2634 unsigned NumExprs) {
2635 if (SubExprs) C.Deallocate(SubExprs);
2636
2637 SubExprs = new (C) Stmt* [NumExprs];
Douglas Gregor94cd5d12009-04-16 00:01:45 +00002638 this->NumExprs = NumExprs;
2639 memcpy(SubExprs, Exprs, sizeof(Expr *) * NumExprs);
Mike Stump1eb44332009-09-09 15:08:12 +00002640}
Nate Begeman888376a2009-08-12 02:28:50 +00002641
Ted Kremenek77ed8e42007-08-24 18:13:47 +00002642//===----------------------------------------------------------------------===//
Douglas Gregor05c13a32009-01-22 00:58:24 +00002643// DesignatedInitExpr
2644//===----------------------------------------------------------------------===//
2645
2646IdentifierInfo *DesignatedInitExpr::Designator::getFieldName() {
2647 assert(Kind == FieldDesignator && "Only valid on a field designator");
2648 if (Field.NameOrField & 0x01)
2649 return reinterpret_cast<IdentifierInfo *>(Field.NameOrField&~0x01);
2650 else
2651 return getField()->getIdentifier();
2652}
2653
Sean Huntc3021132010-05-05 15:23:54 +00002654DesignatedInitExpr::DesignatedInitExpr(ASTContext &C, QualType Ty,
Douglas Gregor319d57f2010-01-06 23:17:19 +00002655 unsigned NumDesignators,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00002656 const Designator *Designators,
Mike Stump1eb44332009-09-09 15:08:12 +00002657 SourceLocation EqualOrColonLoc,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00002658 bool GNUSyntax,
Mike Stump1eb44332009-09-09 15:08:12 +00002659 Expr **IndexExprs,
Douglas Gregor9ea62762009-05-21 23:17:49 +00002660 unsigned NumIndexExprs,
2661 Expr *Init)
Mike Stump1eb44332009-09-09 15:08:12 +00002662 : Expr(DesignatedInitExprClass, Ty,
John McCallf89e55a2010-11-18 06:31:45 +00002663 Init->getValueKind(), Init->getObjectKind(),
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00002664 Init->isTypeDependent(), Init->isValueDependent(),
2665 Init->containsUnexpandedParameterPack()),
Mike Stump1eb44332009-09-09 15:08:12 +00002666 EqualOrColonLoc(EqualOrColonLoc), GNUSyntax(GNUSyntax),
2667 NumDesignators(NumDesignators), NumSubExprs(NumIndexExprs + 1) {
Douglas Gregor319d57f2010-01-06 23:17:19 +00002668 this->Designators = new (C) Designator[NumDesignators];
Douglas Gregor9ea62762009-05-21 23:17:49 +00002669
2670 // Record the initializer itself.
John McCall7502c1d2011-02-13 04:07:26 +00002671 child_range Child = children();
Douglas Gregor9ea62762009-05-21 23:17:49 +00002672 *Child++ = Init;
2673
2674 // Copy the designators and their subexpressions, computing
2675 // value-dependence along the way.
2676 unsigned IndexIdx = 0;
2677 for (unsigned I = 0; I != NumDesignators; ++I) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00002678 this->Designators[I] = Designators[I];
Douglas Gregor9ea62762009-05-21 23:17:49 +00002679
2680 if (this->Designators[I].isArrayDesignator()) {
2681 // Compute type- and value-dependence.
2682 Expr *Index = IndexExprs[IndexIdx];
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00002683 if (Index->isTypeDependent() || Index->isValueDependent())
2684 ExprBits.ValueDependent = true;
2685
2686 // Propagate unexpanded parameter packs.
2687 if (Index->containsUnexpandedParameterPack())
2688 ExprBits.ContainsUnexpandedParameterPack = true;
Douglas Gregor9ea62762009-05-21 23:17:49 +00002689
2690 // Copy the index expressions into permanent storage.
2691 *Child++ = IndexExprs[IndexIdx++];
2692 } else if (this->Designators[I].isArrayRangeDesignator()) {
2693 // Compute type- and value-dependence.
2694 Expr *Start = IndexExprs[IndexIdx];
2695 Expr *End = IndexExprs[IndexIdx + 1];
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00002696 if (Start->isTypeDependent() || Start->isValueDependent() ||
2697 End->isTypeDependent() || End->isValueDependent())
2698 ExprBits.ValueDependent = true;
2699
2700 // Propagate unexpanded parameter packs.
2701 if (Start->containsUnexpandedParameterPack() ||
2702 End->containsUnexpandedParameterPack())
2703 ExprBits.ContainsUnexpandedParameterPack = true;
Douglas Gregor9ea62762009-05-21 23:17:49 +00002704
2705 // Copy the start/end expressions into permanent storage.
2706 *Child++ = IndexExprs[IndexIdx++];
2707 *Child++ = IndexExprs[IndexIdx++];
2708 }
2709 }
2710
2711 assert(IndexIdx == NumIndexExprs && "Wrong number of index expressions");
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00002712}
2713
Douglas Gregor05c13a32009-01-22 00:58:24 +00002714DesignatedInitExpr *
Mike Stump1eb44332009-09-09 15:08:12 +00002715DesignatedInitExpr::Create(ASTContext &C, Designator *Designators,
Douglas Gregor05c13a32009-01-22 00:58:24 +00002716 unsigned NumDesignators,
2717 Expr **IndexExprs, unsigned NumIndexExprs,
2718 SourceLocation ColonOrEqualLoc,
2719 bool UsesColonSyntax, Expr *Init) {
Steve Naroffc0ac4922009-01-27 23:20:32 +00002720 void *Mem = C.Allocate(sizeof(DesignatedInitExpr) +
Steve Naroffc0ac4922009-01-27 23:20:32 +00002721 sizeof(Stmt *) * (NumIndexExprs + 1), 8);
Douglas Gregor319d57f2010-01-06 23:17:19 +00002722 return new (Mem) DesignatedInitExpr(C, C.VoidTy, NumDesignators, Designators,
Douglas Gregor9ea62762009-05-21 23:17:49 +00002723 ColonOrEqualLoc, UsesColonSyntax,
2724 IndexExprs, NumIndexExprs, Init);
Douglas Gregor05c13a32009-01-22 00:58:24 +00002725}
2726
Mike Stump1eb44332009-09-09 15:08:12 +00002727DesignatedInitExpr *DesignatedInitExpr::CreateEmpty(ASTContext &C,
Douglas Gregord077d752009-04-16 00:55:48 +00002728 unsigned NumIndexExprs) {
2729 void *Mem = C.Allocate(sizeof(DesignatedInitExpr) +
2730 sizeof(Stmt *) * (NumIndexExprs + 1), 8);
2731 return new (Mem) DesignatedInitExpr(NumIndexExprs + 1);
2732}
2733
Douglas Gregor319d57f2010-01-06 23:17:19 +00002734void DesignatedInitExpr::setDesignators(ASTContext &C,
2735 const Designator *Desigs,
Douglas Gregord077d752009-04-16 00:55:48 +00002736 unsigned NumDesigs) {
Douglas Gregor319d57f2010-01-06 23:17:19 +00002737 Designators = new (C) Designator[NumDesigs];
Douglas Gregord077d752009-04-16 00:55:48 +00002738 NumDesignators = NumDesigs;
2739 for (unsigned I = 0; I != NumDesigs; ++I)
2740 Designators[I] = Desigs[I];
2741}
2742
Douglas Gregor05c13a32009-01-22 00:58:24 +00002743SourceRange DesignatedInitExpr::getSourceRange() const {
2744 SourceLocation StartLoc;
Chris Lattnerd603eaa2009-02-16 22:33:34 +00002745 Designator &First =
2746 *const_cast<DesignatedInitExpr*>(this)->designators_begin();
Douglas Gregor05c13a32009-01-22 00:58:24 +00002747 if (First.isFieldDesignator()) {
Douglas Gregoreeae8f02009-03-28 00:41:23 +00002748 if (GNUSyntax)
Douglas Gregor05c13a32009-01-22 00:58:24 +00002749 StartLoc = SourceLocation::getFromRawEncoding(First.Field.FieldLoc);
2750 else
2751 StartLoc = SourceLocation::getFromRawEncoding(First.Field.DotLoc);
2752 } else
Chris Lattnerd603eaa2009-02-16 22:33:34 +00002753 StartLoc =
2754 SourceLocation::getFromRawEncoding(First.ArrayOrRange.LBracketLoc);
Douglas Gregor05c13a32009-01-22 00:58:24 +00002755 return SourceRange(StartLoc, getInit()->getSourceRange().getEnd());
2756}
2757
Douglas Gregor05c13a32009-01-22 00:58:24 +00002758Expr *DesignatedInitExpr::getArrayIndex(const Designator& D) {
2759 assert(D.Kind == Designator::ArrayDesignator && "Requires array designator");
2760 char* Ptr = static_cast<char*>(static_cast<void *>(this));
2761 Ptr += sizeof(DesignatedInitExpr);
Douglas Gregor05c13a32009-01-22 00:58:24 +00002762 Stmt **SubExprs = reinterpret_cast<Stmt**>(reinterpret_cast<void**>(Ptr));
2763 return cast<Expr>(*(SubExprs + D.ArrayOrRange.Index + 1));
2764}
2765
2766Expr *DesignatedInitExpr::getArrayRangeStart(const Designator& D) {
Mike Stump1eb44332009-09-09 15:08:12 +00002767 assert(D.Kind == Designator::ArrayRangeDesignator &&
Douglas Gregor05c13a32009-01-22 00:58:24 +00002768 "Requires array range designator");
2769 char* Ptr = static_cast<char*>(static_cast<void *>(this));
2770 Ptr += sizeof(DesignatedInitExpr);
Douglas Gregor05c13a32009-01-22 00:58:24 +00002771 Stmt **SubExprs = reinterpret_cast<Stmt**>(reinterpret_cast<void**>(Ptr));
2772 return cast<Expr>(*(SubExprs + D.ArrayOrRange.Index + 1));
2773}
2774
2775Expr *DesignatedInitExpr::getArrayRangeEnd(const Designator& D) {
Mike Stump1eb44332009-09-09 15:08:12 +00002776 assert(D.Kind == Designator::ArrayRangeDesignator &&
Douglas Gregor05c13a32009-01-22 00:58:24 +00002777 "Requires array range designator");
2778 char* Ptr = static_cast<char*>(static_cast<void *>(this));
2779 Ptr += sizeof(DesignatedInitExpr);
Douglas Gregor05c13a32009-01-22 00:58:24 +00002780 Stmt **SubExprs = reinterpret_cast<Stmt**>(reinterpret_cast<void**>(Ptr));
2781 return cast<Expr>(*(SubExprs + D.ArrayOrRange.Index + 2));
2782}
2783
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00002784/// \brief Replaces the designator at index @p Idx with the series
2785/// of designators in [First, Last).
Douglas Gregor319d57f2010-01-06 23:17:19 +00002786void DesignatedInitExpr::ExpandDesignator(ASTContext &C, unsigned Idx,
Mike Stump1eb44332009-09-09 15:08:12 +00002787 const Designator *First,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00002788 const Designator *Last) {
2789 unsigned NumNewDesignators = Last - First;
2790 if (NumNewDesignators == 0) {
2791 std::copy_backward(Designators + Idx + 1,
2792 Designators + NumDesignators,
2793 Designators + Idx);
2794 --NumNewDesignators;
2795 return;
2796 } else if (NumNewDesignators == 1) {
2797 Designators[Idx] = *First;
2798 return;
2799 }
2800
Mike Stump1eb44332009-09-09 15:08:12 +00002801 Designator *NewDesignators
Douglas Gregor319d57f2010-01-06 23:17:19 +00002802 = new (C) Designator[NumDesignators - 1 + NumNewDesignators];
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00002803 std::copy(Designators, Designators + Idx, NewDesignators);
2804 std::copy(First, Last, NewDesignators + Idx);
2805 std::copy(Designators + Idx + 1, Designators + NumDesignators,
2806 NewDesignators + Idx + NumNewDesignators);
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00002807 Designators = NewDesignators;
2808 NumDesignators = NumDesignators - 1 + NumNewDesignators;
2809}
2810
Mike Stump1eb44332009-09-09 15:08:12 +00002811ParenListExpr::ParenListExpr(ASTContext& C, SourceLocation lparenloc,
Nate Begeman2ef13e52009-08-10 23:49:36 +00002812 Expr **exprs, unsigned nexprs,
2813 SourceLocation rparenloc)
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00002814 : Expr(ParenListExprClass, QualType(), VK_RValue, OK_Ordinary,
2815 false, false, false),
2816 NumExprs(nexprs), LParenLoc(lparenloc), RParenLoc(rparenloc) {
Mike Stump1eb44332009-09-09 15:08:12 +00002817
Nate Begeman2ef13e52009-08-10 23:49:36 +00002818 Exprs = new (C) Stmt*[nexprs];
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00002819 for (unsigned i = 0; i != nexprs; ++i) {
2820 if (exprs[i]->isTypeDependent())
2821 ExprBits.TypeDependent = true;
2822 if (exprs[i]->isValueDependent())
2823 ExprBits.ValueDependent = true;
2824 if (exprs[i]->containsUnexpandedParameterPack())
2825 ExprBits.ContainsUnexpandedParameterPack = true;
2826
Nate Begeman2ef13e52009-08-10 23:49:36 +00002827 Exprs[i] = exprs[i];
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00002828 }
Nate Begeman2ef13e52009-08-10 23:49:36 +00002829}
2830
John McCalle996ffd2011-02-16 08:02:54 +00002831const OpaqueValueExpr *OpaqueValueExpr::findInCopyConstruct(const Expr *e) {
2832 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(e))
2833 e = ewc->getSubExpr();
2834 e = cast<CXXConstructExpr>(e)->getArg(0);
2835 while (const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
2836 e = ice->getSubExpr();
2837 return cast<OpaqueValueExpr>(e);
2838}
2839
Douglas Gregor05c13a32009-01-22 00:58:24 +00002840//===----------------------------------------------------------------------===//
Ted Kremenekce2fc3a2008-10-27 18:40:21 +00002841// ExprIterator.
2842//===----------------------------------------------------------------------===//
2843
2844Expr* ExprIterator::operator[](size_t idx) { return cast<Expr>(I[idx]); }
2845Expr* ExprIterator::operator*() const { return cast<Expr>(*I); }
2846Expr* ExprIterator::operator->() const { return cast<Expr>(*I); }
2847const Expr* ConstExprIterator::operator[](size_t idx) const {
2848 return cast<Expr>(I[idx]);
2849}
2850const Expr* ConstExprIterator::operator*() const { return cast<Expr>(*I); }
2851const Expr* ConstExprIterator::operator->() const { return cast<Expr>(*I); }
2852
2853//===----------------------------------------------------------------------===//
Ted Kremenek77ed8e42007-08-24 18:13:47 +00002854// Child Iterators for iterating over subexpressions/substatements
2855//===----------------------------------------------------------------------===//
2856
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002857// UnaryExprOrTypeTraitExpr
2858Stmt::child_range UnaryExprOrTypeTraitExpr::children() {
Sebastian Redl05189992008-11-11 17:56:53 +00002859 // If this is of a type and the type is a VLA type (and not a typedef), the
2860 // size expression of the VLA needs to be treated as an executable expression.
2861 // Why isn't this weirdness documented better in StmtIterator?
2862 if (isArgumentType()) {
John McCallf4c73712011-01-19 06:33:43 +00002863 if (const VariableArrayType* T = dyn_cast<VariableArrayType>(
Sebastian Redl05189992008-11-11 17:56:53 +00002864 getArgumentType().getTypePtr()))
John McCall63c00d72011-02-09 08:16:59 +00002865 return child_range(child_iterator(T), child_iterator());
2866 return child_range();
Sebastian Redl05189992008-11-11 17:56:53 +00002867 }
John McCall63c00d72011-02-09 08:16:59 +00002868 return child_range(&Argument.Ex, &Argument.Ex + 1);
Ted Kremenek9ac59282007-10-18 23:28:49 +00002869}
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00002870
Steve Naroff563477d2007-09-18 23:55:05 +00002871// ObjCMessageExpr
John McCall63c00d72011-02-09 08:16:59 +00002872Stmt::child_range ObjCMessageExpr::children() {
2873 Stmt **begin;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002874 if (getReceiverKind() == Instance)
John McCall63c00d72011-02-09 08:16:59 +00002875 begin = reinterpret_cast<Stmt **>(this + 1);
2876 else
2877 begin = reinterpret_cast<Stmt **>(getArgs());
2878 return child_range(begin,
2879 reinterpret_cast<Stmt **>(getArgs() + getNumArgs()));
Steve Naroff563477d2007-09-18 23:55:05 +00002880}
2881
Steve Naroff4eb206b2008-09-03 18:15:37 +00002882// Blocks
John McCall6b5a61b2011-02-07 10:33:21 +00002883BlockDeclRefExpr::BlockDeclRefExpr(VarDecl *d, QualType t, ExprValueKind VK,
Douglas Gregora779d9c2011-01-19 21:32:01 +00002884 SourceLocation l, bool ByRef,
John McCall6b5a61b2011-02-07 10:33:21 +00002885 bool constAdded)
Douglas Gregord967e312011-01-19 21:52:31 +00002886 : Expr(BlockDeclRefExprClass, t, VK, OK_Ordinary, false, false,
Douglas Gregora779d9c2011-01-19 21:32:01 +00002887 d->isParameterPack()),
John McCall6b5a61b2011-02-07 10:33:21 +00002888 D(d), Loc(l), IsByRef(ByRef), ConstQualAdded(constAdded)
Douglas Gregora779d9c2011-01-19 21:32:01 +00002889{
Douglas Gregord967e312011-01-19 21:52:31 +00002890 bool TypeDependent = false;
2891 bool ValueDependent = false;
2892 computeDeclRefDependence(D, getType(), TypeDependent, ValueDependent);
2893 ExprBits.TypeDependent = TypeDependent;
2894 ExprBits.ValueDependent = ValueDependent;
Douglas Gregora779d9c2011-01-19 21:32:01 +00002895}
2896