blob: f9f7ba542cdff29ea056dd0c4e641a3f983dd310 [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"
Richard Smith7a614d82011-06-11 17:19:42 +000025#include "clang/Sema/SemaDiagnostic.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000026#include "clang/Basic/Builtins.h"
Chris Lattner08f92e32010-11-17 07:37:15 +000027#include "clang/Basic/SourceManager.h"
Chris Lattnerda5a6b62007-11-27 18:22:04 +000028#include "clang/Basic/TargetInfo.h"
Douglas Gregorcf3293e2009-11-01 20:32:48 +000029#include "llvm/Support/ErrorHandling.h"
Anders Carlsson3a082d82009-09-08 18:24:21 +000030#include "llvm/Support/raw_ostream.h"
Douglas Gregorffb4b6e2009-04-15 06:41:24 +000031#include <algorithm>
Eli Friedman64f45a22011-11-01 02:23:42 +000032#include <cstring>
Reid Spencer5f016e22007-07-11 17:01:13 +000033using namespace clang;
34
Chris Lattner2b334bb2010-04-16 23:34:13 +000035/// isKnownToHaveBooleanValue - Return true if this is an integer expression
36/// that is known to return 0 or 1. This happens for _Bool/bool expressions
37/// but also int expressions which are produced by things like comparisons in
38/// C.
39bool Expr::isKnownToHaveBooleanValue() const {
Peter Collingbournef111d932011-04-15 00:35:48 +000040 const Expr *E = IgnoreParens();
41
Chris Lattner2b334bb2010-04-16 23:34:13 +000042 // If this value has _Bool type, it is obvious 0/1.
Peter Collingbournef111d932011-04-15 00:35:48 +000043 if (E->getType()->isBooleanType()) return true;
Sean Huntc3021132010-05-05 15:23:54 +000044 // If this is a non-scalar-integer type, we don't care enough to try.
Peter Collingbournef111d932011-04-15 00:35:48 +000045 if (!E->getType()->isIntegralOrEnumerationType()) return false;
Sean Huntc3021132010-05-05 15:23:54 +000046
Peter Collingbournef111d932011-04-15 00:35:48 +000047 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
Chris Lattner2b334bb2010-04-16 23:34:13 +000048 switch (UO->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +000049 case UO_Plus:
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.
Peter Collingbournef111d932011-04-15 00:35:48 +000058 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Chris Lattner2b334bb2010-04-16 23:34:13 +000059 return CE->getSubExpr()->isKnownToHaveBooleanValue();
Sean Huntc3021132010-05-05 15:23:54 +000060
Peter Collingbournef111d932011-04-15 00:35:48 +000061 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
Chris Lattner2b334bb2010-04-16 23:34:13 +000062 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
Peter Collingbournef111d932011-04-15 00:35:48 +000087 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
Chris Lattner2b334bb2010-04-16 23:34:13 +000088 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");
John McCall63c00d72011-02-09 08:16:59 +0000127}
128
Reid Spencer5f016e22007-07-11 17:01:13 +0000129//===----------------------------------------------------------------------===//
130// Primary Expressions.
131//===----------------------------------------------------------------------===//
132
Douglas Gregor561f8122011-07-01 01:22:09 +0000133/// \brief Compute the type-, value-, and instantiation-dependence of a
134/// declaration reference
Douglas Gregord967e312011-01-19 21:52:31 +0000135/// based on the declaration being referenced.
136static void computeDeclRefDependence(NamedDecl *D, QualType T,
137 bool &TypeDependent,
Douglas Gregor561f8122011-07-01 01:22:09 +0000138 bool &ValueDependent,
139 bool &InstantiationDependent) {
Douglas Gregord967e312011-01-19 21:52:31 +0000140 TypeDependent = false;
141 ValueDependent = false;
Douglas Gregor561f8122011-07-01 01:22:09 +0000142 InstantiationDependent = false;
Douglas Gregor0da76df2009-11-23 11:41:28 +0000143
144 // (TD) C++ [temp.dep.expr]p3:
145 // An id-expression is type-dependent if it contains:
146 //
Sean Huntc3021132010-05-05 15:23:54 +0000147 // and
Douglas Gregor0da76df2009-11-23 11:41:28 +0000148 //
149 // (VD) C++ [temp.dep.constexpr]p2:
150 // An identifier is value-dependent if it is:
Douglas Gregord967e312011-01-19 21:52:31 +0000151
Douglas Gregor0da76df2009-11-23 11:41:28 +0000152 // (TD) - an identifier that was declared with dependent type
153 // (VD) - a name declared with a dependent type,
Douglas Gregord967e312011-01-19 21:52:31 +0000154 if (T->isDependentType()) {
155 TypeDependent = true;
156 ValueDependent = true;
Douglas Gregor561f8122011-07-01 01:22:09 +0000157 InstantiationDependent = true;
Douglas Gregord967e312011-01-19 21:52:31 +0000158 return;
Douglas Gregor561f8122011-07-01 01:22:09 +0000159 } else if (T->isInstantiationDependentType()) {
160 InstantiationDependent = true;
Douglas Gregor0da76df2009-11-23 11:41:28 +0000161 }
Douglas Gregord967e312011-01-19 21:52:31 +0000162
Douglas Gregor0da76df2009-11-23 11:41:28 +0000163 // (TD) - a conversion-function-id that specifies a dependent type
Douglas Gregord967e312011-01-19 21:52:31 +0000164 if (D->getDeclName().getNameKind()
Douglas Gregor561f8122011-07-01 01:22:09 +0000165 == DeclarationName::CXXConversionFunctionName) {
166 QualType T = D->getDeclName().getCXXNameType();
167 if (T->isDependentType()) {
168 TypeDependent = true;
169 ValueDependent = true;
170 InstantiationDependent = true;
171 return;
172 }
173
174 if (T->isInstantiationDependentType())
175 InstantiationDependent = true;
Douglas Gregor0da76df2009-11-23 11:41:28 +0000176 }
Douglas Gregor561f8122011-07-01 01:22:09 +0000177
Douglas Gregor0da76df2009-11-23 11:41:28 +0000178 // (VD) - the name of a non-type template parameter,
Douglas Gregord967e312011-01-19 21:52:31 +0000179 if (isa<NonTypeTemplateParmDecl>(D)) {
180 ValueDependent = true;
Douglas Gregor561f8122011-07-01 01:22:09 +0000181 InstantiationDependent = true;
Douglas Gregord967e312011-01-19 21:52:31 +0000182 return;
183 }
184
Douglas Gregor0da76df2009-11-23 11:41:28 +0000185 // (VD) - a constant with integral or enumeration type and is
186 // initialized with an expression that is value-dependent.
Richard Smithdb1822c2011-11-08 01:31:09 +0000187 // (VD) - a constant with literal type and is initialized with an
188 // expression that is value-dependent [C++11].
189 // (VD) - FIXME: Missing from the standard:
190 // - an entity with reference type and is initialized with an
191 // expression that is value-dependent [C++11]
Douglas Gregord967e312011-01-19 21:52:31 +0000192 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Richard Smithdb1822c2011-11-08 01:31:09 +0000193 if ((D->getASTContext().getLangOptions().CPlusPlus0x ?
194 Var->getType()->isLiteralType() :
195 Var->getType()->isIntegralOrEnumerationType()) &&
196 (Var->getType().getCVRQualifiers() == Qualifiers::Const ||
197 Var->getType()->isReferenceType())) {
Sebastian Redl31310a22010-02-01 20:16:42 +0000198 if (const Expr *Init = Var->getAnyInitializer())
Douglas Gregor561f8122011-07-01 01:22:09 +0000199 if (Init->isValueDependent()) {
Douglas Gregord967e312011-01-19 21:52:31 +0000200 ValueDependent = true;
Douglas Gregor561f8122011-07-01 01:22:09 +0000201 InstantiationDependent = true;
202 }
Richard Smithdb1822c2011-11-08 01:31:09 +0000203 }
204
Douglas Gregorbb6e73f2010-05-11 08:41:30 +0000205 // (VD) - FIXME: Missing from the standard:
206 // - a member function or a static data member of the current
207 // instantiation
Richard Smithdb1822c2011-11-08 01:31:09 +0000208 if (Var->isStaticDataMember() &&
209 Var->getDeclContext()->isDependentContext()) {
Douglas Gregord967e312011-01-19 21:52:31 +0000210 ValueDependent = true;
Douglas Gregor561f8122011-07-01 01:22:09 +0000211 InstantiationDependent = true;
212 }
Douglas Gregord967e312011-01-19 21:52:31 +0000213
214 return;
215 }
216
Douglas Gregorbb6e73f2010-05-11 08:41:30 +0000217 // (VD) - FIXME: Missing from the standard:
218 // - a member function or a static data member of the current
219 // instantiation
Douglas Gregord967e312011-01-19 21:52:31 +0000220 if (isa<CXXMethodDecl>(D) && D->getDeclContext()->isDependentContext()) {
221 ValueDependent = true;
Douglas Gregor561f8122011-07-01 01:22:09 +0000222 InstantiationDependent = true;
Richard Smithdb1822c2011-11-08 01:31:09 +0000223 }
Douglas Gregord967e312011-01-19 21:52:31 +0000224}
Douglas Gregorbebbe0d2010-12-15 01:34:56 +0000225
Douglas Gregord967e312011-01-19 21:52:31 +0000226void DeclRefExpr::computeDependence() {
227 bool TypeDependent = false;
228 bool ValueDependent = false;
Douglas Gregor561f8122011-07-01 01:22:09 +0000229 bool InstantiationDependent = false;
230 computeDeclRefDependence(getDecl(), getType(), TypeDependent, ValueDependent,
231 InstantiationDependent);
Douglas Gregord967e312011-01-19 21:52:31 +0000232
233 // (TD) C++ [temp.dep.expr]p3:
234 // An id-expression is type-dependent if it contains:
235 //
236 // and
237 //
238 // (VD) C++ [temp.dep.constexpr]p2:
239 // An identifier is value-dependent if it is:
240 if (!TypeDependent && !ValueDependent &&
241 hasExplicitTemplateArgs() &&
242 TemplateSpecializationType::anyDependentTemplateArguments(
243 getTemplateArgs(),
Douglas Gregor561f8122011-07-01 01:22:09 +0000244 getNumTemplateArgs(),
245 InstantiationDependent)) {
Douglas Gregord967e312011-01-19 21:52:31 +0000246 TypeDependent = true;
247 ValueDependent = true;
Douglas Gregor561f8122011-07-01 01:22:09 +0000248 InstantiationDependent = true;
Douglas Gregord967e312011-01-19 21:52:31 +0000249 }
250
251 ExprBits.TypeDependent = TypeDependent;
252 ExprBits.ValueDependent = ValueDependent;
Douglas Gregor561f8122011-07-01 01:22:09 +0000253 ExprBits.InstantiationDependent = InstantiationDependent;
Douglas Gregord967e312011-01-19 21:52:31 +0000254
Douglas Gregor10738d32010-12-23 23:51:58 +0000255 // Is the declaration a parameter pack?
Douglas Gregord967e312011-01-19 21:52:31 +0000256 if (getDecl()->isParameterPack())
Douglas Gregor1fe85ea2011-01-05 21:11:38 +0000257 ExprBits.ContainsUnexpandedParameterPack = true;
Douglas Gregor0da76df2009-11-23 11:41:28 +0000258}
259
Chandler Carruth3aa81402011-05-01 23:48:14 +0000260DeclRefExpr::DeclRefExpr(NestedNameSpecifierLoc QualifierLoc,
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000261 SourceLocation TemplateKWLoc,
Abramo Bagnara25777432010-08-11 22:01:17 +0000262 ValueDecl *D, const DeclarationNameInfo &NameInfo,
Chandler Carruth3aa81402011-05-01 23:48:14 +0000263 NamedDecl *FoundD,
Abramo Bagnara25777432010-08-11 22:01:17 +0000264 const TemplateArgumentListInfo *TemplateArgs,
John McCallf89e55a2010-11-18 06:31:45 +0000265 QualType T, ExprValueKind VK)
Douglas Gregor561f8122011-07-01 01:22:09 +0000266 : Expr(DeclRefExprClass, T, VK, OK_Ordinary, false, false, false, false),
Chandler Carruthcb66cff2011-05-01 21:29:53 +0000267 D(D), Loc(NameInfo.getLoc()), DNLoc(NameInfo.getInfo()) {
268 DeclRefExprBits.HasQualifier = QualifierLoc ? 1 : 0;
Chandler Carruth7e740bd2011-05-01 21:55:21 +0000269 if (QualifierLoc)
Chandler Carruth6857c3e2011-05-01 22:14:37 +0000270 getInternalQualifierLoc() = QualifierLoc;
Chandler Carruth3aa81402011-05-01 23:48:14 +0000271 DeclRefExprBits.HasFoundDecl = FoundD ? 1 : 0;
272 if (FoundD)
273 getInternalFoundDecl() = FoundD;
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000274 DeclRefExprBits.HasTemplateKWAndArgsInfo
275 = (TemplateArgs || TemplateKWLoc.isValid()) ? 1 : 0;
Douglas Gregor561f8122011-07-01 01:22:09 +0000276 if (TemplateArgs) {
277 bool Dependent = false;
278 bool InstantiationDependent = false;
279 bool ContainsUnexpandedParameterPack = false;
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000280 getTemplateKWAndArgsInfo()->initializeFrom(TemplateKWLoc, *TemplateArgs,
281 Dependent,
282 InstantiationDependent,
283 ContainsUnexpandedParameterPack);
Douglas Gregor561f8122011-07-01 01:22:09 +0000284 if (InstantiationDependent)
285 setInstantiationDependent(true);
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000286 } else if (TemplateKWLoc.isValid()) {
287 getTemplateKWAndArgsInfo()->initializeFrom(TemplateKWLoc);
Douglas Gregor561f8122011-07-01 01:22:09 +0000288 }
Benjamin Kramerb8da98a2011-10-10 12:54:05 +0000289 DeclRefExprBits.HadMultipleCandidates = 0;
290
Abramo Bagnara25777432010-08-11 22:01:17 +0000291 computeDependence();
292}
293
Douglas Gregora2813ce2009-10-23 18:54:35 +0000294DeclRefExpr *DeclRefExpr::Create(ASTContext &Context,
Douglas Gregor40d96a62011-02-28 21:54:11 +0000295 NestedNameSpecifierLoc QualifierLoc,
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000296 SourceLocation TemplateKWLoc,
John McCalldbd872f2009-12-08 09:08:17 +0000297 ValueDecl *D,
Douglas Gregora2813ce2009-10-23 18:54:35 +0000298 SourceLocation NameLoc,
Douglas Gregor0da76df2009-11-23 11:41:28 +0000299 QualType T,
John McCallf89e55a2010-11-18 06:31:45 +0000300 ExprValueKind VK,
Chandler Carruth3aa81402011-05-01 23:48:14 +0000301 NamedDecl *FoundD,
Douglas Gregor0da76df2009-11-23 11:41:28 +0000302 const TemplateArgumentListInfo *TemplateArgs) {
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000303 return Create(Context, QualifierLoc, TemplateKWLoc, D,
Abramo Bagnara25777432010-08-11 22:01:17 +0000304 DeclarationNameInfo(D->getDeclName(), NameLoc),
Chandler Carruth3aa81402011-05-01 23:48:14 +0000305 T, VK, FoundD, TemplateArgs);
Abramo Bagnara25777432010-08-11 22:01:17 +0000306}
307
308DeclRefExpr *DeclRefExpr::Create(ASTContext &Context,
Douglas Gregor40d96a62011-02-28 21:54:11 +0000309 NestedNameSpecifierLoc QualifierLoc,
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000310 SourceLocation TemplateKWLoc,
Abramo Bagnara25777432010-08-11 22:01:17 +0000311 ValueDecl *D,
312 const DeclarationNameInfo &NameInfo,
313 QualType T,
John McCallf89e55a2010-11-18 06:31:45 +0000314 ExprValueKind VK,
Chandler Carruth3aa81402011-05-01 23:48:14 +0000315 NamedDecl *FoundD,
Abramo Bagnara25777432010-08-11 22:01:17 +0000316 const TemplateArgumentListInfo *TemplateArgs) {
Chandler Carruth3aa81402011-05-01 23:48:14 +0000317 // Filter out cases where the found Decl is the same as the value refenenced.
318 if (D == FoundD)
319 FoundD = 0;
320
Douglas Gregora2813ce2009-10-23 18:54:35 +0000321 std::size_t Size = sizeof(DeclRefExpr);
Douglas Gregor40d96a62011-02-28 21:54:11 +0000322 if (QualifierLoc != 0)
Chandler Carruth6857c3e2011-05-01 22:14:37 +0000323 Size += sizeof(NestedNameSpecifierLoc);
Chandler Carruth3aa81402011-05-01 23:48:14 +0000324 if (FoundD)
325 Size += sizeof(NamedDecl *);
John McCalld5532b62009-11-23 01:53:49 +0000326 if (TemplateArgs)
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000327 Size += ASTTemplateKWAndArgsInfo::sizeFor(TemplateArgs->size());
328 else if (TemplateKWLoc.isValid())
329 Size += ASTTemplateKWAndArgsInfo::sizeFor(0);
Chandler Carruth3aa81402011-05-01 23:48:14 +0000330
Chris Lattner32488542010-10-30 05:14:06 +0000331 void *Mem = Context.Allocate(Size, llvm::alignOf<DeclRefExpr>());
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000332 return new (Mem) DeclRefExpr(QualifierLoc, TemplateKWLoc, D, NameInfo,
333 FoundD, TemplateArgs, T, VK);
Douglas Gregora2813ce2009-10-23 18:54:35 +0000334}
335
Chandler Carruth3aa81402011-05-01 23:48:14 +0000336DeclRefExpr *DeclRefExpr::CreateEmpty(ASTContext &Context,
Douglas Gregordef03542011-02-04 12:01:24 +0000337 bool HasQualifier,
Chandler Carruth3aa81402011-05-01 23:48:14 +0000338 bool HasFoundDecl,
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000339 bool HasTemplateKWAndArgsInfo,
Argyrios Kyrtzidis663e3802010-07-08 13:09:47 +0000340 unsigned NumTemplateArgs) {
341 std::size_t Size = sizeof(DeclRefExpr);
342 if (HasQualifier)
Chandler Carruth6857c3e2011-05-01 22:14:37 +0000343 Size += sizeof(NestedNameSpecifierLoc);
Chandler Carruth3aa81402011-05-01 23:48:14 +0000344 if (HasFoundDecl)
345 Size += sizeof(NamedDecl *);
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000346 if (HasTemplateKWAndArgsInfo)
347 Size += ASTTemplateKWAndArgsInfo::sizeFor(NumTemplateArgs);
Chandler Carruth3aa81402011-05-01 23:48:14 +0000348
Chris Lattner32488542010-10-30 05:14:06 +0000349 void *Mem = Context.Allocate(Size, llvm::alignOf<DeclRefExpr>());
Argyrios Kyrtzidis663e3802010-07-08 13:09:47 +0000350 return new (Mem) DeclRefExpr(EmptyShell());
351}
352
Douglas Gregora2813ce2009-10-23 18:54:35 +0000353SourceRange DeclRefExpr::getSourceRange() const {
Abramo Bagnara25777432010-08-11 22:01:17 +0000354 SourceRange R = getNameInfo().getSourceRange();
Douglas Gregora2813ce2009-10-23 18:54:35 +0000355 if (hasQualifier())
Douglas Gregor40d96a62011-02-28 21:54:11 +0000356 R.setBegin(getQualifierLoc().getBeginLoc());
John McCall096832c2010-08-19 23:49:38 +0000357 if (hasExplicitTemplateArgs())
Douglas Gregora2813ce2009-10-23 18:54:35 +0000358 R.setEnd(getRAngleLoc());
359 return R;
360}
361
Anders Carlsson3a082d82009-09-08 18:24:21 +0000362// FIXME: Maybe this should use DeclPrinter with a special "print predefined
363// expr" policy instead.
Anders Carlsson848fa642010-02-11 18:20:28 +0000364std::string PredefinedExpr::ComputeName(IdentType IT, const Decl *CurrentDecl) {
365 ASTContext &Context = CurrentDecl->getASTContext();
366
Anders Carlsson3a082d82009-09-08 18:24:21 +0000367 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CurrentDecl)) {
Anders Carlsson848fa642010-02-11 18:20:28 +0000368 if (IT != PrettyFunction && IT != PrettyFunctionNoVirtual)
Anders Carlsson3a082d82009-09-08 18:24:21 +0000369 return FD->getNameAsString();
370
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000371 SmallString<256> Name;
Anders Carlsson3a082d82009-09-08 18:24:21 +0000372 llvm::raw_svector_ostream Out(Name);
373
374 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
Anders Carlsson848fa642010-02-11 18:20:28 +0000375 if (MD->isVirtual() && IT != PrettyFunctionNoVirtual)
Anders Carlsson3a082d82009-09-08 18:24:21 +0000376 Out << "virtual ";
Sam Weinig4eadcc52009-12-27 01:38:20 +0000377 if (MD->isStatic())
378 Out << "static ";
Anders Carlsson3a082d82009-09-08 18:24:21 +0000379 }
380
381 PrintingPolicy Policy(Context.getLangOptions());
Anders Carlsson3a082d82009-09-08 18:24:21 +0000382
383 std::string Proto = FD->getQualifiedNameAsString(Policy);
384
John McCall183700f2009-09-21 23:43:11 +0000385 const FunctionType *AFT = FD->getType()->getAs<FunctionType>();
Anders Carlsson3a082d82009-09-08 18:24:21 +0000386 const FunctionProtoType *FT = 0;
387 if (FD->hasWrittenPrototype())
388 FT = dyn_cast<FunctionProtoType>(AFT);
389
390 Proto += "(";
391 if (FT) {
392 llvm::raw_string_ostream POut(Proto);
393 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) {
394 if (i) POut << ", ";
395 std::string Param;
396 FD->getParamDecl(i)->getType().getAsStringInternal(Param, Policy);
397 POut << Param;
398 }
399
400 if (FT->isVariadic()) {
401 if (FD->getNumParams()) POut << ", ";
402 POut << "...";
403 }
404 }
405 Proto += ")";
406
Sam Weinig4eadcc52009-12-27 01:38:20 +0000407 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
408 Qualifiers ThisQuals = Qualifiers::fromCVRMask(MD->getTypeQualifiers());
409 if (ThisQuals.hasConst())
410 Proto += " const";
411 if (ThisQuals.hasVolatile())
412 Proto += " volatile";
413 }
414
Sam Weinig3a1ce1e2009-12-06 23:55:13 +0000415 if (!isa<CXXConstructorDecl>(FD) && !isa<CXXDestructorDecl>(FD))
416 AFT->getResultType().getAsStringInternal(Proto, Policy);
Anders Carlsson3a082d82009-09-08 18:24:21 +0000417
418 Out << Proto;
419
420 Out.flush();
421 return Name.str().str();
422 }
423 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurrentDecl)) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000424 SmallString<256> Name;
Anders Carlsson3a082d82009-09-08 18:24:21 +0000425 llvm::raw_svector_ostream Out(Name);
426 Out << (MD->isInstanceMethod() ? '-' : '+');
427 Out << '[';
Ted Kremenekb03d33e2010-03-18 21:23:08 +0000428
429 // For incorrect code, there might not be an ObjCInterfaceDecl. Do
430 // a null check to avoid a crash.
431 if (const ObjCInterfaceDecl *ID = MD->getClassInterface())
Benjamin Kramerb8989f22011-10-14 18:45:37 +0000432 Out << *ID;
Ted Kremenekb03d33e2010-03-18 21:23:08 +0000433
Anders Carlsson3a082d82009-09-08 18:24:21 +0000434 if (const ObjCCategoryImplDecl *CID =
Benjamin Kramer900fc632010-04-17 09:33:03 +0000435 dyn_cast<ObjCCategoryImplDecl>(MD->getDeclContext()))
Benjamin Kramerf9780592012-02-07 11:57:45 +0000436 Out << '(' << *CID << ')';
Benjamin Kramer900fc632010-04-17 09:33:03 +0000437
Anders Carlsson3a082d82009-09-08 18:24:21 +0000438 Out << ' ';
439 Out << MD->getSelector().getAsString();
440 Out << ']';
441
442 Out.flush();
443 return Name.str().str();
444 }
445 if (isa<TranslationUnitDecl>(CurrentDecl) && IT == PrettyFunction) {
446 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
447 return "top level";
448 }
449 return "";
450}
451
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +0000452void APNumericStorage::setIntValue(ASTContext &C, const llvm::APInt &Val) {
453 if (hasAllocation())
454 C.Deallocate(pVal);
455
456 BitWidth = Val.getBitWidth();
457 unsigned NumWords = Val.getNumWords();
458 const uint64_t* Words = Val.getRawData();
459 if (NumWords > 1) {
460 pVal = new (C) uint64_t[NumWords];
461 std::copy(Words, Words + NumWords, pVal);
462 } else if (NumWords == 1)
463 VAL = Words[0];
464 else
465 VAL = 0;
466}
467
468IntegerLiteral *
469IntegerLiteral::Create(ASTContext &C, const llvm::APInt &V,
470 QualType type, SourceLocation l) {
471 return new (C) IntegerLiteral(C, V, type, l);
472}
473
474IntegerLiteral *
475IntegerLiteral::Create(ASTContext &C, EmptyShell Empty) {
476 return new (C) IntegerLiteral(Empty);
477}
478
479FloatingLiteral *
480FloatingLiteral::Create(ASTContext &C, const llvm::APFloat &V,
481 bool isexact, QualType Type, SourceLocation L) {
482 return new (C) FloatingLiteral(C, V, isexact, Type, L);
483}
484
485FloatingLiteral *
486FloatingLiteral::Create(ASTContext &C, EmptyShell Empty) {
Akira Hatanaka31dfd642012-01-10 22:40:09 +0000487 return new (C) FloatingLiteral(C, Empty);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +0000488}
489
Chris Lattnerda8249e2008-06-07 22:13:43 +0000490/// getValueAsApproximateDouble - This returns the value as an inaccurate
491/// double. Note that this may cause loss of precision, but is useful for
492/// debugging dumps, etc.
493double FloatingLiteral::getValueAsApproximateDouble() const {
494 llvm::APFloat V = getValue();
Dale Johannesenee5a7002008-10-09 23:02:32 +0000495 bool ignored;
496 V.convert(llvm::APFloat::IEEEdouble, llvm::APFloat::rmNearestTiesToEven,
497 &ignored);
Chris Lattnerda8249e2008-06-07 22:13:43 +0000498 return V.convertToDouble();
499}
500
Eli Friedmand97927d2012-01-06 20:42:20 +0000501int StringLiteral::mapCharByteWidth(TargetInfo const &target,StringKind k) {
502 int CharByteWidth;
Eli Friedman64f45a22011-11-01 02:23:42 +0000503 switch(k) {
504 case Ascii:
505 case UTF8:
506 CharByteWidth = target.getCharWidth();
507 break;
508 case Wide:
509 CharByteWidth = target.getWCharWidth();
510 break;
511 case UTF16:
512 CharByteWidth = target.getChar16Width();
513 break;
514 case UTF32:
515 CharByteWidth = target.getChar32Width();
516 }
517 assert((CharByteWidth & 7) == 0 && "Assumes character size is byte multiple");
518 CharByteWidth /= 8;
519 assert((CharByteWidth==1 || CharByteWidth==2 || CharByteWidth==4)
520 && "character byte widths supported are 1, 2, and 4 only");
521 return CharByteWidth;
522}
523
Chris Lattner5f9e2722011-07-23 10:55:15 +0000524StringLiteral *StringLiteral::Create(ASTContext &C, StringRef Str,
Douglas Gregor5cee1192011-07-27 05:40:30 +0000525 StringKind Kind, bool Pascal, QualType Ty,
Mike Stump1eb44332009-09-09 15:08:12 +0000526 const SourceLocation *Loc,
Anders Carlssona135fb42009-03-15 18:34:13 +0000527 unsigned NumStrs) {
Chris Lattner2085fd62009-02-18 06:40:38 +0000528 // Allocate enough space for the StringLiteral plus an array of locations for
529 // any concatenated string tokens.
530 void *Mem = C.Allocate(sizeof(StringLiteral)+
531 sizeof(SourceLocation)*(NumStrs-1),
Chris Lattner32488542010-10-30 05:14:06 +0000532 llvm::alignOf<StringLiteral>());
Chris Lattner2085fd62009-02-18 06:40:38 +0000533 StringLiteral *SL = new (Mem) StringLiteral(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +0000534
Reid Spencer5f016e22007-07-11 17:01:13 +0000535 // OPTIMIZE: could allocate this appended to the StringLiteral.
Eli Friedman64f45a22011-11-01 02:23:42 +0000536 SL->setString(C,Str,Kind,Pascal);
537
Chris Lattner2085fd62009-02-18 06:40:38 +0000538 SL->TokLocs[0] = Loc[0];
539 SL->NumConcatenated = NumStrs;
Reid Spencer5f016e22007-07-11 17:01:13 +0000540
Chris Lattner726e1682009-02-18 05:49:11 +0000541 if (NumStrs != 1)
Chris Lattner2085fd62009-02-18 06:40:38 +0000542 memcpy(&SL->TokLocs[1], Loc+1, sizeof(SourceLocation)*(NumStrs-1));
543 return SL;
Chris Lattner726e1682009-02-18 05:49:11 +0000544}
545
Douglas Gregor673ecd62009-04-15 16:35:07 +0000546StringLiteral *StringLiteral::CreateEmpty(ASTContext &C, unsigned NumStrs) {
547 void *Mem = C.Allocate(sizeof(StringLiteral)+
548 sizeof(SourceLocation)*(NumStrs-1),
Chris Lattner32488542010-10-30 05:14:06 +0000549 llvm::alignOf<StringLiteral>());
Douglas Gregor673ecd62009-04-15 16:35:07 +0000550 StringLiteral *SL = new (Mem) StringLiteral(QualType());
Eli Friedman64f45a22011-11-01 02:23:42 +0000551 SL->CharByteWidth = 0;
552 SL->Length = 0;
Douglas Gregor673ecd62009-04-15 16:35:07 +0000553 SL->NumConcatenated = NumStrs;
554 return SL;
555}
556
Eli Friedman64f45a22011-11-01 02:23:42 +0000557void StringLiteral::setString(ASTContext &C, StringRef Str,
558 StringKind Kind, bool IsPascal) {
559 //FIXME: we assume that the string data comes from a target that uses the same
560 // code unit size and endianess for the type of string.
561 this->Kind = Kind;
562 this->IsPascal = IsPascal;
563
564 CharByteWidth = mapCharByteWidth(C.getTargetInfo(),Kind);
565 assert((Str.size()%CharByteWidth == 0)
566 && "size of data must be multiple of CharByteWidth");
567 Length = Str.size()/CharByteWidth;
568
569 switch(CharByteWidth) {
570 case 1: {
571 char *AStrData = new (C) char[Length];
572 std::memcpy(AStrData,Str.data(),Str.size());
573 StrData.asChar = AStrData;
574 break;
575 }
576 case 2: {
577 uint16_t *AStrData = new (C) uint16_t[Length];
578 std::memcpy(AStrData,Str.data(),Str.size());
579 StrData.asUInt16 = AStrData;
580 break;
581 }
582 case 4: {
583 uint32_t *AStrData = new (C) uint32_t[Length];
584 std::memcpy(AStrData,Str.data(),Str.size());
585 StrData.asUInt32 = AStrData;
586 break;
587 }
588 default:
589 assert(false && "unsupported CharByteWidth");
590 }
Douglas Gregor673ecd62009-04-15 16:35:07 +0000591}
592
Chris Lattner08f92e32010-11-17 07:37:15 +0000593/// getLocationOfByte - Return a source location that points to the specified
594/// byte of this string literal.
595///
596/// Strings are amazingly complex. They can be formed from multiple tokens and
597/// can have escape sequences in them in addition to the usual trigraph and
598/// escaped newline business. This routine handles this complexity.
599///
600SourceLocation StringLiteral::
601getLocationOfByte(unsigned ByteNo, const SourceManager &SM,
602 const LangOptions &Features, const TargetInfo &Target) const {
Douglas Gregor5cee1192011-07-27 05:40:30 +0000603 assert(Kind == StringLiteral::Ascii && "This only works for ASCII strings");
604
Chris Lattner08f92e32010-11-17 07:37:15 +0000605 // Loop over all of the tokens in this string until we find the one that
606 // contains the byte we're looking for.
607 unsigned TokNo = 0;
608 while (1) {
609 assert(TokNo < getNumConcatenated() && "Invalid byte number!");
610 SourceLocation StrTokLoc = getStrTokenLoc(TokNo);
611
612 // Get the spelling of the string so that we can get the data that makes up
613 // the string literal, not the identifier for the macro it is potentially
614 // expanded through.
615 SourceLocation StrTokSpellingLoc = SM.getSpellingLoc(StrTokLoc);
616
617 // Re-lex the token to get its length and original spelling.
618 std::pair<FileID, unsigned> LocInfo =SM.getDecomposedLoc(StrTokSpellingLoc);
619 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000620 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
Chris Lattner08f92e32010-11-17 07:37:15 +0000621 if (Invalid)
622 return StrTokSpellingLoc;
623
624 const char *StrData = Buffer.data()+LocInfo.second;
625
626 // Create a langops struct and enable trigraphs. This is sufficient for
627 // relexing tokens.
628 LangOptions LangOpts;
629 LangOpts.Trigraphs = true;
630
631 // Create a lexer starting at the beginning of this token.
632 Lexer TheLexer(StrTokSpellingLoc, Features, Buffer.begin(), StrData,
633 Buffer.end());
634 Token TheTok;
635 TheLexer.LexFromRawLexer(TheTok);
636
637 // Use the StringLiteralParser to compute the length of the string in bytes.
638 StringLiteralParser SLP(&TheTok, 1, SM, Features, Target);
639 unsigned TokNumBytes = SLP.GetStringLength();
640
641 // If the byte is in this token, return the location of the byte.
642 if (ByteNo < TokNumBytes ||
Hans Wennborg935a70c2011-06-30 20:17:41 +0000643 (ByteNo == TokNumBytes && TokNo == getNumConcatenated() - 1)) {
Chris Lattner08f92e32010-11-17 07:37:15 +0000644 unsigned Offset = SLP.getOffsetOfStringByte(TheTok, ByteNo);
645
646 // Now that we know the offset of the token in the spelling, use the
647 // preprocessor to get the offset in the original source.
648 return Lexer::AdvanceToTokenCharacter(StrTokLoc, Offset, SM, Features);
649 }
650
651 // Move to the next string token.
652 ++TokNo;
653 ByteNo -= TokNumBytes;
654 }
655}
656
657
658
Reid Spencer5f016e22007-07-11 17:01:13 +0000659/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
660/// corresponds to, e.g. "sizeof" or "[pre]++".
661const char *UnaryOperator::getOpcodeStr(Opcode Op) {
662 switch (Op) {
John McCall2de56d12010-08-25 11:45:40 +0000663 case UO_PostInc: return "++";
664 case UO_PostDec: return "--";
665 case UO_PreInc: return "++";
666 case UO_PreDec: return "--";
667 case UO_AddrOf: return "&";
668 case UO_Deref: return "*";
669 case UO_Plus: return "+";
670 case UO_Minus: return "-";
671 case UO_Not: return "~";
672 case UO_LNot: return "!";
673 case UO_Real: return "__real";
674 case UO_Imag: return "__imag";
675 case UO_Extension: return "__extension__";
Reid Spencer5f016e22007-07-11 17:01:13 +0000676 }
David Blaikie561d3ab2012-01-17 02:30:50 +0000677 llvm_unreachable("Unknown unary operator");
Reid Spencer5f016e22007-07-11 17:01:13 +0000678}
679
John McCall2de56d12010-08-25 11:45:40 +0000680UnaryOperatorKind
Douglas Gregorbc736fc2009-03-13 23:49:33 +0000681UnaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix) {
682 switch (OO) {
David Blaikieb219cfc2011-09-23 05:06:16 +0000683 default: llvm_unreachable("No unary operator for overloaded function");
John McCall2de56d12010-08-25 11:45:40 +0000684 case OO_PlusPlus: return Postfix ? UO_PostInc : UO_PreInc;
685 case OO_MinusMinus: return Postfix ? UO_PostDec : UO_PreDec;
686 case OO_Amp: return UO_AddrOf;
687 case OO_Star: return UO_Deref;
688 case OO_Plus: return UO_Plus;
689 case OO_Minus: return UO_Minus;
690 case OO_Tilde: return UO_Not;
691 case OO_Exclaim: return UO_LNot;
Douglas Gregorbc736fc2009-03-13 23:49:33 +0000692 }
693}
694
695OverloadedOperatorKind UnaryOperator::getOverloadedOperator(Opcode Opc) {
696 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +0000697 case UO_PostInc: case UO_PreInc: return OO_PlusPlus;
698 case UO_PostDec: case UO_PreDec: return OO_MinusMinus;
699 case UO_AddrOf: return OO_Amp;
700 case UO_Deref: return OO_Star;
701 case UO_Plus: return OO_Plus;
702 case UO_Minus: return OO_Minus;
703 case UO_Not: return OO_Tilde;
704 case UO_LNot: return OO_Exclaim;
Douglas Gregorbc736fc2009-03-13 23:49:33 +0000705 default: return OO_None;
706 }
707}
708
709
Reid Spencer5f016e22007-07-11 17:01:13 +0000710//===----------------------------------------------------------------------===//
711// Postfix Operators.
712//===----------------------------------------------------------------------===//
713
Peter Collingbournecc324ad2011-02-08 21:18:02 +0000714CallExpr::CallExpr(ASTContext& C, StmtClass SC, Expr *fn, unsigned NumPreArgs,
715 Expr **args, unsigned numargs, QualType t, ExprValueKind VK,
John McCallf89e55a2010-11-18 06:31:45 +0000716 SourceLocation rparenloc)
717 : Expr(SC, t, VK, OK_Ordinary,
Douglas Gregorbebbe0d2010-12-15 01:34:56 +0000718 fn->isTypeDependent(),
719 fn->isValueDependent(),
Douglas Gregor561f8122011-07-01 01:22:09 +0000720 fn->isInstantiationDependent(),
Douglas Gregorbebbe0d2010-12-15 01:34:56 +0000721 fn->containsUnexpandedParameterPack()),
Douglas Gregor898574e2008-12-05 23:32:09 +0000722 NumArgs(numargs) {
Mike Stump1eb44332009-09-09 15:08:12 +0000723
Peter Collingbournecc324ad2011-02-08 21:18:02 +0000724 SubExprs = new (C) Stmt*[numargs+PREARGS_START+NumPreArgs];
Douglas Gregorb4609802008-11-14 16:09:21 +0000725 SubExprs[FN] = fn;
Douglas Gregorbebbe0d2010-12-15 01:34:56 +0000726 for (unsigned i = 0; i != numargs; ++i) {
727 if (args[i]->isTypeDependent())
728 ExprBits.TypeDependent = true;
729 if (args[i]->isValueDependent())
730 ExprBits.ValueDependent = true;
Douglas Gregor561f8122011-07-01 01:22:09 +0000731 if (args[i]->isInstantiationDependent())
732 ExprBits.InstantiationDependent = true;
Douglas Gregorbebbe0d2010-12-15 01:34:56 +0000733 if (args[i]->containsUnexpandedParameterPack())
734 ExprBits.ContainsUnexpandedParameterPack = true;
735
Peter Collingbournecc324ad2011-02-08 21:18:02 +0000736 SubExprs[i+PREARGS_START+NumPreArgs] = args[i];
Douglas Gregorbebbe0d2010-12-15 01:34:56 +0000737 }
Ted Kremenek668bf912009-02-09 20:51:47 +0000738
Peter Collingbournecc324ad2011-02-08 21:18:02 +0000739 CallExprBits.NumPreArgs = NumPreArgs;
Douglas Gregorb4609802008-11-14 16:09:21 +0000740 RParenLoc = rparenloc;
741}
Nate Begemane2ce1d92008-01-17 17:46:27 +0000742
Ted Kremenek668bf912009-02-09 20:51:47 +0000743CallExpr::CallExpr(ASTContext& C, Expr *fn, Expr **args, unsigned numargs,
John McCallf89e55a2010-11-18 06:31:45 +0000744 QualType t, ExprValueKind VK, SourceLocation rparenloc)
745 : Expr(CallExprClass, t, VK, OK_Ordinary,
Douglas Gregorbebbe0d2010-12-15 01:34:56 +0000746 fn->isTypeDependent(),
747 fn->isValueDependent(),
Douglas Gregor561f8122011-07-01 01:22:09 +0000748 fn->isInstantiationDependent(),
Douglas Gregorbebbe0d2010-12-15 01:34:56 +0000749 fn->containsUnexpandedParameterPack()),
Douglas Gregor898574e2008-12-05 23:32:09 +0000750 NumArgs(numargs) {
Ted Kremenek668bf912009-02-09 20:51:47 +0000751
Peter Collingbournecc324ad2011-02-08 21:18:02 +0000752 SubExprs = new (C) Stmt*[numargs+PREARGS_START];
Ted Kremenek77ed8e42007-08-24 18:13:47 +0000753 SubExprs[FN] = fn;
Douglas Gregorbebbe0d2010-12-15 01:34:56 +0000754 for (unsigned i = 0; i != numargs; ++i) {
755 if (args[i]->isTypeDependent())
756 ExprBits.TypeDependent = true;
757 if (args[i]->isValueDependent())
758 ExprBits.ValueDependent = true;
Douglas Gregor561f8122011-07-01 01:22:09 +0000759 if (args[i]->isInstantiationDependent())
760 ExprBits.InstantiationDependent = true;
Douglas Gregorbebbe0d2010-12-15 01:34:56 +0000761 if (args[i]->containsUnexpandedParameterPack())
762 ExprBits.ContainsUnexpandedParameterPack = true;
763
Peter Collingbournecc324ad2011-02-08 21:18:02 +0000764 SubExprs[i+PREARGS_START] = args[i];
Douglas Gregorbebbe0d2010-12-15 01:34:56 +0000765 }
Ted Kremenek668bf912009-02-09 20:51:47 +0000766
Peter Collingbournecc324ad2011-02-08 21:18:02 +0000767 CallExprBits.NumPreArgs = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +0000768 RParenLoc = rparenloc;
769}
770
Mike Stump1eb44332009-09-09 15:08:12 +0000771CallExpr::CallExpr(ASTContext &C, StmtClass SC, EmptyShell Empty)
772 : Expr(SC, Empty), SubExprs(0), NumArgs(0) {
Douglas Gregorbebbe0d2010-12-15 01:34:56 +0000773 // FIXME: Why do we allocate this?
Peter Collingbournecc324ad2011-02-08 21:18:02 +0000774 SubExprs = new (C) Stmt*[PREARGS_START];
775 CallExprBits.NumPreArgs = 0;
776}
777
778CallExpr::CallExpr(ASTContext &C, StmtClass SC, unsigned NumPreArgs,
779 EmptyShell Empty)
780 : Expr(SC, Empty), SubExprs(0), NumArgs(0) {
781 // FIXME: Why do we allocate this?
782 SubExprs = new (C) Stmt*[PREARGS_START+NumPreArgs];
783 CallExprBits.NumPreArgs = NumPreArgs;
Douglas Gregor1f0d0132009-04-15 17:43:59 +0000784}
785
Nuno Lopesd20254f2009-12-20 23:11:08 +0000786Decl *CallExpr::getCalleeDecl() {
John McCalle8683d62011-09-13 23:08:34 +0000787 Expr *CEE = getCallee()->IgnoreParenImpCasts();
Douglas Gregor1ddc9c42011-09-06 21:41:04 +0000788
789 while (SubstNonTypeTemplateParmExpr *NTTP
790 = dyn_cast<SubstNonTypeTemplateParmExpr>(CEE)) {
791 CEE = NTTP->getReplacement()->IgnoreParenCasts();
792 }
793
Sebastian Redl20012152010-09-10 20:55:30 +0000794 // If we're calling a dereference, look at the pointer instead.
795 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CEE)) {
796 if (BO->isPtrMemOp())
797 CEE = BO->getRHS()->IgnoreParenCasts();
798 } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(CEE)) {
799 if (UO->getOpcode() == UO_Deref)
800 CEE = UO->getSubExpr()->IgnoreParenCasts();
801 }
Chris Lattner6346f962009-07-17 15:46:27 +0000802 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CEE))
Nuno Lopesd20254f2009-12-20 23:11:08 +0000803 return DRE->getDecl();
Nuno Lopescb1c77f2009-12-24 00:28:18 +0000804 if (MemberExpr *ME = dyn_cast<MemberExpr>(CEE))
805 return ME->getMemberDecl();
Zhongxing Xua0042542009-07-17 07:29:51 +0000806
807 return 0;
808}
809
Nuno Lopesd20254f2009-12-20 23:11:08 +0000810FunctionDecl *CallExpr::getDirectCallee() {
Chris Lattnercaabf9b2009-12-21 01:10:56 +0000811 return dyn_cast_or_null<FunctionDecl>(getCalleeDecl());
Nuno Lopesd20254f2009-12-20 23:11:08 +0000812}
813
Chris Lattnerd18b3292007-12-28 05:25:02 +0000814/// setNumArgs - This changes the number of arguments present in this call.
815/// Any orphaned expressions are deleted by this, and any new operands are set
816/// to null.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000817void CallExpr::setNumArgs(ASTContext& C, unsigned NumArgs) {
Chris Lattnerd18b3292007-12-28 05:25:02 +0000818 // No change, just return.
819 if (NumArgs == getNumArgs()) return;
Mike Stump1eb44332009-09-09 15:08:12 +0000820
Chris Lattnerd18b3292007-12-28 05:25:02 +0000821 // If shrinking # arguments, just delete the extras and forgot them.
822 if (NumArgs < getNumArgs()) {
Chris Lattnerd18b3292007-12-28 05:25:02 +0000823 this->NumArgs = NumArgs;
824 return;
825 }
826
827 // Otherwise, we are growing the # arguments. New an bigger argument array.
Peter Collingbournecc324ad2011-02-08 21:18:02 +0000828 unsigned NumPreArgs = getNumPreArgs();
829 Stmt **NewSubExprs = new (C) Stmt*[NumArgs+PREARGS_START+NumPreArgs];
Chris Lattnerd18b3292007-12-28 05:25:02 +0000830 // Copy over args.
Peter Collingbournecc324ad2011-02-08 21:18:02 +0000831 for (unsigned i = 0; i != getNumArgs()+PREARGS_START+NumPreArgs; ++i)
Chris Lattnerd18b3292007-12-28 05:25:02 +0000832 NewSubExprs[i] = SubExprs[i];
833 // Null out new args.
Peter Collingbournecc324ad2011-02-08 21:18:02 +0000834 for (unsigned i = getNumArgs()+PREARGS_START+NumPreArgs;
835 i != NumArgs+PREARGS_START+NumPreArgs; ++i)
Chris Lattnerd18b3292007-12-28 05:25:02 +0000836 NewSubExprs[i] = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000837
Douglas Gregor88c9a462009-04-17 21:46:47 +0000838 if (SubExprs) C.Deallocate(SubExprs);
Chris Lattnerd18b3292007-12-28 05:25:02 +0000839 SubExprs = NewSubExprs;
840 this->NumArgs = NumArgs;
841}
842
Chris Lattnercb888962008-10-06 05:00:53 +0000843/// isBuiltinCall - If this is a call to a builtin, return the builtin ID. If
844/// not, return 0.
Richard Smith180f4792011-11-10 06:34:14 +0000845unsigned CallExpr::isBuiltinCall() const {
Steve Naroffc4f8e8b2008-01-31 01:07:12 +0000846 // All simple function calls (e.g. func()) are implicitly cast to pointer to
Mike Stump1eb44332009-09-09 15:08:12 +0000847 // function. As a result, we try and obtain the DeclRefExpr from the
Steve Naroffc4f8e8b2008-01-31 01:07:12 +0000848 // ImplicitCastExpr.
849 const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(getCallee());
850 if (!ICE) // FIXME: deal with more complex calls (e.g. (func)(), (*func)()).
Chris Lattnercb888962008-10-06 05:00:53 +0000851 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000852
Steve Naroffc4f8e8b2008-01-31 01:07:12 +0000853 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr());
854 if (!DRE)
Chris Lattnercb888962008-10-06 05:00:53 +0000855 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000856
Anders Carlssonbcba2012008-01-31 02:13:57 +0000857 const FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
858 if (!FDecl)
Chris Lattnercb888962008-10-06 05:00:53 +0000859 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000860
Douglas Gregor4fcd3992008-11-21 15:30:19 +0000861 if (!FDecl->getIdentifier())
862 return 0;
863
Douglas Gregor7814e6d2009-09-12 00:22:50 +0000864 return FDecl->getBuiltinID();
Chris Lattnercb888962008-10-06 05:00:53 +0000865}
Anders Carlssonbcba2012008-01-31 02:13:57 +0000866
Anders Carlsson6dde78f2009-05-26 04:57:27 +0000867QualType CallExpr::getCallReturnType() const {
868 QualType CalleeType = getCallee()->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000869 if (const PointerType *FnTypePtr = CalleeType->getAs<PointerType>())
Anders Carlsson6dde78f2009-05-26 04:57:27 +0000870 CalleeType = FnTypePtr->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000871 else if (const BlockPointerType *BPT = CalleeType->getAs<BlockPointerType>())
Anders Carlsson6dde78f2009-05-26 04:57:27 +0000872 CalleeType = BPT->getPointeeType();
John McCall864c0412011-04-26 20:42:42 +0000873 else if (CalleeType->isSpecificPlaceholderType(BuiltinType::BoundMember))
874 // This should never be overloaded and so should never return null.
875 CalleeType = Expr::findBoundMemberType(getCallee());
Douglas Gregor5291c3c2010-07-13 08:18:22 +0000876
John McCall864c0412011-04-26 20:42:42 +0000877 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
Anders Carlsson6dde78f2009-05-26 04:57:27 +0000878 return FnType->getResultType();
879}
Chris Lattnercb888962008-10-06 05:00:53 +0000880
John McCall2882eca2011-02-21 06:23:05 +0000881SourceRange CallExpr::getSourceRange() const {
882 if (isa<CXXOperatorCallExpr>(this))
883 return cast<CXXOperatorCallExpr>(this)->getSourceRange();
884
885 SourceLocation begin = getCallee()->getLocStart();
886 if (begin.isInvalid() && getNumArgs() > 0)
887 begin = getArg(0)->getLocStart();
888 SourceLocation end = getRParenLoc();
889 if (end.isInvalid() && getNumArgs() > 0)
890 end = getArg(getNumArgs() - 1)->getLocEnd();
891 return SourceRange(begin, end);
892}
893
Sean Huntc3021132010-05-05 15:23:54 +0000894OffsetOfExpr *OffsetOfExpr::Create(ASTContext &C, QualType type,
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000895 SourceLocation OperatorLoc,
Sean Huntc3021132010-05-05 15:23:54 +0000896 TypeSourceInfo *tsi,
897 OffsetOfNode* compsPtr, unsigned numComps,
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000898 Expr** exprsPtr, unsigned numExprs,
899 SourceLocation RParenLoc) {
900 void *Mem = C.Allocate(sizeof(OffsetOfExpr) +
Sean Huntc3021132010-05-05 15:23:54 +0000901 sizeof(OffsetOfNode) * numComps +
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000902 sizeof(Expr*) * numExprs);
903
904 return new (Mem) OffsetOfExpr(C, type, OperatorLoc, tsi, compsPtr, numComps,
905 exprsPtr, numExprs, RParenLoc);
906}
907
908OffsetOfExpr *OffsetOfExpr::CreateEmpty(ASTContext &C,
909 unsigned numComps, unsigned numExprs) {
910 void *Mem = C.Allocate(sizeof(OffsetOfExpr) +
911 sizeof(OffsetOfNode) * numComps +
912 sizeof(Expr*) * numExprs);
913 return new (Mem) OffsetOfExpr(numComps, numExprs);
914}
915
Sean Huntc3021132010-05-05 15:23:54 +0000916OffsetOfExpr::OffsetOfExpr(ASTContext &C, QualType type,
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000917 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
Sean Huntc3021132010-05-05 15:23:54 +0000918 OffsetOfNode* compsPtr, unsigned numComps,
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000919 Expr** exprsPtr, unsigned numExprs,
920 SourceLocation RParenLoc)
John McCallf89e55a2010-11-18 06:31:45 +0000921 : Expr(OffsetOfExprClass, type, VK_RValue, OK_Ordinary,
922 /*TypeDependent=*/false,
Douglas Gregorbebbe0d2010-12-15 01:34:56 +0000923 /*ValueDependent=*/tsi->getType()->isDependentType(),
Douglas Gregor561f8122011-07-01 01:22:09 +0000924 tsi->getType()->isInstantiationDependentType(),
Douglas Gregorbebbe0d2010-12-15 01:34:56 +0000925 tsi->getType()->containsUnexpandedParameterPack()),
Sean Huntc3021132010-05-05 15:23:54 +0000926 OperatorLoc(OperatorLoc), RParenLoc(RParenLoc), TSInfo(tsi),
927 NumComps(numComps), NumExprs(numExprs)
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000928{
929 for(unsigned i = 0; i < numComps; ++i) {
930 setComponent(i, compsPtr[i]);
931 }
Sean Huntc3021132010-05-05 15:23:54 +0000932
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000933 for(unsigned i = 0; i < numExprs; ++i) {
Douglas Gregorbebbe0d2010-12-15 01:34:56 +0000934 if (exprsPtr[i]->isTypeDependent() || exprsPtr[i]->isValueDependent())
935 ExprBits.ValueDependent = true;
936 if (exprsPtr[i]->containsUnexpandedParameterPack())
937 ExprBits.ContainsUnexpandedParameterPack = true;
938
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000939 setIndexExpr(i, exprsPtr[i]);
940 }
941}
942
943IdentifierInfo *OffsetOfExpr::OffsetOfNode::getFieldName() const {
944 assert(getKind() == Field || getKind() == Identifier);
945 if (getKind() == Field)
946 return getField()->getIdentifier();
Sean Huntc3021132010-05-05 15:23:54 +0000947
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000948 return reinterpret_cast<IdentifierInfo *> (Data & ~(uintptr_t)Mask);
949}
950
Mike Stump1eb44332009-09-09 15:08:12 +0000951MemberExpr *MemberExpr::Create(ASTContext &C, Expr *base, bool isarrow,
Douglas Gregor40d96a62011-02-28 21:54:11 +0000952 NestedNameSpecifierLoc QualifierLoc,
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000953 SourceLocation TemplateKWLoc,
Eli Friedmanf595cc42009-12-04 06:40:45 +0000954 ValueDecl *memberdecl,
John McCall161755a2010-04-06 21:38:20 +0000955 DeclAccessPair founddecl,
Abramo Bagnara25777432010-08-11 22:01:17 +0000956 DeclarationNameInfo nameinfo,
John McCalld5532b62009-11-23 01:53:49 +0000957 const TemplateArgumentListInfo *targs,
John McCallf89e55a2010-11-18 06:31:45 +0000958 QualType ty,
959 ExprValueKind vk,
960 ExprObjectKind ok) {
Douglas Gregor83f6faf2009-08-31 23:41:50 +0000961 std::size_t Size = sizeof(MemberExpr);
John McCall6bb80172010-03-30 21:47:33 +0000962
Douglas Gregor40d96a62011-02-28 21:54:11 +0000963 bool hasQualOrFound = (QualifierLoc ||
John McCall161755a2010-04-06 21:38:20 +0000964 founddecl.getDecl() != memberdecl ||
965 founddecl.getAccess() != memberdecl->getAccess());
John McCall6bb80172010-03-30 21:47:33 +0000966 if (hasQualOrFound)
967 Size += sizeof(MemberNameQualifier);
Mike Stump1eb44332009-09-09 15:08:12 +0000968
John McCalld5532b62009-11-23 01:53:49 +0000969 if (targs)
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000970 Size += ASTTemplateKWAndArgsInfo::sizeFor(targs->size());
971 else if (TemplateKWLoc.isValid())
972 Size += ASTTemplateKWAndArgsInfo::sizeFor(0);
Mike Stump1eb44332009-09-09 15:08:12 +0000973
Chris Lattner32488542010-10-30 05:14:06 +0000974 void *Mem = C.Allocate(Size, llvm::alignOf<MemberExpr>());
John McCallf89e55a2010-11-18 06:31:45 +0000975 MemberExpr *E = new (Mem) MemberExpr(base, isarrow, memberdecl, nameinfo,
976 ty, vk, ok);
John McCall6bb80172010-03-30 21:47:33 +0000977
978 if (hasQualOrFound) {
Douglas Gregor40d96a62011-02-28 21:54:11 +0000979 // FIXME: Wrong. We should be looking at the member declaration we found.
980 if (QualifierLoc && QualifierLoc.getNestedNameSpecifier()->isDependent()) {
John McCall6bb80172010-03-30 21:47:33 +0000981 E->setValueDependent(true);
982 E->setTypeDependent(true);
Douglas Gregor561f8122011-07-01 01:22:09 +0000983 E->setInstantiationDependent(true);
984 }
985 else if (QualifierLoc &&
986 QualifierLoc.getNestedNameSpecifier()->isInstantiationDependent())
987 E->setInstantiationDependent(true);
988
John McCall6bb80172010-03-30 21:47:33 +0000989 E->HasQualifierOrFoundDecl = true;
990
991 MemberNameQualifier *NQ = E->getMemberQualifier();
Douglas Gregor40d96a62011-02-28 21:54:11 +0000992 NQ->QualifierLoc = QualifierLoc;
John McCall6bb80172010-03-30 21:47:33 +0000993 NQ->FoundDecl = founddecl;
994 }
995
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000996 E->HasTemplateKWAndArgsInfo = (targs || TemplateKWLoc.isValid());
997
John McCall6bb80172010-03-30 21:47:33 +0000998 if (targs) {
Douglas Gregor561f8122011-07-01 01:22:09 +0000999 bool Dependent = false;
1000 bool InstantiationDependent = false;
1001 bool ContainsUnexpandedParameterPack = false;
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001002 E->getTemplateKWAndArgsInfo()->initializeFrom(TemplateKWLoc, *targs,
1003 Dependent,
1004 InstantiationDependent,
1005 ContainsUnexpandedParameterPack);
Douglas Gregor561f8122011-07-01 01:22:09 +00001006 if (InstantiationDependent)
1007 E->setInstantiationDependent(true);
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001008 } else if (TemplateKWLoc.isValid()) {
1009 E->getTemplateKWAndArgsInfo()->initializeFrom(TemplateKWLoc);
John McCall6bb80172010-03-30 21:47:33 +00001010 }
1011
1012 return E;
Douglas Gregor83f6faf2009-08-31 23:41:50 +00001013}
1014
Douglas Gregor75e85042011-03-02 21:06:53 +00001015SourceRange MemberExpr::getSourceRange() const {
1016 SourceLocation StartLoc;
1017 if (isImplicitAccess()) {
1018 if (hasQualifier())
1019 StartLoc = getQualifierLoc().getBeginLoc();
1020 else
1021 StartLoc = MemberLoc;
1022 } else {
1023 // FIXME: We don't want this to happen. Rather, we should be able to
1024 // detect all kinds of implicit accesses more cleanly.
1025 StartLoc = getBase()->getLocStart();
1026 if (StartLoc.isInvalid())
1027 StartLoc = MemberLoc;
1028 }
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001029
1030 SourceLocation EndLoc = hasExplicitTemplateArgs()
1031 ? getRAngleLoc() : getMemberNameInfo().getEndLoc();
1032
Douglas Gregor75e85042011-03-02 21:06:53 +00001033 return SourceRange(StartLoc, EndLoc);
1034}
1035
John McCall1d9b3b22011-09-09 05:25:32 +00001036void CastExpr::CheckCastConsistency() const {
1037 switch (getCastKind()) {
1038 case CK_DerivedToBase:
1039 case CK_UncheckedDerivedToBase:
1040 case CK_DerivedToBaseMemberPointer:
1041 case CK_BaseToDerived:
1042 case CK_BaseToDerivedMemberPointer:
1043 assert(!path_empty() && "Cast kind should have a base path!");
1044 break;
1045
1046 case CK_CPointerToObjCPointerCast:
1047 assert(getType()->isObjCObjectPointerType());
1048 assert(getSubExpr()->getType()->isPointerType());
1049 goto CheckNoBasePath;
1050
1051 case CK_BlockPointerToObjCPointerCast:
1052 assert(getType()->isObjCObjectPointerType());
1053 assert(getSubExpr()->getType()->isBlockPointerType());
1054 goto CheckNoBasePath;
1055
John McCall4d4e5c12012-02-15 01:22:51 +00001056 case CK_ReinterpretMemberPointer:
1057 assert(getType()->isMemberPointerType());
1058 assert(getSubExpr()->getType()->isMemberPointerType());
1059 goto CheckNoBasePath;
1060
John McCall1d9b3b22011-09-09 05:25:32 +00001061 case CK_BitCast:
1062 // Arbitrary casts to C pointer types count as bitcasts.
1063 // Otherwise, we should only have block and ObjC pointer casts
1064 // here if they stay within the type kind.
1065 if (!getType()->isPointerType()) {
1066 assert(getType()->isObjCObjectPointerType() ==
1067 getSubExpr()->getType()->isObjCObjectPointerType());
1068 assert(getType()->isBlockPointerType() ==
1069 getSubExpr()->getType()->isBlockPointerType());
1070 }
1071 goto CheckNoBasePath;
1072
1073 case CK_AnyPointerToBlockPointerCast:
1074 assert(getType()->isBlockPointerType());
1075 assert(getSubExpr()->getType()->isAnyPointerType() &&
1076 !getSubExpr()->getType()->isBlockPointerType());
1077 goto CheckNoBasePath;
1078
1079 // These should not have an inheritance path.
1080 case CK_Dynamic:
1081 case CK_ToUnion:
1082 case CK_ArrayToPointerDecay:
1083 case CK_FunctionToPointerDecay:
1084 case CK_NullToMemberPointer:
1085 case CK_NullToPointer:
1086 case CK_ConstructorConversion:
1087 case CK_IntegralToPointer:
1088 case CK_PointerToIntegral:
1089 case CK_ToVoid:
1090 case CK_VectorSplat:
1091 case CK_IntegralCast:
1092 case CK_IntegralToFloating:
1093 case CK_FloatingToIntegral:
1094 case CK_FloatingCast:
1095 case CK_ObjCObjectLValueCast:
1096 case CK_FloatingRealToComplex:
1097 case CK_FloatingComplexToReal:
1098 case CK_FloatingComplexCast:
1099 case CK_FloatingComplexToIntegralComplex:
1100 case CK_IntegralRealToComplex:
1101 case CK_IntegralComplexToReal:
1102 case CK_IntegralComplexCast:
1103 case CK_IntegralComplexToFloatingComplex:
John McCall33e56f32011-09-10 06:18:15 +00001104 case CK_ARCProduceObject:
1105 case CK_ARCConsumeObject:
1106 case CK_ARCReclaimReturnedObject:
1107 case CK_ARCExtendBlockObject:
John McCall1d9b3b22011-09-09 05:25:32 +00001108 assert(!getType()->isBooleanType() && "unheralded conversion to bool");
1109 goto CheckNoBasePath;
1110
1111 case CK_Dependent:
1112 case CK_LValueToRValue:
John McCall1d9b3b22011-09-09 05:25:32 +00001113 case CK_NoOp:
David Chisnall7a7ee302012-01-16 17:27:18 +00001114 case CK_AtomicToNonAtomic:
1115 case CK_NonAtomicToAtomic:
John McCall1d9b3b22011-09-09 05:25:32 +00001116 case CK_PointerToBoolean:
1117 case CK_IntegralToBoolean:
1118 case CK_FloatingToBoolean:
1119 case CK_MemberPointerToBoolean:
1120 case CK_FloatingComplexToBoolean:
1121 case CK_IntegralComplexToBoolean:
1122 case CK_LValueBitCast: // -> bool&
1123 case CK_UserDefinedConversion: // operator bool()
1124 CheckNoBasePath:
1125 assert(path_empty() && "Cast kind should not have a base path!");
1126 break;
1127 }
1128}
1129
Anders Carlssonf8ec55a2009-09-03 00:59:21 +00001130const char *CastExpr::getCastKindName() const {
1131 switch (getCastKind()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00001132 case CK_Dependent:
1133 return "Dependent";
John McCall2de56d12010-08-25 11:45:40 +00001134 case CK_BitCast:
Anders Carlssonf8ec55a2009-09-03 00:59:21 +00001135 return "BitCast";
John McCall2de56d12010-08-25 11:45:40 +00001136 case CK_LValueBitCast:
Douglas Gregore39a3892010-07-13 23:17:26 +00001137 return "LValueBitCast";
John McCall0ae287a2010-12-01 04:43:34 +00001138 case CK_LValueToRValue:
1139 return "LValueToRValue";
John McCall2de56d12010-08-25 11:45:40 +00001140 case CK_NoOp:
Anders Carlssonf8ec55a2009-09-03 00:59:21 +00001141 return "NoOp";
John McCall2de56d12010-08-25 11:45:40 +00001142 case CK_BaseToDerived:
Anders Carlsson11de6de2009-11-12 16:43:42 +00001143 return "BaseToDerived";
John McCall2de56d12010-08-25 11:45:40 +00001144 case CK_DerivedToBase:
Anders Carlssonf8ec55a2009-09-03 00:59:21 +00001145 return "DerivedToBase";
John McCall2de56d12010-08-25 11:45:40 +00001146 case CK_UncheckedDerivedToBase:
John McCall23cba802010-03-30 23:58:03 +00001147 return "UncheckedDerivedToBase";
John McCall2de56d12010-08-25 11:45:40 +00001148 case CK_Dynamic:
Anders Carlssonf8ec55a2009-09-03 00:59:21 +00001149 return "Dynamic";
John McCall2de56d12010-08-25 11:45:40 +00001150 case CK_ToUnion:
Anders Carlssonf8ec55a2009-09-03 00:59:21 +00001151 return "ToUnion";
John McCall2de56d12010-08-25 11:45:40 +00001152 case CK_ArrayToPointerDecay:
Anders Carlssonf8ec55a2009-09-03 00:59:21 +00001153 return "ArrayToPointerDecay";
John McCall2de56d12010-08-25 11:45:40 +00001154 case CK_FunctionToPointerDecay:
Anders Carlssonf8ec55a2009-09-03 00:59:21 +00001155 return "FunctionToPointerDecay";
John McCall2de56d12010-08-25 11:45:40 +00001156 case CK_NullToMemberPointer:
Anders Carlssonf8ec55a2009-09-03 00:59:21 +00001157 return "NullToMemberPointer";
John McCall404cd162010-11-13 01:35:44 +00001158 case CK_NullToPointer:
1159 return "NullToPointer";
John McCall2de56d12010-08-25 11:45:40 +00001160 case CK_BaseToDerivedMemberPointer:
Anders Carlssonf8ec55a2009-09-03 00:59:21 +00001161 return "BaseToDerivedMemberPointer";
John McCall2de56d12010-08-25 11:45:40 +00001162 case CK_DerivedToBaseMemberPointer:
Anders Carlsson1a31a182009-10-30 00:46:35 +00001163 return "DerivedToBaseMemberPointer";
John McCall4d4e5c12012-02-15 01:22:51 +00001164 case CK_ReinterpretMemberPointer:
1165 return "ReinterpretMemberPointer";
John McCall2de56d12010-08-25 11:45:40 +00001166 case CK_UserDefinedConversion:
Anders Carlssonf8ec55a2009-09-03 00:59:21 +00001167 return "UserDefinedConversion";
John McCall2de56d12010-08-25 11:45:40 +00001168 case CK_ConstructorConversion:
Anders Carlssonf8ec55a2009-09-03 00:59:21 +00001169 return "ConstructorConversion";
John McCall2de56d12010-08-25 11:45:40 +00001170 case CK_IntegralToPointer:
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001171 return "IntegralToPointer";
John McCall2de56d12010-08-25 11:45:40 +00001172 case CK_PointerToIntegral:
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001173 return "PointerToIntegral";
John McCalldaa8e4e2010-11-15 09:13:47 +00001174 case CK_PointerToBoolean:
1175 return "PointerToBoolean";
John McCall2de56d12010-08-25 11:45:40 +00001176 case CK_ToVoid:
Anders Carlssonebeaf202009-10-16 02:35:04 +00001177 return "ToVoid";
John McCall2de56d12010-08-25 11:45:40 +00001178 case CK_VectorSplat:
Anders Carlsson16a89042009-10-16 05:23:41 +00001179 return "VectorSplat";
John McCall2de56d12010-08-25 11:45:40 +00001180 case CK_IntegralCast:
Anders Carlsson82debc72009-10-18 18:12:03 +00001181 return "IntegralCast";
John McCalldaa8e4e2010-11-15 09:13:47 +00001182 case CK_IntegralToBoolean:
1183 return "IntegralToBoolean";
John McCall2de56d12010-08-25 11:45:40 +00001184 case CK_IntegralToFloating:
Anders Carlsson82debc72009-10-18 18:12:03 +00001185 return "IntegralToFloating";
John McCall2de56d12010-08-25 11:45:40 +00001186 case CK_FloatingToIntegral:
Anders Carlsson82debc72009-10-18 18:12:03 +00001187 return "FloatingToIntegral";
John McCall2de56d12010-08-25 11:45:40 +00001188 case CK_FloatingCast:
Benjamin Kramerc6b29162009-10-18 19:02:15 +00001189 return "FloatingCast";
John McCalldaa8e4e2010-11-15 09:13:47 +00001190 case CK_FloatingToBoolean:
1191 return "FloatingToBoolean";
John McCall2de56d12010-08-25 11:45:40 +00001192 case CK_MemberPointerToBoolean:
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001193 return "MemberPointerToBoolean";
John McCall1d9b3b22011-09-09 05:25:32 +00001194 case CK_CPointerToObjCPointerCast:
1195 return "CPointerToObjCPointerCast";
1196 case CK_BlockPointerToObjCPointerCast:
1197 return "BlockPointerToObjCPointerCast";
John McCall2de56d12010-08-25 11:45:40 +00001198 case CK_AnyPointerToBlockPointerCast:
Fariborz Jahanian3b27f1a2009-12-11 22:40:48 +00001199 return "AnyPointerToBlockPointerCast";
John McCall2de56d12010-08-25 11:45:40 +00001200 case CK_ObjCObjectLValueCast:
Douglas Gregor569c3162010-08-07 11:51:51 +00001201 return "ObjCObjectLValueCast";
John McCall2bb5d002010-11-13 09:02:35 +00001202 case CK_FloatingRealToComplex:
1203 return "FloatingRealToComplex";
John McCallf3ea8cf2010-11-14 08:17:51 +00001204 case CK_FloatingComplexToReal:
1205 return "FloatingComplexToReal";
1206 case CK_FloatingComplexToBoolean:
1207 return "FloatingComplexToBoolean";
John McCall2bb5d002010-11-13 09:02:35 +00001208 case CK_FloatingComplexCast:
1209 return "FloatingComplexCast";
John McCallf3ea8cf2010-11-14 08:17:51 +00001210 case CK_FloatingComplexToIntegralComplex:
1211 return "FloatingComplexToIntegralComplex";
John McCall2bb5d002010-11-13 09:02:35 +00001212 case CK_IntegralRealToComplex:
1213 return "IntegralRealToComplex";
John McCallf3ea8cf2010-11-14 08:17:51 +00001214 case CK_IntegralComplexToReal:
1215 return "IntegralComplexToReal";
1216 case CK_IntegralComplexToBoolean:
1217 return "IntegralComplexToBoolean";
John McCall2bb5d002010-11-13 09:02:35 +00001218 case CK_IntegralComplexCast:
1219 return "IntegralComplexCast";
John McCallf3ea8cf2010-11-14 08:17:51 +00001220 case CK_IntegralComplexToFloatingComplex:
1221 return "IntegralComplexToFloatingComplex";
John McCall33e56f32011-09-10 06:18:15 +00001222 case CK_ARCConsumeObject:
1223 return "ARCConsumeObject";
1224 case CK_ARCProduceObject:
1225 return "ARCProduceObject";
1226 case CK_ARCReclaimReturnedObject:
1227 return "ARCReclaimReturnedObject";
1228 case CK_ARCExtendBlockObject:
1229 return "ARCCExtendBlockObject";
David Chisnall7a7ee302012-01-16 17:27:18 +00001230 case CK_AtomicToNonAtomic:
1231 return "AtomicToNonAtomic";
1232 case CK_NonAtomicToAtomic:
1233 return "NonAtomicToAtomic";
Anders Carlssonf8ec55a2009-09-03 00:59:21 +00001234 }
Mike Stump1eb44332009-09-09 15:08:12 +00001235
John McCall2bb5d002010-11-13 09:02:35 +00001236 llvm_unreachable("Unhandled cast kind!");
Anders Carlssonf8ec55a2009-09-03 00:59:21 +00001237}
1238
Douglas Gregor6eef5192009-12-14 19:27:10 +00001239Expr *CastExpr::getSubExprAsWritten() {
1240 Expr *SubExpr = 0;
1241 CastExpr *E = this;
1242 do {
1243 SubExpr = E->getSubExpr();
Douglas Gregor03e80032011-06-21 17:03:29 +00001244
1245 // Skip through reference binding to temporary.
1246 if (MaterializeTemporaryExpr *Materialize
1247 = dyn_cast<MaterializeTemporaryExpr>(SubExpr))
1248 SubExpr = Materialize->GetTemporaryExpr();
1249
Douglas Gregor6eef5192009-12-14 19:27:10 +00001250 // Skip any temporary bindings; they're implicit.
1251 if (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(SubExpr))
1252 SubExpr = Binder->getSubExpr();
Sean Huntc3021132010-05-05 15:23:54 +00001253
Douglas Gregor6eef5192009-12-14 19:27:10 +00001254 // Conversions by constructor and conversion functions have a
1255 // subexpression describing the call; strip it off.
John McCall2de56d12010-08-25 11:45:40 +00001256 if (E->getCastKind() == CK_ConstructorConversion)
Douglas Gregor6eef5192009-12-14 19:27:10 +00001257 SubExpr = cast<CXXConstructExpr>(SubExpr)->getArg(0);
John McCall2de56d12010-08-25 11:45:40 +00001258 else if (E->getCastKind() == CK_UserDefinedConversion)
Douglas Gregor6eef5192009-12-14 19:27:10 +00001259 SubExpr = cast<CXXMemberCallExpr>(SubExpr)->getImplicitObjectArgument();
Sean Huntc3021132010-05-05 15:23:54 +00001260
Douglas Gregor6eef5192009-12-14 19:27:10 +00001261 // If the subexpression we're left with is an implicit cast, look
1262 // through that, too.
Sean Huntc3021132010-05-05 15:23:54 +00001263 } while ((E = dyn_cast<ImplicitCastExpr>(SubExpr)));
1264
Douglas Gregor6eef5192009-12-14 19:27:10 +00001265 return SubExpr;
1266}
1267
John McCallf871d0c2010-08-07 06:22:56 +00001268CXXBaseSpecifier **CastExpr::path_buffer() {
1269 switch (getStmtClass()) {
1270#define ABSTRACT_STMT(x)
1271#define CASTEXPR(Type, Base) \
1272 case Stmt::Type##Class: \
1273 return reinterpret_cast<CXXBaseSpecifier**>(static_cast<Type*>(this)+1);
1274#define STMT(Type, Base)
1275#include "clang/AST/StmtNodes.inc"
1276 default:
1277 llvm_unreachable("non-cast expressions not possible here");
John McCallf871d0c2010-08-07 06:22:56 +00001278 }
1279}
1280
1281void CastExpr::setCastPath(const CXXCastPath &Path) {
1282 assert(Path.size() == path_size());
1283 memcpy(path_buffer(), Path.data(), Path.size() * sizeof(CXXBaseSpecifier*));
1284}
1285
1286ImplicitCastExpr *ImplicitCastExpr::Create(ASTContext &C, QualType T,
1287 CastKind Kind, Expr *Operand,
1288 const CXXCastPath *BasePath,
John McCall5baba9d2010-08-25 10:28:54 +00001289 ExprValueKind VK) {
John McCallf871d0c2010-08-07 06:22:56 +00001290 unsigned PathSize = (BasePath ? BasePath->size() : 0);
1291 void *Buffer =
1292 C.Allocate(sizeof(ImplicitCastExpr) + PathSize * sizeof(CXXBaseSpecifier*));
1293 ImplicitCastExpr *E =
John McCall5baba9d2010-08-25 10:28:54 +00001294 new (Buffer) ImplicitCastExpr(T, Kind, Operand, PathSize, VK);
John McCallf871d0c2010-08-07 06:22:56 +00001295 if (PathSize) E->setCastPath(*BasePath);
1296 return E;
1297}
1298
1299ImplicitCastExpr *ImplicitCastExpr::CreateEmpty(ASTContext &C,
1300 unsigned PathSize) {
1301 void *Buffer =
1302 C.Allocate(sizeof(ImplicitCastExpr) + PathSize * sizeof(CXXBaseSpecifier*));
1303 return new (Buffer) ImplicitCastExpr(EmptyShell(), PathSize);
1304}
1305
1306
1307CStyleCastExpr *CStyleCastExpr::Create(ASTContext &C, QualType T,
John McCallf89e55a2010-11-18 06:31:45 +00001308 ExprValueKind VK, CastKind K, Expr *Op,
John McCallf871d0c2010-08-07 06:22:56 +00001309 const CXXCastPath *BasePath,
1310 TypeSourceInfo *WrittenTy,
1311 SourceLocation L, SourceLocation R) {
1312 unsigned PathSize = (BasePath ? BasePath->size() : 0);
1313 void *Buffer =
1314 C.Allocate(sizeof(CStyleCastExpr) + PathSize * sizeof(CXXBaseSpecifier*));
1315 CStyleCastExpr *E =
John McCallf89e55a2010-11-18 06:31:45 +00001316 new (Buffer) CStyleCastExpr(T, VK, K, Op, PathSize, WrittenTy, L, R);
John McCallf871d0c2010-08-07 06:22:56 +00001317 if (PathSize) E->setCastPath(*BasePath);
1318 return E;
1319}
1320
1321CStyleCastExpr *CStyleCastExpr::CreateEmpty(ASTContext &C, unsigned PathSize) {
1322 void *Buffer =
1323 C.Allocate(sizeof(CStyleCastExpr) + PathSize * sizeof(CXXBaseSpecifier*));
1324 return new (Buffer) CStyleCastExpr(EmptyShell(), PathSize);
1325}
1326
Reid Spencer5f016e22007-07-11 17:01:13 +00001327/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1328/// corresponds to, e.g. "<<=".
1329const char *BinaryOperator::getOpcodeStr(Opcode Op) {
1330 switch (Op) {
John McCall2de56d12010-08-25 11:45:40 +00001331 case BO_PtrMemD: return ".*";
1332 case BO_PtrMemI: return "->*";
1333 case BO_Mul: return "*";
1334 case BO_Div: return "/";
1335 case BO_Rem: return "%";
1336 case BO_Add: return "+";
1337 case BO_Sub: return "-";
1338 case BO_Shl: return "<<";
1339 case BO_Shr: return ">>";
1340 case BO_LT: return "<";
1341 case BO_GT: return ">";
1342 case BO_LE: return "<=";
1343 case BO_GE: return ">=";
1344 case BO_EQ: return "==";
1345 case BO_NE: return "!=";
1346 case BO_And: return "&";
1347 case BO_Xor: return "^";
1348 case BO_Or: return "|";
1349 case BO_LAnd: return "&&";
1350 case BO_LOr: return "||";
1351 case BO_Assign: return "=";
1352 case BO_MulAssign: return "*=";
1353 case BO_DivAssign: return "/=";
1354 case BO_RemAssign: return "%=";
1355 case BO_AddAssign: return "+=";
1356 case BO_SubAssign: return "-=";
1357 case BO_ShlAssign: return "<<=";
1358 case BO_ShrAssign: return ">>=";
1359 case BO_AndAssign: return "&=";
1360 case BO_XorAssign: return "^=";
1361 case BO_OrAssign: return "|=";
1362 case BO_Comma: return ",";
Reid Spencer5f016e22007-07-11 17:01:13 +00001363 }
Douglas Gregorbaf53482009-03-12 22:51:37 +00001364
David Blaikie30263482012-01-20 21:50:17 +00001365 llvm_unreachable("Invalid OpCode!");
Reid Spencer5f016e22007-07-11 17:01:13 +00001366}
1367
John McCall2de56d12010-08-25 11:45:40 +00001368BinaryOperatorKind
Douglas Gregor063daf62009-03-13 18:40:31 +00001369BinaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO) {
1370 switch (OO) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001371 default: llvm_unreachable("Not an overloadable binary operator");
John McCall2de56d12010-08-25 11:45:40 +00001372 case OO_Plus: return BO_Add;
1373 case OO_Minus: return BO_Sub;
1374 case OO_Star: return BO_Mul;
1375 case OO_Slash: return BO_Div;
1376 case OO_Percent: return BO_Rem;
1377 case OO_Caret: return BO_Xor;
1378 case OO_Amp: return BO_And;
1379 case OO_Pipe: return BO_Or;
1380 case OO_Equal: return BO_Assign;
1381 case OO_Less: return BO_LT;
1382 case OO_Greater: return BO_GT;
1383 case OO_PlusEqual: return BO_AddAssign;
1384 case OO_MinusEqual: return BO_SubAssign;
1385 case OO_StarEqual: return BO_MulAssign;
1386 case OO_SlashEqual: return BO_DivAssign;
1387 case OO_PercentEqual: return BO_RemAssign;
1388 case OO_CaretEqual: return BO_XorAssign;
1389 case OO_AmpEqual: return BO_AndAssign;
1390 case OO_PipeEqual: return BO_OrAssign;
1391 case OO_LessLess: return BO_Shl;
1392 case OO_GreaterGreater: return BO_Shr;
1393 case OO_LessLessEqual: return BO_ShlAssign;
1394 case OO_GreaterGreaterEqual: return BO_ShrAssign;
1395 case OO_EqualEqual: return BO_EQ;
1396 case OO_ExclaimEqual: return BO_NE;
1397 case OO_LessEqual: return BO_LE;
1398 case OO_GreaterEqual: return BO_GE;
1399 case OO_AmpAmp: return BO_LAnd;
1400 case OO_PipePipe: return BO_LOr;
1401 case OO_Comma: return BO_Comma;
1402 case OO_ArrowStar: return BO_PtrMemI;
Douglas Gregor063daf62009-03-13 18:40:31 +00001403 }
1404}
1405
1406OverloadedOperatorKind BinaryOperator::getOverloadedOperator(Opcode Opc) {
1407 static const OverloadedOperatorKind OverOps[] = {
1408 /* .* Cannot be overloaded */OO_None, OO_ArrowStar,
1409 OO_Star, OO_Slash, OO_Percent,
1410 OO_Plus, OO_Minus,
1411 OO_LessLess, OO_GreaterGreater,
1412 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
1413 OO_EqualEqual, OO_ExclaimEqual,
1414 OO_Amp,
1415 OO_Caret,
1416 OO_Pipe,
1417 OO_AmpAmp,
1418 OO_PipePipe,
1419 OO_Equal, OO_StarEqual,
1420 OO_SlashEqual, OO_PercentEqual,
1421 OO_PlusEqual, OO_MinusEqual,
1422 OO_LessLessEqual, OO_GreaterGreaterEqual,
1423 OO_AmpEqual, OO_CaretEqual,
1424 OO_PipeEqual,
1425 OO_Comma
1426 };
1427 return OverOps[Opc];
1428}
1429
Ted Kremenek709210f2010-04-13 23:39:13 +00001430InitListExpr::InitListExpr(ASTContext &C, SourceLocation lbraceloc,
Chris Lattner418f6c72008-10-26 23:43:26 +00001431 Expr **initExprs, unsigned numInits,
Douglas Gregor4c678342009-01-28 21:54:33 +00001432 SourceLocation rbraceloc)
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00001433 : Expr(InitListExprClass, QualType(), VK_RValue, OK_Ordinary, false, false,
Douglas Gregor561f8122011-07-01 01:22:09 +00001434 false, false),
Ted Kremenek709210f2010-04-13 23:39:13 +00001435 InitExprs(C, numInits),
Mike Stump1eb44332009-09-09 15:08:12 +00001436 LBraceLoc(lbraceloc), RBraceLoc(rbraceloc), SyntacticForm(0),
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +00001437 HadArrayRangeDesignator(false)
Sean Huntc3021132010-05-05 15:23:54 +00001438{
Ted Kremenekba7bc552010-02-19 01:50:18 +00001439 for (unsigned I = 0; I != numInits; ++I) {
1440 if (initExprs[I]->isTypeDependent())
John McCall8e6285a2010-10-26 08:39:16 +00001441 ExprBits.TypeDependent = true;
Ted Kremenekba7bc552010-02-19 01:50:18 +00001442 if (initExprs[I]->isValueDependent())
John McCall8e6285a2010-10-26 08:39:16 +00001443 ExprBits.ValueDependent = true;
Douglas Gregor561f8122011-07-01 01:22:09 +00001444 if (initExprs[I]->isInstantiationDependent())
1445 ExprBits.InstantiationDependent = true;
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00001446 if (initExprs[I]->containsUnexpandedParameterPack())
1447 ExprBits.ContainsUnexpandedParameterPack = true;
Douglas Gregor73460a32009-11-19 23:25:22 +00001448 }
Sean Huntc3021132010-05-05 15:23:54 +00001449
Ted Kremenek709210f2010-04-13 23:39:13 +00001450 InitExprs.insert(C, InitExprs.end(), initExprs, initExprs+numInits);
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00001451}
Reid Spencer5f016e22007-07-11 17:01:13 +00001452
Ted Kremenek709210f2010-04-13 23:39:13 +00001453void InitListExpr::reserveInits(ASTContext &C, unsigned NumInits) {
Ted Kremenekba7bc552010-02-19 01:50:18 +00001454 if (NumInits > InitExprs.size())
Ted Kremenek709210f2010-04-13 23:39:13 +00001455 InitExprs.reserve(C, NumInits);
Douglas Gregorfa219202009-03-20 23:58:33 +00001456}
1457
Ted Kremenek709210f2010-04-13 23:39:13 +00001458void InitListExpr::resizeInits(ASTContext &C, unsigned NumInits) {
Ted Kremenek709210f2010-04-13 23:39:13 +00001459 InitExprs.resize(C, NumInits, 0);
Douglas Gregor4c678342009-01-28 21:54:33 +00001460}
1461
Ted Kremenek709210f2010-04-13 23:39:13 +00001462Expr *InitListExpr::updateInit(ASTContext &C, unsigned Init, Expr *expr) {
Ted Kremenekba7bc552010-02-19 01:50:18 +00001463 if (Init >= InitExprs.size()) {
Ted Kremenek709210f2010-04-13 23:39:13 +00001464 InitExprs.insert(C, InitExprs.end(), Init - InitExprs.size() + 1, 0);
Ted Kremenekba7bc552010-02-19 01:50:18 +00001465 InitExprs.back() = expr;
1466 return 0;
Douglas Gregor4c678342009-01-28 21:54:33 +00001467 }
Mike Stump1eb44332009-09-09 15:08:12 +00001468
Douglas Gregor4c678342009-01-28 21:54:33 +00001469 Expr *Result = cast_or_null<Expr>(InitExprs[Init]);
1470 InitExprs[Init] = expr;
1471 return Result;
1472}
1473
Argyrios Kyrtzidis3e8dc2a2011-04-21 20:03:38 +00001474void InitListExpr::setArrayFiller(Expr *filler) {
Argyrios Kyrtzidis21f77cd2011-10-21 23:02:22 +00001475 assert(!hasArrayFiller() && "Filler already set!");
Argyrios Kyrtzidis3e8dc2a2011-04-21 20:03:38 +00001476 ArrayFillerOrUnionFieldInit = filler;
1477 // Fill out any "holes" in the array due to designated initializers.
1478 Expr **inits = getInits();
1479 for (unsigned i = 0, e = getNumInits(); i != e; ++i)
1480 if (inits[i] == 0)
1481 inits[i] = filler;
1482}
1483
Ted Kremenekc4ba51f2010-11-09 02:11:40 +00001484SourceRange InitListExpr::getSourceRange() const {
1485 if (SyntacticForm)
1486 return SyntacticForm->getSourceRange();
1487 SourceLocation Beg = LBraceLoc, End = RBraceLoc;
1488 if (Beg.isInvalid()) {
1489 // Find the first non-null initializer.
1490 for (InitExprsTy::const_iterator I = InitExprs.begin(),
1491 E = InitExprs.end();
1492 I != E; ++I) {
1493 if (Stmt *S = *I) {
1494 Beg = S->getLocStart();
1495 break;
1496 }
1497 }
1498 }
1499 if (End.isInvalid()) {
1500 // Find the first non-null initializer from the end.
1501 for (InitExprsTy::const_reverse_iterator I = InitExprs.rbegin(),
1502 E = InitExprs.rend();
1503 I != E; ++I) {
1504 if (Stmt *S = *I) {
1505 End = S->getSourceRange().getEnd();
1506 break;
1507 }
1508 }
1509 }
1510 return SourceRange(Beg, End);
1511}
1512
Steve Naroffbfdcae62008-09-04 15:31:07 +00001513/// getFunctionType - Return the underlying function type for this block.
Steve Naroff4eb206b2008-09-03 18:15:37 +00001514///
1515const FunctionType *BlockExpr::getFunctionType() const {
Ted Kremenek6217b802009-07-29 21:53:49 +00001516 return getType()->getAs<BlockPointerType>()->
John McCall183700f2009-09-21 23:43:11 +00001517 getPointeeType()->getAs<FunctionType>();
Steve Naroff4eb206b2008-09-03 18:15:37 +00001518}
1519
Mike Stump1eb44332009-09-09 15:08:12 +00001520SourceLocation BlockExpr::getCaretLocation() const {
1521 return TheBlock->getCaretLocation();
Steve Naroff56ee6892008-10-08 17:01:13 +00001522}
Mike Stump1eb44332009-09-09 15:08:12 +00001523const Stmt *BlockExpr::getBody() const {
Douglas Gregor72971342009-04-18 00:02:19 +00001524 return TheBlock->getBody();
1525}
Mike Stump1eb44332009-09-09 15:08:12 +00001526Stmt *BlockExpr::getBody() {
1527 return TheBlock->getBody();
Douglas Gregor72971342009-04-18 00:02:19 +00001528}
Steve Naroff56ee6892008-10-08 17:01:13 +00001529
1530
Reid Spencer5f016e22007-07-11 17:01:13 +00001531//===----------------------------------------------------------------------===//
1532// Generic Expression Routines
1533//===----------------------------------------------------------------------===//
1534
Chris Lattner026dc962009-02-14 07:37:35 +00001535/// isUnusedResultAWarning - Return true if this immediate expression should
1536/// be warned about if the result is unused. If so, fill in Loc and Ranges
1537/// with location to warn on and the source range[s] to report with the
1538/// warning.
1539bool Expr::isUnusedResultAWarning(SourceLocation &Loc, SourceRange &R1,
Mike Stumpdf317bf2009-11-03 23:25:48 +00001540 SourceRange &R2, ASTContext &Ctx) const {
Anders Carlssonffce2df2009-05-15 23:10:19 +00001541 // Don't warn if the expr is type dependent. The type could end up
1542 // instantiating to void.
1543 if (isTypeDependent())
1544 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001545
Reid Spencer5f016e22007-07-11 17:01:13 +00001546 switch (getStmtClass()) {
1547 default:
John McCall0faede62010-03-12 07:11:26 +00001548 if (getType()->isVoidType())
1549 return false;
Chris Lattner026dc962009-02-14 07:37:35 +00001550 Loc = getExprLoc();
1551 R1 = getSourceRange();
1552 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001553 case ParenExprClass:
Chris Lattner026dc962009-02-14 07:37:35 +00001554 return cast<ParenExpr>(this)->getSubExpr()->
Mike Stumpdf317bf2009-11-03 23:25:48 +00001555 isUnusedResultAWarning(Loc, R1, R2, Ctx);
Peter Collingbournef111d932011-04-15 00:35:48 +00001556 case GenericSelectionExprClass:
1557 return cast<GenericSelectionExpr>(this)->getResultExpr()->
1558 isUnusedResultAWarning(Loc, R1, R2, Ctx);
Reid Spencer5f016e22007-07-11 17:01:13 +00001559 case UnaryOperatorClass: {
1560 const UnaryOperator *UO = cast<UnaryOperator>(this);
Mike Stump1eb44332009-09-09 15:08:12 +00001561
Reid Spencer5f016e22007-07-11 17:01:13 +00001562 switch (UO->getOpcode()) {
Chris Lattner026dc962009-02-14 07:37:35 +00001563 default: break;
John McCall2de56d12010-08-25 11:45:40 +00001564 case UO_PostInc:
1565 case UO_PostDec:
1566 case UO_PreInc:
1567 case UO_PreDec: // ++/--
Chris Lattner026dc962009-02-14 07:37:35 +00001568 return false; // Not a warning.
John McCall2de56d12010-08-25 11:45:40 +00001569 case UO_Deref:
Reid Spencer5f016e22007-07-11 17:01:13 +00001570 // Dereferencing a volatile pointer is a side-effect.
Mike Stumpdf317bf2009-11-03 23:25:48 +00001571 if (Ctx.getCanonicalType(getType()).isVolatileQualified())
Chris Lattner026dc962009-02-14 07:37:35 +00001572 return false;
1573 break;
John McCall2de56d12010-08-25 11:45:40 +00001574 case UO_Real:
1575 case UO_Imag:
Reid Spencer5f016e22007-07-11 17:01:13 +00001576 // accessing a piece of a volatile complex is a side-effect.
Mike Stumpdf317bf2009-11-03 23:25:48 +00001577 if (Ctx.getCanonicalType(UO->getSubExpr()->getType())
1578 .isVolatileQualified())
Chris Lattner026dc962009-02-14 07:37:35 +00001579 return false;
1580 break;
John McCall2de56d12010-08-25 11:45:40 +00001581 case UO_Extension:
Mike Stumpdf317bf2009-11-03 23:25:48 +00001582 return UO->getSubExpr()->isUnusedResultAWarning(Loc, R1, R2, Ctx);
Reid Spencer5f016e22007-07-11 17:01:13 +00001583 }
Chris Lattner026dc962009-02-14 07:37:35 +00001584 Loc = UO->getOperatorLoc();
1585 R1 = UO->getSubExpr()->getSourceRange();
1586 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001587 }
Chris Lattnere7716e62007-12-01 06:07:34 +00001588 case BinaryOperatorClass: {
Chris Lattner026dc962009-02-14 07:37:35 +00001589 const BinaryOperator *BO = cast<BinaryOperator>(this);
Ted Kremenekc46a2462010-04-07 18:49:21 +00001590 switch (BO->getOpcode()) {
1591 default:
1592 break;
Argyrios Kyrtzidis25973452010-06-30 10:53:14 +00001593 // Consider the RHS of comma for side effects. LHS was checked by
1594 // Sema::CheckCommaOperands.
John McCall2de56d12010-08-25 11:45:40 +00001595 case BO_Comma:
Ted Kremenekc46a2462010-04-07 18:49:21 +00001596 // ((foo = <blah>), 0) is an idiom for hiding the result (and
1597 // lvalue-ness) of an assignment written in a macro.
1598 if (IntegerLiteral *IE =
1599 dyn_cast<IntegerLiteral>(BO->getRHS()->IgnoreParens()))
1600 if (IE->getValue() == 0)
1601 return false;
Argyrios Kyrtzidis25973452010-06-30 10:53:14 +00001602 return BO->getRHS()->isUnusedResultAWarning(Loc, R1, R2, Ctx);
1603 // Consider '||', '&&' to have side effects if the LHS or RHS does.
John McCall2de56d12010-08-25 11:45:40 +00001604 case BO_LAnd:
1605 case BO_LOr:
Argyrios Kyrtzidis25973452010-06-30 10:53:14 +00001606 if (!BO->getLHS()->isUnusedResultAWarning(Loc, R1, R2, Ctx) ||
1607 !BO->getRHS()->isUnusedResultAWarning(Loc, R1, R2, Ctx))
1608 return false;
1609 break;
John McCallbf0ee352010-02-16 04:10:53 +00001610 }
Chris Lattner026dc962009-02-14 07:37:35 +00001611 if (BO->isAssignmentOp())
1612 return false;
1613 Loc = BO->getOperatorLoc();
1614 R1 = BO->getLHS()->getSourceRange();
1615 R2 = BO->getRHS()->getSourceRange();
1616 return true;
Chris Lattnere7716e62007-12-01 06:07:34 +00001617 }
Chris Lattnereb14fe82007-08-25 02:00:02 +00001618 case CompoundAssignOperatorClass:
Douglas Gregorc6dfe192010-05-08 22:41:50 +00001619 case VAArgExprClass:
Eli Friedman276b0612011-10-11 02:20:01 +00001620 case AtomicExprClass:
Chris Lattner026dc962009-02-14 07:37:35 +00001621 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001622
Fariborz Jahanianab38e4b2007-12-01 19:58:28 +00001623 case ConditionalOperatorClass: {
Ted Kremenekfb7cb352011-03-01 20:34:48 +00001624 // If only one of the LHS or RHS is a warning, the operator might
1625 // be being used for control flow. Only warn if both the LHS and
1626 // RHS are warnings.
Fariborz Jahanianab38e4b2007-12-01 19:58:28 +00001627 const ConditionalOperator *Exp = cast<ConditionalOperator>(this);
Ted Kremenekfb7cb352011-03-01 20:34:48 +00001628 if (!Exp->getRHS()->isUnusedResultAWarning(Loc, R1, R2, Ctx))
1629 return false;
1630 if (!Exp->getLHS())
Chris Lattner026dc962009-02-14 07:37:35 +00001631 return true;
Ted Kremenekfb7cb352011-03-01 20:34:48 +00001632 return Exp->getLHS()->isUnusedResultAWarning(Loc, R1, R2, Ctx);
Fariborz Jahanianab38e4b2007-12-01 19:58:28 +00001633 }
1634
Reid Spencer5f016e22007-07-11 17:01:13 +00001635 case MemberExprClass:
Chris Lattner026dc962009-02-14 07:37:35 +00001636 // If the base pointer or element is to a volatile pointer/field, accessing
1637 // it is a side effect.
Mike Stumpdf317bf2009-11-03 23:25:48 +00001638 if (Ctx.getCanonicalType(getType()).isVolatileQualified())
Chris Lattner026dc962009-02-14 07:37:35 +00001639 return false;
1640 Loc = cast<MemberExpr>(this)->getMemberLoc();
1641 R1 = SourceRange(Loc, Loc);
1642 R2 = cast<MemberExpr>(this)->getBase()->getSourceRange();
1643 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001644
Reid Spencer5f016e22007-07-11 17:01:13 +00001645 case ArraySubscriptExprClass:
1646 // If the base pointer or element is to a volatile pointer/field, accessing
Chris Lattner026dc962009-02-14 07:37:35 +00001647 // it is a side effect.
Mike Stumpdf317bf2009-11-03 23:25:48 +00001648 if (Ctx.getCanonicalType(getType()).isVolatileQualified())
Chris Lattner026dc962009-02-14 07:37:35 +00001649 return false;
1650 Loc = cast<ArraySubscriptExpr>(this)->getRBracketLoc();
1651 R1 = cast<ArraySubscriptExpr>(this)->getLHS()->getSourceRange();
1652 R2 = cast<ArraySubscriptExpr>(this)->getRHS()->getSourceRange();
1653 return true;
Eli Friedman211f6ad2008-05-27 15:24:04 +00001654
Chandler Carruth9b106832011-08-17 09:49:44 +00001655 case CXXOperatorCallExprClass: {
1656 // We warn about operator== and operator!= even when user-defined operator
1657 // overloads as there is no reasonable way to define these such that they
1658 // have non-trivial, desirable side-effects. See the -Wunused-comparison
1659 // warning: these operators are commonly typo'ed, and so warning on them
1660 // provides additional value as well. If this list is updated,
1661 // DiagnoseUnusedComparison should be as well.
1662 const CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(this);
1663 if (Op->getOperator() == OO_EqualEqual ||
Matt Beaumont-Gay6e521832011-09-19 18:51:20 +00001664 Op->getOperator() == OO_ExclaimEqual) {
1665 Loc = Op->getOperatorLoc();
1666 R1 = Op->getSourceRange();
Chandler Carruth9b106832011-08-17 09:49:44 +00001667 return true;
Matt Beaumont-Gay6e521832011-09-19 18:51:20 +00001668 }
Chandler Carruth9b106832011-08-17 09:49:44 +00001669
1670 // Fallthrough for generic call handling.
1671 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001672 case CallExprClass:
Eli Friedman852871a2009-04-29 16:35:53 +00001673 case CXXMemberCallExprClass: {
Chris Lattner026dc962009-02-14 07:37:35 +00001674 // If this is a direct call, get the callee.
1675 const CallExpr *CE = cast<CallExpr>(this);
Nuno Lopesd20254f2009-12-20 23:11:08 +00001676 if (const Decl *FD = CE->getCalleeDecl()) {
Chris Lattner026dc962009-02-14 07:37:35 +00001677 // If the callee has attribute pure, const, or warn_unused_result, warn
1678 // about it. void foo() { strlen("bar"); } should warn.
Chris Lattnerbc8d42c2009-10-13 04:53:48 +00001679 //
1680 // Note: If new cases are added here, DiagnoseUnusedExprResult should be
1681 // updated to match for QoI.
1682 if (FD->getAttr<WarnUnusedResultAttr>() ||
1683 FD->getAttr<PureAttr>() || FD->getAttr<ConstAttr>()) {
1684 Loc = CE->getCallee()->getLocStart();
1685 R1 = CE->getCallee()->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001686
Chris Lattnerbc8d42c2009-10-13 04:53:48 +00001687 if (unsigned NumArgs = CE->getNumArgs())
1688 R2 = SourceRange(CE->getArg(0)->getLocStart(),
1689 CE->getArg(NumArgs-1)->getLocEnd());
1690 return true;
1691 }
Chris Lattner026dc962009-02-14 07:37:35 +00001692 }
1693 return false;
1694 }
Anders Carlsson58beed92009-11-17 17:11:23 +00001695
1696 case CXXTemporaryObjectExprClass:
1697 case CXXConstructExprClass:
1698 return false;
1699
Fariborz Jahanianf0317742010-03-30 18:22:15 +00001700 case ObjCMessageExprClass: {
1701 const ObjCMessageExpr *ME = cast<ObjCMessageExpr>(this);
John McCallf85e1932011-06-15 23:02:42 +00001702 if (Ctx.getLangOptions().ObjCAutoRefCount &&
1703 ME->isInstanceMessage() &&
1704 !ME->getType()->isVoidType() &&
1705 ME->getSelector().getIdentifierInfoForSlot(0) &&
1706 ME->getSelector().getIdentifierInfoForSlot(0)
1707 ->getName().startswith("init")) {
1708 Loc = getExprLoc();
1709 R1 = ME->getSourceRange();
1710 return true;
1711 }
1712
Fariborz Jahanianf0317742010-03-30 18:22:15 +00001713 const ObjCMethodDecl *MD = ME->getMethodDecl();
1714 if (MD && MD->getAttr<WarnUnusedResultAttr>()) {
1715 Loc = getExprLoc();
1716 return true;
1717 }
Chris Lattner026dc962009-02-14 07:37:35 +00001718 return false;
Fariborz Jahanianf0317742010-03-30 18:22:15 +00001719 }
Mike Stump1eb44332009-09-09 15:08:12 +00001720
John McCall12f78a62010-12-02 01:19:52 +00001721 case ObjCPropertyRefExprClass:
Chris Lattner5e94a0d2009-08-16 16:51:50 +00001722 Loc = getExprLoc();
1723 R1 = getSourceRange();
Chris Lattnera50089e2009-08-16 16:45:18 +00001724 return true;
John McCall12f78a62010-12-02 01:19:52 +00001725
John McCall4b9c2d22011-11-06 09:01:30 +00001726 case PseudoObjectExprClass: {
1727 const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this);
1728
1729 // Only complain about things that have the form of a getter.
1730 if (isa<UnaryOperator>(PO->getSyntacticForm()) ||
1731 isa<BinaryOperator>(PO->getSyntacticForm()))
1732 return false;
1733
1734 Loc = getExprLoc();
1735 R1 = getSourceRange();
1736 return true;
1737 }
1738
Chris Lattner611b2ec2008-07-26 19:51:01 +00001739 case StmtExprClass: {
1740 // Statement exprs don't logically have side effects themselves, but are
1741 // sometimes used in macros in ways that give them a type that is unused.
1742 // For example ({ blah; foo(); }) will end up with a type if foo has a type.
1743 // however, if the result of the stmt expr is dead, we don't want to emit a
1744 // warning.
1745 const CompoundStmt *CS = cast<StmtExpr>(this)->getSubStmt();
Argyrios Kyrtzidisd2827af2010-09-19 21:21:10 +00001746 if (!CS->body_empty()) {
Chris Lattner611b2ec2008-07-26 19:51:01 +00001747 if (const Expr *E = dyn_cast<Expr>(CS->body_back()))
Mike Stumpdf317bf2009-11-03 23:25:48 +00001748 return E->isUnusedResultAWarning(Loc, R1, R2, Ctx);
Argyrios Kyrtzidisd2827af2010-09-19 21:21:10 +00001749 if (const LabelStmt *Label = dyn_cast<LabelStmt>(CS->body_back()))
1750 if (const Expr *E = dyn_cast<Expr>(Label->getSubStmt()))
1751 return E->isUnusedResultAWarning(Loc, R1, R2, Ctx);
1752 }
Mike Stump1eb44332009-09-09 15:08:12 +00001753
John McCall0faede62010-03-12 07:11:26 +00001754 if (getType()->isVoidType())
1755 return false;
Chris Lattner026dc962009-02-14 07:37:35 +00001756 Loc = cast<StmtExpr>(this)->getLParenLoc();
1757 R1 = getSourceRange();
1758 return true;
Chris Lattner611b2ec2008-07-26 19:51:01 +00001759 }
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001760 case CStyleCastExprClass:
Chris Lattnerfb846642009-07-28 18:25:28 +00001761 // If this is an explicit cast to void, allow it. People do this when they
1762 // think they know what they're doing :).
Chris Lattner026dc962009-02-14 07:37:35 +00001763 if (getType()->isVoidType())
Chris Lattnerfb846642009-07-28 18:25:28 +00001764 return false;
Chris Lattner026dc962009-02-14 07:37:35 +00001765 Loc = cast<CStyleCastExpr>(this)->getLParenLoc();
1766 R1 = cast<CStyleCastExpr>(this)->getSubExpr()->getSourceRange();
1767 return true;
Anders Carlsson58beed92009-11-17 17:11:23 +00001768 case CXXFunctionalCastExprClass: {
John McCall0faede62010-03-12 07:11:26 +00001769 if (getType()->isVoidType())
1770 return false;
Anders Carlsson58beed92009-11-17 17:11:23 +00001771 const CastExpr *CE = cast<CastExpr>(this);
Sean Huntc3021132010-05-05 15:23:54 +00001772
Anders Carlsson58beed92009-11-17 17:11:23 +00001773 // If this is a cast to void or a constructor conversion, check the operand.
1774 // Otherwise, the result of the cast is unused.
John McCall2de56d12010-08-25 11:45:40 +00001775 if (CE->getCastKind() == CK_ToVoid ||
1776 CE->getCastKind() == CK_ConstructorConversion)
Mike Stumpdf317bf2009-11-03 23:25:48 +00001777 return (cast<CastExpr>(this)->getSubExpr()
1778 ->isUnusedResultAWarning(Loc, R1, R2, Ctx));
Chris Lattner026dc962009-02-14 07:37:35 +00001779 Loc = cast<CXXFunctionalCastExpr>(this)->getTypeBeginLoc();
1780 R1 = cast<CXXFunctionalCastExpr>(this)->getSubExpr()->getSourceRange();
1781 return true;
Anders Carlsson58beed92009-11-17 17:11:23 +00001782 }
Mike Stump1eb44332009-09-09 15:08:12 +00001783
Eli Friedman4be1f472008-05-19 21:24:43 +00001784 case ImplicitCastExprClass:
1785 // Check the operand, since implicit casts are inserted by Sema
Mike Stumpdf317bf2009-11-03 23:25:48 +00001786 return (cast<ImplicitCastExpr>(this)
1787 ->getSubExpr()->isUnusedResultAWarning(Loc, R1, R2, Ctx));
Eli Friedman4be1f472008-05-19 21:24:43 +00001788
Chris Lattner04421082008-04-08 04:40:51 +00001789 case CXXDefaultArgExprClass:
Mike Stumpdf317bf2009-11-03 23:25:48 +00001790 return (cast<CXXDefaultArgExpr>(this)
1791 ->getExpr()->isUnusedResultAWarning(Loc, R1, R2, Ctx));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001792
1793 case CXXNewExprClass:
1794 // FIXME: In theory, there might be new expressions that don't have side
1795 // effects (e.g. a placement new with an uninitialized POD).
1796 case CXXDeleteExprClass:
Chris Lattner026dc962009-02-14 07:37:35 +00001797 return false;
Anders Carlsson2d46eb22009-08-16 04:11:06 +00001798 case CXXBindTemporaryExprClass:
Mike Stumpdf317bf2009-11-03 23:25:48 +00001799 return (cast<CXXBindTemporaryExpr>(this)
1800 ->getSubExpr()->isUnusedResultAWarning(Loc, R1, R2, Ctx));
John McCall4765fa02010-12-06 08:20:24 +00001801 case ExprWithCleanupsClass:
1802 return (cast<ExprWithCleanups>(this)
Mike Stumpdf317bf2009-11-03 23:25:48 +00001803 ->getSubExpr()->isUnusedResultAWarning(Loc, R1, R2, Ctx));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001804 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001805}
1806
Fariborz Jahanian44baa8a2009-02-22 18:40:18 +00001807/// isOBJCGCCandidate - Check if an expression is objc gc'able.
Fariborz Jahanian7f4f86a2009-09-08 23:38:54 +00001808/// returns true, if it is; false otherwise.
Fariborz Jahanian102e3902009-06-01 21:29:32 +00001809bool Expr::isOBJCGCCandidate(ASTContext &Ctx) const {
Peter Collingbournef111d932011-04-15 00:35:48 +00001810 const Expr *E = IgnoreParens();
1811 switch (E->getStmtClass()) {
Fariborz Jahanian44baa8a2009-02-22 18:40:18 +00001812 default:
1813 return false;
1814 case ObjCIvarRefExprClass:
1815 return true;
Fariborz Jahanian207c5212009-02-23 18:59:50 +00001816 case Expr::UnaryOperatorClass:
Peter Collingbournef111d932011-04-15 00:35:48 +00001817 return cast<UnaryOperator>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
Fariborz Jahanian44baa8a2009-02-22 18:40:18 +00001818 case ImplicitCastExprClass:
Peter Collingbournef111d932011-04-15 00:35:48 +00001819 return cast<ImplicitCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
Douglas Gregor03e80032011-06-21 17:03:29 +00001820 case MaterializeTemporaryExprClass:
1821 return cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr()
1822 ->isOBJCGCCandidate(Ctx);
Fariborz Jahanian06b89122009-05-05 23:28:21 +00001823 case CStyleCastExprClass:
Peter Collingbournef111d932011-04-15 00:35:48 +00001824 return cast<CStyleCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
Fariborz Jahaniane3f83492011-09-23 18:57:30 +00001825 case BlockDeclRefExprClass:
Douglas Gregora2813ce2009-10-23 18:54:35 +00001826 case DeclRefExprClass: {
Fariborz Jahaniane3f83492011-09-23 18:57:30 +00001827
1828 const Decl *D;
1829 if (const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E))
1830 D = BDRE->getDecl();
1831 else
1832 D = cast<DeclRefExpr>(E)->getDecl();
1833
Fariborz Jahanian102e3902009-06-01 21:29:32 +00001834 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1835 if (VD->hasGlobalStorage())
1836 return true;
1837 QualType T = VD->getType();
Fariborz Jahanian59a53fa2009-09-16 18:09:18 +00001838 // dereferencing to a pointer is always a gc'able candidate,
1839 // unless it is __weak.
Daniel Dunbar7e88a602009-09-17 06:31:17 +00001840 return T->isPointerType() &&
John McCall0953e762009-09-24 19:53:00 +00001841 (Ctx.getObjCGCAttrKind(T) != Qualifiers::Weak);
Fariborz Jahanian102e3902009-06-01 21:29:32 +00001842 }
Fariborz Jahanian44baa8a2009-02-22 18:40:18 +00001843 return false;
1844 }
Douglas Gregor83f6faf2009-08-31 23:41:50 +00001845 case MemberExprClass: {
Peter Collingbournef111d932011-04-15 00:35:48 +00001846 const MemberExpr *M = cast<MemberExpr>(E);
Fariborz Jahanian102e3902009-06-01 21:29:32 +00001847 return M->getBase()->isOBJCGCCandidate(Ctx);
Fariborz Jahanian44baa8a2009-02-22 18:40:18 +00001848 }
1849 case ArraySubscriptExprClass:
Peter Collingbournef111d932011-04-15 00:35:48 +00001850 return cast<ArraySubscriptExpr>(E)->getBase()->isOBJCGCCandidate(Ctx);
Fariborz Jahanian44baa8a2009-02-22 18:40:18 +00001851 }
1852}
Sebastian Redl369e51f2010-09-10 20:55:33 +00001853
Argyrios Kyrtzidis11ab7902010-11-01 18:49:26 +00001854bool Expr::isBoundMemberFunction(ASTContext &Ctx) const {
1855 if (isTypeDependent())
1856 return false;
John McCall7eb0a9e2010-11-24 05:12:34 +00001857 return ClassifyLValue(Ctx) == Expr::LV_MemberFunction;
Argyrios Kyrtzidis11ab7902010-11-01 18:49:26 +00001858}
1859
John McCall864c0412011-04-26 20:42:42 +00001860QualType Expr::findBoundMemberType(const Expr *expr) {
John McCalle0a22d02011-10-18 21:02:43 +00001861 assert(expr->hasPlaceholderType(BuiltinType::BoundMember));
John McCall864c0412011-04-26 20:42:42 +00001862
1863 // Bound member expressions are always one of these possibilities:
1864 // x->m x.m x->*y x.*y
1865 // (possibly parenthesized)
1866
1867 expr = expr->IgnoreParens();
1868 if (const MemberExpr *mem = dyn_cast<MemberExpr>(expr)) {
1869 assert(isa<CXXMethodDecl>(mem->getMemberDecl()));
1870 return mem->getMemberDecl()->getType();
1871 }
1872
1873 if (const BinaryOperator *op = dyn_cast<BinaryOperator>(expr)) {
1874 QualType type = op->getRHS()->getType()->castAs<MemberPointerType>()
1875 ->getPointeeType();
1876 assert(type->isFunctionType());
1877 return type;
1878 }
1879
1880 assert(isa<UnresolvedMemberExpr>(expr));
1881 return QualType();
1882}
1883
Sebastian Redl369e51f2010-09-10 20:55:33 +00001884static Expr::CanThrowResult MergeCanThrow(Expr::CanThrowResult CT1,
1885 Expr::CanThrowResult CT2) {
1886 // CanThrowResult constants are ordered so that the maximum is the correct
1887 // merge result.
1888 return CT1 > CT2 ? CT1 : CT2;
1889}
1890
1891static Expr::CanThrowResult CanSubExprsThrow(ASTContext &C, const Expr *CE) {
1892 Expr *E = const_cast<Expr*>(CE);
1893 Expr::CanThrowResult R = Expr::CT_Cannot;
John McCall7502c1d2011-02-13 04:07:26 +00001894 for (Expr::child_range I = E->children(); I && R != Expr::CT_Can; ++I) {
Sebastian Redl369e51f2010-09-10 20:55:33 +00001895 R = MergeCanThrow(R, cast<Expr>(*I)->CanThrow(C));
1896 }
1897 return R;
1898}
1899
Richard Smith7a614d82011-06-11 17:19:42 +00001900static Expr::CanThrowResult CanCalleeThrow(ASTContext &Ctx, const Expr *E,
1901 const Decl *D,
Sebastian Redl369e51f2010-09-10 20:55:33 +00001902 bool NullThrows = true) {
1903 if (!D)
1904 return NullThrows ? Expr::CT_Can : Expr::CT_Cannot;
1905
1906 // See if we can get a function type from the decl somehow.
1907 const ValueDecl *VD = dyn_cast<ValueDecl>(D);
1908 if (!VD) // If we have no clue what we're calling, assume the worst.
1909 return Expr::CT_Can;
1910
Sebastian Redl5221d8f2010-09-10 22:34:40 +00001911 // As an extension, we assume that __attribute__((nothrow)) functions don't
1912 // throw.
1913 if (isa<FunctionDecl>(D) && D->hasAttr<NoThrowAttr>())
1914 return Expr::CT_Cannot;
1915
Sebastian Redl369e51f2010-09-10 20:55:33 +00001916 QualType T = VD->getType();
1917 const FunctionProtoType *FT;
1918 if ((FT = T->getAs<FunctionProtoType>())) {
1919 } else if (const PointerType *PT = T->getAs<PointerType>())
1920 FT = PT->getPointeeType()->getAs<FunctionProtoType>();
1921 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
1922 FT = RT->getPointeeType()->getAs<FunctionProtoType>();
1923 else if (const MemberPointerType *MT = T->getAs<MemberPointerType>())
1924 FT = MT->getPointeeType()->getAs<FunctionProtoType>();
1925 else if (const BlockPointerType *BT = T->getAs<BlockPointerType>())
1926 FT = BT->getPointeeType()->getAs<FunctionProtoType>();
1927
1928 if (!FT)
1929 return Expr::CT_Can;
1930
Richard Smith7a614d82011-06-11 17:19:42 +00001931 if (FT->getExceptionSpecType() == EST_Delayed) {
1932 assert(isa<CXXConstructorDecl>(D) &&
1933 "only constructor exception specs can be unknown");
1934 Ctx.getDiagnostics().Report(E->getLocStart(),
1935 diag::err_exception_spec_unknown)
1936 << E->getSourceRange();
1937 return Expr::CT_Can;
1938 }
1939
Sebastian Redl8026f6d2011-03-13 17:09:40 +00001940 return FT->isNothrow(Ctx) ? Expr::CT_Cannot : Expr::CT_Can;
Sebastian Redl369e51f2010-09-10 20:55:33 +00001941}
1942
1943static Expr::CanThrowResult CanDynamicCastThrow(const CXXDynamicCastExpr *DC) {
1944 if (DC->isTypeDependent())
1945 return Expr::CT_Dependent;
1946
Sebastian Redl295995c2010-09-10 20:55:47 +00001947 if (!DC->getTypeAsWritten()->isReferenceType())
1948 return Expr::CT_Cannot;
1949
Eli Friedmanbe57cf42011-05-11 05:22:44 +00001950 if (DC->getSubExpr()->isTypeDependent())
1951 return Expr::CT_Dependent;
1952
Sebastian Redl369e51f2010-09-10 20:55:33 +00001953 return DC->getCastKind() == clang::CK_Dynamic? Expr::CT_Can : Expr::CT_Cannot;
1954}
1955
1956static Expr::CanThrowResult CanTypeidThrow(ASTContext &C,
1957 const CXXTypeidExpr *DC) {
1958 if (DC->isTypeOperand())
1959 return Expr::CT_Cannot;
1960
1961 Expr *Op = DC->getExprOperand();
1962 if (Op->isTypeDependent())
1963 return Expr::CT_Dependent;
1964
1965 const RecordType *RT = Op->getType()->getAs<RecordType>();
1966 if (!RT)
1967 return Expr::CT_Cannot;
1968
1969 if (!cast<CXXRecordDecl>(RT->getDecl())->isPolymorphic())
1970 return Expr::CT_Cannot;
1971
1972 if (Op->Classify(C).isPRValue())
1973 return Expr::CT_Cannot;
1974
1975 return Expr::CT_Can;
1976}
1977
1978Expr::CanThrowResult Expr::CanThrow(ASTContext &C) const {
1979 // C++ [expr.unary.noexcept]p3:
1980 // [Can throw] if in a potentially-evaluated context the expression would
1981 // contain:
1982 switch (getStmtClass()) {
1983 case CXXThrowExprClass:
1984 // - a potentially evaluated throw-expression
1985 return CT_Can;
1986
1987 case CXXDynamicCastExprClass: {
1988 // - a potentially evaluated dynamic_cast expression dynamic_cast<T>(v),
1989 // where T is a reference type, that requires a run-time check
1990 CanThrowResult CT = CanDynamicCastThrow(cast<CXXDynamicCastExpr>(this));
1991 if (CT == CT_Can)
1992 return CT;
1993 return MergeCanThrow(CT, CanSubExprsThrow(C, this));
1994 }
1995
1996 case CXXTypeidExprClass:
1997 // - a potentially evaluated typeid expression applied to a glvalue
1998 // expression whose type is a polymorphic class type
1999 return CanTypeidThrow(C, cast<CXXTypeidExpr>(this));
2000
2001 // - a potentially evaluated call to a function, member function, function
2002 // pointer, or member function pointer that does not have a non-throwing
2003 // exception-specification
2004 case CallExprClass:
Eli Friedmanc9674be2012-01-31 01:21:45 +00002005 case CXXMemberCallExprClass:
2006 case CXXOperatorCallExprClass: {
Eli Friedmanebc93e1762011-05-12 02:11:32 +00002007 const CallExpr *CE = cast<CallExpr>(this);
Eli Friedmanbe57cf42011-05-11 05:22:44 +00002008 CanThrowResult CT;
2009 if (isTypeDependent())
2010 CT = CT_Dependent;
Eli Friedmanebc93e1762011-05-12 02:11:32 +00002011 else if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens()))
2012 CT = CT_Cannot;
Eli Friedmanbe57cf42011-05-11 05:22:44 +00002013 else
Richard Smith7a614d82011-06-11 17:19:42 +00002014 CT = CanCalleeThrow(C, this, CE->getCalleeDecl());
Sebastian Redl369e51f2010-09-10 20:55:33 +00002015 if (CT == CT_Can)
2016 return CT;
2017 return MergeCanThrow(CT, CanSubExprsThrow(C, this));
2018 }
2019
Sebastian Redl295995c2010-09-10 20:55:47 +00002020 case CXXConstructExprClass:
2021 case CXXTemporaryObjectExprClass: {
Richard Smith7a614d82011-06-11 17:19:42 +00002022 CanThrowResult CT = CanCalleeThrow(C, this,
Sebastian Redl369e51f2010-09-10 20:55:33 +00002023 cast<CXXConstructExpr>(this)->getConstructor());
2024 if (CT == CT_Can)
2025 return CT;
2026 return MergeCanThrow(CT, CanSubExprsThrow(C, this));
2027 }
2028
Douglas Gregor01d08012012-02-07 10:09:13 +00002029 case LambdaExprClass: {
2030 const LambdaExpr *Lambda = cast<LambdaExpr>(this);
2031 CanThrowResult CT = Expr::CT_Cannot;
2032 for (LambdaExpr::capture_init_iterator Cap = Lambda->capture_init_begin(),
2033 CapEnd = Lambda->capture_init_end();
2034 Cap != CapEnd; ++Cap)
2035 CT = MergeCanThrow(CT, (*Cap)->CanThrow(C));
2036 return CT;
2037 }
2038
Sebastian Redl369e51f2010-09-10 20:55:33 +00002039 case CXXNewExprClass: {
Eli Friedmanbe57cf42011-05-11 05:22:44 +00002040 CanThrowResult CT;
2041 if (isTypeDependent())
2042 CT = CT_Dependent;
2043 else
2044 CT = MergeCanThrow(
Richard Smith7a614d82011-06-11 17:19:42 +00002045 CanCalleeThrow(C, this, cast<CXXNewExpr>(this)->getOperatorNew()),
2046 CanCalleeThrow(C, this, cast<CXXNewExpr>(this)->getConstructor(),
Sebastian Redl369e51f2010-09-10 20:55:33 +00002047 /*NullThrows*/false));
2048 if (CT == CT_Can)
2049 return CT;
2050 return MergeCanThrow(CT, CanSubExprsThrow(C, this));
2051 }
2052
2053 case CXXDeleteExprClass: {
Eli Friedmanbe57cf42011-05-11 05:22:44 +00002054 CanThrowResult CT;
2055 QualType DTy = cast<CXXDeleteExpr>(this)->getDestroyedType();
2056 if (DTy.isNull() || DTy->isDependentType()) {
2057 CT = CT_Dependent;
2058 } else {
Richard Smith7a614d82011-06-11 17:19:42 +00002059 CT = CanCalleeThrow(C, this,
2060 cast<CXXDeleteExpr>(this)->getOperatorDelete());
Eli Friedmanbe57cf42011-05-11 05:22:44 +00002061 if (const RecordType *RT = DTy->getAs<RecordType>()) {
2062 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Richard Smith7a614d82011-06-11 17:19:42 +00002063 CT = MergeCanThrow(CT, CanCalleeThrow(C, this, RD->getDestructor()));
Sebastian Redl0b34cf72010-09-10 23:27:10 +00002064 }
Eli Friedmanbe57cf42011-05-11 05:22:44 +00002065 if (CT == CT_Can)
2066 return CT;
Sebastian Redl0b34cf72010-09-10 23:27:10 +00002067 }
2068 return MergeCanThrow(CT, CanSubExprsThrow(C, this));
2069 }
2070
2071 case CXXBindTemporaryExprClass: {
2072 // The bound temporary has to be destroyed again, which might throw.
Richard Smith7a614d82011-06-11 17:19:42 +00002073 CanThrowResult CT = CanCalleeThrow(C, this,
Sebastian Redl0b34cf72010-09-10 23:27:10 +00002074 cast<CXXBindTemporaryExpr>(this)->getTemporary()->getDestructor());
2075 if (CT == CT_Can)
2076 return CT;
Sebastian Redl369e51f2010-09-10 20:55:33 +00002077 return MergeCanThrow(CT, CanSubExprsThrow(C, this));
2078 }
2079
2080 // ObjC message sends are like function calls, but never have exception
2081 // specs.
2082 case ObjCMessageExprClass:
2083 case ObjCPropertyRefExprClass:
Sebastian Redl369e51f2010-09-10 20:55:33 +00002084 return CT_Can;
2085
2086 // Many other things have subexpressions, so we have to test those.
2087 // Some are simple:
Sebastian Redl369e51f2010-09-10 20:55:33 +00002088 case ConditionalOperatorClass:
2089 case CompoundLiteralExprClass:
Eli Friedmanc9674be2012-01-31 01:21:45 +00002090 case CXXConstCastExprClass:
2091 case CXXDefaultArgExprClass:
2092 case CXXReinterpretCastExprClass:
2093 case DesignatedInitExprClass:
2094 case ExprWithCleanupsClass:
Sebastian Redl369e51f2010-09-10 20:55:33 +00002095 case ExtVectorElementExprClass:
2096 case InitListExprClass:
Eli Friedmanc9674be2012-01-31 01:21:45 +00002097 case MemberExprClass:
Sebastian Redl369e51f2010-09-10 20:55:33 +00002098 case ObjCIsaExprClass:
Eli Friedmanc9674be2012-01-31 01:21:45 +00002099 case ObjCIvarRefExprClass:
2100 case ParenExprClass:
2101 case ParenListExprClass:
Sebastian Redl369e51f2010-09-10 20:55:33 +00002102 case ShuffleVectorExprClass:
Eli Friedmanc9674be2012-01-31 01:21:45 +00002103 case VAArgExprClass:
Sebastian Redl369e51f2010-09-10 20:55:33 +00002104 return CanSubExprsThrow(C, this);
2105
2106 // Some might be dependent for other reasons.
Sebastian Redl369e51f2010-09-10 20:55:33 +00002107 case ArraySubscriptExprClass:
Eli Friedmanc9674be2012-01-31 01:21:45 +00002108 case BinaryOperatorClass:
2109 case CompoundAssignOperatorClass:
Sebastian Redl369e51f2010-09-10 20:55:33 +00002110 case CStyleCastExprClass:
2111 case CXXStaticCastExprClass:
2112 case CXXFunctionalCastExprClass:
Eli Friedmanc9674be2012-01-31 01:21:45 +00002113 case ImplicitCastExprClass:
2114 case MaterializeTemporaryExprClass:
2115 case UnaryOperatorClass: {
Sebastian Redl369e51f2010-09-10 20:55:33 +00002116 CanThrowResult CT = isTypeDependent() ? CT_Dependent : CT_Cannot;
2117 return MergeCanThrow(CT, CanSubExprsThrow(C, this));
2118 }
2119
2120 // FIXME: We should handle StmtExpr, but that opens a MASSIVE can of worms.
2121 case StmtExprClass:
2122 return CT_Can;
2123
2124 case ChooseExprClass:
2125 if (isTypeDependent() || isValueDependent())
2126 return CT_Dependent;
2127 return cast<ChooseExpr>(this)->getChosenSubExpr(C)->CanThrow(C);
2128
Peter Collingbournef111d932011-04-15 00:35:48 +00002129 case GenericSelectionExprClass:
2130 if (cast<GenericSelectionExpr>(this)->isResultDependent())
2131 return CT_Dependent;
2132 return cast<GenericSelectionExpr>(this)->getResultExpr()->CanThrow(C);
2133
Sebastian Redl369e51f2010-09-10 20:55:33 +00002134 // Some expressions are always dependent.
Sebastian Redl369e51f2010-09-10 20:55:33 +00002135 case CXXDependentScopeMemberExprClass:
Eli Friedmanc9674be2012-01-31 01:21:45 +00002136 case CXXUnresolvedConstructExprClass:
2137 case DependentScopeDeclRefExprClass:
Sebastian Redl369e51f2010-09-10 20:55:33 +00002138 return CT_Dependent;
2139
Eli Friedmanc9674be2012-01-31 01:21:45 +00002140 case AtomicExprClass:
2141 case AsTypeExprClass:
2142 case BinaryConditionalOperatorClass:
2143 case BlockExprClass:
2144 case BlockDeclRefExprClass:
2145 case CUDAKernelCallExprClass:
2146 case DeclRefExprClass:
2147 case ObjCBridgedCastExprClass:
2148 case ObjCIndirectCopyRestoreExprClass:
2149 case ObjCProtocolExprClass:
2150 case ObjCSelectorExprClass:
2151 case OffsetOfExprClass:
2152 case PackExpansionExprClass:
2153 case PseudoObjectExprClass:
2154 case SubstNonTypeTemplateParmExprClass:
2155 case SubstNonTypeTemplateParmPackExprClass:
2156 case UnaryExprOrTypeTraitExprClass:
2157 case UnresolvedLookupExprClass:
2158 case UnresolvedMemberExprClass:
2159 // FIXME: Can any of the above throw? If so, when?
Sebastian Redl369e51f2010-09-10 20:55:33 +00002160 return CT_Cannot;
Eli Friedmanc9674be2012-01-31 01:21:45 +00002161
2162 case AddrLabelExprClass:
2163 case ArrayTypeTraitExprClass:
2164 case BinaryTypeTraitExprClass:
2165 case CXXBoolLiteralExprClass:
2166 case CXXNoexceptExprClass:
2167 case CXXNullPtrLiteralExprClass:
2168 case CXXPseudoDestructorExprClass:
2169 case CXXScalarValueInitExprClass:
2170 case CXXThisExprClass:
2171 case CXXUuidofExprClass:
2172 case CharacterLiteralClass:
2173 case ExpressionTraitExprClass:
2174 case FloatingLiteralClass:
2175 case GNUNullExprClass:
2176 case ImaginaryLiteralClass:
2177 case ImplicitValueInitExprClass:
2178 case IntegerLiteralClass:
2179 case ObjCEncodeExprClass:
2180 case ObjCStringLiteralClass:
2181 case OpaqueValueExprClass:
2182 case PredefinedExprClass:
2183 case SizeOfPackExprClass:
2184 case StringLiteralClass:
2185 case UnaryTypeTraitExprClass:
2186 // These expressions can never throw.
2187 return CT_Cannot;
2188
2189#define STMT(CLASS, PARENT) case CLASS##Class:
2190#define STMT_RANGE(Base, First, Last)
2191#define LAST_STMT_RANGE(BASE, FIRST, LAST)
2192#define EXPR(CLASS, PARENT)
2193#define ABSTRACT_STMT(STMT)
2194#include "clang/AST/StmtNodes.inc"
2195 case NoStmtClass:
2196 llvm_unreachable("Invalid class for expression");
Sebastian Redl369e51f2010-09-10 20:55:33 +00002197 }
Matt Beaumont-Gay56e68b72012-01-31 18:59:25 +00002198 llvm_unreachable("Bogus StmtClass");
Sebastian Redl369e51f2010-09-10 20:55:33 +00002199}
2200
Ted Kremenek4e99a5f2008-01-17 16:57:34 +00002201Expr* Expr::IgnoreParens() {
2202 Expr* E = this;
Abramo Bagnarab9eb35c2010-10-15 07:51:18 +00002203 while (true) {
2204 if (ParenExpr* P = dyn_cast<ParenExpr>(E)) {
2205 E = P->getSubExpr();
2206 continue;
2207 }
2208 if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) {
2209 if (P->getOpcode() == UO_Extension) {
2210 E = P->getSubExpr();
2211 continue;
2212 }
2213 }
Peter Collingbournef111d932011-04-15 00:35:48 +00002214 if (GenericSelectionExpr* P = dyn_cast<GenericSelectionExpr>(E)) {
2215 if (!P->isResultDependent()) {
2216 E = P->getResultExpr();
2217 continue;
2218 }
2219 }
Abramo Bagnarab9eb35c2010-10-15 07:51:18 +00002220 return E;
2221 }
Ted Kremenek4e99a5f2008-01-17 16:57:34 +00002222}
2223
Chris Lattner56f34942008-02-13 01:02:39 +00002224/// IgnoreParenCasts - Ignore parentheses and casts. Strip off any ParenExpr
2225/// or CastExprs or ImplicitCastExprs, returning their operand.
2226Expr *Expr::IgnoreParenCasts() {
2227 Expr *E = this;
2228 while (true) {
Abramo Bagnarab9eb35c2010-10-15 07:51:18 +00002229 if (ParenExpr* P = dyn_cast<ParenExpr>(E)) {
Chris Lattner56f34942008-02-13 01:02:39 +00002230 E = P->getSubExpr();
Abramo Bagnarab9eb35c2010-10-15 07:51:18 +00002231 continue;
2232 }
2233 if (CastExpr *P = dyn_cast<CastExpr>(E)) {
Chris Lattner56f34942008-02-13 01:02:39 +00002234 E = P->getSubExpr();
Abramo Bagnarab9eb35c2010-10-15 07:51:18 +00002235 continue;
2236 }
2237 if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) {
2238 if (P->getOpcode() == UO_Extension) {
2239 E = P->getSubExpr();
2240 continue;
2241 }
2242 }
Peter Collingbournef111d932011-04-15 00:35:48 +00002243 if (GenericSelectionExpr* P = dyn_cast<GenericSelectionExpr>(E)) {
2244 if (!P->isResultDependent()) {
2245 E = P->getResultExpr();
2246 continue;
2247 }
2248 }
Douglas Gregor03e80032011-06-21 17:03:29 +00002249 if (MaterializeTemporaryExpr *Materialize
2250 = dyn_cast<MaterializeTemporaryExpr>(E)) {
2251 E = Materialize->GetTemporaryExpr();
2252 continue;
2253 }
Douglas Gregorc0244c52011-09-08 17:56:33 +00002254 if (SubstNonTypeTemplateParmExpr *NTTP
2255 = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2256 E = NTTP->getReplacement();
2257 continue;
2258 }
Abramo Bagnarab9eb35c2010-10-15 07:51:18 +00002259 return E;
Chris Lattner56f34942008-02-13 01:02:39 +00002260 }
2261}
2262
John McCall9c5d70c2010-12-04 08:24:19 +00002263/// IgnoreParenLValueCasts - Ignore parentheses and lvalue-to-rvalue
2264/// casts. This is intended purely as a temporary workaround for code
2265/// that hasn't yet been rewritten to do the right thing about those
2266/// casts, and may disappear along with the last internal use.
John McCallf6a16482010-12-04 03:47:34 +00002267Expr *Expr::IgnoreParenLValueCasts() {
2268 Expr *E = this;
John McCall9c5d70c2010-12-04 08:24:19 +00002269 while (true) {
John McCallf6a16482010-12-04 03:47:34 +00002270 if (ParenExpr *P = dyn_cast<ParenExpr>(E)) {
2271 E = P->getSubExpr();
2272 continue;
John McCall9c5d70c2010-12-04 08:24:19 +00002273 } else if (CastExpr *P = dyn_cast<CastExpr>(E)) {
John McCallf6a16482010-12-04 03:47:34 +00002274 if (P->getCastKind() == CK_LValueToRValue) {
2275 E = P->getSubExpr();
2276 continue;
2277 }
John McCall9c5d70c2010-12-04 08:24:19 +00002278 } else if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) {
2279 if (P->getOpcode() == UO_Extension) {
2280 E = P->getSubExpr();
2281 continue;
2282 }
Peter Collingbournef111d932011-04-15 00:35:48 +00002283 } else if (GenericSelectionExpr* P = dyn_cast<GenericSelectionExpr>(E)) {
2284 if (!P->isResultDependent()) {
2285 E = P->getResultExpr();
2286 continue;
2287 }
Douglas Gregor03e80032011-06-21 17:03:29 +00002288 } else if (MaterializeTemporaryExpr *Materialize
2289 = dyn_cast<MaterializeTemporaryExpr>(E)) {
2290 E = Materialize->GetTemporaryExpr();
2291 continue;
Douglas Gregorc0244c52011-09-08 17:56:33 +00002292 } else if (SubstNonTypeTemplateParmExpr *NTTP
2293 = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2294 E = NTTP->getReplacement();
2295 continue;
John McCallf6a16482010-12-04 03:47:34 +00002296 }
2297 break;
2298 }
2299 return E;
2300}
2301
John McCall2fc46bf2010-05-05 22:59:52 +00002302Expr *Expr::IgnoreParenImpCasts() {
2303 Expr *E = this;
2304 while (true) {
Abramo Bagnarab9eb35c2010-10-15 07:51:18 +00002305 if (ParenExpr *P = dyn_cast<ParenExpr>(E)) {
John McCall2fc46bf2010-05-05 22:59:52 +00002306 E = P->getSubExpr();
Abramo Bagnarab9eb35c2010-10-15 07:51:18 +00002307 continue;
2308 }
2309 if (ImplicitCastExpr *P = dyn_cast<ImplicitCastExpr>(E)) {
John McCall2fc46bf2010-05-05 22:59:52 +00002310 E = P->getSubExpr();
Abramo Bagnarab9eb35c2010-10-15 07:51:18 +00002311 continue;
2312 }
2313 if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) {
2314 if (P->getOpcode() == UO_Extension) {
2315 E = P->getSubExpr();
2316 continue;
2317 }
2318 }
Peter Collingbournef111d932011-04-15 00:35:48 +00002319 if (GenericSelectionExpr* P = dyn_cast<GenericSelectionExpr>(E)) {
2320 if (!P->isResultDependent()) {
2321 E = P->getResultExpr();
2322 continue;
2323 }
2324 }
Douglas Gregor03e80032011-06-21 17:03:29 +00002325 if (MaterializeTemporaryExpr *Materialize
2326 = dyn_cast<MaterializeTemporaryExpr>(E)) {
2327 E = Materialize->GetTemporaryExpr();
2328 continue;
2329 }
Douglas Gregorc0244c52011-09-08 17:56:33 +00002330 if (SubstNonTypeTemplateParmExpr *NTTP
2331 = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2332 E = NTTP->getReplacement();
2333 continue;
2334 }
Abramo Bagnarab9eb35c2010-10-15 07:51:18 +00002335 return E;
John McCall2fc46bf2010-05-05 22:59:52 +00002336 }
2337}
2338
Hans Wennborg2f072b42011-06-09 17:06:51 +00002339Expr *Expr::IgnoreConversionOperator() {
2340 if (CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(this)) {
Chandler Carruth14d251c2011-06-21 17:22:09 +00002341 if (MCE->getMethodDecl() && isa<CXXConversionDecl>(MCE->getMethodDecl()))
Hans Wennborg2f072b42011-06-09 17:06:51 +00002342 return MCE->getImplicitObjectArgument();
2343 }
2344 return this;
2345}
2346
Chris Lattnerecdd8412009-03-13 17:28:01 +00002347/// IgnoreParenNoopCasts - Ignore parentheses and casts that do not change the
2348/// value (including ptr->int casts of the same size). Strip off any
2349/// ParenExpr or CastExprs, returning their operand.
2350Expr *Expr::IgnoreParenNoopCasts(ASTContext &Ctx) {
2351 Expr *E = this;
2352 while (true) {
2353 if (ParenExpr *P = dyn_cast<ParenExpr>(E)) {
2354 E = P->getSubExpr();
2355 continue;
2356 }
Mike Stump1eb44332009-09-09 15:08:12 +00002357
Chris Lattnerecdd8412009-03-13 17:28:01 +00002358 if (CastExpr *P = dyn_cast<CastExpr>(E)) {
2359 // We ignore integer <-> casts that are of the same width, ptr<->ptr and
Douglas Gregor2ade35e2010-06-16 00:17:44 +00002360 // ptr<->int casts of the same width. We also ignore all identity casts.
Chris Lattnerecdd8412009-03-13 17:28:01 +00002361 Expr *SE = P->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00002362
Chris Lattnerecdd8412009-03-13 17:28:01 +00002363 if (Ctx.hasSameUnqualifiedType(E->getType(), SE->getType())) {
2364 E = SE;
2365 continue;
2366 }
Mike Stump1eb44332009-09-09 15:08:12 +00002367
Abramo Bagnarab9eb35c2010-10-15 07:51:18 +00002368 if ((E->getType()->isPointerType() ||
Douglas Gregor9d3347a2010-06-16 00:35:25 +00002369 E->getType()->isIntegralType(Ctx)) &&
Abramo Bagnarab9eb35c2010-10-15 07:51:18 +00002370 (SE->getType()->isPointerType() ||
Douglas Gregor9d3347a2010-06-16 00:35:25 +00002371 SE->getType()->isIntegralType(Ctx)) &&
Chris Lattnerecdd8412009-03-13 17:28:01 +00002372 Ctx.getTypeSize(E->getType()) == Ctx.getTypeSize(SE->getType())) {
2373 E = SE;
2374 continue;
2375 }
2376 }
Mike Stump1eb44332009-09-09 15:08:12 +00002377
Abramo Bagnarab9eb35c2010-10-15 07:51:18 +00002378 if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) {
2379 if (P->getOpcode() == UO_Extension) {
2380 E = P->getSubExpr();
2381 continue;
2382 }
2383 }
2384
Peter Collingbournef111d932011-04-15 00:35:48 +00002385 if (GenericSelectionExpr* P = dyn_cast<GenericSelectionExpr>(E)) {
2386 if (!P->isResultDependent()) {
2387 E = P->getResultExpr();
2388 continue;
2389 }
2390 }
2391
Douglas Gregorc0244c52011-09-08 17:56:33 +00002392 if (SubstNonTypeTemplateParmExpr *NTTP
2393 = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2394 E = NTTP->getReplacement();
2395 continue;
2396 }
2397
Chris Lattnerecdd8412009-03-13 17:28:01 +00002398 return E;
2399 }
2400}
2401
Douglas Gregor6eef5192009-12-14 19:27:10 +00002402bool Expr::isDefaultArgument() const {
2403 const Expr *E = this;
Douglas Gregor03e80032011-06-21 17:03:29 +00002404 if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
2405 E = M->GetTemporaryExpr();
2406
Douglas Gregor6eef5192009-12-14 19:27:10 +00002407 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
2408 E = ICE->getSubExprAsWritten();
Sean Huntc3021132010-05-05 15:23:54 +00002409
Douglas Gregor6eef5192009-12-14 19:27:10 +00002410 return isa<CXXDefaultArgExpr>(E);
2411}
Chris Lattnerecdd8412009-03-13 17:28:01 +00002412
Douglas Gregor2f599792010-04-02 18:24:57 +00002413/// \brief Skip over any no-op casts and any temporary-binding
2414/// expressions.
Anders Carlssonf8b30152010-11-28 16:40:49 +00002415static const Expr *skipTemporaryBindingsNoOpCastsAndParens(const Expr *E) {
Douglas Gregor03e80032011-06-21 17:03:29 +00002416 if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
2417 E = M->GetTemporaryExpr();
2418
Douglas Gregor2f599792010-04-02 18:24:57 +00002419 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall2de56d12010-08-25 11:45:40 +00002420 if (ICE->getCastKind() == CK_NoOp)
Douglas Gregor2f599792010-04-02 18:24:57 +00002421 E = ICE->getSubExpr();
2422 else
2423 break;
2424 }
2425
2426 while (const CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
2427 E = BE->getSubExpr();
2428
2429 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall2de56d12010-08-25 11:45:40 +00002430 if (ICE->getCastKind() == CK_NoOp)
Douglas Gregor2f599792010-04-02 18:24:57 +00002431 E = ICE->getSubExpr();
2432 else
2433 break;
2434 }
Anders Carlssonf8b30152010-11-28 16:40:49 +00002435
2436 return E->IgnoreParens();
Douglas Gregor2f599792010-04-02 18:24:57 +00002437}
2438
John McCall558d2ab2010-09-15 10:14:12 +00002439/// isTemporaryObject - Determines if this expression produces a
2440/// temporary of the given class type.
2441bool Expr::isTemporaryObject(ASTContext &C, const CXXRecordDecl *TempTy) const {
2442 if (!C.hasSameUnqualifiedType(getType(), C.getTypeDeclType(TempTy)))
2443 return false;
2444
Anders Carlssonf8b30152010-11-28 16:40:49 +00002445 const Expr *E = skipTemporaryBindingsNoOpCastsAndParens(this);
Douglas Gregor2f599792010-04-02 18:24:57 +00002446
John McCall58277b52010-09-15 20:59:13 +00002447 // Temporaries are by definition pr-values of class type.
Fariborz Jahaniandb148be2010-09-27 17:30:38 +00002448 if (!E->Classify(C).isPRValue()) {
2449 // In this context, property reference is a message call and is pr-value.
John McCall12f78a62010-12-02 01:19:52 +00002450 if (!isa<ObjCPropertyRefExpr>(E))
Fariborz Jahaniandb148be2010-09-27 17:30:38 +00002451 return false;
2452 }
Douglas Gregor2f599792010-04-02 18:24:57 +00002453
John McCall19e60ad2010-09-16 06:57:56 +00002454 // Black-list a few cases which yield pr-values of class type that don't
2455 // refer to temporaries of that type:
2456
2457 // - implicit derived-to-base conversions
John McCall558d2ab2010-09-15 10:14:12 +00002458 if (isa<ImplicitCastExpr>(E)) {
2459 switch (cast<ImplicitCastExpr>(E)->getCastKind()) {
2460 case CK_DerivedToBase:
2461 case CK_UncheckedDerivedToBase:
2462 return false;
2463 default:
2464 break;
2465 }
Douglas Gregor2f599792010-04-02 18:24:57 +00002466 }
2467
John McCall19e60ad2010-09-16 06:57:56 +00002468 // - member expressions (all)
2469 if (isa<MemberExpr>(E))
2470 return false;
2471
John McCall56ca35d2011-02-17 10:25:35 +00002472 // - opaque values (all)
2473 if (isa<OpaqueValueExpr>(E))
2474 return false;
2475
John McCall558d2ab2010-09-15 10:14:12 +00002476 return true;
Douglas Gregor2f599792010-04-02 18:24:57 +00002477}
2478
Douglas Gregor75e85042011-03-02 21:06:53 +00002479bool Expr::isImplicitCXXThis() const {
2480 const Expr *E = this;
2481
2482 // Strip away parentheses and casts we don't care about.
2483 while (true) {
2484 if (const ParenExpr *Paren = dyn_cast<ParenExpr>(E)) {
2485 E = Paren->getSubExpr();
2486 continue;
2487 }
2488
2489 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2490 if (ICE->getCastKind() == CK_NoOp ||
2491 ICE->getCastKind() == CK_LValueToRValue ||
2492 ICE->getCastKind() == CK_DerivedToBase ||
2493 ICE->getCastKind() == CK_UncheckedDerivedToBase) {
2494 E = ICE->getSubExpr();
2495 continue;
2496 }
2497 }
2498
2499 if (const UnaryOperator* UnOp = dyn_cast<UnaryOperator>(E)) {
2500 if (UnOp->getOpcode() == UO_Extension) {
2501 E = UnOp->getSubExpr();
2502 continue;
2503 }
2504 }
2505
Douglas Gregor03e80032011-06-21 17:03:29 +00002506 if (const MaterializeTemporaryExpr *M
2507 = dyn_cast<MaterializeTemporaryExpr>(E)) {
2508 E = M->GetTemporaryExpr();
2509 continue;
2510 }
2511
Douglas Gregor75e85042011-03-02 21:06:53 +00002512 break;
2513 }
2514
2515 if (const CXXThisExpr *This = dyn_cast<CXXThisExpr>(E))
2516 return This->isImplicit();
2517
2518 return false;
2519}
2520
Douglas Gregor898574e2008-12-05 23:32:09 +00002521/// hasAnyTypeDependentArguments - Determines if any of the expressions
2522/// in Exprs is type-dependent.
2523bool Expr::hasAnyTypeDependentArguments(Expr** Exprs, unsigned NumExprs) {
2524 for (unsigned I = 0; I < NumExprs; ++I)
2525 if (Exprs[I]->isTypeDependent())
2526 return true;
2527
2528 return false;
2529}
2530
2531/// hasAnyValueDependentArguments - Determines if any of the expressions
2532/// in Exprs is value-dependent.
2533bool Expr::hasAnyValueDependentArguments(Expr** Exprs, unsigned NumExprs) {
2534 for (unsigned I = 0; I < NumExprs; ++I)
2535 if (Exprs[I]->isValueDependent())
2536 return true;
2537
2538 return false;
2539}
2540
John McCall4204f072010-08-02 21:13:48 +00002541bool Expr::isConstantInitializer(ASTContext &Ctx, bool IsForRef) const {
Eli Friedmanc39dc9a2009-01-25 03:12:18 +00002542 // This function is attempting whether an expression is an initializer
2543 // which can be evaluated at compile-time. isEvaluatable handles most
2544 // of the cases, but it can't deal with some initializer-specific
2545 // expressions, and it can't deal with aggregates; we deal with those here,
2546 // and fall back to isEvaluatable for the other cases.
2547
John McCall4204f072010-08-02 21:13:48 +00002548 // If we ever capture reference-binding directly in the AST, we can
2549 // kill the second parameter.
2550
2551 if (IsForRef) {
2552 EvalResult Result;
2553 return EvaluateAsLValue(Result, Ctx) && !Result.HasSideEffects;
2554 }
Eli Friedman1f4a6db2009-02-20 02:36:22 +00002555
Anders Carlssone8a32b82008-11-24 05:23:59 +00002556 switch (getStmtClass()) {
Eli Friedmanc39dc9a2009-01-25 03:12:18 +00002557 default: break;
Richard Smith4ec40892011-12-09 06:47:34 +00002558 case IntegerLiteralClass:
2559 case FloatingLiteralClass:
Anders Carlssone8a32b82008-11-24 05:23:59 +00002560 case StringLiteralClass:
Steve Naroff14108da2009-07-10 23:34:53 +00002561 case ObjCStringLiteralClass:
Chris Lattnereaf2bb82009-02-24 22:18:39 +00002562 case ObjCEncodeExprClass:
Anders Carlssone8a32b82008-11-24 05:23:59 +00002563 return true;
John McCallb4b9b152010-08-01 21:51:45 +00002564 case CXXTemporaryObjectExprClass:
2565 case CXXConstructExprClass: {
2566 const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
John McCall4204f072010-08-02 21:13:48 +00002567
2568 // Only if it's
Richard Smith180f4792011-11-10 06:34:14 +00002569 if (CE->getConstructor()->isTrivial()) {
2570 // 1) an application of the trivial default constructor or
2571 if (!CE->getNumArgs()) return true;
John McCall4204f072010-08-02 21:13:48 +00002572
Richard Smith180f4792011-11-10 06:34:14 +00002573 // 2) an elidable trivial copy construction of an operand which is
2574 // itself a constant initializer. Note that we consider the
2575 // operand on its own, *not* as a reference binding.
2576 if (CE->isElidable() &&
2577 CE->getArg(0)->isConstantInitializer(Ctx, false))
2578 return true;
2579 }
2580
2581 // 3) a foldable constexpr constructor.
2582 break;
John McCallb4b9b152010-08-01 21:51:45 +00002583 }
Nate Begeman59b5da62009-01-18 03:20:47 +00002584 case CompoundLiteralExprClass: {
Eli Friedman1f4a6db2009-02-20 02:36:22 +00002585 // This handles gcc's extension that allows global initializers like
2586 // "struct x {int x;} x = (struct x) {};".
2587 // FIXME: This accepts other cases it shouldn't!
Nate Begeman59b5da62009-01-18 03:20:47 +00002588 const Expr *Exp = cast<CompoundLiteralExpr>(this)->getInitializer();
John McCall4204f072010-08-02 21:13:48 +00002589 return Exp->isConstantInitializer(Ctx, false);
Nate Begeman59b5da62009-01-18 03:20:47 +00002590 }
Anders Carlssone8a32b82008-11-24 05:23:59 +00002591 case InitListExprClass: {
Eli Friedman1f4a6db2009-02-20 02:36:22 +00002592 // FIXME: This doesn't deal with fields with reference types correctly.
2593 // FIXME: This incorrectly allows pointers cast to integers to be assigned
2594 // to bitfields.
Anders Carlssone8a32b82008-11-24 05:23:59 +00002595 const InitListExpr *Exp = cast<InitListExpr>(this);
2596 unsigned numInits = Exp->getNumInits();
2597 for (unsigned i = 0; i < numInits; i++) {
John McCall4204f072010-08-02 21:13:48 +00002598 if (!Exp->getInit(i)->isConstantInitializer(Ctx, false))
Anders Carlssone8a32b82008-11-24 05:23:59 +00002599 return false;
2600 }
Eli Friedmanc39dc9a2009-01-25 03:12:18 +00002601 return true;
Anders Carlssone8a32b82008-11-24 05:23:59 +00002602 }
Douglas Gregor3498bdb2009-01-29 17:44:32 +00002603 case ImplicitValueInitExprClass:
2604 return true;
Chris Lattner3ae9f482009-10-13 07:14:16 +00002605 case ParenExprClass:
John McCall4204f072010-08-02 21:13:48 +00002606 return cast<ParenExpr>(this)->getSubExpr()
2607 ->isConstantInitializer(Ctx, IsForRef);
Peter Collingbournef111d932011-04-15 00:35:48 +00002608 case GenericSelectionExprClass:
2609 if (cast<GenericSelectionExpr>(this)->isResultDependent())
2610 return false;
2611 return cast<GenericSelectionExpr>(this)->getResultExpr()
2612 ->isConstantInitializer(Ctx, IsForRef);
Abramo Bagnara5cadfab2010-09-27 07:13:32 +00002613 case ChooseExprClass:
2614 return cast<ChooseExpr>(this)->getChosenSubExpr(Ctx)
2615 ->isConstantInitializer(Ctx, IsForRef);
Eli Friedmanc39dc9a2009-01-25 03:12:18 +00002616 case UnaryOperatorClass: {
2617 const UnaryOperator* Exp = cast<UnaryOperator>(this);
John McCall2de56d12010-08-25 11:45:40 +00002618 if (Exp->getOpcode() == UO_Extension)
John McCall4204f072010-08-02 21:13:48 +00002619 return Exp->getSubExpr()->isConstantInitializer(Ctx, false);
Eli Friedmanc39dc9a2009-01-25 03:12:18 +00002620 break;
2621 }
John McCall4204f072010-08-02 21:13:48 +00002622 case CXXFunctionalCastExprClass:
John McCallb4b9b152010-08-01 21:51:45 +00002623 case CXXStaticCastExprClass:
Chris Lattner81045d82009-04-21 05:19:11 +00002624 case ImplicitCastExprClass:
Richard Smithd62ca372011-12-06 22:44:34 +00002625 case CStyleCastExprClass: {
2626 const CastExpr *CE = cast<CastExpr>(this);
2627
David Chisnall7a7ee302012-01-16 17:27:18 +00002628 // If we're promoting an integer to an _Atomic type then this is constant
2629 // if the integer is constant. We also need to check the converse in case
2630 // someone does something like:
2631 //
2632 // int a = (_Atomic(int))42;
2633 //
2634 // I doubt anyone would write code like this directly, but it's quite
2635 // possible as the result of macro expansions.
2636 if (CE->getCastKind() == CK_NonAtomicToAtomic ||
2637 CE->getCastKind() == CK_AtomicToNonAtomic)
2638 return CE->getSubExpr()->isConstantInitializer(Ctx, false);
2639
Richard Smithd62ca372011-12-06 22:44:34 +00002640 // Handle bitcasts of vector constants.
2641 if (getType()->isVectorType() && CE->getCastKind() == CK_BitCast)
2642 return CE->getSubExpr()->isConstantInitializer(Ctx, false);
2643
Eli Friedman6bd97192011-12-21 00:43:02 +00002644 // Handle misc casts we want to ignore.
2645 // FIXME: Is it really safe to ignore all these?
2646 if (CE->getCastKind() == CK_NoOp ||
2647 CE->getCastKind() == CK_LValueToRValue ||
2648 CE->getCastKind() == CK_ToUnion ||
2649 CE->getCastKind() == CK_ConstructorConversion)
Richard Smithd62ca372011-12-06 22:44:34 +00002650 return CE->getSubExpr()->isConstantInitializer(Ctx, false);
2651
Eli Friedmanc39dc9a2009-01-25 03:12:18 +00002652 break;
Richard Smithd62ca372011-12-06 22:44:34 +00002653 }
Douglas Gregor03e80032011-06-21 17:03:29 +00002654 case MaterializeTemporaryExprClass:
Chris Lattner5f9e2722011-07-23 10:55:15 +00002655 return cast<MaterializeTemporaryExpr>(this)->GetTemporaryExpr()
Douglas Gregor03e80032011-06-21 17:03:29 +00002656 ->isConstantInitializer(Ctx, false);
Anders Carlssone8a32b82008-11-24 05:23:59 +00002657 }
Eli Friedmanc39dc9a2009-01-25 03:12:18 +00002658 return isEvaluatable(Ctx);
Steve Naroff38374b02007-09-02 20:30:18 +00002659}
2660
Chandler Carruth82214a82011-02-18 23:54:50 +00002661/// isNullPointerConstant - C99 6.3.2.3p3 - Return whether this is a null
2662/// pointer constant or not, as well as the specific kind of constant detected.
2663/// Null pointer constants can be integer constant expressions with the
2664/// value zero, casts of zero to void*, nullptr (C++0X), or __null
2665/// (a GNU extension).
2666Expr::NullPointerConstantKind
2667Expr::isNullPointerConstant(ASTContext &Ctx,
2668 NullPointerConstantValueDependence NPC) const {
Douglas Gregorce940492009-09-25 04:25:58 +00002669 if (isValueDependent()) {
2670 switch (NPC) {
2671 case NPC_NeverValueDependent:
David Blaikieb219cfc2011-09-23 05:06:16 +00002672 llvm_unreachable("Unexpected value dependent expression!");
Douglas Gregorce940492009-09-25 04:25:58 +00002673 case NPC_ValueDependentIsNull:
Chandler Carruth82214a82011-02-18 23:54:50 +00002674 if (isTypeDependent() || getType()->isIntegralType(Ctx))
2675 return NPCK_ZeroInteger;
2676 else
2677 return NPCK_NotNull;
Sean Huntc3021132010-05-05 15:23:54 +00002678
Douglas Gregorce940492009-09-25 04:25:58 +00002679 case NPC_ValueDependentIsNotNull:
Chandler Carruth82214a82011-02-18 23:54:50 +00002680 return NPCK_NotNull;
Douglas Gregorce940492009-09-25 04:25:58 +00002681 }
2682 }
Daniel Dunbarf515b222009-09-18 08:46:16 +00002683
Sebastian Redl07779722008-10-31 14:43:28 +00002684 // Strip off a cast to void*, if it exists. Except in C++.
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002685 if (const ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(this)) {
Sebastian Redl6215dee2008-11-04 11:45:54 +00002686 if (!Ctx.getLangOptions().CPlusPlus) {
Sebastian Redl07779722008-10-31 14:43:28 +00002687 // Check that it is a cast to void*.
Ted Kremenek6217b802009-07-29 21:53:49 +00002688 if (const PointerType *PT = CE->getType()->getAs<PointerType>()) {
Sebastian Redl07779722008-10-31 14:43:28 +00002689 QualType Pointee = PT->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00002690 if (!Pointee.hasQualifiers() &&
Sebastian Redl07779722008-10-31 14:43:28 +00002691 Pointee->isVoidType() && // to void*
2692 CE->getSubExpr()->getType()->isIntegerType()) // from int.
Douglas Gregorce940492009-09-25 04:25:58 +00002693 return CE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
Sebastian Redl07779722008-10-31 14:43:28 +00002694 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002695 }
Steve Naroffaa58f002008-01-14 16:10:57 +00002696 } else if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(this)) {
2697 // Ignore the ImplicitCastExpr type entirely.
Douglas Gregorce940492009-09-25 04:25:58 +00002698 return ICE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
Steve Naroffaa58f002008-01-14 16:10:57 +00002699 } else if (const ParenExpr *PE = dyn_cast<ParenExpr>(this)) {
2700 // Accept ((void*)0) as a null pointer constant, as many other
2701 // implementations do.
Douglas Gregorce940492009-09-25 04:25:58 +00002702 return PE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
Peter Collingbournef111d932011-04-15 00:35:48 +00002703 } else if (const GenericSelectionExpr *GE =
2704 dyn_cast<GenericSelectionExpr>(this)) {
2705 return GE->getResultExpr()->isNullPointerConstant(Ctx, NPC);
Mike Stump1eb44332009-09-09 15:08:12 +00002706 } else if (const CXXDefaultArgExpr *DefaultArg
Chris Lattner8123a952008-04-10 02:22:51 +00002707 = dyn_cast<CXXDefaultArgExpr>(this)) {
Chris Lattner04421082008-04-08 04:40:51 +00002708 // See through default argument expressions
Douglas Gregorce940492009-09-25 04:25:58 +00002709 return DefaultArg->getExpr()->isNullPointerConstant(Ctx, NPC);
Douglas Gregor2d8b2732008-11-29 04:51:27 +00002710 } else if (isa<GNUNullExpr>(this)) {
2711 // The GNU __null extension is always a null pointer constant.
Chandler Carruth82214a82011-02-18 23:54:50 +00002712 return NPCK_GNUNull;
Douglas Gregor03e80032011-06-21 17:03:29 +00002713 } else if (const MaterializeTemporaryExpr *M
2714 = dyn_cast<MaterializeTemporaryExpr>(this)) {
2715 return M->GetTemporaryExpr()->isNullPointerConstant(Ctx, NPC);
John McCall4b9c2d22011-11-06 09:01:30 +00002716 } else if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(this)) {
2717 if (const Expr *Source = OVE->getSourceExpr())
2718 return Source->isNullPointerConstant(Ctx, NPC);
Steve Naroffaaffbf72008-01-14 02:53:34 +00002719 }
Douglas Gregor2d8b2732008-11-29 04:51:27 +00002720
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002721 // C++0x nullptr_t is always a null pointer constant.
2722 if (getType()->isNullPtrType())
Chandler Carruth82214a82011-02-18 23:54:50 +00002723 return NPCK_CXX0X_nullptr;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002724
Fariborz Jahanianff3a0782010-09-27 22:42:37 +00002725 if (const RecordType *UT = getType()->getAsUnionType())
2726 if (UT && UT->getDecl()->hasAttr<TransparentUnionAttr>())
2727 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(this)){
2728 const Expr *InitExpr = CLE->getInitializer();
2729 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(InitExpr))
2730 return ILE->getInit(0)->isNullPointerConstant(Ctx, NPC);
2731 }
Steve Naroffaa58f002008-01-14 16:10:57 +00002732 // This expression must be an integer type.
Sean Huntc3021132010-05-05 15:23:54 +00002733 if (!getType()->isIntegerType() ||
Fariborz Jahanian56fc0d12009-10-06 00:09:31 +00002734 (Ctx.getLangOptions().CPlusPlus && getType()->isEnumeralType()))
Chandler Carruth82214a82011-02-18 23:54:50 +00002735 return NPCK_NotNull;
Mike Stump1eb44332009-09-09 15:08:12 +00002736
Reid Spencer5f016e22007-07-11 17:01:13 +00002737 // If we have an integer constant expression, we need to *evaluate* it and
Richard Smith70488e22012-02-14 21:38:30 +00002738 // test for the value 0. Don't use the C++11 constant expression semantics
2739 // for this, for now; once the dust settles on core issue 903, we might only
2740 // allow a literal 0 here in C++11 mode.
2741 if (Ctx.getLangOptions().CPlusPlus0x) {
2742 if (!isCXX98IntegralConstantExpr(Ctx))
2743 return NPCK_NotNull;
2744 } else {
2745 if (!isIntegerConstantExpr(Ctx))
2746 return NPCK_NotNull;
2747 }
Chandler Carruth82214a82011-02-18 23:54:50 +00002748
Richard Smith70488e22012-02-14 21:38:30 +00002749 return (EvaluateKnownConstInt(Ctx) == 0) ? NPCK_ZeroInteger : NPCK_NotNull;
Reid Spencer5f016e22007-07-11 17:01:13 +00002750}
Steve Naroff31a45842007-07-28 23:10:27 +00002751
John McCallf6a16482010-12-04 03:47:34 +00002752/// \brief If this expression is an l-value for an Objective C
2753/// property, find the underlying property reference expression.
2754const ObjCPropertyRefExpr *Expr::getObjCProperty() const {
2755 const Expr *E = this;
2756 while (true) {
2757 assert((E->getValueKind() == VK_LValue &&
2758 E->getObjectKind() == OK_ObjCProperty) &&
2759 "expression is not a property reference");
2760 E = E->IgnoreParenCasts();
2761 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2762 if (BO->getOpcode() == BO_Comma) {
2763 E = BO->getRHS();
2764 continue;
2765 }
2766 }
2767
2768 break;
2769 }
2770
2771 return cast<ObjCPropertyRefExpr>(E);
2772}
2773
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002774FieldDecl *Expr::getBitField() {
Douglas Gregor6f4a69a2009-07-06 15:38:40 +00002775 Expr *E = this->IgnoreParens();
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002776
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002777 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCallf6a16482010-12-04 03:47:34 +00002778 if (ICE->getCastKind() == CK_LValueToRValue ||
2779 (ICE->getValueKind() != VK_RValue && ICE->getCastKind() == CK_NoOp))
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002780 E = ICE->getSubExpr()->IgnoreParens();
2781 else
2782 break;
2783 }
2784
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002785 if (MemberExpr *MemRef = dyn_cast<MemberExpr>(E))
Douglas Gregor86f19402008-12-20 23:49:58 +00002786 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemRef->getMemberDecl()))
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002787 if (Field->isBitField())
2788 return Field;
2789
Argyrios Kyrtzidis0f279e72010-10-30 19:52:22 +00002790 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E))
2791 if (FieldDecl *Field = dyn_cast<FieldDecl>(DeclRef->getDecl()))
2792 if (Field->isBitField())
2793 return Field;
2794
Eli Friedman42068e92011-07-13 02:05:57 +00002795 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(E)) {
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002796 if (BinOp->isAssignmentOp() && BinOp->getLHS())
2797 return BinOp->getLHS()->getBitField();
2798
Eli Friedman42068e92011-07-13 02:05:57 +00002799 if (BinOp->getOpcode() == BO_Comma && BinOp->getRHS())
2800 return BinOp->getRHS()->getBitField();
2801 }
2802
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002803 return 0;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002804}
2805
Anders Carlsson09380262010-01-31 17:18:49 +00002806bool Expr::refersToVectorElement() const {
2807 const Expr *E = this->IgnoreParens();
Sean Huntc3021132010-05-05 15:23:54 +00002808
Anders Carlsson09380262010-01-31 17:18:49 +00002809 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall5baba9d2010-08-25 10:28:54 +00002810 if (ICE->getValueKind() != VK_RValue &&
John McCall2de56d12010-08-25 11:45:40 +00002811 ICE->getCastKind() == CK_NoOp)
Anders Carlsson09380262010-01-31 17:18:49 +00002812 E = ICE->getSubExpr()->IgnoreParens();
2813 else
2814 break;
2815 }
Sean Huntc3021132010-05-05 15:23:54 +00002816
Anders Carlsson09380262010-01-31 17:18:49 +00002817 if (const ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(E))
2818 return ASE->getBase()->getType()->isVectorType();
2819
2820 if (isa<ExtVectorElementExpr>(E))
2821 return true;
2822
2823 return false;
2824}
2825
Chris Lattner2140e902009-02-16 22:14:05 +00002826/// isArrow - Return true if the base expression is a pointer to vector,
2827/// return false if the base expression is a vector.
2828bool ExtVectorElementExpr::isArrow() const {
2829 return getBase()->getType()->isPointerType();
2830}
2831
Nate Begeman213541a2008-04-18 23:10:10 +00002832unsigned ExtVectorElementExpr::getNumElements() const {
John McCall183700f2009-09-21 23:43:11 +00002833 if (const VectorType *VT = getType()->getAs<VectorType>())
Nate Begeman8a997642008-05-09 06:41:27 +00002834 return VT->getNumElements();
2835 return 1;
Chris Lattner4d0ac882007-08-03 16:00:20 +00002836}
2837
Nate Begeman8a997642008-05-09 06:41:27 +00002838/// containsDuplicateElements - Return true if any element access is repeated.
Nate Begeman213541a2008-04-18 23:10:10 +00002839bool ExtVectorElementExpr::containsDuplicateElements() const {
Daniel Dunbara2b34eb2009-10-18 02:09:09 +00002840 // FIXME: Refactor this code to an accessor on the AST node which returns the
2841 // "type" of component access, and share with code below and in Sema.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002842 StringRef Comp = Accessor->getName();
Nate Begeman190d6a22009-01-18 02:01:21 +00002843
2844 // Halving swizzles do not contain duplicate elements.
Daniel Dunbar15027422009-10-17 23:53:04 +00002845 if (Comp == "hi" || Comp == "lo" || Comp == "even" || Comp == "odd")
Nate Begeman190d6a22009-01-18 02:01:21 +00002846 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002847
Nate Begeman190d6a22009-01-18 02:01:21 +00002848 // Advance past s-char prefix on hex swizzles.
Daniel Dunbar15027422009-10-17 23:53:04 +00002849 if (Comp[0] == 's' || Comp[0] == 'S')
2850 Comp = Comp.substr(1);
Mike Stump1eb44332009-09-09 15:08:12 +00002851
Daniel Dunbar15027422009-10-17 23:53:04 +00002852 for (unsigned i = 0, e = Comp.size(); i != e; ++i)
Chris Lattner5f9e2722011-07-23 10:55:15 +00002853 if (Comp.substr(i + 1).find(Comp[i]) != StringRef::npos)
Steve Narofffec0b492007-07-30 03:29:09 +00002854 return true;
Daniel Dunbar15027422009-10-17 23:53:04 +00002855
Steve Narofffec0b492007-07-30 03:29:09 +00002856 return false;
2857}
Chris Lattnerb8f849d2007-08-02 23:36:59 +00002858
Nate Begeman8a997642008-05-09 06:41:27 +00002859/// getEncodedElementAccess - We encode the fields as a llvm ConstantArray.
Nate Begeman3b8d1162008-05-13 21:03:02 +00002860void ExtVectorElementExpr::getEncodedElementAccess(
Chris Lattner5f9e2722011-07-23 10:55:15 +00002861 SmallVectorImpl<unsigned> &Elts) const {
2862 StringRef Comp = Accessor->getName();
Daniel Dunbar4b55b242009-10-18 02:09:31 +00002863 if (Comp[0] == 's' || Comp[0] == 'S')
2864 Comp = Comp.substr(1);
Mike Stump1eb44332009-09-09 15:08:12 +00002865
Daniel Dunbar4b55b242009-10-18 02:09:31 +00002866 bool isHi = Comp == "hi";
2867 bool isLo = Comp == "lo";
2868 bool isEven = Comp == "even";
2869 bool isOdd = Comp == "odd";
Mike Stump1eb44332009-09-09 15:08:12 +00002870
Nate Begeman8a997642008-05-09 06:41:27 +00002871 for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
2872 uint64_t Index;
Mike Stump1eb44332009-09-09 15:08:12 +00002873
Nate Begeman8a997642008-05-09 06:41:27 +00002874 if (isHi)
2875 Index = e + i;
2876 else if (isLo)
2877 Index = i;
2878 else if (isEven)
2879 Index = 2 * i;
2880 else if (isOdd)
2881 Index = 2 * i + 1;
2882 else
Daniel Dunbar4b55b242009-10-18 02:09:31 +00002883 Index = ExtVectorType::getAccessorIdx(Comp[i]);
Chris Lattnerb8f849d2007-08-02 23:36:59 +00002884
Nate Begeman3b8d1162008-05-13 21:03:02 +00002885 Elts.push_back(Index);
Chris Lattnerb8f849d2007-08-02 23:36:59 +00002886 }
Nate Begeman8a997642008-05-09 06:41:27 +00002887}
2888
Douglas Gregor04badcf2010-04-21 00:45:42 +00002889ObjCMessageExpr::ObjCMessageExpr(QualType T,
John McCallf89e55a2010-11-18 06:31:45 +00002890 ExprValueKind VK,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002891 SourceLocation LBracLoc,
2892 SourceLocation SuperLoc,
2893 bool IsInstanceSuper,
2894 QualType SuperType,
Sean Huntc3021132010-05-05 15:23:54 +00002895 Selector Sel,
Argyrios Kyrtzidis20718082011-10-03 06:36:51 +00002896 ArrayRef<SourceLocation> SelLocs,
2897 SelectorLocationsKind SelLocsK,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002898 ObjCMethodDecl *Method,
Argyrios Kyrtzidis8d9ed792011-10-03 06:36:45 +00002899 ArrayRef<Expr *> Args,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00002900 SourceLocation RBracLoc,
2901 bool isImplicit)
John McCallf89e55a2010-11-18 06:31:45 +00002902 : Expr(ObjCMessageExprClass, T, VK, OK_Ordinary,
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00002903 /*TypeDependent=*/false, /*ValueDependent=*/false,
Douglas Gregor561f8122011-07-01 01:22:09 +00002904 /*InstantiationDependent=*/false,
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00002905 /*ContainsUnexpandedParameterPack=*/false),
Douglas Gregor04badcf2010-04-21 00:45:42 +00002906 SelectorOrMethod(reinterpret_cast<uintptr_t>(Method? Method
2907 : Sel.getAsOpaquePtr())),
Argyrios Kyrtzidisb994e6c2011-10-03 06:36:55 +00002908 Kind(IsInstanceSuper? SuperInstance : SuperClass),
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00002909 HasMethod(Method != 0), IsDelegateInitCall(false), IsImplicit(isImplicit),
2910 SuperLoc(SuperLoc), LBracLoc(LBracLoc), RBracLoc(RBracLoc)
Douglas Gregorc2350e52010-03-08 16:40:19 +00002911{
Argyrios Kyrtzidis20718082011-10-03 06:36:51 +00002912 initArgsAndSelLocs(Args, SelLocs, SelLocsK);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002913 setReceiverPointer(SuperType.getAsOpaquePtr());
Ted Kremenek4df728e2008-06-24 15:50:53 +00002914}
2915
Douglas Gregor04badcf2010-04-21 00:45:42 +00002916ObjCMessageExpr::ObjCMessageExpr(QualType T,
John McCallf89e55a2010-11-18 06:31:45 +00002917 ExprValueKind VK,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002918 SourceLocation LBracLoc,
2919 TypeSourceInfo *Receiver,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00002920 Selector Sel,
Argyrios Kyrtzidis20718082011-10-03 06:36:51 +00002921 ArrayRef<SourceLocation> SelLocs,
2922 SelectorLocationsKind SelLocsK,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002923 ObjCMethodDecl *Method,
Argyrios Kyrtzidis8d9ed792011-10-03 06:36:45 +00002924 ArrayRef<Expr *> Args,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00002925 SourceLocation RBracLoc,
2926 bool isImplicit)
John McCallf89e55a2010-11-18 06:31:45 +00002927 : Expr(ObjCMessageExprClass, T, VK, OK_Ordinary, T->isDependentType(),
Douglas Gregor561f8122011-07-01 01:22:09 +00002928 T->isDependentType(), T->isInstantiationDependentType(),
2929 T->containsUnexpandedParameterPack()),
Douglas Gregor04badcf2010-04-21 00:45:42 +00002930 SelectorOrMethod(reinterpret_cast<uintptr_t>(Method? Method
2931 : Sel.getAsOpaquePtr())),
Argyrios Kyrtzidisb994e6c2011-10-03 06:36:55 +00002932 Kind(Class),
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00002933 HasMethod(Method != 0), IsDelegateInitCall(false), IsImplicit(isImplicit),
Argyrios Kyrtzidis20718082011-10-03 06:36:51 +00002934 LBracLoc(LBracLoc), RBracLoc(RBracLoc)
Douglas Gregor04badcf2010-04-21 00:45:42 +00002935{
Argyrios Kyrtzidis20718082011-10-03 06:36:51 +00002936 initArgsAndSelLocs(Args, SelLocs, SelLocsK);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002937 setReceiverPointer(Receiver);
Ted Kremenek4df728e2008-06-24 15:50:53 +00002938}
2939
Douglas Gregor04badcf2010-04-21 00:45:42 +00002940ObjCMessageExpr::ObjCMessageExpr(QualType T,
John McCallf89e55a2010-11-18 06:31:45 +00002941 ExprValueKind VK,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002942 SourceLocation LBracLoc,
2943 Expr *Receiver,
Sean Huntc3021132010-05-05 15:23:54 +00002944 Selector Sel,
Argyrios Kyrtzidis20718082011-10-03 06:36:51 +00002945 ArrayRef<SourceLocation> SelLocs,
2946 SelectorLocationsKind SelLocsK,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002947 ObjCMethodDecl *Method,
Argyrios Kyrtzidis8d9ed792011-10-03 06:36:45 +00002948 ArrayRef<Expr *> Args,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00002949 SourceLocation RBracLoc,
2950 bool isImplicit)
John McCallf89e55a2010-11-18 06:31:45 +00002951 : Expr(ObjCMessageExprClass, T, VK, OK_Ordinary, Receiver->isTypeDependent(),
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00002952 Receiver->isTypeDependent(),
Douglas Gregor561f8122011-07-01 01:22:09 +00002953 Receiver->isInstantiationDependent(),
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00002954 Receiver->containsUnexpandedParameterPack()),
Douglas Gregor04badcf2010-04-21 00:45:42 +00002955 SelectorOrMethod(reinterpret_cast<uintptr_t>(Method? Method
2956 : Sel.getAsOpaquePtr())),
Argyrios Kyrtzidisb994e6c2011-10-03 06:36:55 +00002957 Kind(Instance),
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00002958 HasMethod(Method != 0), IsDelegateInitCall(false), IsImplicit(isImplicit),
Argyrios Kyrtzidis20718082011-10-03 06:36:51 +00002959 LBracLoc(LBracLoc), RBracLoc(RBracLoc)
Douglas Gregor04badcf2010-04-21 00:45:42 +00002960{
Argyrios Kyrtzidis20718082011-10-03 06:36:51 +00002961 initArgsAndSelLocs(Args, SelLocs, SelLocsK);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002962 setReceiverPointer(Receiver);
Argyrios Kyrtzidis20718082011-10-03 06:36:51 +00002963}
2964
2965void ObjCMessageExpr::initArgsAndSelLocs(ArrayRef<Expr *> Args,
2966 ArrayRef<SourceLocation> SelLocs,
2967 SelectorLocationsKind SelLocsK) {
2968 setNumArgs(Args.size());
Douglas Gregoraa165f82011-01-03 19:04:46 +00002969 Expr **MyArgs = getArgs();
Argyrios Kyrtzidis8d9ed792011-10-03 06:36:45 +00002970 for (unsigned I = 0; I != Args.size(); ++I) {
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00002971 if (Args[I]->isTypeDependent())
2972 ExprBits.TypeDependent = true;
2973 if (Args[I]->isValueDependent())
2974 ExprBits.ValueDependent = true;
Douglas Gregor561f8122011-07-01 01:22:09 +00002975 if (Args[I]->isInstantiationDependent())
2976 ExprBits.InstantiationDependent = true;
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00002977 if (Args[I]->containsUnexpandedParameterPack())
2978 ExprBits.ContainsUnexpandedParameterPack = true;
2979
2980 MyArgs[I] = Args[I];
2981 }
Argyrios Kyrtzidis20718082011-10-03 06:36:51 +00002982
Argyrios Kyrtzidis0c6b8e32012-01-12 22:34:19 +00002983 if (!isImplicit()) {
2984 SelLocsKind = SelLocsK;
2985 if (SelLocsK == SelLoc_NonStandard)
2986 std::copy(SelLocs.begin(), SelLocs.end(), getStoredSelLocs());
2987 }
Chris Lattner0389e6b2009-04-26 00:44:05 +00002988}
2989
Douglas Gregor04badcf2010-04-21 00:45:42 +00002990ObjCMessageExpr *ObjCMessageExpr::Create(ASTContext &Context, QualType T,
John McCallf89e55a2010-11-18 06:31:45 +00002991 ExprValueKind VK,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002992 SourceLocation LBracLoc,
2993 SourceLocation SuperLoc,
2994 bool IsInstanceSuper,
2995 QualType SuperType,
Sean Huntc3021132010-05-05 15:23:54 +00002996 Selector Sel,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002997 ArrayRef<SourceLocation> SelLocs,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002998 ObjCMethodDecl *Method,
Argyrios Kyrtzidis8d9ed792011-10-03 06:36:45 +00002999 ArrayRef<Expr *> Args,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00003000 SourceLocation RBracLoc,
3001 bool isImplicit) {
3002 assert((!SelLocs.empty() || isImplicit) &&
3003 "No selector locs for non-implicit message");
3004 ObjCMessageExpr *Mem;
3005 SelectorLocationsKind SelLocsK = SelectorLocationsKind();
3006 if (isImplicit)
3007 Mem = alloc(Context, Args.size(), 0);
3008 else
3009 Mem = alloc(Context, Args, RBracLoc, SelLocs, Sel, SelLocsK);
John McCallf89e55a2010-11-18 06:31:45 +00003010 return new (Mem) ObjCMessageExpr(T, VK, LBracLoc, SuperLoc, IsInstanceSuper,
Argyrios Kyrtzidis20718082011-10-03 06:36:51 +00003011 SuperType, Sel, SelLocs, SelLocsK,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00003012 Method, Args, RBracLoc, isImplicit);
Douglas Gregor04badcf2010-04-21 00:45:42 +00003013}
3014
3015ObjCMessageExpr *ObjCMessageExpr::Create(ASTContext &Context, QualType T,
John McCallf89e55a2010-11-18 06:31:45 +00003016 ExprValueKind VK,
Douglas Gregor04badcf2010-04-21 00:45:42 +00003017 SourceLocation LBracLoc,
3018 TypeSourceInfo *Receiver,
Sean Huntc3021132010-05-05 15:23:54 +00003019 Selector Sel,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00003020 ArrayRef<SourceLocation> SelLocs,
Douglas Gregor04badcf2010-04-21 00:45:42 +00003021 ObjCMethodDecl *Method,
Argyrios Kyrtzidis8d9ed792011-10-03 06:36:45 +00003022 ArrayRef<Expr *> Args,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00003023 SourceLocation RBracLoc,
3024 bool isImplicit) {
3025 assert((!SelLocs.empty() || isImplicit) &&
3026 "No selector locs for non-implicit message");
3027 ObjCMessageExpr *Mem;
3028 SelectorLocationsKind SelLocsK = SelectorLocationsKind();
3029 if (isImplicit)
3030 Mem = alloc(Context, Args.size(), 0);
3031 else
3032 Mem = alloc(Context, Args, RBracLoc, SelLocs, Sel, SelLocsK);
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00003033 return new (Mem) ObjCMessageExpr(T, VK, LBracLoc, Receiver, Sel,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00003034 SelLocs, SelLocsK, Method, Args, RBracLoc,
3035 isImplicit);
Douglas Gregor04badcf2010-04-21 00:45:42 +00003036}
3037
3038ObjCMessageExpr *ObjCMessageExpr::Create(ASTContext &Context, QualType T,
John McCallf89e55a2010-11-18 06:31:45 +00003039 ExprValueKind VK,
Douglas Gregor04badcf2010-04-21 00:45:42 +00003040 SourceLocation LBracLoc,
3041 Expr *Receiver,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00003042 Selector Sel,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00003043 ArrayRef<SourceLocation> SelLocs,
Douglas Gregor04badcf2010-04-21 00:45:42 +00003044 ObjCMethodDecl *Method,
Argyrios Kyrtzidis8d9ed792011-10-03 06:36:45 +00003045 ArrayRef<Expr *> Args,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00003046 SourceLocation RBracLoc,
3047 bool isImplicit) {
3048 assert((!SelLocs.empty() || isImplicit) &&
3049 "No selector locs for non-implicit message");
3050 ObjCMessageExpr *Mem;
3051 SelectorLocationsKind SelLocsK = SelectorLocationsKind();
3052 if (isImplicit)
3053 Mem = alloc(Context, Args.size(), 0);
3054 else
3055 Mem = alloc(Context, Args, RBracLoc, SelLocs, Sel, SelLocsK);
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00003056 return new (Mem) ObjCMessageExpr(T, VK, LBracLoc, Receiver, Sel,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00003057 SelLocs, SelLocsK, Method, Args, RBracLoc,
3058 isImplicit);
Douglas Gregor04badcf2010-04-21 00:45:42 +00003059}
3060
Sean Huntc3021132010-05-05 15:23:54 +00003061ObjCMessageExpr *ObjCMessageExpr::CreateEmpty(ASTContext &Context,
Argyrios Kyrtzidis20718082011-10-03 06:36:51 +00003062 unsigned NumArgs,
3063 unsigned NumStoredSelLocs) {
3064 ObjCMessageExpr *Mem = alloc(Context, NumArgs, NumStoredSelLocs);
Douglas Gregor04badcf2010-04-21 00:45:42 +00003065 return new (Mem) ObjCMessageExpr(EmptyShell(), NumArgs);
3066}
Argyrios Kyrtzidise005d192010-12-10 20:08:30 +00003067
Argyrios Kyrtzidis20718082011-10-03 06:36:51 +00003068ObjCMessageExpr *ObjCMessageExpr::alloc(ASTContext &C,
3069 ArrayRef<Expr *> Args,
3070 SourceLocation RBraceLoc,
3071 ArrayRef<SourceLocation> SelLocs,
3072 Selector Sel,
3073 SelectorLocationsKind &SelLocsK) {
3074 SelLocsK = hasStandardSelectorLocs(Sel, SelLocs, Args, RBraceLoc);
3075 unsigned NumStoredSelLocs = (SelLocsK == SelLoc_NonStandard) ? SelLocs.size()
3076 : 0;
3077 return alloc(C, Args.size(), NumStoredSelLocs);
3078}
3079
3080ObjCMessageExpr *ObjCMessageExpr::alloc(ASTContext &C,
3081 unsigned NumArgs,
3082 unsigned NumStoredSelLocs) {
3083 unsigned Size = sizeof(ObjCMessageExpr) + sizeof(void *) +
3084 NumArgs * sizeof(Expr *) + NumStoredSelLocs * sizeof(SourceLocation);
3085 return (ObjCMessageExpr *)C.Allocate(Size,
3086 llvm::AlignOf<ObjCMessageExpr>::Alignment);
3087}
3088
3089void ObjCMessageExpr::getSelectorLocs(
3090 SmallVectorImpl<SourceLocation> &SelLocs) const {
3091 for (unsigned i = 0, e = getNumSelectorLocs(); i != e; ++i)
3092 SelLocs.push_back(getSelectorLoc(i));
3093}
3094
Argyrios Kyrtzidise005d192010-12-10 20:08:30 +00003095SourceRange ObjCMessageExpr::getReceiverRange() const {
3096 switch (getReceiverKind()) {
3097 case Instance:
3098 return getInstanceReceiver()->getSourceRange();
3099
3100 case Class:
3101 return getClassReceiverTypeInfo()->getTypeLoc().getSourceRange();
3102
3103 case SuperInstance:
3104 case SuperClass:
3105 return getSuperLoc();
3106 }
3107
David Blaikie30263482012-01-20 21:50:17 +00003108 llvm_unreachable("Invalid ReceiverKind!");
Argyrios Kyrtzidise005d192010-12-10 20:08:30 +00003109}
3110
Douglas Gregor04badcf2010-04-21 00:45:42 +00003111Selector ObjCMessageExpr::getSelector() const {
3112 if (HasMethod)
3113 return reinterpret_cast<const ObjCMethodDecl *>(SelectorOrMethod)
3114 ->getSelector();
Sean Huntc3021132010-05-05 15:23:54 +00003115 return Selector(SelectorOrMethod);
Douglas Gregor04badcf2010-04-21 00:45:42 +00003116}
3117
3118ObjCInterfaceDecl *ObjCMessageExpr::getReceiverInterface() const {
3119 switch (getReceiverKind()) {
3120 case Instance:
3121 if (const ObjCObjectPointerType *Ptr
3122 = getInstanceReceiver()->getType()->getAs<ObjCObjectPointerType>())
3123 return Ptr->getInterfaceDecl();
3124 break;
3125
3126 case Class:
John McCallc12c5bb2010-05-15 11:32:37 +00003127 if (const ObjCObjectType *Ty
3128 = getClassReceiver()->getAs<ObjCObjectType>())
3129 return Ty->getInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00003130 break;
3131
3132 case SuperInstance:
3133 if (const ObjCObjectPointerType *Ptr
3134 = getSuperType()->getAs<ObjCObjectPointerType>())
3135 return Ptr->getInterfaceDecl();
3136 break;
3137
3138 case SuperClass:
Argyrios Kyrtzidisee8a6ca2011-01-25 00:03:48 +00003139 if (const ObjCObjectType *Iface
3140 = getSuperType()->getAs<ObjCObjectType>())
3141 return Iface->getInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00003142 break;
3143 }
3144
3145 return 0;
Ted Kremenekeb3b3242010-02-11 22:41:21 +00003146}
Chris Lattner0389e6b2009-04-26 00:44:05 +00003147
Chris Lattner5f9e2722011-07-23 10:55:15 +00003148StringRef ObjCBridgedCastExpr::getBridgeKindName() const {
John McCallf85e1932011-06-15 23:02:42 +00003149 switch (getBridgeKind()) {
3150 case OBC_Bridge:
3151 return "__bridge";
3152 case OBC_BridgeTransfer:
3153 return "__bridge_transfer";
3154 case OBC_BridgeRetained:
3155 return "__bridge_retained";
3156 }
David Blaikie30263482012-01-20 21:50:17 +00003157
3158 llvm_unreachable("Invalid BridgeKind!");
John McCallf85e1932011-06-15 23:02:42 +00003159}
3160
Jay Foad4ba2a172011-01-12 09:06:06 +00003161bool ChooseExpr::isConditionTrue(const ASTContext &C) const {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003162 return getCond()->EvaluateKnownConstInt(C) != 0;
Chris Lattner27437ca2007-10-25 00:29:32 +00003163}
3164
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00003165ShuffleVectorExpr::ShuffleVectorExpr(ASTContext &C, Expr **args, unsigned nexpr,
3166 QualType Type, SourceLocation BLoc,
3167 SourceLocation RP)
3168 : Expr(ShuffleVectorExprClass, Type, VK_RValue, OK_Ordinary,
3169 Type->isDependentType(), Type->isDependentType(),
Douglas Gregor561f8122011-07-01 01:22:09 +00003170 Type->isInstantiationDependentType(),
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00003171 Type->containsUnexpandedParameterPack()),
3172 BuiltinLoc(BLoc), RParenLoc(RP), NumExprs(nexpr)
3173{
3174 SubExprs = new (C) Stmt*[nexpr];
3175 for (unsigned i = 0; i < nexpr; i++) {
3176 if (args[i]->isTypeDependent())
3177 ExprBits.TypeDependent = true;
3178 if (args[i]->isValueDependent())
3179 ExprBits.ValueDependent = true;
Douglas Gregor561f8122011-07-01 01:22:09 +00003180 if (args[i]->isInstantiationDependent())
3181 ExprBits.InstantiationDependent = true;
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00003182 if (args[i]->containsUnexpandedParameterPack())
3183 ExprBits.ContainsUnexpandedParameterPack = true;
3184
3185 SubExprs[i] = args[i];
3186 }
3187}
3188
Nate Begeman888376a2009-08-12 02:28:50 +00003189void ShuffleVectorExpr::setExprs(ASTContext &C, Expr ** Exprs,
3190 unsigned NumExprs) {
3191 if (SubExprs) C.Deallocate(SubExprs);
3192
3193 SubExprs = new (C) Stmt* [NumExprs];
Douglas Gregor94cd5d12009-04-16 00:01:45 +00003194 this->NumExprs = NumExprs;
3195 memcpy(SubExprs, Exprs, sizeof(Expr *) * NumExprs);
Mike Stump1eb44332009-09-09 15:08:12 +00003196}
Nate Begeman888376a2009-08-12 02:28:50 +00003197
Peter Collingbournef111d932011-04-15 00:35:48 +00003198GenericSelectionExpr::GenericSelectionExpr(ASTContext &Context,
3199 SourceLocation GenericLoc, Expr *ControllingExpr,
3200 TypeSourceInfo **AssocTypes, Expr **AssocExprs,
3201 unsigned NumAssocs, SourceLocation DefaultLoc,
3202 SourceLocation RParenLoc,
3203 bool ContainsUnexpandedParameterPack,
3204 unsigned ResultIndex)
3205 : Expr(GenericSelectionExprClass,
3206 AssocExprs[ResultIndex]->getType(),
3207 AssocExprs[ResultIndex]->getValueKind(),
3208 AssocExprs[ResultIndex]->getObjectKind(),
3209 AssocExprs[ResultIndex]->isTypeDependent(),
3210 AssocExprs[ResultIndex]->isValueDependent(),
Douglas Gregor561f8122011-07-01 01:22:09 +00003211 AssocExprs[ResultIndex]->isInstantiationDependent(),
Peter Collingbournef111d932011-04-15 00:35:48 +00003212 ContainsUnexpandedParameterPack),
3213 AssocTypes(new (Context) TypeSourceInfo*[NumAssocs]),
3214 SubExprs(new (Context) Stmt*[END_EXPR+NumAssocs]), NumAssocs(NumAssocs),
3215 ResultIndex(ResultIndex), GenericLoc(GenericLoc), DefaultLoc(DefaultLoc),
3216 RParenLoc(RParenLoc) {
3217 SubExprs[CONTROLLING] = ControllingExpr;
3218 std::copy(AssocTypes, AssocTypes+NumAssocs, this->AssocTypes);
3219 std::copy(AssocExprs, AssocExprs+NumAssocs, SubExprs+END_EXPR);
3220}
3221
3222GenericSelectionExpr::GenericSelectionExpr(ASTContext &Context,
3223 SourceLocation GenericLoc, Expr *ControllingExpr,
3224 TypeSourceInfo **AssocTypes, Expr **AssocExprs,
3225 unsigned NumAssocs, SourceLocation DefaultLoc,
3226 SourceLocation RParenLoc,
3227 bool ContainsUnexpandedParameterPack)
3228 : Expr(GenericSelectionExprClass,
3229 Context.DependentTy,
3230 VK_RValue,
3231 OK_Ordinary,
Douglas Gregor561f8122011-07-01 01:22:09 +00003232 /*isTypeDependent=*/true,
3233 /*isValueDependent=*/true,
3234 /*isInstantiationDependent=*/true,
Peter Collingbournef111d932011-04-15 00:35:48 +00003235 ContainsUnexpandedParameterPack),
3236 AssocTypes(new (Context) TypeSourceInfo*[NumAssocs]),
3237 SubExprs(new (Context) Stmt*[END_EXPR+NumAssocs]), NumAssocs(NumAssocs),
3238 ResultIndex(-1U), GenericLoc(GenericLoc), DefaultLoc(DefaultLoc),
3239 RParenLoc(RParenLoc) {
3240 SubExprs[CONTROLLING] = ControllingExpr;
3241 std::copy(AssocTypes, AssocTypes+NumAssocs, this->AssocTypes);
3242 std::copy(AssocExprs, AssocExprs+NumAssocs, SubExprs+END_EXPR);
3243}
3244
Ted Kremenek77ed8e42007-08-24 18:13:47 +00003245//===----------------------------------------------------------------------===//
Douglas Gregor05c13a32009-01-22 00:58:24 +00003246// DesignatedInitExpr
3247//===----------------------------------------------------------------------===//
3248
Chandler Carruthb1138242011-06-16 06:47:06 +00003249IdentifierInfo *DesignatedInitExpr::Designator::getFieldName() const {
Douglas Gregor05c13a32009-01-22 00:58:24 +00003250 assert(Kind == FieldDesignator && "Only valid on a field designator");
3251 if (Field.NameOrField & 0x01)
3252 return reinterpret_cast<IdentifierInfo *>(Field.NameOrField&~0x01);
3253 else
3254 return getField()->getIdentifier();
3255}
3256
Sean Huntc3021132010-05-05 15:23:54 +00003257DesignatedInitExpr::DesignatedInitExpr(ASTContext &C, QualType Ty,
Douglas Gregor319d57f2010-01-06 23:17:19 +00003258 unsigned NumDesignators,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00003259 const Designator *Designators,
Mike Stump1eb44332009-09-09 15:08:12 +00003260 SourceLocation EqualOrColonLoc,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00003261 bool GNUSyntax,
Mike Stump1eb44332009-09-09 15:08:12 +00003262 Expr **IndexExprs,
Douglas Gregor9ea62762009-05-21 23:17:49 +00003263 unsigned NumIndexExprs,
3264 Expr *Init)
Mike Stump1eb44332009-09-09 15:08:12 +00003265 : Expr(DesignatedInitExprClass, Ty,
John McCallf89e55a2010-11-18 06:31:45 +00003266 Init->getValueKind(), Init->getObjectKind(),
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00003267 Init->isTypeDependent(), Init->isValueDependent(),
Douglas Gregor561f8122011-07-01 01:22:09 +00003268 Init->isInstantiationDependent(),
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00003269 Init->containsUnexpandedParameterPack()),
Mike Stump1eb44332009-09-09 15:08:12 +00003270 EqualOrColonLoc(EqualOrColonLoc), GNUSyntax(GNUSyntax),
3271 NumDesignators(NumDesignators), NumSubExprs(NumIndexExprs + 1) {
Douglas Gregor319d57f2010-01-06 23:17:19 +00003272 this->Designators = new (C) Designator[NumDesignators];
Douglas Gregor9ea62762009-05-21 23:17:49 +00003273
3274 // Record the initializer itself.
John McCall7502c1d2011-02-13 04:07:26 +00003275 child_range Child = children();
Douglas Gregor9ea62762009-05-21 23:17:49 +00003276 *Child++ = Init;
3277
3278 // Copy the designators and their subexpressions, computing
3279 // value-dependence along the way.
3280 unsigned IndexIdx = 0;
3281 for (unsigned I = 0; I != NumDesignators; ++I) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00003282 this->Designators[I] = Designators[I];
Douglas Gregor9ea62762009-05-21 23:17:49 +00003283
3284 if (this->Designators[I].isArrayDesignator()) {
3285 // Compute type- and value-dependence.
3286 Expr *Index = IndexExprs[IndexIdx];
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00003287 if (Index->isTypeDependent() || Index->isValueDependent())
3288 ExprBits.ValueDependent = true;
Douglas Gregor561f8122011-07-01 01:22:09 +00003289 if (Index->isInstantiationDependent())
3290 ExprBits.InstantiationDependent = true;
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00003291 // Propagate unexpanded parameter packs.
3292 if (Index->containsUnexpandedParameterPack())
3293 ExprBits.ContainsUnexpandedParameterPack = true;
Douglas Gregor9ea62762009-05-21 23:17:49 +00003294
3295 // Copy the index expressions into permanent storage.
3296 *Child++ = IndexExprs[IndexIdx++];
3297 } else if (this->Designators[I].isArrayRangeDesignator()) {
3298 // Compute type- and value-dependence.
3299 Expr *Start = IndexExprs[IndexIdx];
3300 Expr *End = IndexExprs[IndexIdx + 1];
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00003301 if (Start->isTypeDependent() || Start->isValueDependent() ||
Douglas Gregor561f8122011-07-01 01:22:09 +00003302 End->isTypeDependent() || End->isValueDependent()) {
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00003303 ExprBits.ValueDependent = true;
Douglas Gregor561f8122011-07-01 01:22:09 +00003304 ExprBits.InstantiationDependent = true;
3305 } else if (Start->isInstantiationDependent() ||
3306 End->isInstantiationDependent()) {
3307 ExprBits.InstantiationDependent = true;
3308 }
3309
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00003310 // Propagate unexpanded parameter packs.
3311 if (Start->containsUnexpandedParameterPack() ||
3312 End->containsUnexpandedParameterPack())
3313 ExprBits.ContainsUnexpandedParameterPack = true;
Douglas Gregor9ea62762009-05-21 23:17:49 +00003314
3315 // Copy the start/end expressions into permanent storage.
3316 *Child++ = IndexExprs[IndexIdx++];
3317 *Child++ = IndexExprs[IndexIdx++];
3318 }
3319 }
3320
3321 assert(IndexIdx == NumIndexExprs && "Wrong number of index expressions");
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00003322}
3323
Douglas Gregor05c13a32009-01-22 00:58:24 +00003324DesignatedInitExpr *
Mike Stump1eb44332009-09-09 15:08:12 +00003325DesignatedInitExpr::Create(ASTContext &C, Designator *Designators,
Douglas Gregor05c13a32009-01-22 00:58:24 +00003326 unsigned NumDesignators,
3327 Expr **IndexExprs, unsigned NumIndexExprs,
3328 SourceLocation ColonOrEqualLoc,
3329 bool UsesColonSyntax, Expr *Init) {
Steve Naroffc0ac4922009-01-27 23:20:32 +00003330 void *Mem = C.Allocate(sizeof(DesignatedInitExpr) +
Steve Naroffc0ac4922009-01-27 23:20:32 +00003331 sizeof(Stmt *) * (NumIndexExprs + 1), 8);
Douglas Gregor319d57f2010-01-06 23:17:19 +00003332 return new (Mem) DesignatedInitExpr(C, C.VoidTy, NumDesignators, Designators,
Douglas Gregor9ea62762009-05-21 23:17:49 +00003333 ColonOrEqualLoc, UsesColonSyntax,
3334 IndexExprs, NumIndexExprs, Init);
Douglas Gregor05c13a32009-01-22 00:58:24 +00003335}
3336
Mike Stump1eb44332009-09-09 15:08:12 +00003337DesignatedInitExpr *DesignatedInitExpr::CreateEmpty(ASTContext &C,
Douglas Gregord077d752009-04-16 00:55:48 +00003338 unsigned NumIndexExprs) {
3339 void *Mem = C.Allocate(sizeof(DesignatedInitExpr) +
3340 sizeof(Stmt *) * (NumIndexExprs + 1), 8);
3341 return new (Mem) DesignatedInitExpr(NumIndexExprs + 1);
3342}
3343
Douglas Gregor319d57f2010-01-06 23:17:19 +00003344void DesignatedInitExpr::setDesignators(ASTContext &C,
3345 const Designator *Desigs,
Douglas Gregord077d752009-04-16 00:55:48 +00003346 unsigned NumDesigs) {
Douglas Gregor319d57f2010-01-06 23:17:19 +00003347 Designators = new (C) Designator[NumDesigs];
Douglas Gregord077d752009-04-16 00:55:48 +00003348 NumDesignators = NumDesigs;
3349 for (unsigned I = 0; I != NumDesigs; ++I)
3350 Designators[I] = Desigs[I];
3351}
3352
Abramo Bagnara24f46742011-03-16 15:08:46 +00003353SourceRange DesignatedInitExpr::getDesignatorsSourceRange() const {
3354 DesignatedInitExpr *DIE = const_cast<DesignatedInitExpr*>(this);
3355 if (size() == 1)
3356 return DIE->getDesignator(0)->getSourceRange();
3357 return SourceRange(DIE->getDesignator(0)->getStartLocation(),
3358 DIE->getDesignator(size()-1)->getEndLocation());
3359}
3360
Douglas Gregor05c13a32009-01-22 00:58:24 +00003361SourceRange DesignatedInitExpr::getSourceRange() const {
3362 SourceLocation StartLoc;
Chris Lattnerd603eaa2009-02-16 22:33:34 +00003363 Designator &First =
3364 *const_cast<DesignatedInitExpr*>(this)->designators_begin();
Douglas Gregor05c13a32009-01-22 00:58:24 +00003365 if (First.isFieldDesignator()) {
Douglas Gregoreeae8f02009-03-28 00:41:23 +00003366 if (GNUSyntax)
Douglas Gregor05c13a32009-01-22 00:58:24 +00003367 StartLoc = SourceLocation::getFromRawEncoding(First.Field.FieldLoc);
3368 else
3369 StartLoc = SourceLocation::getFromRawEncoding(First.Field.DotLoc);
3370 } else
Chris Lattnerd603eaa2009-02-16 22:33:34 +00003371 StartLoc =
3372 SourceLocation::getFromRawEncoding(First.ArrayOrRange.LBracketLoc);
Douglas Gregor05c13a32009-01-22 00:58:24 +00003373 return SourceRange(StartLoc, getInit()->getSourceRange().getEnd());
3374}
3375
Douglas Gregor05c13a32009-01-22 00:58:24 +00003376Expr *DesignatedInitExpr::getArrayIndex(const Designator& D) {
3377 assert(D.Kind == Designator::ArrayDesignator && "Requires array designator");
3378 char* Ptr = static_cast<char*>(static_cast<void *>(this));
3379 Ptr += sizeof(DesignatedInitExpr);
Douglas Gregor05c13a32009-01-22 00:58:24 +00003380 Stmt **SubExprs = reinterpret_cast<Stmt**>(reinterpret_cast<void**>(Ptr));
3381 return cast<Expr>(*(SubExprs + D.ArrayOrRange.Index + 1));
3382}
3383
3384Expr *DesignatedInitExpr::getArrayRangeStart(const Designator& D) {
Mike Stump1eb44332009-09-09 15:08:12 +00003385 assert(D.Kind == Designator::ArrayRangeDesignator &&
Douglas Gregor05c13a32009-01-22 00:58:24 +00003386 "Requires array range designator");
3387 char* Ptr = static_cast<char*>(static_cast<void *>(this));
3388 Ptr += sizeof(DesignatedInitExpr);
Douglas Gregor05c13a32009-01-22 00:58:24 +00003389 Stmt **SubExprs = reinterpret_cast<Stmt**>(reinterpret_cast<void**>(Ptr));
3390 return cast<Expr>(*(SubExprs + D.ArrayOrRange.Index + 1));
3391}
3392
3393Expr *DesignatedInitExpr::getArrayRangeEnd(const Designator& D) {
Mike Stump1eb44332009-09-09 15:08:12 +00003394 assert(D.Kind == Designator::ArrayRangeDesignator &&
Douglas Gregor05c13a32009-01-22 00:58:24 +00003395 "Requires array range designator");
3396 char* Ptr = static_cast<char*>(static_cast<void *>(this));
3397 Ptr += sizeof(DesignatedInitExpr);
Douglas Gregor05c13a32009-01-22 00:58:24 +00003398 Stmt **SubExprs = reinterpret_cast<Stmt**>(reinterpret_cast<void**>(Ptr));
3399 return cast<Expr>(*(SubExprs + D.ArrayOrRange.Index + 2));
3400}
3401
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00003402/// \brief Replaces the designator at index @p Idx with the series
3403/// of designators in [First, Last).
Douglas Gregor319d57f2010-01-06 23:17:19 +00003404void DesignatedInitExpr::ExpandDesignator(ASTContext &C, unsigned Idx,
Mike Stump1eb44332009-09-09 15:08:12 +00003405 const Designator *First,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00003406 const Designator *Last) {
3407 unsigned NumNewDesignators = Last - First;
3408 if (NumNewDesignators == 0) {
3409 std::copy_backward(Designators + Idx + 1,
3410 Designators + NumDesignators,
3411 Designators + Idx);
3412 --NumNewDesignators;
3413 return;
3414 } else if (NumNewDesignators == 1) {
3415 Designators[Idx] = *First;
3416 return;
3417 }
3418
Mike Stump1eb44332009-09-09 15:08:12 +00003419 Designator *NewDesignators
Douglas Gregor319d57f2010-01-06 23:17:19 +00003420 = new (C) Designator[NumDesignators - 1 + NumNewDesignators];
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00003421 std::copy(Designators, Designators + Idx, NewDesignators);
3422 std::copy(First, Last, NewDesignators + Idx);
3423 std::copy(Designators + Idx + 1, Designators + NumDesignators,
3424 NewDesignators + Idx + NumNewDesignators);
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00003425 Designators = NewDesignators;
3426 NumDesignators = NumDesignators - 1 + NumNewDesignators;
3427}
3428
Mike Stump1eb44332009-09-09 15:08:12 +00003429ParenListExpr::ParenListExpr(ASTContext& C, SourceLocation lparenloc,
Nate Begeman2ef13e52009-08-10 23:49:36 +00003430 Expr **exprs, unsigned nexprs,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003431 SourceLocation rparenloc)
3432 : Expr(ParenListExprClass, QualType(), VK_RValue, OK_Ordinary,
Douglas Gregor561f8122011-07-01 01:22:09 +00003433 false, false, false, false),
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00003434 NumExprs(nexprs), LParenLoc(lparenloc), RParenLoc(rparenloc) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00003435 Exprs = new (C) Stmt*[nexprs];
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00003436 for (unsigned i = 0; i != nexprs; ++i) {
3437 if (exprs[i]->isTypeDependent())
3438 ExprBits.TypeDependent = true;
3439 if (exprs[i]->isValueDependent())
3440 ExprBits.ValueDependent = true;
Douglas Gregor561f8122011-07-01 01:22:09 +00003441 if (exprs[i]->isInstantiationDependent())
3442 ExprBits.InstantiationDependent = true;
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00003443 if (exprs[i]->containsUnexpandedParameterPack())
3444 ExprBits.ContainsUnexpandedParameterPack = true;
3445
Nate Begeman2ef13e52009-08-10 23:49:36 +00003446 Exprs[i] = exprs[i];
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00003447 }
Nate Begeman2ef13e52009-08-10 23:49:36 +00003448}
3449
John McCalle996ffd2011-02-16 08:02:54 +00003450const OpaqueValueExpr *OpaqueValueExpr::findInCopyConstruct(const Expr *e) {
3451 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(e))
3452 e = ewc->getSubExpr();
Douglas Gregor03e80032011-06-21 17:03:29 +00003453 if (const MaterializeTemporaryExpr *m = dyn_cast<MaterializeTemporaryExpr>(e))
3454 e = m->GetTemporaryExpr();
John McCalle996ffd2011-02-16 08:02:54 +00003455 e = cast<CXXConstructExpr>(e)->getArg(0);
3456 while (const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
3457 e = ice->getSubExpr();
3458 return cast<OpaqueValueExpr>(e);
3459}
3460
John McCall4b9c2d22011-11-06 09:01:30 +00003461PseudoObjectExpr *PseudoObjectExpr::Create(ASTContext &Context, EmptyShell sh,
3462 unsigned numSemanticExprs) {
3463 void *buffer = Context.Allocate(sizeof(PseudoObjectExpr) +
3464 (1 + numSemanticExprs) * sizeof(Expr*),
3465 llvm::alignOf<PseudoObjectExpr>());
3466 return new(buffer) PseudoObjectExpr(sh, numSemanticExprs);
3467}
3468
3469PseudoObjectExpr::PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs)
3470 : Expr(PseudoObjectExprClass, shell) {
3471 PseudoObjectExprBits.NumSubExprs = numSemanticExprs + 1;
3472}
3473
3474PseudoObjectExpr *PseudoObjectExpr::Create(ASTContext &C, Expr *syntax,
3475 ArrayRef<Expr*> semantics,
3476 unsigned resultIndex) {
3477 assert(syntax && "no syntactic expression!");
3478 assert(semantics.size() && "no semantic expressions!");
3479
3480 QualType type;
3481 ExprValueKind VK;
3482 if (resultIndex == NoResult) {
3483 type = C.VoidTy;
3484 VK = VK_RValue;
3485 } else {
3486 assert(resultIndex < semantics.size());
3487 type = semantics[resultIndex]->getType();
3488 VK = semantics[resultIndex]->getValueKind();
3489 assert(semantics[resultIndex]->getObjectKind() == OK_Ordinary);
3490 }
3491
3492 void *buffer = C.Allocate(sizeof(PseudoObjectExpr) +
3493 (1 + semantics.size()) * sizeof(Expr*),
3494 llvm::alignOf<PseudoObjectExpr>());
3495 return new(buffer) PseudoObjectExpr(type, VK, syntax, semantics,
3496 resultIndex);
3497}
3498
3499PseudoObjectExpr::PseudoObjectExpr(QualType type, ExprValueKind VK,
3500 Expr *syntax, ArrayRef<Expr*> semantics,
3501 unsigned resultIndex)
3502 : Expr(PseudoObjectExprClass, type, VK, OK_Ordinary,
3503 /*filled in at end of ctor*/ false, false, false, false) {
3504 PseudoObjectExprBits.NumSubExprs = semantics.size() + 1;
3505 PseudoObjectExprBits.ResultIndex = resultIndex + 1;
3506
3507 for (unsigned i = 0, e = semantics.size() + 1; i != e; ++i) {
3508 Expr *E = (i == 0 ? syntax : semantics[i-1]);
3509 getSubExprsBuffer()[i] = E;
3510
3511 if (E->isTypeDependent())
3512 ExprBits.TypeDependent = true;
3513 if (E->isValueDependent())
3514 ExprBits.ValueDependent = true;
3515 if (E->isInstantiationDependent())
3516 ExprBits.InstantiationDependent = true;
3517 if (E->containsUnexpandedParameterPack())
3518 ExprBits.ContainsUnexpandedParameterPack = true;
3519
3520 if (isa<OpaqueValueExpr>(E))
3521 assert(cast<OpaqueValueExpr>(E)->getSourceExpr() != 0 &&
3522 "opaque-value semantic expressions for pseudo-object "
3523 "operations must have sources");
3524 }
3525}
3526
Douglas Gregor05c13a32009-01-22 00:58:24 +00003527//===----------------------------------------------------------------------===//
Ted Kremenekce2fc3a2008-10-27 18:40:21 +00003528// ExprIterator.
3529//===----------------------------------------------------------------------===//
3530
3531Expr* ExprIterator::operator[](size_t idx) { return cast<Expr>(I[idx]); }
3532Expr* ExprIterator::operator*() const { return cast<Expr>(*I); }
3533Expr* ExprIterator::operator->() const { return cast<Expr>(*I); }
3534const Expr* ConstExprIterator::operator[](size_t idx) const {
3535 return cast<Expr>(I[idx]);
3536}
3537const Expr* ConstExprIterator::operator*() const { return cast<Expr>(*I); }
3538const Expr* ConstExprIterator::operator->() const { return cast<Expr>(*I); }
3539
3540//===----------------------------------------------------------------------===//
Ted Kremenek77ed8e42007-08-24 18:13:47 +00003541// Child Iterators for iterating over subexpressions/substatements
3542//===----------------------------------------------------------------------===//
3543
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003544// UnaryExprOrTypeTraitExpr
3545Stmt::child_range UnaryExprOrTypeTraitExpr::children() {
Sebastian Redl05189992008-11-11 17:56:53 +00003546 // If this is of a type and the type is a VLA type (and not a typedef), the
3547 // size expression of the VLA needs to be treated as an executable expression.
3548 // Why isn't this weirdness documented better in StmtIterator?
3549 if (isArgumentType()) {
John McCallf4c73712011-01-19 06:33:43 +00003550 if (const VariableArrayType* T = dyn_cast<VariableArrayType>(
Sebastian Redl05189992008-11-11 17:56:53 +00003551 getArgumentType().getTypePtr()))
John McCall63c00d72011-02-09 08:16:59 +00003552 return child_range(child_iterator(T), child_iterator());
3553 return child_range();
Sebastian Redl05189992008-11-11 17:56:53 +00003554 }
John McCall63c00d72011-02-09 08:16:59 +00003555 return child_range(&Argument.Ex, &Argument.Ex + 1);
Ted Kremenek9ac59282007-10-18 23:28:49 +00003556}
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00003557
Steve Naroff563477d2007-09-18 23:55:05 +00003558// ObjCMessageExpr
John McCall63c00d72011-02-09 08:16:59 +00003559Stmt::child_range ObjCMessageExpr::children() {
3560 Stmt **begin;
Douglas Gregor04badcf2010-04-21 00:45:42 +00003561 if (getReceiverKind() == Instance)
John McCall63c00d72011-02-09 08:16:59 +00003562 begin = reinterpret_cast<Stmt **>(this + 1);
3563 else
3564 begin = reinterpret_cast<Stmt **>(getArgs());
3565 return child_range(begin,
3566 reinterpret_cast<Stmt **>(getArgs() + getNumArgs()));
Steve Naroff563477d2007-09-18 23:55:05 +00003567}
3568
Steve Naroff4eb206b2008-09-03 18:15:37 +00003569// Blocks
John McCall6b5a61b2011-02-07 10:33:21 +00003570BlockDeclRefExpr::BlockDeclRefExpr(VarDecl *d, QualType t, ExprValueKind VK,
Douglas Gregora779d9c2011-01-19 21:32:01 +00003571 SourceLocation l, bool ByRef,
John McCall6b5a61b2011-02-07 10:33:21 +00003572 bool constAdded)
Douglas Gregor561f8122011-07-01 01:22:09 +00003573 : Expr(BlockDeclRefExprClass, t, VK, OK_Ordinary, false, false, false,
Douglas Gregora779d9c2011-01-19 21:32:01 +00003574 d->isParameterPack()),
John McCall6b5a61b2011-02-07 10:33:21 +00003575 D(d), Loc(l), IsByRef(ByRef), ConstQualAdded(constAdded)
Douglas Gregora779d9c2011-01-19 21:32:01 +00003576{
Douglas Gregord967e312011-01-19 21:52:31 +00003577 bool TypeDependent = false;
3578 bool ValueDependent = false;
Douglas Gregor561f8122011-07-01 01:22:09 +00003579 bool InstantiationDependent = false;
3580 computeDeclRefDependence(D, getType(), TypeDependent, ValueDependent,
3581 InstantiationDependent);
Douglas Gregord967e312011-01-19 21:52:31 +00003582 ExprBits.TypeDependent = TypeDependent;
3583 ExprBits.ValueDependent = ValueDependent;
Douglas Gregor561f8122011-07-01 01:22:09 +00003584 ExprBits.InstantiationDependent = InstantiationDependent;
Douglas Gregora779d9c2011-01-19 21:32:01 +00003585}
Eli Friedmandfa64ba2011-10-14 22:48:56 +00003586
3587
3588AtomicExpr::AtomicExpr(SourceLocation BLoc, Expr **args, unsigned nexpr,
3589 QualType t, AtomicOp op, SourceLocation RP)
3590 : Expr(AtomicExprClass, t, VK_RValue, OK_Ordinary,
3591 false, false, false, false),
3592 NumSubExprs(nexpr), BuiltinLoc(BLoc), RParenLoc(RP), Op(op)
3593{
3594 for (unsigned i = 0; i < nexpr; i++) {
3595 if (args[i]->isTypeDependent())
3596 ExprBits.TypeDependent = true;
3597 if (args[i]->isValueDependent())
3598 ExprBits.ValueDependent = true;
3599 if (args[i]->isInstantiationDependent())
3600 ExprBits.InstantiationDependent = true;
3601 if (args[i]->containsUnexpandedParameterPack())
3602 ExprBits.ContainsUnexpandedParameterPack = true;
3603
3604 SubExprs[i] = args[i];
3605 }
3606}