blob: 3c8cbb56a0252f03be5f20a60f290a0eba0acb52 [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"
Douglas Gregor25d0a0f2012-02-23 07:33:15 +000021#include "clang/AST/EvaluatedExprVisitor.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000022#include "clang/AST/RecordLayout.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000023#include "clang/AST/StmtVisitor.h"
Chris Lattner08f92e32010-11-17 07:37:15 +000024#include "clang/Lex/LiteralSupport.h"
25#include "clang/Lex/Lexer.h"
Richard Smith7a614d82011-06-11 17:19:42 +000026#include "clang/Sema/SemaDiagnostic.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000027#include "clang/Basic/Builtins.h"
Chris Lattner08f92e32010-11-17 07:37:15 +000028#include "clang/Basic/SourceManager.h"
Chris Lattnerda5a6b62007-11-27 18:22:04 +000029#include "clang/Basic/TargetInfo.h"
Douglas Gregorcf3293e2009-11-01 20:32:48 +000030#include "llvm/Support/ErrorHandling.h"
Anders Carlsson3a082d82009-09-08 18:24:21 +000031#include "llvm/Support/raw_ostream.h"
Douglas Gregorffb4b6e2009-04-15 06:41:24 +000032#include <algorithm>
Eli Friedman64f45a22011-11-01 02:23:42 +000033#include <cstring>
Reid Spencer5f016e22007-07-11 17:01:13 +000034using namespace clang;
35
Rafael Espindola8d852e32012-06-27 18:18:05 +000036const CXXRecordDecl *Expr::getBestDynamicClassType() const {
Rafael Espindola632fbaa2012-06-28 01:56:38 +000037 const Expr *E = ignoreParenBaseCasts();
Rafael Espindola0b4fe502012-06-26 17:45:31 +000038
39 QualType DerivedType = E->getType();
Rafael Espindola0b4fe502012-06-26 17:45:31 +000040 if (const PointerType *PTy = DerivedType->getAs<PointerType>())
41 DerivedType = PTy->getPointeeType();
42
Rafael Espindola251c4492012-07-17 20:24:05 +000043 if (DerivedType->isDependentType())
44 return NULL;
45
Rafael Espindola0b4fe502012-06-26 17:45:31 +000046 const RecordType *Ty = DerivedType->castAs<RecordType>();
Rafael Espindola0b4fe502012-06-26 17:45:31 +000047 Decl *D = Ty->getDecl();
48 return cast<CXXRecordDecl>(D);
49}
50
Chris Lattner2b334bb2010-04-16 23:34:13 +000051/// isKnownToHaveBooleanValue - Return true if this is an integer expression
52/// that is known to return 0 or 1. This happens for _Bool/bool expressions
53/// but also int expressions which are produced by things like comparisons in
54/// C.
55bool Expr::isKnownToHaveBooleanValue() const {
Peter Collingbournef111d932011-04-15 00:35:48 +000056 const Expr *E = IgnoreParens();
57
Chris Lattner2b334bb2010-04-16 23:34:13 +000058 // If this value has _Bool type, it is obvious 0/1.
Peter Collingbournef111d932011-04-15 00:35:48 +000059 if (E->getType()->isBooleanType()) return true;
Sean Huntc3021132010-05-05 15:23:54 +000060 // If this is a non-scalar-integer type, we don't care enough to try.
Peter Collingbournef111d932011-04-15 00:35:48 +000061 if (!E->getType()->isIntegralOrEnumerationType()) return false;
Sean Huntc3021132010-05-05 15:23:54 +000062
Peter Collingbournef111d932011-04-15 00:35:48 +000063 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
Chris Lattner2b334bb2010-04-16 23:34:13 +000064 switch (UO->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +000065 case UO_Plus:
Chris Lattner2b334bb2010-04-16 23:34:13 +000066 return UO->getSubExpr()->isKnownToHaveBooleanValue();
67 default:
68 return false;
69 }
70 }
Sean Huntc3021132010-05-05 15:23:54 +000071
John McCall6907fbe2010-06-12 01:56:02 +000072 // Only look through implicit casts. If the user writes
73 // '(int) (a && b)' treat it as an arbitrary int.
Peter Collingbournef111d932011-04-15 00:35:48 +000074 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Chris Lattner2b334bb2010-04-16 23:34:13 +000075 return CE->getSubExpr()->isKnownToHaveBooleanValue();
Sean Huntc3021132010-05-05 15:23:54 +000076
Peter Collingbournef111d932011-04-15 00:35:48 +000077 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
Chris Lattner2b334bb2010-04-16 23:34:13 +000078 switch (BO->getOpcode()) {
79 default: return false;
John McCall2de56d12010-08-25 11:45:40 +000080 case BO_LT: // Relational operators.
81 case BO_GT:
82 case BO_LE:
83 case BO_GE:
84 case BO_EQ: // Equality operators.
85 case BO_NE:
86 case BO_LAnd: // AND operator.
87 case BO_LOr: // Logical OR operator.
Chris Lattner2b334bb2010-04-16 23:34:13 +000088 return true;
Sean Huntc3021132010-05-05 15:23:54 +000089
John McCall2de56d12010-08-25 11:45:40 +000090 case BO_And: // Bitwise AND operator.
91 case BO_Xor: // Bitwise XOR operator.
92 case BO_Or: // Bitwise OR operator.
Chris Lattner2b334bb2010-04-16 23:34:13 +000093 // Handle things like (x==2)|(y==12).
94 return BO->getLHS()->isKnownToHaveBooleanValue() &&
95 BO->getRHS()->isKnownToHaveBooleanValue();
Sean Huntc3021132010-05-05 15:23:54 +000096
John McCall2de56d12010-08-25 11:45:40 +000097 case BO_Comma:
98 case BO_Assign:
Chris Lattner2b334bb2010-04-16 23:34:13 +000099 return BO->getRHS()->isKnownToHaveBooleanValue();
100 }
101 }
Sean Huntc3021132010-05-05 15:23:54 +0000102
Peter Collingbournef111d932011-04-15 00:35:48 +0000103 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
Chris Lattner2b334bb2010-04-16 23:34:13 +0000104 return CO->getTrueExpr()->isKnownToHaveBooleanValue() &&
105 CO->getFalseExpr()->isKnownToHaveBooleanValue();
Sean Huntc3021132010-05-05 15:23:54 +0000106
Chris Lattner2b334bb2010-04-16 23:34:13 +0000107 return false;
108}
109
John McCall63c00d72011-02-09 08:16:59 +0000110// Amusing macro metaprogramming hack: check whether a class provides
111// a more specific implementation of getExprLoc().
Daniel Dunbar90e25a82012-03-09 15:39:19 +0000112//
113// See also Stmt.cpp:{getLocStart(),getLocEnd()}.
John McCall63c00d72011-02-09 08:16:59 +0000114namespace {
115 /// This implementation is used when a class provides a custom
116 /// implementation of getExprLoc.
117 template <class E, class T>
118 SourceLocation getExprLocImpl(const Expr *expr,
119 SourceLocation (T::*v)() const) {
120 return static_cast<const E*>(expr)->getExprLoc();
121 }
122
123 /// This implementation is used when a class doesn't provide
124 /// a custom implementation of getExprLoc. Overload resolution
125 /// should pick it over the implementation above because it's
126 /// more specialized according to function template partial ordering.
127 template <class E>
128 SourceLocation getExprLocImpl(const Expr *expr,
129 SourceLocation (Expr::*v)() const) {
Daniel Dunbar90e25a82012-03-09 15:39:19 +0000130 return static_cast<const E*>(expr)->getLocStart();
John McCall63c00d72011-02-09 08:16:59 +0000131 }
132}
133
134SourceLocation Expr::getExprLoc() const {
135 switch (getStmtClass()) {
136 case Stmt::NoStmtClass: llvm_unreachable("statement without class");
137#define ABSTRACT_STMT(type)
138#define STMT(type, base) \
139 case Stmt::type##Class: llvm_unreachable(#type " is not an Expr"); break;
140#define EXPR(type, base) \
141 case Stmt::type##Class: return getExprLocImpl<type>(this, &type::getExprLoc);
142#include "clang/AST/StmtNodes.inc"
143 }
144 llvm_unreachable("unknown statement kind");
John McCall63c00d72011-02-09 08:16:59 +0000145}
146
Reid Spencer5f016e22007-07-11 17:01:13 +0000147//===----------------------------------------------------------------------===//
148// Primary Expressions.
149//===----------------------------------------------------------------------===//
150
Douglas Gregor561f8122011-07-01 01:22:09 +0000151/// \brief Compute the type-, value-, and instantiation-dependence of a
152/// declaration reference
Douglas Gregord967e312011-01-19 21:52:31 +0000153/// based on the declaration being referenced.
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +0000154static void computeDeclRefDependence(ASTContext &Ctx, NamedDecl *D, QualType T,
Douglas Gregord967e312011-01-19 21:52:31 +0000155 bool &TypeDependent,
Douglas Gregor561f8122011-07-01 01:22:09 +0000156 bool &ValueDependent,
157 bool &InstantiationDependent) {
Douglas Gregord967e312011-01-19 21:52:31 +0000158 TypeDependent = false;
159 ValueDependent = false;
Douglas Gregor561f8122011-07-01 01:22:09 +0000160 InstantiationDependent = false;
Douglas Gregor0da76df2009-11-23 11:41:28 +0000161
162 // (TD) C++ [temp.dep.expr]p3:
163 // An id-expression is type-dependent if it contains:
164 //
Sean Huntc3021132010-05-05 15:23:54 +0000165 // and
Douglas Gregor0da76df2009-11-23 11:41:28 +0000166 //
167 // (VD) C++ [temp.dep.constexpr]p2:
168 // An identifier is value-dependent if it is:
Douglas Gregord967e312011-01-19 21:52:31 +0000169
Douglas Gregor0da76df2009-11-23 11:41:28 +0000170 // (TD) - an identifier that was declared with dependent type
171 // (VD) - a name declared with a dependent type,
Douglas Gregord967e312011-01-19 21:52:31 +0000172 if (T->isDependentType()) {
173 TypeDependent = true;
174 ValueDependent = true;
Douglas Gregor561f8122011-07-01 01:22:09 +0000175 InstantiationDependent = true;
Douglas Gregord967e312011-01-19 21:52:31 +0000176 return;
Douglas Gregor561f8122011-07-01 01:22:09 +0000177 } else if (T->isInstantiationDependentType()) {
178 InstantiationDependent = true;
Douglas Gregor0da76df2009-11-23 11:41:28 +0000179 }
Douglas Gregord967e312011-01-19 21:52:31 +0000180
Douglas Gregor0da76df2009-11-23 11:41:28 +0000181 // (TD) - a conversion-function-id that specifies a dependent type
Douglas Gregord967e312011-01-19 21:52:31 +0000182 if (D->getDeclName().getNameKind()
Douglas Gregor561f8122011-07-01 01:22:09 +0000183 == DeclarationName::CXXConversionFunctionName) {
184 QualType T = D->getDeclName().getCXXNameType();
185 if (T->isDependentType()) {
186 TypeDependent = true;
187 ValueDependent = true;
188 InstantiationDependent = true;
189 return;
190 }
191
192 if (T->isInstantiationDependentType())
193 InstantiationDependent = true;
Douglas Gregor0da76df2009-11-23 11:41:28 +0000194 }
Douglas Gregor561f8122011-07-01 01:22:09 +0000195
Douglas Gregor0da76df2009-11-23 11:41:28 +0000196 // (VD) - the name of a non-type template parameter,
Douglas Gregord967e312011-01-19 21:52:31 +0000197 if (isa<NonTypeTemplateParmDecl>(D)) {
198 ValueDependent = true;
Douglas Gregor561f8122011-07-01 01:22:09 +0000199 InstantiationDependent = true;
Douglas Gregord967e312011-01-19 21:52:31 +0000200 return;
201 }
202
Douglas Gregor0da76df2009-11-23 11:41:28 +0000203 // (VD) - a constant with integral or enumeration type and is
204 // initialized with an expression that is value-dependent.
Richard Smithdb1822c2011-11-08 01:31:09 +0000205 // (VD) - a constant with literal type and is initialized with an
206 // expression that is value-dependent [C++11].
207 // (VD) - FIXME: Missing from the standard:
208 // - an entity with reference type and is initialized with an
209 // expression that is value-dependent [C++11]
Douglas Gregord967e312011-01-19 21:52:31 +0000210 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000211 if ((Ctx.getLangOpts().CPlusPlus0x ?
Richard Smithdb1822c2011-11-08 01:31:09 +0000212 Var->getType()->isLiteralType() :
213 Var->getType()->isIntegralOrEnumerationType()) &&
David Blaikie4ef832f2012-08-10 00:55:35 +0000214 (Var->getType().isConstQualified() ||
Richard Smithdb1822c2011-11-08 01:31:09 +0000215 Var->getType()->isReferenceType())) {
Sebastian Redl31310a22010-02-01 20:16:42 +0000216 if (const Expr *Init = Var->getAnyInitializer())
Douglas Gregor561f8122011-07-01 01:22:09 +0000217 if (Init->isValueDependent()) {
Douglas Gregord967e312011-01-19 21:52:31 +0000218 ValueDependent = true;
Douglas Gregor561f8122011-07-01 01:22:09 +0000219 InstantiationDependent = true;
220 }
Richard Smithdb1822c2011-11-08 01:31:09 +0000221 }
222
Douglas Gregorbb6e73f2010-05-11 08:41:30 +0000223 // (VD) - FIXME: Missing from the standard:
224 // - a member function or a static data member of the current
225 // instantiation
Richard Smithdb1822c2011-11-08 01:31:09 +0000226 if (Var->isStaticDataMember() &&
227 Var->getDeclContext()->isDependentContext()) {
Douglas Gregord967e312011-01-19 21:52:31 +0000228 ValueDependent = true;
Douglas Gregor561f8122011-07-01 01:22:09 +0000229 InstantiationDependent = true;
230 }
Douglas Gregord967e312011-01-19 21:52:31 +0000231
232 return;
233 }
234
Douglas Gregorbb6e73f2010-05-11 08:41:30 +0000235 // (VD) - FIXME: Missing from the standard:
236 // - a member function or a static data member of the current
237 // instantiation
Douglas Gregord967e312011-01-19 21:52:31 +0000238 if (isa<CXXMethodDecl>(D) && D->getDeclContext()->isDependentContext()) {
239 ValueDependent = true;
Douglas Gregor561f8122011-07-01 01:22:09 +0000240 InstantiationDependent = true;
Richard Smithdb1822c2011-11-08 01:31:09 +0000241 }
Douglas Gregord967e312011-01-19 21:52:31 +0000242}
Douglas Gregorbebbe0d2010-12-15 01:34:56 +0000243
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +0000244void DeclRefExpr::computeDependence(ASTContext &Ctx) {
Douglas Gregord967e312011-01-19 21:52:31 +0000245 bool TypeDependent = false;
246 bool ValueDependent = false;
Douglas Gregor561f8122011-07-01 01:22:09 +0000247 bool InstantiationDependent = false;
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +0000248 computeDeclRefDependence(Ctx, getDecl(), getType(), TypeDependent,
249 ValueDependent, InstantiationDependent);
Douglas Gregord967e312011-01-19 21:52:31 +0000250
251 // (TD) C++ [temp.dep.expr]p3:
252 // An id-expression is type-dependent if it contains:
253 //
254 // and
255 //
256 // (VD) C++ [temp.dep.constexpr]p2:
257 // An identifier is value-dependent if it is:
258 if (!TypeDependent && !ValueDependent &&
259 hasExplicitTemplateArgs() &&
260 TemplateSpecializationType::anyDependentTemplateArguments(
261 getTemplateArgs(),
Douglas Gregor561f8122011-07-01 01:22:09 +0000262 getNumTemplateArgs(),
263 InstantiationDependent)) {
Douglas Gregord967e312011-01-19 21:52:31 +0000264 TypeDependent = true;
265 ValueDependent = true;
Douglas Gregor561f8122011-07-01 01:22:09 +0000266 InstantiationDependent = true;
Douglas Gregord967e312011-01-19 21:52:31 +0000267 }
268
269 ExprBits.TypeDependent = TypeDependent;
270 ExprBits.ValueDependent = ValueDependent;
Douglas Gregor561f8122011-07-01 01:22:09 +0000271 ExprBits.InstantiationDependent = InstantiationDependent;
Douglas Gregord967e312011-01-19 21:52:31 +0000272
Douglas Gregor10738d32010-12-23 23:51:58 +0000273 // Is the declaration a parameter pack?
Douglas Gregord967e312011-01-19 21:52:31 +0000274 if (getDecl()->isParameterPack())
Douglas Gregor1fe85ea2011-01-05 21:11:38 +0000275 ExprBits.ContainsUnexpandedParameterPack = true;
Douglas Gregor0da76df2009-11-23 11:41:28 +0000276}
277
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +0000278DeclRefExpr::DeclRefExpr(ASTContext &Ctx,
279 NestedNameSpecifierLoc QualifierLoc,
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000280 SourceLocation TemplateKWLoc,
John McCallf4b88a42012-03-10 09:33:50 +0000281 ValueDecl *D, bool RefersToEnclosingLocal,
282 const DeclarationNameInfo &NameInfo,
Chandler Carruth3aa81402011-05-01 23:48:14 +0000283 NamedDecl *FoundD,
Abramo Bagnara25777432010-08-11 22:01:17 +0000284 const TemplateArgumentListInfo *TemplateArgs,
John McCallf89e55a2010-11-18 06:31:45 +0000285 QualType T, ExprValueKind VK)
Douglas Gregor561f8122011-07-01 01:22:09 +0000286 : Expr(DeclRefExprClass, T, VK, OK_Ordinary, false, false, false, false),
Chandler Carruthcb66cff2011-05-01 21:29:53 +0000287 D(D), Loc(NameInfo.getLoc()), DNLoc(NameInfo.getInfo()) {
288 DeclRefExprBits.HasQualifier = QualifierLoc ? 1 : 0;
Chandler Carruth7e740bd2011-05-01 21:55:21 +0000289 if (QualifierLoc)
Chandler Carruth6857c3e2011-05-01 22:14:37 +0000290 getInternalQualifierLoc() = QualifierLoc;
Chandler Carruth3aa81402011-05-01 23:48:14 +0000291 DeclRefExprBits.HasFoundDecl = FoundD ? 1 : 0;
292 if (FoundD)
293 getInternalFoundDecl() = FoundD;
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000294 DeclRefExprBits.HasTemplateKWAndArgsInfo
295 = (TemplateArgs || TemplateKWLoc.isValid()) ? 1 : 0;
John McCallf4b88a42012-03-10 09:33:50 +0000296 DeclRefExprBits.RefersToEnclosingLocal = RefersToEnclosingLocal;
Douglas Gregor561f8122011-07-01 01:22:09 +0000297 if (TemplateArgs) {
298 bool Dependent = false;
299 bool InstantiationDependent = false;
300 bool ContainsUnexpandedParameterPack = false;
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000301 getTemplateKWAndArgsInfo()->initializeFrom(TemplateKWLoc, *TemplateArgs,
302 Dependent,
303 InstantiationDependent,
304 ContainsUnexpandedParameterPack);
Douglas Gregor561f8122011-07-01 01:22:09 +0000305 if (InstantiationDependent)
306 setInstantiationDependent(true);
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000307 } else if (TemplateKWLoc.isValid()) {
308 getTemplateKWAndArgsInfo()->initializeFrom(TemplateKWLoc);
Douglas Gregor561f8122011-07-01 01:22:09 +0000309 }
Benjamin Kramerb8da98a2011-10-10 12:54:05 +0000310 DeclRefExprBits.HadMultipleCandidates = 0;
311
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +0000312 computeDependence(Ctx);
Abramo Bagnara25777432010-08-11 22:01:17 +0000313}
314
Douglas Gregora2813ce2009-10-23 18:54:35 +0000315DeclRefExpr *DeclRefExpr::Create(ASTContext &Context,
Douglas Gregor40d96a62011-02-28 21:54:11 +0000316 NestedNameSpecifierLoc QualifierLoc,
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000317 SourceLocation TemplateKWLoc,
John McCalldbd872f2009-12-08 09:08:17 +0000318 ValueDecl *D,
John McCallf4b88a42012-03-10 09:33:50 +0000319 bool RefersToEnclosingLocal,
Douglas Gregora2813ce2009-10-23 18:54:35 +0000320 SourceLocation NameLoc,
Douglas Gregor0da76df2009-11-23 11:41:28 +0000321 QualType T,
John McCallf89e55a2010-11-18 06:31:45 +0000322 ExprValueKind VK,
Chandler Carruth3aa81402011-05-01 23:48:14 +0000323 NamedDecl *FoundD,
Douglas Gregor0da76df2009-11-23 11:41:28 +0000324 const TemplateArgumentListInfo *TemplateArgs) {
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000325 return Create(Context, QualifierLoc, TemplateKWLoc, D,
John McCallf4b88a42012-03-10 09:33:50 +0000326 RefersToEnclosingLocal,
Abramo Bagnara25777432010-08-11 22:01:17 +0000327 DeclarationNameInfo(D->getDeclName(), NameLoc),
Chandler Carruth3aa81402011-05-01 23:48:14 +0000328 T, VK, FoundD, TemplateArgs);
Abramo Bagnara25777432010-08-11 22:01:17 +0000329}
330
331DeclRefExpr *DeclRefExpr::Create(ASTContext &Context,
Douglas Gregor40d96a62011-02-28 21:54:11 +0000332 NestedNameSpecifierLoc QualifierLoc,
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000333 SourceLocation TemplateKWLoc,
Abramo Bagnara25777432010-08-11 22:01:17 +0000334 ValueDecl *D,
John McCallf4b88a42012-03-10 09:33:50 +0000335 bool RefersToEnclosingLocal,
Abramo Bagnara25777432010-08-11 22:01:17 +0000336 const DeclarationNameInfo &NameInfo,
337 QualType T,
John McCallf89e55a2010-11-18 06:31:45 +0000338 ExprValueKind VK,
Chandler Carruth3aa81402011-05-01 23:48:14 +0000339 NamedDecl *FoundD,
Abramo Bagnara25777432010-08-11 22:01:17 +0000340 const TemplateArgumentListInfo *TemplateArgs) {
Chandler Carruth3aa81402011-05-01 23:48:14 +0000341 // Filter out cases where the found Decl is the same as the value refenenced.
342 if (D == FoundD)
343 FoundD = 0;
344
Douglas Gregora2813ce2009-10-23 18:54:35 +0000345 std::size_t Size = sizeof(DeclRefExpr);
Douglas Gregor40d96a62011-02-28 21:54:11 +0000346 if (QualifierLoc != 0)
Chandler Carruth6857c3e2011-05-01 22:14:37 +0000347 Size += sizeof(NestedNameSpecifierLoc);
Chandler Carruth3aa81402011-05-01 23:48:14 +0000348 if (FoundD)
349 Size += sizeof(NamedDecl *);
John McCalld5532b62009-11-23 01:53:49 +0000350 if (TemplateArgs)
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000351 Size += ASTTemplateKWAndArgsInfo::sizeFor(TemplateArgs->size());
352 else if (TemplateKWLoc.isValid())
353 Size += ASTTemplateKWAndArgsInfo::sizeFor(0);
Chandler Carruth3aa81402011-05-01 23:48:14 +0000354
Chris Lattner32488542010-10-30 05:14:06 +0000355 void *Mem = Context.Allocate(Size, llvm::alignOf<DeclRefExpr>());
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +0000356 return new (Mem) DeclRefExpr(Context, QualifierLoc, TemplateKWLoc, D,
John McCallf4b88a42012-03-10 09:33:50 +0000357 RefersToEnclosingLocal,
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +0000358 NameInfo, FoundD, TemplateArgs, T, VK);
Douglas Gregora2813ce2009-10-23 18:54:35 +0000359}
360
Chandler Carruth3aa81402011-05-01 23:48:14 +0000361DeclRefExpr *DeclRefExpr::CreateEmpty(ASTContext &Context,
Douglas Gregordef03542011-02-04 12:01:24 +0000362 bool HasQualifier,
Chandler Carruth3aa81402011-05-01 23:48:14 +0000363 bool HasFoundDecl,
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000364 bool HasTemplateKWAndArgsInfo,
Argyrios Kyrtzidis663e3802010-07-08 13:09:47 +0000365 unsigned NumTemplateArgs) {
366 std::size_t Size = sizeof(DeclRefExpr);
367 if (HasQualifier)
Chandler Carruth6857c3e2011-05-01 22:14:37 +0000368 Size += sizeof(NestedNameSpecifierLoc);
Chandler Carruth3aa81402011-05-01 23:48:14 +0000369 if (HasFoundDecl)
370 Size += sizeof(NamedDecl *);
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000371 if (HasTemplateKWAndArgsInfo)
372 Size += ASTTemplateKWAndArgsInfo::sizeFor(NumTemplateArgs);
Chandler Carruth3aa81402011-05-01 23:48:14 +0000373
Chris Lattner32488542010-10-30 05:14:06 +0000374 void *Mem = Context.Allocate(Size, llvm::alignOf<DeclRefExpr>());
Argyrios Kyrtzidis663e3802010-07-08 13:09:47 +0000375 return new (Mem) DeclRefExpr(EmptyShell());
376}
377
Douglas Gregora2813ce2009-10-23 18:54:35 +0000378SourceRange DeclRefExpr::getSourceRange() const {
Abramo Bagnara25777432010-08-11 22:01:17 +0000379 SourceRange R = getNameInfo().getSourceRange();
Douglas Gregora2813ce2009-10-23 18:54:35 +0000380 if (hasQualifier())
Douglas Gregor40d96a62011-02-28 21:54:11 +0000381 R.setBegin(getQualifierLoc().getBeginLoc());
John McCall096832c2010-08-19 23:49:38 +0000382 if (hasExplicitTemplateArgs())
Douglas Gregora2813ce2009-10-23 18:54:35 +0000383 R.setEnd(getRAngleLoc());
384 return R;
385}
Daniel Dunbar396ec672012-03-09 15:39:15 +0000386SourceLocation DeclRefExpr::getLocStart() const {
387 if (hasQualifier())
388 return getQualifierLoc().getBeginLoc();
389 return getNameInfo().getLocStart();
390}
391SourceLocation DeclRefExpr::getLocEnd() const {
392 if (hasExplicitTemplateArgs())
393 return getRAngleLoc();
394 return getNameInfo().getLocEnd();
395}
Douglas Gregora2813ce2009-10-23 18:54:35 +0000396
Anders Carlsson3a082d82009-09-08 18:24:21 +0000397// FIXME: Maybe this should use DeclPrinter with a special "print predefined
398// expr" policy instead.
Anders Carlsson848fa642010-02-11 18:20:28 +0000399std::string PredefinedExpr::ComputeName(IdentType IT, const Decl *CurrentDecl) {
400 ASTContext &Context = CurrentDecl->getASTContext();
401
Anders Carlsson3a082d82009-09-08 18:24:21 +0000402 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CurrentDecl)) {
Anders Carlsson848fa642010-02-11 18:20:28 +0000403 if (IT != PrettyFunction && IT != PrettyFunctionNoVirtual)
Anders Carlsson3a082d82009-09-08 18:24:21 +0000404 return FD->getNameAsString();
405
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000406 SmallString<256> Name;
Anders Carlsson3a082d82009-09-08 18:24:21 +0000407 llvm::raw_svector_ostream Out(Name);
408
409 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
Anders Carlsson848fa642010-02-11 18:20:28 +0000410 if (MD->isVirtual() && IT != PrettyFunctionNoVirtual)
Anders Carlsson3a082d82009-09-08 18:24:21 +0000411 Out << "virtual ";
Sam Weinig4eadcc52009-12-27 01:38:20 +0000412 if (MD->isStatic())
413 Out << "static ";
Anders Carlsson3a082d82009-09-08 18:24:21 +0000414 }
415
David Blaikie4e4d0842012-03-11 07:00:24 +0000416 PrintingPolicy Policy(Context.getLangOpts());
Anders Carlsson3a082d82009-09-08 18:24:21 +0000417 std::string Proto = FD->getQualifiedNameAsString(Policy);
Douglas Gregorabf65ce2012-04-10 20:14:15 +0000418 llvm::raw_string_ostream POut(Proto);
Anders Carlsson3a082d82009-09-08 18:24:21 +0000419
Douglas Gregorabf65ce2012-04-10 20:14:15 +0000420 const FunctionDecl *Decl = FD;
421 if (const FunctionDecl* Pattern = FD->getTemplateInstantiationPattern())
422 Decl = Pattern;
423 const FunctionType *AFT = Decl->getType()->getAs<FunctionType>();
Anders Carlsson3a082d82009-09-08 18:24:21 +0000424 const FunctionProtoType *FT = 0;
425 if (FD->hasWrittenPrototype())
426 FT = dyn_cast<FunctionProtoType>(AFT);
427
Douglas Gregorabf65ce2012-04-10 20:14:15 +0000428 POut << "(";
Anders Carlsson3a082d82009-09-08 18:24:21 +0000429 if (FT) {
Douglas Gregorabf65ce2012-04-10 20:14:15 +0000430 for (unsigned i = 0, e = Decl->getNumParams(); i != e; ++i) {
Anders Carlsson3a082d82009-09-08 18:24:21 +0000431 if (i) POut << ", ";
Argyrios Kyrtzidis7ad5c992012-05-05 04:20:37 +0000432 POut << Decl->getParamDecl(i)->getType().stream(Policy);
Anders Carlsson3a082d82009-09-08 18:24:21 +0000433 }
434
435 if (FT->isVariadic()) {
436 if (FD->getNumParams()) POut << ", ";
437 POut << "...";
438 }
439 }
Douglas Gregorabf65ce2012-04-10 20:14:15 +0000440 POut << ")";
Anders Carlsson3a082d82009-09-08 18:24:21 +0000441
Sam Weinig4eadcc52009-12-27 01:38:20 +0000442 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
David Blaikie4ef832f2012-08-10 00:55:35 +0000443 const FunctionType *FT = cast<FunctionType>(MD->getType().getTypePtr());
444 if (FT->isConst())
Douglas Gregorabf65ce2012-04-10 20:14:15 +0000445 POut << " const";
David Blaikie4ef832f2012-08-10 00:55:35 +0000446 if (FT->isVolatile())
Douglas Gregorabf65ce2012-04-10 20:14:15 +0000447 POut << " volatile";
448 RefQualifierKind Ref = MD->getRefQualifier();
449 if (Ref == RQ_LValue)
450 POut << " &";
451 else if (Ref == RQ_RValue)
452 POut << " &&";
Sam Weinig4eadcc52009-12-27 01:38:20 +0000453 }
454
Douglas Gregorabf65ce2012-04-10 20:14:15 +0000455 typedef SmallVector<const ClassTemplateSpecializationDecl *, 8> SpecsTy;
456 SpecsTy Specs;
457 const DeclContext *Ctx = FD->getDeclContext();
458 while (Ctx && isa<NamedDecl>(Ctx)) {
459 const ClassTemplateSpecializationDecl *Spec
460 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx);
461 if (Spec && !Spec->isExplicitSpecialization())
462 Specs.push_back(Spec);
463 Ctx = Ctx->getParent();
464 }
465
466 std::string TemplateParams;
467 llvm::raw_string_ostream TOut(TemplateParams);
468 for (SpecsTy::reverse_iterator I = Specs.rbegin(), E = Specs.rend();
469 I != E; ++I) {
470 const TemplateParameterList *Params
471 = (*I)->getSpecializedTemplate()->getTemplateParameters();
472 const TemplateArgumentList &Args = (*I)->getTemplateArgs();
473 assert(Params->size() == Args.size());
474 for (unsigned i = 0, numParams = Params->size(); i != numParams; ++i) {
475 StringRef Param = Params->getParam(i)->getName();
476 if (Param.empty()) continue;
477 TOut << Param << " = ";
478 Args.get(i).print(Policy, TOut);
479 TOut << ", ";
480 }
481 }
482
483 FunctionTemplateSpecializationInfo *FSI
484 = FD->getTemplateSpecializationInfo();
485 if (FSI && !FSI->isExplicitSpecialization()) {
486 const TemplateParameterList* Params
487 = FSI->getTemplate()->getTemplateParameters();
488 const TemplateArgumentList* Args = FSI->TemplateArguments;
489 assert(Params->size() == Args->size());
490 for (unsigned i = 0, e = Params->size(); i != e; ++i) {
491 StringRef Param = Params->getParam(i)->getName();
492 if (Param.empty()) continue;
493 TOut << Param << " = ";
494 Args->get(i).print(Policy, TOut);
495 TOut << ", ";
496 }
497 }
498
499 TOut.flush();
500 if (!TemplateParams.empty()) {
501 // remove the trailing comma and space
502 TemplateParams.resize(TemplateParams.size() - 2);
503 POut << " [" << TemplateParams << "]";
504 }
505
506 POut.flush();
507
Sam Weinig3a1ce1e2009-12-06 23:55:13 +0000508 if (!isa<CXXConstructorDecl>(FD) && !isa<CXXDestructorDecl>(FD))
509 AFT->getResultType().getAsStringInternal(Proto, Policy);
Anders Carlsson3a082d82009-09-08 18:24:21 +0000510
511 Out << Proto;
512
513 Out.flush();
514 return Name.str().str();
515 }
516 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurrentDecl)) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000517 SmallString<256> Name;
Anders Carlsson3a082d82009-09-08 18:24:21 +0000518 llvm::raw_svector_ostream Out(Name);
519 Out << (MD->isInstanceMethod() ? '-' : '+');
520 Out << '[';
Ted Kremenekb03d33e2010-03-18 21:23:08 +0000521
522 // For incorrect code, there might not be an ObjCInterfaceDecl. Do
523 // a null check to avoid a crash.
524 if (const ObjCInterfaceDecl *ID = MD->getClassInterface())
Benjamin Kramerb8989f22011-10-14 18:45:37 +0000525 Out << *ID;
Ted Kremenekb03d33e2010-03-18 21:23:08 +0000526
Anders Carlsson3a082d82009-09-08 18:24:21 +0000527 if (const ObjCCategoryImplDecl *CID =
Benjamin Kramer900fc632010-04-17 09:33:03 +0000528 dyn_cast<ObjCCategoryImplDecl>(MD->getDeclContext()))
Benjamin Kramerf9780592012-02-07 11:57:45 +0000529 Out << '(' << *CID << ')';
Benjamin Kramer900fc632010-04-17 09:33:03 +0000530
Anders Carlsson3a082d82009-09-08 18:24:21 +0000531 Out << ' ';
532 Out << MD->getSelector().getAsString();
533 Out << ']';
534
535 Out.flush();
536 return Name.str().str();
537 }
538 if (isa<TranslationUnitDecl>(CurrentDecl) && IT == PrettyFunction) {
539 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
540 return "top level";
541 }
542 return "";
543}
544
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +0000545void APNumericStorage::setIntValue(ASTContext &C, const llvm::APInt &Val) {
546 if (hasAllocation())
547 C.Deallocate(pVal);
548
549 BitWidth = Val.getBitWidth();
550 unsigned NumWords = Val.getNumWords();
551 const uint64_t* Words = Val.getRawData();
552 if (NumWords > 1) {
553 pVal = new (C) uint64_t[NumWords];
554 std::copy(Words, Words + NumWords, pVal);
555 } else if (NumWords == 1)
556 VAL = Words[0];
557 else
558 VAL = 0;
559}
560
Benjamin Kramer478851c2012-07-04 17:04:04 +0000561IntegerLiteral::IntegerLiteral(ASTContext &C, const llvm::APInt &V,
562 QualType type, SourceLocation l)
563 : Expr(IntegerLiteralClass, type, VK_RValue, OK_Ordinary, false, false,
564 false, false),
565 Loc(l) {
566 assert(type->isIntegerType() && "Illegal type in IntegerLiteral");
567 assert(V.getBitWidth() == C.getIntWidth(type) &&
568 "Integer type is not the correct size for constant.");
569 setValue(C, V);
570}
571
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +0000572IntegerLiteral *
573IntegerLiteral::Create(ASTContext &C, const llvm::APInt &V,
574 QualType type, SourceLocation l) {
575 return new (C) IntegerLiteral(C, V, type, l);
576}
577
578IntegerLiteral *
579IntegerLiteral::Create(ASTContext &C, EmptyShell Empty) {
580 return new (C) IntegerLiteral(Empty);
581}
582
Benjamin Kramer478851c2012-07-04 17:04:04 +0000583FloatingLiteral::FloatingLiteral(ASTContext &C, const llvm::APFloat &V,
584 bool isexact, QualType Type, SourceLocation L)
585 : Expr(FloatingLiteralClass, Type, VK_RValue, OK_Ordinary, false, false,
586 false, false), Loc(L) {
587 FloatingLiteralBits.IsIEEE =
588 &C.getTargetInfo().getLongDoubleFormat() == &llvm::APFloat::IEEEquad;
589 FloatingLiteralBits.IsExact = isexact;
590 setValue(C, V);
591}
592
593FloatingLiteral::FloatingLiteral(ASTContext &C, EmptyShell Empty)
594 : Expr(FloatingLiteralClass, Empty) {
595 FloatingLiteralBits.IsIEEE =
596 &C.getTargetInfo().getLongDoubleFormat() == &llvm::APFloat::IEEEquad;
597 FloatingLiteralBits.IsExact = false;
598}
599
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +0000600FloatingLiteral *
601FloatingLiteral::Create(ASTContext &C, const llvm::APFloat &V,
602 bool isexact, QualType Type, SourceLocation L) {
603 return new (C) FloatingLiteral(C, V, isexact, Type, L);
604}
605
606FloatingLiteral *
607FloatingLiteral::Create(ASTContext &C, EmptyShell Empty) {
Akira Hatanaka31dfd642012-01-10 22:40:09 +0000608 return new (C) FloatingLiteral(C, Empty);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +0000609}
610
Chris Lattnerda8249e2008-06-07 22:13:43 +0000611/// getValueAsApproximateDouble - This returns the value as an inaccurate
612/// double. Note that this may cause loss of precision, but is useful for
613/// debugging dumps, etc.
614double FloatingLiteral::getValueAsApproximateDouble() const {
615 llvm::APFloat V = getValue();
Dale Johannesenee5a7002008-10-09 23:02:32 +0000616 bool ignored;
617 V.convert(llvm::APFloat::IEEEdouble, llvm::APFloat::rmNearestTiesToEven,
618 &ignored);
Chris Lattnerda8249e2008-06-07 22:13:43 +0000619 return V.convertToDouble();
620}
621
Nick Lewycky0fd7f4d2012-02-24 09:07:53 +0000622int StringLiteral::mapCharByteWidth(TargetInfo const &target,StringKind k) {
Eli Friedmanfd819782012-02-29 20:59:56 +0000623 int CharByteWidth = 0;
Nick Lewycky0fd7f4d2012-02-24 09:07:53 +0000624 switch(k) {
Eli Friedman64f45a22011-11-01 02:23:42 +0000625 case Ascii:
626 case UTF8:
Nick Lewycky0fd7f4d2012-02-24 09:07:53 +0000627 CharByteWidth = target.getCharWidth();
Eli Friedman64f45a22011-11-01 02:23:42 +0000628 break;
629 case Wide:
Nick Lewycky0fd7f4d2012-02-24 09:07:53 +0000630 CharByteWidth = target.getWCharWidth();
Eli Friedman64f45a22011-11-01 02:23:42 +0000631 break;
632 case UTF16:
Nick Lewycky0fd7f4d2012-02-24 09:07:53 +0000633 CharByteWidth = target.getChar16Width();
Eli Friedman64f45a22011-11-01 02:23:42 +0000634 break;
635 case UTF32:
Nick Lewycky0fd7f4d2012-02-24 09:07:53 +0000636 CharByteWidth = target.getChar32Width();
Eli Friedmanfd819782012-02-29 20:59:56 +0000637 break;
Eli Friedman64f45a22011-11-01 02:23:42 +0000638 }
639 assert((CharByteWidth & 7) == 0 && "Assumes character size is byte multiple");
640 CharByteWidth /= 8;
Nick Lewycky0fd7f4d2012-02-24 09:07:53 +0000641 assert((CharByteWidth==1 || CharByteWidth==2 || CharByteWidth==4)
Eli Friedman64f45a22011-11-01 02:23:42 +0000642 && "character byte widths supported are 1, 2, and 4 only");
643 return CharByteWidth;
644}
645
Chris Lattner5f9e2722011-07-23 10:55:15 +0000646StringLiteral *StringLiteral::Create(ASTContext &C, StringRef Str,
Douglas Gregor5cee1192011-07-27 05:40:30 +0000647 StringKind Kind, bool Pascal, QualType Ty,
Mike Stump1eb44332009-09-09 15:08:12 +0000648 const SourceLocation *Loc,
Anders Carlssona135fb42009-03-15 18:34:13 +0000649 unsigned NumStrs) {
Chris Lattner2085fd62009-02-18 06:40:38 +0000650 // Allocate enough space for the StringLiteral plus an array of locations for
651 // any concatenated string tokens.
652 void *Mem = C.Allocate(sizeof(StringLiteral)+
653 sizeof(SourceLocation)*(NumStrs-1),
Chris Lattner32488542010-10-30 05:14:06 +0000654 llvm::alignOf<StringLiteral>());
Chris Lattner2085fd62009-02-18 06:40:38 +0000655 StringLiteral *SL = new (Mem) StringLiteral(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +0000656
Reid Spencer5f016e22007-07-11 17:01:13 +0000657 // OPTIMIZE: could allocate this appended to the StringLiteral.
Eli Friedman64f45a22011-11-01 02:23:42 +0000658 SL->setString(C,Str,Kind,Pascal);
659
Chris Lattner2085fd62009-02-18 06:40:38 +0000660 SL->TokLocs[0] = Loc[0];
661 SL->NumConcatenated = NumStrs;
Reid Spencer5f016e22007-07-11 17:01:13 +0000662
Chris Lattner726e1682009-02-18 05:49:11 +0000663 if (NumStrs != 1)
Chris Lattner2085fd62009-02-18 06:40:38 +0000664 memcpy(&SL->TokLocs[1], Loc+1, sizeof(SourceLocation)*(NumStrs-1));
665 return SL;
Chris Lattner726e1682009-02-18 05:49:11 +0000666}
667
Douglas Gregor673ecd62009-04-15 16:35:07 +0000668StringLiteral *StringLiteral::CreateEmpty(ASTContext &C, unsigned NumStrs) {
669 void *Mem = C.Allocate(sizeof(StringLiteral)+
670 sizeof(SourceLocation)*(NumStrs-1),
Chris Lattner32488542010-10-30 05:14:06 +0000671 llvm::alignOf<StringLiteral>());
Douglas Gregor673ecd62009-04-15 16:35:07 +0000672 StringLiteral *SL = new (Mem) StringLiteral(QualType());
Eli Friedman64f45a22011-11-01 02:23:42 +0000673 SL->CharByteWidth = 0;
674 SL->Length = 0;
Douglas Gregor673ecd62009-04-15 16:35:07 +0000675 SL->NumConcatenated = NumStrs;
676 return SL;
677}
678
Richard Trieu8ab09da2012-06-13 20:25:24 +0000679void StringLiteral::outputString(raw_ostream &OS) {
680 switch (getKind()) {
681 case Ascii: break; // no prefix.
682 case Wide: OS << 'L'; break;
683 case UTF8: OS << "u8"; break;
684 case UTF16: OS << 'u'; break;
685 case UTF32: OS << 'U'; break;
686 }
687 OS << '"';
688 static const char Hex[] = "0123456789ABCDEF";
689
690 unsigned LastSlashX = getLength();
691 for (unsigned I = 0, N = getLength(); I != N; ++I) {
692 switch (uint32_t Char = getCodeUnit(I)) {
693 default:
694 // FIXME: Convert UTF-8 back to codepoints before rendering.
695
696 // Convert UTF-16 surrogate pairs back to codepoints before rendering.
697 // Leave invalid surrogates alone; we'll use \x for those.
698 if (getKind() == UTF16 && I != N - 1 && Char >= 0xd800 &&
699 Char <= 0xdbff) {
700 uint32_t Trail = getCodeUnit(I + 1);
701 if (Trail >= 0xdc00 && Trail <= 0xdfff) {
702 Char = 0x10000 + ((Char - 0xd800) << 10) + (Trail - 0xdc00);
703 ++I;
704 }
705 }
706
707 if (Char > 0xff) {
708 // If this is a wide string, output characters over 0xff using \x
709 // escapes. Otherwise, this is a UTF-16 or UTF-32 string, and Char is a
710 // codepoint: use \x escapes for invalid codepoints.
711 if (getKind() == Wide ||
712 (Char >= 0xd800 && Char <= 0xdfff) || Char >= 0x110000) {
713 // FIXME: Is this the best way to print wchar_t?
714 OS << "\\x";
715 int Shift = 28;
716 while ((Char >> Shift) == 0)
717 Shift -= 4;
718 for (/**/; Shift >= 0; Shift -= 4)
719 OS << Hex[(Char >> Shift) & 15];
720 LastSlashX = I;
721 break;
722 }
723
724 if (Char > 0xffff)
725 OS << "\\U00"
726 << Hex[(Char >> 20) & 15]
727 << Hex[(Char >> 16) & 15];
728 else
729 OS << "\\u";
730 OS << Hex[(Char >> 12) & 15]
731 << Hex[(Char >> 8) & 15]
732 << Hex[(Char >> 4) & 15]
733 << Hex[(Char >> 0) & 15];
734 break;
735 }
736
737 // If we used \x... for the previous character, and this character is a
738 // hexadecimal digit, prevent it being slurped as part of the \x.
739 if (LastSlashX + 1 == I) {
740 switch (Char) {
741 case '0': case '1': case '2': case '3': case '4':
742 case '5': case '6': case '7': case '8': case '9':
743 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
744 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
745 OS << "\"\"";
746 }
747 }
748
749 assert(Char <= 0xff &&
750 "Characters above 0xff should already have been handled.");
751
752 if (isprint(Char))
753 OS << (char)Char;
754 else // Output anything hard as an octal escape.
755 OS << '\\'
756 << (char)('0' + ((Char >> 6) & 7))
757 << (char)('0' + ((Char >> 3) & 7))
758 << (char)('0' + ((Char >> 0) & 7));
759 break;
760 // Handle some common non-printable cases to make dumps prettier.
761 case '\\': OS << "\\\\"; break;
762 case '"': OS << "\\\""; break;
763 case '\n': OS << "\\n"; break;
764 case '\t': OS << "\\t"; break;
765 case '\a': OS << "\\a"; break;
766 case '\b': OS << "\\b"; break;
767 }
768 }
769 OS << '"';
770}
771
Eli Friedman64f45a22011-11-01 02:23:42 +0000772void StringLiteral::setString(ASTContext &C, StringRef Str,
773 StringKind Kind, bool IsPascal) {
774 //FIXME: we assume that the string data comes from a target that uses the same
775 // code unit size and endianess for the type of string.
776 this->Kind = Kind;
777 this->IsPascal = IsPascal;
778
Nick Lewycky0fd7f4d2012-02-24 09:07:53 +0000779 CharByteWidth = mapCharByteWidth(C.getTargetInfo(),Kind);
Eli Friedman64f45a22011-11-01 02:23:42 +0000780 assert((Str.size()%CharByteWidth == 0)
781 && "size of data must be multiple of CharByteWidth");
782 Length = Str.size()/CharByteWidth;
783
784 switch(CharByteWidth) {
785 case 1: {
786 char *AStrData = new (C) char[Length];
Argyrios Kyrtzidis66dfef12012-09-14 21:17:41 +0000787 std::memcpy(AStrData,Str.data(),Length*sizeof(*AStrData));
Eli Friedman64f45a22011-11-01 02:23:42 +0000788 StrData.asChar = AStrData;
789 break;
790 }
791 case 2: {
792 uint16_t *AStrData = new (C) uint16_t[Length];
Argyrios Kyrtzidis66dfef12012-09-14 21:17:41 +0000793 std::memcpy(AStrData,Str.data(),Length*sizeof(*AStrData));
Eli Friedman64f45a22011-11-01 02:23:42 +0000794 StrData.asUInt16 = AStrData;
795 break;
796 }
797 case 4: {
798 uint32_t *AStrData = new (C) uint32_t[Length];
Argyrios Kyrtzidis66dfef12012-09-14 21:17:41 +0000799 std::memcpy(AStrData,Str.data(),Length*sizeof(*AStrData));
Eli Friedman64f45a22011-11-01 02:23:42 +0000800 StrData.asUInt32 = AStrData;
801 break;
802 }
803 default:
804 assert(false && "unsupported CharByteWidth");
805 }
Douglas Gregor673ecd62009-04-15 16:35:07 +0000806}
807
Chris Lattner08f92e32010-11-17 07:37:15 +0000808/// getLocationOfByte - Return a source location that points to the specified
809/// byte of this string literal.
810///
811/// Strings are amazingly complex. They can be formed from multiple tokens and
812/// can have escape sequences in them in addition to the usual trigraph and
813/// escaped newline business. This routine handles this complexity.
814///
815SourceLocation StringLiteral::
816getLocationOfByte(unsigned ByteNo, const SourceManager &SM,
817 const LangOptions &Features, const TargetInfo &Target) const {
Richard Smithdf9ef1b2012-06-13 05:37:23 +0000818 assert((Kind == StringLiteral::Ascii || Kind == StringLiteral::UTF8) &&
819 "Only narrow string literals are currently supported");
Douglas Gregor5cee1192011-07-27 05:40:30 +0000820
Chris Lattner08f92e32010-11-17 07:37:15 +0000821 // Loop over all of the tokens in this string until we find the one that
822 // contains the byte we're looking for.
823 unsigned TokNo = 0;
824 while (1) {
825 assert(TokNo < getNumConcatenated() && "Invalid byte number!");
826 SourceLocation StrTokLoc = getStrTokenLoc(TokNo);
827
828 // Get the spelling of the string so that we can get the data that makes up
829 // the string literal, not the identifier for the macro it is potentially
830 // expanded through.
831 SourceLocation StrTokSpellingLoc = SM.getSpellingLoc(StrTokLoc);
832
833 // Re-lex the token to get its length and original spelling.
834 std::pair<FileID, unsigned> LocInfo =SM.getDecomposedLoc(StrTokSpellingLoc);
835 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000836 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
Chris Lattner08f92e32010-11-17 07:37:15 +0000837 if (Invalid)
838 return StrTokSpellingLoc;
839
840 const char *StrData = Buffer.data()+LocInfo.second;
841
Chris Lattner08f92e32010-11-17 07:37:15 +0000842 // Create a lexer starting at the beginning of this token.
Argyrios Kyrtzidisdf875582012-05-11 21:39:18 +0000843 Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), Features,
844 Buffer.begin(), StrData, Buffer.end());
Chris Lattner08f92e32010-11-17 07:37:15 +0000845 Token TheTok;
846 TheLexer.LexFromRawLexer(TheTok);
847
848 // Use the StringLiteralParser to compute the length of the string in bytes.
849 StringLiteralParser SLP(&TheTok, 1, SM, Features, Target);
850 unsigned TokNumBytes = SLP.GetStringLength();
851
852 // If the byte is in this token, return the location of the byte.
853 if (ByteNo < TokNumBytes ||
Hans Wennborg935a70c2011-06-30 20:17:41 +0000854 (ByteNo == TokNumBytes && TokNo == getNumConcatenated() - 1)) {
Chris Lattner08f92e32010-11-17 07:37:15 +0000855 unsigned Offset = SLP.getOffsetOfStringByte(TheTok, ByteNo);
856
857 // Now that we know the offset of the token in the spelling, use the
858 // preprocessor to get the offset in the original source.
859 return Lexer::AdvanceToTokenCharacter(StrTokLoc, Offset, SM, Features);
860 }
861
862 // Move to the next string token.
863 ++TokNo;
864 ByteNo -= TokNumBytes;
865 }
866}
867
868
869
Reid Spencer5f016e22007-07-11 17:01:13 +0000870/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
871/// corresponds to, e.g. "sizeof" or "[pre]++".
David Blaikie0bea8632012-10-08 01:11:04 +0000872StringRef UnaryOperator::getOpcodeStr(Opcode Op) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000873 switch (Op) {
John McCall2de56d12010-08-25 11:45:40 +0000874 case UO_PostInc: return "++";
875 case UO_PostDec: return "--";
876 case UO_PreInc: return "++";
877 case UO_PreDec: return "--";
878 case UO_AddrOf: return "&";
879 case UO_Deref: return "*";
880 case UO_Plus: return "+";
881 case UO_Minus: return "-";
882 case UO_Not: return "~";
883 case UO_LNot: return "!";
884 case UO_Real: return "__real";
885 case UO_Imag: return "__imag";
886 case UO_Extension: return "__extension__";
Reid Spencer5f016e22007-07-11 17:01:13 +0000887 }
David Blaikie561d3ab2012-01-17 02:30:50 +0000888 llvm_unreachable("Unknown unary operator");
Reid Spencer5f016e22007-07-11 17:01:13 +0000889}
890
John McCall2de56d12010-08-25 11:45:40 +0000891UnaryOperatorKind
Douglas Gregorbc736fc2009-03-13 23:49:33 +0000892UnaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix) {
893 switch (OO) {
David Blaikieb219cfc2011-09-23 05:06:16 +0000894 default: llvm_unreachable("No unary operator for overloaded function");
John McCall2de56d12010-08-25 11:45:40 +0000895 case OO_PlusPlus: return Postfix ? UO_PostInc : UO_PreInc;
896 case OO_MinusMinus: return Postfix ? UO_PostDec : UO_PreDec;
897 case OO_Amp: return UO_AddrOf;
898 case OO_Star: return UO_Deref;
899 case OO_Plus: return UO_Plus;
900 case OO_Minus: return UO_Minus;
901 case OO_Tilde: return UO_Not;
902 case OO_Exclaim: return UO_LNot;
Douglas Gregorbc736fc2009-03-13 23:49:33 +0000903 }
904}
905
906OverloadedOperatorKind UnaryOperator::getOverloadedOperator(Opcode Opc) {
907 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +0000908 case UO_PostInc: case UO_PreInc: return OO_PlusPlus;
909 case UO_PostDec: case UO_PreDec: return OO_MinusMinus;
910 case UO_AddrOf: return OO_Amp;
911 case UO_Deref: return OO_Star;
912 case UO_Plus: return OO_Plus;
913 case UO_Minus: return OO_Minus;
914 case UO_Not: return OO_Tilde;
915 case UO_LNot: return OO_Exclaim;
Douglas Gregorbc736fc2009-03-13 23:49:33 +0000916 default: return OO_None;
917 }
918}
919
920
Reid Spencer5f016e22007-07-11 17:01:13 +0000921//===----------------------------------------------------------------------===//
922// Postfix Operators.
923//===----------------------------------------------------------------------===//
924
Peter Collingbournecc324ad2011-02-08 21:18:02 +0000925CallExpr::CallExpr(ASTContext& C, StmtClass SC, Expr *fn, unsigned NumPreArgs,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +0000926 ArrayRef<Expr*> args, QualType t, ExprValueKind VK,
John McCallf89e55a2010-11-18 06:31:45 +0000927 SourceLocation rparenloc)
928 : Expr(SC, t, VK, OK_Ordinary,
Douglas Gregorbebbe0d2010-12-15 01:34:56 +0000929 fn->isTypeDependent(),
930 fn->isValueDependent(),
Douglas Gregor561f8122011-07-01 01:22:09 +0000931 fn->isInstantiationDependent(),
Douglas Gregorbebbe0d2010-12-15 01:34:56 +0000932 fn->containsUnexpandedParameterPack()),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +0000933 NumArgs(args.size()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000934
Benjamin Kramer3b6bef92012-08-24 11:54:20 +0000935 SubExprs = new (C) Stmt*[args.size()+PREARGS_START+NumPreArgs];
Douglas Gregorb4609802008-11-14 16:09:21 +0000936 SubExprs[FN] = fn;
Benjamin Kramer3b6bef92012-08-24 11:54:20 +0000937 for (unsigned i = 0; i != args.size(); ++i) {
Douglas Gregorbebbe0d2010-12-15 01:34:56 +0000938 if (args[i]->isTypeDependent())
939 ExprBits.TypeDependent = true;
940 if (args[i]->isValueDependent())
941 ExprBits.ValueDependent = true;
Douglas Gregor561f8122011-07-01 01:22:09 +0000942 if (args[i]->isInstantiationDependent())
943 ExprBits.InstantiationDependent = true;
Douglas Gregorbebbe0d2010-12-15 01:34:56 +0000944 if (args[i]->containsUnexpandedParameterPack())
945 ExprBits.ContainsUnexpandedParameterPack = true;
946
Peter Collingbournecc324ad2011-02-08 21:18:02 +0000947 SubExprs[i+PREARGS_START+NumPreArgs] = args[i];
Douglas Gregorbebbe0d2010-12-15 01:34:56 +0000948 }
Ted Kremenek668bf912009-02-09 20:51:47 +0000949
Peter Collingbournecc324ad2011-02-08 21:18:02 +0000950 CallExprBits.NumPreArgs = NumPreArgs;
Douglas Gregorb4609802008-11-14 16:09:21 +0000951 RParenLoc = rparenloc;
952}
Nate Begemane2ce1d92008-01-17 17:46:27 +0000953
Benjamin Kramer3b6bef92012-08-24 11:54:20 +0000954CallExpr::CallExpr(ASTContext& C, Expr *fn, ArrayRef<Expr*> args,
John McCallf89e55a2010-11-18 06:31:45 +0000955 QualType t, ExprValueKind VK, SourceLocation rparenloc)
956 : Expr(CallExprClass, t, VK, OK_Ordinary,
Douglas Gregorbebbe0d2010-12-15 01:34:56 +0000957 fn->isTypeDependent(),
958 fn->isValueDependent(),
Douglas Gregor561f8122011-07-01 01:22:09 +0000959 fn->isInstantiationDependent(),
Douglas Gregorbebbe0d2010-12-15 01:34:56 +0000960 fn->containsUnexpandedParameterPack()),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +0000961 NumArgs(args.size()) {
Ted Kremenek668bf912009-02-09 20:51:47 +0000962
Benjamin Kramer3b6bef92012-08-24 11:54:20 +0000963 SubExprs = new (C) Stmt*[args.size()+PREARGS_START];
Ted Kremenek77ed8e42007-08-24 18:13:47 +0000964 SubExprs[FN] = fn;
Benjamin Kramer3b6bef92012-08-24 11:54:20 +0000965 for (unsigned i = 0; i != args.size(); ++i) {
Douglas Gregorbebbe0d2010-12-15 01:34:56 +0000966 if (args[i]->isTypeDependent())
967 ExprBits.TypeDependent = true;
968 if (args[i]->isValueDependent())
969 ExprBits.ValueDependent = true;
Douglas Gregor561f8122011-07-01 01:22:09 +0000970 if (args[i]->isInstantiationDependent())
971 ExprBits.InstantiationDependent = true;
Douglas Gregorbebbe0d2010-12-15 01:34:56 +0000972 if (args[i]->containsUnexpandedParameterPack())
973 ExprBits.ContainsUnexpandedParameterPack = true;
974
Peter Collingbournecc324ad2011-02-08 21:18:02 +0000975 SubExprs[i+PREARGS_START] = args[i];
Douglas Gregorbebbe0d2010-12-15 01:34:56 +0000976 }
Ted Kremenek668bf912009-02-09 20:51:47 +0000977
Peter Collingbournecc324ad2011-02-08 21:18:02 +0000978 CallExprBits.NumPreArgs = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +0000979 RParenLoc = rparenloc;
980}
981
Mike Stump1eb44332009-09-09 15:08:12 +0000982CallExpr::CallExpr(ASTContext &C, StmtClass SC, EmptyShell Empty)
983 : Expr(SC, Empty), SubExprs(0), NumArgs(0) {
Douglas Gregorbebbe0d2010-12-15 01:34:56 +0000984 // FIXME: Why do we allocate this?
Peter Collingbournecc324ad2011-02-08 21:18:02 +0000985 SubExprs = new (C) Stmt*[PREARGS_START];
986 CallExprBits.NumPreArgs = 0;
987}
988
989CallExpr::CallExpr(ASTContext &C, StmtClass SC, unsigned NumPreArgs,
990 EmptyShell Empty)
991 : Expr(SC, Empty), SubExprs(0), NumArgs(0) {
992 // FIXME: Why do we allocate this?
993 SubExprs = new (C) Stmt*[PREARGS_START+NumPreArgs];
994 CallExprBits.NumPreArgs = NumPreArgs;
Douglas Gregor1f0d0132009-04-15 17:43:59 +0000995}
996
Nuno Lopesd20254f2009-12-20 23:11:08 +0000997Decl *CallExpr::getCalleeDecl() {
John McCalle8683d62011-09-13 23:08:34 +0000998 Expr *CEE = getCallee()->IgnoreParenImpCasts();
Douglas Gregor1ddc9c42011-09-06 21:41:04 +0000999
1000 while (SubstNonTypeTemplateParmExpr *NTTP
1001 = dyn_cast<SubstNonTypeTemplateParmExpr>(CEE)) {
1002 CEE = NTTP->getReplacement()->IgnoreParenCasts();
1003 }
1004
Sebastian Redl20012152010-09-10 20:55:30 +00001005 // If we're calling a dereference, look at the pointer instead.
1006 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CEE)) {
1007 if (BO->isPtrMemOp())
1008 CEE = BO->getRHS()->IgnoreParenCasts();
1009 } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(CEE)) {
1010 if (UO->getOpcode() == UO_Deref)
1011 CEE = UO->getSubExpr()->IgnoreParenCasts();
1012 }
Chris Lattner6346f962009-07-17 15:46:27 +00001013 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CEE))
Nuno Lopesd20254f2009-12-20 23:11:08 +00001014 return DRE->getDecl();
Nuno Lopescb1c77f2009-12-24 00:28:18 +00001015 if (MemberExpr *ME = dyn_cast<MemberExpr>(CEE))
1016 return ME->getMemberDecl();
Zhongxing Xua0042542009-07-17 07:29:51 +00001017
1018 return 0;
1019}
1020
Nuno Lopesd20254f2009-12-20 23:11:08 +00001021FunctionDecl *CallExpr::getDirectCallee() {
Chris Lattnercaabf9b2009-12-21 01:10:56 +00001022 return dyn_cast_or_null<FunctionDecl>(getCalleeDecl());
Nuno Lopesd20254f2009-12-20 23:11:08 +00001023}
1024
Chris Lattnerd18b3292007-12-28 05:25:02 +00001025/// setNumArgs - This changes the number of arguments present in this call.
1026/// Any orphaned expressions are deleted by this, and any new operands are set
1027/// to null.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001028void CallExpr::setNumArgs(ASTContext& C, unsigned NumArgs) {
Chris Lattnerd18b3292007-12-28 05:25:02 +00001029 // No change, just return.
1030 if (NumArgs == getNumArgs()) return;
Mike Stump1eb44332009-09-09 15:08:12 +00001031
Chris Lattnerd18b3292007-12-28 05:25:02 +00001032 // If shrinking # arguments, just delete the extras and forgot them.
1033 if (NumArgs < getNumArgs()) {
Chris Lattnerd18b3292007-12-28 05:25:02 +00001034 this->NumArgs = NumArgs;
1035 return;
1036 }
1037
1038 // Otherwise, we are growing the # arguments. New an bigger argument array.
Peter Collingbournecc324ad2011-02-08 21:18:02 +00001039 unsigned NumPreArgs = getNumPreArgs();
1040 Stmt **NewSubExprs = new (C) Stmt*[NumArgs+PREARGS_START+NumPreArgs];
Chris Lattnerd18b3292007-12-28 05:25:02 +00001041 // Copy over args.
Peter Collingbournecc324ad2011-02-08 21:18:02 +00001042 for (unsigned i = 0; i != getNumArgs()+PREARGS_START+NumPreArgs; ++i)
Chris Lattnerd18b3292007-12-28 05:25:02 +00001043 NewSubExprs[i] = SubExprs[i];
1044 // Null out new args.
Peter Collingbournecc324ad2011-02-08 21:18:02 +00001045 for (unsigned i = getNumArgs()+PREARGS_START+NumPreArgs;
1046 i != NumArgs+PREARGS_START+NumPreArgs; ++i)
Chris Lattnerd18b3292007-12-28 05:25:02 +00001047 NewSubExprs[i] = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001048
Douglas Gregor88c9a462009-04-17 21:46:47 +00001049 if (SubExprs) C.Deallocate(SubExprs);
Chris Lattnerd18b3292007-12-28 05:25:02 +00001050 SubExprs = NewSubExprs;
1051 this->NumArgs = NumArgs;
1052}
1053
Chris Lattnercb888962008-10-06 05:00:53 +00001054/// isBuiltinCall - If this is a call to a builtin, return the builtin ID. If
1055/// not, return 0.
Richard Smith180f4792011-11-10 06:34:14 +00001056unsigned CallExpr::isBuiltinCall() const {
Steve Naroffc4f8e8b2008-01-31 01:07:12 +00001057 // All simple function calls (e.g. func()) are implicitly cast to pointer to
Mike Stump1eb44332009-09-09 15:08:12 +00001058 // function. As a result, we try and obtain the DeclRefExpr from the
Steve Naroffc4f8e8b2008-01-31 01:07:12 +00001059 // ImplicitCastExpr.
1060 const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(getCallee());
1061 if (!ICE) // FIXME: deal with more complex calls (e.g. (func)(), (*func)()).
Chris Lattnercb888962008-10-06 05:00:53 +00001062 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001063
Steve Naroffc4f8e8b2008-01-31 01:07:12 +00001064 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr());
1065 if (!DRE)
Chris Lattnercb888962008-10-06 05:00:53 +00001066 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001067
Anders Carlssonbcba2012008-01-31 02:13:57 +00001068 const FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
1069 if (!FDecl)
Chris Lattnercb888962008-10-06 05:00:53 +00001070 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001071
Douglas Gregor4fcd3992008-11-21 15:30:19 +00001072 if (!FDecl->getIdentifier())
1073 return 0;
1074
Douglas Gregor7814e6d2009-09-12 00:22:50 +00001075 return FDecl->getBuiltinID();
Chris Lattnercb888962008-10-06 05:00:53 +00001076}
Anders Carlssonbcba2012008-01-31 02:13:57 +00001077
Anders Carlsson6dde78f2009-05-26 04:57:27 +00001078QualType CallExpr::getCallReturnType() const {
1079 QualType CalleeType = getCallee()->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001080 if (const PointerType *FnTypePtr = CalleeType->getAs<PointerType>())
Anders Carlsson6dde78f2009-05-26 04:57:27 +00001081 CalleeType = FnTypePtr->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001082 else if (const BlockPointerType *BPT = CalleeType->getAs<BlockPointerType>())
Anders Carlsson6dde78f2009-05-26 04:57:27 +00001083 CalleeType = BPT->getPointeeType();
John McCall864c0412011-04-26 20:42:42 +00001084 else if (CalleeType->isSpecificPlaceholderType(BuiltinType::BoundMember))
1085 // This should never be overloaded and so should never return null.
1086 CalleeType = Expr::findBoundMemberType(getCallee());
Douglas Gregor5291c3c2010-07-13 08:18:22 +00001087
John McCall864c0412011-04-26 20:42:42 +00001088 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
Anders Carlsson6dde78f2009-05-26 04:57:27 +00001089 return FnType->getResultType();
1090}
Chris Lattnercb888962008-10-06 05:00:53 +00001091
John McCall2882eca2011-02-21 06:23:05 +00001092SourceRange CallExpr::getSourceRange() const {
1093 if (isa<CXXOperatorCallExpr>(this))
1094 return cast<CXXOperatorCallExpr>(this)->getSourceRange();
1095
1096 SourceLocation begin = getCallee()->getLocStart();
1097 if (begin.isInvalid() && getNumArgs() > 0)
1098 begin = getArg(0)->getLocStart();
1099 SourceLocation end = getRParenLoc();
1100 if (end.isInvalid() && getNumArgs() > 0)
1101 end = getArg(getNumArgs() - 1)->getLocEnd();
1102 return SourceRange(begin, end);
1103}
Daniel Dunbar8fbc6d22012-03-09 15:39:24 +00001104SourceLocation CallExpr::getLocStart() const {
1105 if (isa<CXXOperatorCallExpr>(this))
1106 return cast<CXXOperatorCallExpr>(this)->getSourceRange().getBegin();
1107
1108 SourceLocation begin = getCallee()->getLocStart();
1109 if (begin.isInvalid() && getNumArgs() > 0)
1110 begin = getArg(0)->getLocStart();
1111 return begin;
1112}
1113SourceLocation CallExpr::getLocEnd() const {
1114 if (isa<CXXOperatorCallExpr>(this))
1115 return cast<CXXOperatorCallExpr>(this)->getSourceRange().getEnd();
1116
1117 SourceLocation end = getRParenLoc();
1118 if (end.isInvalid() && getNumArgs() > 0)
1119 end = getArg(getNumArgs() - 1)->getLocEnd();
1120 return end;
1121}
John McCall2882eca2011-02-21 06:23:05 +00001122
Sean Huntc3021132010-05-05 15:23:54 +00001123OffsetOfExpr *OffsetOfExpr::Create(ASTContext &C, QualType type,
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001124 SourceLocation OperatorLoc,
Sean Huntc3021132010-05-05 15:23:54 +00001125 TypeSourceInfo *tsi,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00001126 ArrayRef<OffsetOfNode> comps,
1127 ArrayRef<Expr*> exprs,
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001128 SourceLocation RParenLoc) {
1129 void *Mem = C.Allocate(sizeof(OffsetOfExpr) +
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00001130 sizeof(OffsetOfNode) * comps.size() +
1131 sizeof(Expr*) * exprs.size());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001132
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00001133 return new (Mem) OffsetOfExpr(C, type, OperatorLoc, tsi, comps, exprs,
1134 RParenLoc);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001135}
1136
1137OffsetOfExpr *OffsetOfExpr::CreateEmpty(ASTContext &C,
1138 unsigned numComps, unsigned numExprs) {
1139 void *Mem = C.Allocate(sizeof(OffsetOfExpr) +
1140 sizeof(OffsetOfNode) * numComps +
1141 sizeof(Expr*) * numExprs);
1142 return new (Mem) OffsetOfExpr(numComps, numExprs);
1143}
1144
Sean Huntc3021132010-05-05 15:23:54 +00001145OffsetOfExpr::OffsetOfExpr(ASTContext &C, QualType type,
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001146 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00001147 ArrayRef<OffsetOfNode> comps, ArrayRef<Expr*> exprs,
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001148 SourceLocation RParenLoc)
John McCallf89e55a2010-11-18 06:31:45 +00001149 : Expr(OffsetOfExprClass, type, VK_RValue, OK_Ordinary,
1150 /*TypeDependent=*/false,
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00001151 /*ValueDependent=*/tsi->getType()->isDependentType(),
Douglas Gregor561f8122011-07-01 01:22:09 +00001152 tsi->getType()->isInstantiationDependentType(),
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00001153 tsi->getType()->containsUnexpandedParameterPack()),
Sean Huntc3021132010-05-05 15:23:54 +00001154 OperatorLoc(OperatorLoc), RParenLoc(RParenLoc), TSInfo(tsi),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00001155 NumComps(comps.size()), NumExprs(exprs.size())
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001156{
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00001157 for (unsigned i = 0; i != comps.size(); ++i) {
1158 setComponent(i, comps[i]);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001159 }
Sean Huntc3021132010-05-05 15:23:54 +00001160
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00001161 for (unsigned i = 0; i != exprs.size(); ++i) {
1162 if (exprs[i]->isTypeDependent() || exprs[i]->isValueDependent())
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00001163 ExprBits.ValueDependent = true;
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00001164 if (exprs[i]->containsUnexpandedParameterPack())
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00001165 ExprBits.ContainsUnexpandedParameterPack = true;
1166
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00001167 setIndexExpr(i, exprs[i]);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001168 }
1169}
1170
1171IdentifierInfo *OffsetOfExpr::OffsetOfNode::getFieldName() const {
1172 assert(getKind() == Field || getKind() == Identifier);
1173 if (getKind() == Field)
1174 return getField()->getIdentifier();
Sean Huntc3021132010-05-05 15:23:54 +00001175
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001176 return reinterpret_cast<IdentifierInfo *> (Data & ~(uintptr_t)Mask);
1177}
1178
Mike Stump1eb44332009-09-09 15:08:12 +00001179MemberExpr *MemberExpr::Create(ASTContext &C, Expr *base, bool isarrow,
Douglas Gregor40d96a62011-02-28 21:54:11 +00001180 NestedNameSpecifierLoc QualifierLoc,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001181 SourceLocation TemplateKWLoc,
Eli Friedmanf595cc42009-12-04 06:40:45 +00001182 ValueDecl *memberdecl,
John McCall161755a2010-04-06 21:38:20 +00001183 DeclAccessPair founddecl,
Abramo Bagnara25777432010-08-11 22:01:17 +00001184 DeclarationNameInfo nameinfo,
John McCalld5532b62009-11-23 01:53:49 +00001185 const TemplateArgumentListInfo *targs,
John McCallf89e55a2010-11-18 06:31:45 +00001186 QualType ty,
1187 ExprValueKind vk,
1188 ExprObjectKind ok) {
Douglas Gregor83f6faf2009-08-31 23:41:50 +00001189 std::size_t Size = sizeof(MemberExpr);
John McCall6bb80172010-03-30 21:47:33 +00001190
Douglas Gregor40d96a62011-02-28 21:54:11 +00001191 bool hasQualOrFound = (QualifierLoc ||
John McCall161755a2010-04-06 21:38:20 +00001192 founddecl.getDecl() != memberdecl ||
1193 founddecl.getAccess() != memberdecl->getAccess());
John McCall6bb80172010-03-30 21:47:33 +00001194 if (hasQualOrFound)
1195 Size += sizeof(MemberNameQualifier);
Mike Stump1eb44332009-09-09 15:08:12 +00001196
John McCalld5532b62009-11-23 01:53:49 +00001197 if (targs)
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001198 Size += ASTTemplateKWAndArgsInfo::sizeFor(targs->size());
1199 else if (TemplateKWLoc.isValid())
1200 Size += ASTTemplateKWAndArgsInfo::sizeFor(0);
Mike Stump1eb44332009-09-09 15:08:12 +00001201
Chris Lattner32488542010-10-30 05:14:06 +00001202 void *Mem = C.Allocate(Size, llvm::alignOf<MemberExpr>());
John McCallf89e55a2010-11-18 06:31:45 +00001203 MemberExpr *E = new (Mem) MemberExpr(base, isarrow, memberdecl, nameinfo,
1204 ty, vk, ok);
John McCall6bb80172010-03-30 21:47:33 +00001205
1206 if (hasQualOrFound) {
Douglas Gregor40d96a62011-02-28 21:54:11 +00001207 // FIXME: Wrong. We should be looking at the member declaration we found.
1208 if (QualifierLoc && QualifierLoc.getNestedNameSpecifier()->isDependent()) {
John McCall6bb80172010-03-30 21:47:33 +00001209 E->setValueDependent(true);
1210 E->setTypeDependent(true);
Douglas Gregor561f8122011-07-01 01:22:09 +00001211 E->setInstantiationDependent(true);
1212 }
1213 else if (QualifierLoc &&
1214 QualifierLoc.getNestedNameSpecifier()->isInstantiationDependent())
1215 E->setInstantiationDependent(true);
1216
John McCall6bb80172010-03-30 21:47:33 +00001217 E->HasQualifierOrFoundDecl = true;
1218
1219 MemberNameQualifier *NQ = E->getMemberQualifier();
Douglas Gregor40d96a62011-02-28 21:54:11 +00001220 NQ->QualifierLoc = QualifierLoc;
John McCall6bb80172010-03-30 21:47:33 +00001221 NQ->FoundDecl = founddecl;
1222 }
1223
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001224 E->HasTemplateKWAndArgsInfo = (targs || TemplateKWLoc.isValid());
1225
John McCall6bb80172010-03-30 21:47:33 +00001226 if (targs) {
Douglas Gregor561f8122011-07-01 01:22:09 +00001227 bool Dependent = false;
1228 bool InstantiationDependent = false;
1229 bool ContainsUnexpandedParameterPack = false;
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001230 E->getTemplateKWAndArgsInfo()->initializeFrom(TemplateKWLoc, *targs,
1231 Dependent,
1232 InstantiationDependent,
1233 ContainsUnexpandedParameterPack);
Douglas Gregor561f8122011-07-01 01:22:09 +00001234 if (InstantiationDependent)
1235 E->setInstantiationDependent(true);
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001236 } else if (TemplateKWLoc.isValid()) {
1237 E->getTemplateKWAndArgsInfo()->initializeFrom(TemplateKWLoc);
John McCall6bb80172010-03-30 21:47:33 +00001238 }
1239
1240 return E;
Douglas Gregor83f6faf2009-08-31 23:41:50 +00001241}
1242
Douglas Gregor75e85042011-03-02 21:06:53 +00001243SourceRange MemberExpr::getSourceRange() const {
Daniel Dunbar396ec672012-03-09 15:39:15 +00001244 return SourceRange(getLocStart(), getLocEnd());
1245}
1246SourceLocation MemberExpr::getLocStart() const {
Douglas Gregor75e85042011-03-02 21:06:53 +00001247 if (isImplicitAccess()) {
1248 if (hasQualifier())
Daniel Dunbar396ec672012-03-09 15:39:15 +00001249 return getQualifierLoc().getBeginLoc();
1250 return MemberLoc;
Douglas Gregor75e85042011-03-02 21:06:53 +00001251 }
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001252
Daniel Dunbar396ec672012-03-09 15:39:15 +00001253 // FIXME: We don't want this to happen. Rather, we should be able to
1254 // detect all kinds of implicit accesses more cleanly.
1255 SourceLocation BaseStartLoc = getBase()->getLocStart();
1256 if (BaseStartLoc.isValid())
1257 return BaseStartLoc;
1258 return MemberLoc;
1259}
1260SourceLocation MemberExpr::getLocEnd() const {
1261 if (hasExplicitTemplateArgs())
1262 return getRAngleLoc();
1263 return getMemberNameInfo().getEndLoc();
Douglas Gregor75e85042011-03-02 21:06:53 +00001264}
1265
John McCall1d9b3b22011-09-09 05:25:32 +00001266void CastExpr::CheckCastConsistency() const {
1267 switch (getCastKind()) {
1268 case CK_DerivedToBase:
1269 case CK_UncheckedDerivedToBase:
1270 case CK_DerivedToBaseMemberPointer:
1271 case CK_BaseToDerived:
1272 case CK_BaseToDerivedMemberPointer:
1273 assert(!path_empty() && "Cast kind should have a base path!");
1274 break;
1275
1276 case CK_CPointerToObjCPointerCast:
1277 assert(getType()->isObjCObjectPointerType());
1278 assert(getSubExpr()->getType()->isPointerType());
1279 goto CheckNoBasePath;
1280
1281 case CK_BlockPointerToObjCPointerCast:
1282 assert(getType()->isObjCObjectPointerType());
1283 assert(getSubExpr()->getType()->isBlockPointerType());
1284 goto CheckNoBasePath;
1285
John McCall4d4e5c12012-02-15 01:22:51 +00001286 case CK_ReinterpretMemberPointer:
1287 assert(getType()->isMemberPointerType());
1288 assert(getSubExpr()->getType()->isMemberPointerType());
1289 goto CheckNoBasePath;
1290
John McCall1d9b3b22011-09-09 05:25:32 +00001291 case CK_BitCast:
1292 // Arbitrary casts to C pointer types count as bitcasts.
1293 // Otherwise, we should only have block and ObjC pointer casts
1294 // here if they stay within the type kind.
1295 if (!getType()->isPointerType()) {
1296 assert(getType()->isObjCObjectPointerType() ==
1297 getSubExpr()->getType()->isObjCObjectPointerType());
1298 assert(getType()->isBlockPointerType() ==
1299 getSubExpr()->getType()->isBlockPointerType());
1300 }
1301 goto CheckNoBasePath;
1302
1303 case CK_AnyPointerToBlockPointerCast:
1304 assert(getType()->isBlockPointerType());
1305 assert(getSubExpr()->getType()->isAnyPointerType() &&
1306 !getSubExpr()->getType()->isBlockPointerType());
1307 goto CheckNoBasePath;
1308
Douglas Gregorac1303e2012-02-22 05:02:47 +00001309 case CK_CopyAndAutoreleaseBlockObject:
1310 assert(getType()->isBlockPointerType());
1311 assert(getSubExpr()->getType()->isBlockPointerType());
1312 goto CheckNoBasePath;
Eli Friedmana6c66ce2012-08-31 00:14:07 +00001313
1314 case CK_FunctionToPointerDecay:
1315 assert(getType()->isPointerType());
1316 assert(getSubExpr()->getType()->isFunctionType());
1317 goto CheckNoBasePath;
1318
John McCall1d9b3b22011-09-09 05:25:32 +00001319 // These should not have an inheritance path.
1320 case CK_Dynamic:
1321 case CK_ToUnion:
1322 case CK_ArrayToPointerDecay:
John McCall1d9b3b22011-09-09 05:25:32 +00001323 case CK_NullToMemberPointer:
1324 case CK_NullToPointer:
1325 case CK_ConstructorConversion:
1326 case CK_IntegralToPointer:
1327 case CK_PointerToIntegral:
1328 case CK_ToVoid:
1329 case CK_VectorSplat:
1330 case CK_IntegralCast:
1331 case CK_IntegralToFloating:
1332 case CK_FloatingToIntegral:
1333 case CK_FloatingCast:
1334 case CK_ObjCObjectLValueCast:
1335 case CK_FloatingRealToComplex:
1336 case CK_FloatingComplexToReal:
1337 case CK_FloatingComplexCast:
1338 case CK_FloatingComplexToIntegralComplex:
1339 case CK_IntegralRealToComplex:
1340 case CK_IntegralComplexToReal:
1341 case CK_IntegralComplexCast:
1342 case CK_IntegralComplexToFloatingComplex:
John McCall33e56f32011-09-10 06:18:15 +00001343 case CK_ARCProduceObject:
1344 case CK_ARCConsumeObject:
1345 case CK_ARCReclaimReturnedObject:
1346 case CK_ARCExtendBlockObject:
John McCall1d9b3b22011-09-09 05:25:32 +00001347 assert(!getType()->isBooleanType() && "unheralded conversion to bool");
1348 goto CheckNoBasePath;
1349
1350 case CK_Dependent:
1351 case CK_LValueToRValue:
John McCall1d9b3b22011-09-09 05:25:32 +00001352 case CK_NoOp:
David Chisnall7a7ee302012-01-16 17:27:18 +00001353 case CK_AtomicToNonAtomic:
1354 case CK_NonAtomicToAtomic:
John McCall1d9b3b22011-09-09 05:25:32 +00001355 case CK_PointerToBoolean:
1356 case CK_IntegralToBoolean:
1357 case CK_FloatingToBoolean:
1358 case CK_MemberPointerToBoolean:
1359 case CK_FloatingComplexToBoolean:
1360 case CK_IntegralComplexToBoolean:
1361 case CK_LValueBitCast: // -> bool&
1362 case CK_UserDefinedConversion: // operator bool()
Eli Friedmana6c66ce2012-08-31 00:14:07 +00001363 case CK_BuiltinFnToFnPtr:
John McCall1d9b3b22011-09-09 05:25:32 +00001364 CheckNoBasePath:
1365 assert(path_empty() && "Cast kind should not have a base path!");
1366 break;
1367 }
1368}
1369
Anders Carlssonf8ec55a2009-09-03 00:59:21 +00001370const char *CastExpr::getCastKindName() const {
1371 switch (getCastKind()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00001372 case CK_Dependent:
1373 return "Dependent";
John McCall2de56d12010-08-25 11:45:40 +00001374 case CK_BitCast:
Anders Carlssonf8ec55a2009-09-03 00:59:21 +00001375 return "BitCast";
John McCall2de56d12010-08-25 11:45:40 +00001376 case CK_LValueBitCast:
Douglas Gregore39a3892010-07-13 23:17:26 +00001377 return "LValueBitCast";
John McCall0ae287a2010-12-01 04:43:34 +00001378 case CK_LValueToRValue:
1379 return "LValueToRValue";
John McCall2de56d12010-08-25 11:45:40 +00001380 case CK_NoOp:
Anders Carlssonf8ec55a2009-09-03 00:59:21 +00001381 return "NoOp";
John McCall2de56d12010-08-25 11:45:40 +00001382 case CK_BaseToDerived:
Anders Carlsson11de6de2009-11-12 16:43:42 +00001383 return "BaseToDerived";
John McCall2de56d12010-08-25 11:45:40 +00001384 case CK_DerivedToBase:
Anders Carlssonf8ec55a2009-09-03 00:59:21 +00001385 return "DerivedToBase";
John McCall2de56d12010-08-25 11:45:40 +00001386 case CK_UncheckedDerivedToBase:
John McCall23cba802010-03-30 23:58:03 +00001387 return "UncheckedDerivedToBase";
John McCall2de56d12010-08-25 11:45:40 +00001388 case CK_Dynamic:
Anders Carlssonf8ec55a2009-09-03 00:59:21 +00001389 return "Dynamic";
John McCall2de56d12010-08-25 11:45:40 +00001390 case CK_ToUnion:
Anders Carlssonf8ec55a2009-09-03 00:59:21 +00001391 return "ToUnion";
John McCall2de56d12010-08-25 11:45:40 +00001392 case CK_ArrayToPointerDecay:
Anders Carlssonf8ec55a2009-09-03 00:59:21 +00001393 return "ArrayToPointerDecay";
John McCall2de56d12010-08-25 11:45:40 +00001394 case CK_FunctionToPointerDecay:
Anders Carlssonf8ec55a2009-09-03 00:59:21 +00001395 return "FunctionToPointerDecay";
John McCall2de56d12010-08-25 11:45:40 +00001396 case CK_NullToMemberPointer:
Anders Carlssonf8ec55a2009-09-03 00:59:21 +00001397 return "NullToMemberPointer";
John McCall404cd162010-11-13 01:35:44 +00001398 case CK_NullToPointer:
1399 return "NullToPointer";
John McCall2de56d12010-08-25 11:45:40 +00001400 case CK_BaseToDerivedMemberPointer:
Anders Carlssonf8ec55a2009-09-03 00:59:21 +00001401 return "BaseToDerivedMemberPointer";
John McCall2de56d12010-08-25 11:45:40 +00001402 case CK_DerivedToBaseMemberPointer:
Anders Carlsson1a31a182009-10-30 00:46:35 +00001403 return "DerivedToBaseMemberPointer";
John McCall4d4e5c12012-02-15 01:22:51 +00001404 case CK_ReinterpretMemberPointer:
1405 return "ReinterpretMemberPointer";
John McCall2de56d12010-08-25 11:45:40 +00001406 case CK_UserDefinedConversion:
Anders Carlssonf8ec55a2009-09-03 00:59:21 +00001407 return "UserDefinedConversion";
John McCall2de56d12010-08-25 11:45:40 +00001408 case CK_ConstructorConversion:
Anders Carlssonf8ec55a2009-09-03 00:59:21 +00001409 return "ConstructorConversion";
John McCall2de56d12010-08-25 11:45:40 +00001410 case CK_IntegralToPointer:
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001411 return "IntegralToPointer";
John McCall2de56d12010-08-25 11:45:40 +00001412 case CK_PointerToIntegral:
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001413 return "PointerToIntegral";
John McCalldaa8e4e2010-11-15 09:13:47 +00001414 case CK_PointerToBoolean:
1415 return "PointerToBoolean";
John McCall2de56d12010-08-25 11:45:40 +00001416 case CK_ToVoid:
Anders Carlssonebeaf202009-10-16 02:35:04 +00001417 return "ToVoid";
John McCall2de56d12010-08-25 11:45:40 +00001418 case CK_VectorSplat:
Anders Carlsson16a89042009-10-16 05:23:41 +00001419 return "VectorSplat";
John McCall2de56d12010-08-25 11:45:40 +00001420 case CK_IntegralCast:
Anders Carlsson82debc72009-10-18 18:12:03 +00001421 return "IntegralCast";
John McCalldaa8e4e2010-11-15 09:13:47 +00001422 case CK_IntegralToBoolean:
1423 return "IntegralToBoolean";
John McCall2de56d12010-08-25 11:45:40 +00001424 case CK_IntegralToFloating:
Anders Carlsson82debc72009-10-18 18:12:03 +00001425 return "IntegralToFloating";
John McCall2de56d12010-08-25 11:45:40 +00001426 case CK_FloatingToIntegral:
Anders Carlsson82debc72009-10-18 18:12:03 +00001427 return "FloatingToIntegral";
John McCall2de56d12010-08-25 11:45:40 +00001428 case CK_FloatingCast:
Benjamin Kramerc6b29162009-10-18 19:02:15 +00001429 return "FloatingCast";
John McCalldaa8e4e2010-11-15 09:13:47 +00001430 case CK_FloatingToBoolean:
1431 return "FloatingToBoolean";
John McCall2de56d12010-08-25 11:45:40 +00001432 case CK_MemberPointerToBoolean:
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001433 return "MemberPointerToBoolean";
John McCall1d9b3b22011-09-09 05:25:32 +00001434 case CK_CPointerToObjCPointerCast:
1435 return "CPointerToObjCPointerCast";
1436 case CK_BlockPointerToObjCPointerCast:
1437 return "BlockPointerToObjCPointerCast";
John McCall2de56d12010-08-25 11:45:40 +00001438 case CK_AnyPointerToBlockPointerCast:
Fariborz Jahanian3b27f1a2009-12-11 22:40:48 +00001439 return "AnyPointerToBlockPointerCast";
John McCall2de56d12010-08-25 11:45:40 +00001440 case CK_ObjCObjectLValueCast:
Douglas Gregor569c3162010-08-07 11:51:51 +00001441 return "ObjCObjectLValueCast";
John McCall2bb5d002010-11-13 09:02:35 +00001442 case CK_FloatingRealToComplex:
1443 return "FloatingRealToComplex";
John McCallf3ea8cf2010-11-14 08:17:51 +00001444 case CK_FloatingComplexToReal:
1445 return "FloatingComplexToReal";
1446 case CK_FloatingComplexToBoolean:
1447 return "FloatingComplexToBoolean";
John McCall2bb5d002010-11-13 09:02:35 +00001448 case CK_FloatingComplexCast:
1449 return "FloatingComplexCast";
John McCallf3ea8cf2010-11-14 08:17:51 +00001450 case CK_FloatingComplexToIntegralComplex:
1451 return "FloatingComplexToIntegralComplex";
John McCall2bb5d002010-11-13 09:02:35 +00001452 case CK_IntegralRealToComplex:
1453 return "IntegralRealToComplex";
John McCallf3ea8cf2010-11-14 08:17:51 +00001454 case CK_IntegralComplexToReal:
1455 return "IntegralComplexToReal";
1456 case CK_IntegralComplexToBoolean:
1457 return "IntegralComplexToBoolean";
John McCall2bb5d002010-11-13 09:02:35 +00001458 case CK_IntegralComplexCast:
1459 return "IntegralComplexCast";
John McCallf3ea8cf2010-11-14 08:17:51 +00001460 case CK_IntegralComplexToFloatingComplex:
1461 return "IntegralComplexToFloatingComplex";
John McCall33e56f32011-09-10 06:18:15 +00001462 case CK_ARCConsumeObject:
1463 return "ARCConsumeObject";
1464 case CK_ARCProduceObject:
1465 return "ARCProduceObject";
1466 case CK_ARCReclaimReturnedObject:
1467 return "ARCReclaimReturnedObject";
1468 case CK_ARCExtendBlockObject:
1469 return "ARCCExtendBlockObject";
David Chisnall7a7ee302012-01-16 17:27:18 +00001470 case CK_AtomicToNonAtomic:
1471 return "AtomicToNonAtomic";
1472 case CK_NonAtomicToAtomic:
1473 return "NonAtomicToAtomic";
Douglas Gregorac1303e2012-02-22 05:02:47 +00001474 case CK_CopyAndAutoreleaseBlockObject:
1475 return "CopyAndAutoreleaseBlockObject";
Eli Friedmana6c66ce2012-08-31 00:14:07 +00001476 case CK_BuiltinFnToFnPtr:
1477 return "BuiltinFnToFnPtr";
Anders Carlssonf8ec55a2009-09-03 00:59:21 +00001478 }
Mike Stump1eb44332009-09-09 15:08:12 +00001479
John McCall2bb5d002010-11-13 09:02:35 +00001480 llvm_unreachable("Unhandled cast kind!");
Anders Carlssonf8ec55a2009-09-03 00:59:21 +00001481}
1482
Douglas Gregor6eef5192009-12-14 19:27:10 +00001483Expr *CastExpr::getSubExprAsWritten() {
1484 Expr *SubExpr = 0;
1485 CastExpr *E = this;
1486 do {
1487 SubExpr = E->getSubExpr();
Douglas Gregor03e80032011-06-21 17:03:29 +00001488
1489 // Skip through reference binding to temporary.
1490 if (MaterializeTemporaryExpr *Materialize
1491 = dyn_cast<MaterializeTemporaryExpr>(SubExpr))
1492 SubExpr = Materialize->GetTemporaryExpr();
1493
Douglas Gregor6eef5192009-12-14 19:27:10 +00001494 // Skip any temporary bindings; they're implicit.
1495 if (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(SubExpr))
1496 SubExpr = Binder->getSubExpr();
Sean Huntc3021132010-05-05 15:23:54 +00001497
Douglas Gregor6eef5192009-12-14 19:27:10 +00001498 // Conversions by constructor and conversion functions have a
1499 // subexpression describing the call; strip it off.
John McCall2de56d12010-08-25 11:45:40 +00001500 if (E->getCastKind() == CK_ConstructorConversion)
Douglas Gregor6eef5192009-12-14 19:27:10 +00001501 SubExpr = cast<CXXConstructExpr>(SubExpr)->getArg(0);
John McCall2de56d12010-08-25 11:45:40 +00001502 else if (E->getCastKind() == CK_UserDefinedConversion)
Douglas Gregor6eef5192009-12-14 19:27:10 +00001503 SubExpr = cast<CXXMemberCallExpr>(SubExpr)->getImplicitObjectArgument();
Sean Huntc3021132010-05-05 15:23:54 +00001504
Douglas Gregor6eef5192009-12-14 19:27:10 +00001505 // If the subexpression we're left with is an implicit cast, look
1506 // through that, too.
Sean Huntc3021132010-05-05 15:23:54 +00001507 } while ((E = dyn_cast<ImplicitCastExpr>(SubExpr)));
1508
Douglas Gregor6eef5192009-12-14 19:27:10 +00001509 return SubExpr;
1510}
1511
John McCallf871d0c2010-08-07 06:22:56 +00001512CXXBaseSpecifier **CastExpr::path_buffer() {
1513 switch (getStmtClass()) {
1514#define ABSTRACT_STMT(x)
1515#define CASTEXPR(Type, Base) \
1516 case Stmt::Type##Class: \
1517 return reinterpret_cast<CXXBaseSpecifier**>(static_cast<Type*>(this)+1);
1518#define STMT(Type, Base)
1519#include "clang/AST/StmtNodes.inc"
1520 default:
1521 llvm_unreachable("non-cast expressions not possible here");
John McCallf871d0c2010-08-07 06:22:56 +00001522 }
1523}
1524
1525void CastExpr::setCastPath(const CXXCastPath &Path) {
1526 assert(Path.size() == path_size());
1527 memcpy(path_buffer(), Path.data(), Path.size() * sizeof(CXXBaseSpecifier*));
1528}
1529
1530ImplicitCastExpr *ImplicitCastExpr::Create(ASTContext &C, QualType T,
1531 CastKind Kind, Expr *Operand,
1532 const CXXCastPath *BasePath,
John McCall5baba9d2010-08-25 10:28:54 +00001533 ExprValueKind VK) {
John McCallf871d0c2010-08-07 06:22:56 +00001534 unsigned PathSize = (BasePath ? BasePath->size() : 0);
1535 void *Buffer =
1536 C.Allocate(sizeof(ImplicitCastExpr) + PathSize * sizeof(CXXBaseSpecifier*));
1537 ImplicitCastExpr *E =
John McCall5baba9d2010-08-25 10:28:54 +00001538 new (Buffer) ImplicitCastExpr(T, Kind, Operand, PathSize, VK);
John McCallf871d0c2010-08-07 06:22:56 +00001539 if (PathSize) E->setCastPath(*BasePath);
1540 return E;
1541}
1542
1543ImplicitCastExpr *ImplicitCastExpr::CreateEmpty(ASTContext &C,
1544 unsigned PathSize) {
1545 void *Buffer =
1546 C.Allocate(sizeof(ImplicitCastExpr) + PathSize * sizeof(CXXBaseSpecifier*));
1547 return new (Buffer) ImplicitCastExpr(EmptyShell(), PathSize);
1548}
1549
1550
1551CStyleCastExpr *CStyleCastExpr::Create(ASTContext &C, QualType T,
John McCallf89e55a2010-11-18 06:31:45 +00001552 ExprValueKind VK, CastKind K, Expr *Op,
John McCallf871d0c2010-08-07 06:22:56 +00001553 const CXXCastPath *BasePath,
1554 TypeSourceInfo *WrittenTy,
1555 SourceLocation L, SourceLocation R) {
1556 unsigned PathSize = (BasePath ? BasePath->size() : 0);
1557 void *Buffer =
1558 C.Allocate(sizeof(CStyleCastExpr) + PathSize * sizeof(CXXBaseSpecifier*));
1559 CStyleCastExpr *E =
John McCallf89e55a2010-11-18 06:31:45 +00001560 new (Buffer) CStyleCastExpr(T, VK, K, Op, PathSize, WrittenTy, L, R);
John McCallf871d0c2010-08-07 06:22:56 +00001561 if (PathSize) E->setCastPath(*BasePath);
1562 return E;
1563}
1564
1565CStyleCastExpr *CStyleCastExpr::CreateEmpty(ASTContext &C, unsigned PathSize) {
1566 void *Buffer =
1567 C.Allocate(sizeof(CStyleCastExpr) + PathSize * sizeof(CXXBaseSpecifier*));
1568 return new (Buffer) CStyleCastExpr(EmptyShell(), PathSize);
1569}
1570
Reid Spencer5f016e22007-07-11 17:01:13 +00001571/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1572/// corresponds to, e.g. "<<=".
David Blaikie0bea8632012-10-08 01:11:04 +00001573StringRef BinaryOperator::getOpcodeStr(Opcode Op) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001574 switch (Op) {
John McCall2de56d12010-08-25 11:45:40 +00001575 case BO_PtrMemD: return ".*";
1576 case BO_PtrMemI: return "->*";
1577 case BO_Mul: return "*";
1578 case BO_Div: return "/";
1579 case BO_Rem: return "%";
1580 case BO_Add: return "+";
1581 case BO_Sub: return "-";
1582 case BO_Shl: return "<<";
1583 case BO_Shr: return ">>";
1584 case BO_LT: return "<";
1585 case BO_GT: return ">";
1586 case BO_LE: return "<=";
1587 case BO_GE: return ">=";
1588 case BO_EQ: return "==";
1589 case BO_NE: return "!=";
1590 case BO_And: return "&";
1591 case BO_Xor: return "^";
1592 case BO_Or: return "|";
1593 case BO_LAnd: return "&&";
1594 case BO_LOr: return "||";
1595 case BO_Assign: return "=";
1596 case BO_MulAssign: return "*=";
1597 case BO_DivAssign: return "/=";
1598 case BO_RemAssign: return "%=";
1599 case BO_AddAssign: return "+=";
1600 case BO_SubAssign: return "-=";
1601 case BO_ShlAssign: return "<<=";
1602 case BO_ShrAssign: return ">>=";
1603 case BO_AndAssign: return "&=";
1604 case BO_XorAssign: return "^=";
1605 case BO_OrAssign: return "|=";
1606 case BO_Comma: return ",";
Reid Spencer5f016e22007-07-11 17:01:13 +00001607 }
Douglas Gregorbaf53482009-03-12 22:51:37 +00001608
David Blaikie30263482012-01-20 21:50:17 +00001609 llvm_unreachable("Invalid OpCode!");
Reid Spencer5f016e22007-07-11 17:01:13 +00001610}
1611
John McCall2de56d12010-08-25 11:45:40 +00001612BinaryOperatorKind
Douglas Gregor063daf62009-03-13 18:40:31 +00001613BinaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO) {
1614 switch (OO) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001615 default: llvm_unreachable("Not an overloadable binary operator");
John McCall2de56d12010-08-25 11:45:40 +00001616 case OO_Plus: return BO_Add;
1617 case OO_Minus: return BO_Sub;
1618 case OO_Star: return BO_Mul;
1619 case OO_Slash: return BO_Div;
1620 case OO_Percent: return BO_Rem;
1621 case OO_Caret: return BO_Xor;
1622 case OO_Amp: return BO_And;
1623 case OO_Pipe: return BO_Or;
1624 case OO_Equal: return BO_Assign;
1625 case OO_Less: return BO_LT;
1626 case OO_Greater: return BO_GT;
1627 case OO_PlusEqual: return BO_AddAssign;
1628 case OO_MinusEqual: return BO_SubAssign;
1629 case OO_StarEqual: return BO_MulAssign;
1630 case OO_SlashEqual: return BO_DivAssign;
1631 case OO_PercentEqual: return BO_RemAssign;
1632 case OO_CaretEqual: return BO_XorAssign;
1633 case OO_AmpEqual: return BO_AndAssign;
1634 case OO_PipeEqual: return BO_OrAssign;
1635 case OO_LessLess: return BO_Shl;
1636 case OO_GreaterGreater: return BO_Shr;
1637 case OO_LessLessEqual: return BO_ShlAssign;
1638 case OO_GreaterGreaterEqual: return BO_ShrAssign;
1639 case OO_EqualEqual: return BO_EQ;
1640 case OO_ExclaimEqual: return BO_NE;
1641 case OO_LessEqual: return BO_LE;
1642 case OO_GreaterEqual: return BO_GE;
1643 case OO_AmpAmp: return BO_LAnd;
1644 case OO_PipePipe: return BO_LOr;
1645 case OO_Comma: return BO_Comma;
1646 case OO_ArrowStar: return BO_PtrMemI;
Douglas Gregor063daf62009-03-13 18:40:31 +00001647 }
1648}
1649
1650OverloadedOperatorKind BinaryOperator::getOverloadedOperator(Opcode Opc) {
1651 static const OverloadedOperatorKind OverOps[] = {
1652 /* .* Cannot be overloaded */OO_None, OO_ArrowStar,
1653 OO_Star, OO_Slash, OO_Percent,
1654 OO_Plus, OO_Minus,
1655 OO_LessLess, OO_GreaterGreater,
1656 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
1657 OO_EqualEqual, OO_ExclaimEqual,
1658 OO_Amp,
1659 OO_Caret,
1660 OO_Pipe,
1661 OO_AmpAmp,
1662 OO_PipePipe,
1663 OO_Equal, OO_StarEqual,
1664 OO_SlashEqual, OO_PercentEqual,
1665 OO_PlusEqual, OO_MinusEqual,
1666 OO_LessLessEqual, OO_GreaterGreaterEqual,
1667 OO_AmpEqual, OO_CaretEqual,
1668 OO_PipeEqual,
1669 OO_Comma
1670 };
1671 return OverOps[Opc];
1672}
1673
Ted Kremenek709210f2010-04-13 23:39:13 +00001674InitListExpr::InitListExpr(ASTContext &C, SourceLocation lbraceloc,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00001675 ArrayRef<Expr*> initExprs, SourceLocation rbraceloc)
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00001676 : Expr(InitListExprClass, QualType(), VK_RValue, OK_Ordinary, false, false,
Douglas Gregor561f8122011-07-01 01:22:09 +00001677 false, false),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00001678 InitExprs(C, initExprs.size()),
Sebastian Redl32cf1f22012-02-17 08:42:25 +00001679 LBraceLoc(lbraceloc), RBraceLoc(rbraceloc), SyntacticForm(0)
1680{
1681 sawArrayRangeDesignator(false);
1682 setInitializesStdInitializerList(false);
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00001683 for (unsigned I = 0; I != initExprs.size(); ++I) {
Ted Kremenekba7bc552010-02-19 01:50:18 +00001684 if (initExprs[I]->isTypeDependent())
John McCall8e6285a2010-10-26 08:39:16 +00001685 ExprBits.TypeDependent = true;
Ted Kremenekba7bc552010-02-19 01:50:18 +00001686 if (initExprs[I]->isValueDependent())
John McCall8e6285a2010-10-26 08:39:16 +00001687 ExprBits.ValueDependent = true;
Douglas Gregor561f8122011-07-01 01:22:09 +00001688 if (initExprs[I]->isInstantiationDependent())
1689 ExprBits.InstantiationDependent = true;
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00001690 if (initExprs[I]->containsUnexpandedParameterPack())
1691 ExprBits.ContainsUnexpandedParameterPack = true;
Douglas Gregor73460a32009-11-19 23:25:22 +00001692 }
Sean Huntc3021132010-05-05 15:23:54 +00001693
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00001694 InitExprs.insert(C, InitExprs.end(), initExprs.begin(), initExprs.end());
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00001695}
Reid Spencer5f016e22007-07-11 17:01:13 +00001696
Ted Kremenek709210f2010-04-13 23:39:13 +00001697void InitListExpr::reserveInits(ASTContext &C, unsigned NumInits) {
Ted Kremenekba7bc552010-02-19 01:50:18 +00001698 if (NumInits > InitExprs.size())
Ted Kremenek709210f2010-04-13 23:39:13 +00001699 InitExprs.reserve(C, NumInits);
Douglas Gregorfa219202009-03-20 23:58:33 +00001700}
1701
Ted Kremenek709210f2010-04-13 23:39:13 +00001702void InitListExpr::resizeInits(ASTContext &C, unsigned NumInits) {
Ted Kremenek709210f2010-04-13 23:39:13 +00001703 InitExprs.resize(C, NumInits, 0);
Douglas Gregor4c678342009-01-28 21:54:33 +00001704}
1705
Ted Kremenek709210f2010-04-13 23:39:13 +00001706Expr *InitListExpr::updateInit(ASTContext &C, unsigned Init, Expr *expr) {
Ted Kremenekba7bc552010-02-19 01:50:18 +00001707 if (Init >= InitExprs.size()) {
Ted Kremenek709210f2010-04-13 23:39:13 +00001708 InitExprs.insert(C, InitExprs.end(), Init - InitExprs.size() + 1, 0);
Ted Kremenekba7bc552010-02-19 01:50:18 +00001709 InitExprs.back() = expr;
1710 return 0;
Douglas Gregor4c678342009-01-28 21:54:33 +00001711 }
Mike Stump1eb44332009-09-09 15:08:12 +00001712
Douglas Gregor4c678342009-01-28 21:54:33 +00001713 Expr *Result = cast_or_null<Expr>(InitExprs[Init]);
1714 InitExprs[Init] = expr;
1715 return Result;
1716}
1717
Argyrios Kyrtzidis3e8dc2a2011-04-21 20:03:38 +00001718void InitListExpr::setArrayFiller(Expr *filler) {
Argyrios Kyrtzidis21f77cd2011-10-21 23:02:22 +00001719 assert(!hasArrayFiller() && "Filler already set!");
Argyrios Kyrtzidis3e8dc2a2011-04-21 20:03:38 +00001720 ArrayFillerOrUnionFieldInit = filler;
1721 // Fill out any "holes" in the array due to designated initializers.
1722 Expr **inits = getInits();
1723 for (unsigned i = 0, e = getNumInits(); i != e; ++i)
1724 if (inits[i] == 0)
1725 inits[i] = filler;
1726}
1727
Richard Smithfe587202012-04-15 02:50:59 +00001728bool InitListExpr::isStringLiteralInit() const {
1729 if (getNumInits() != 1)
1730 return false;
Eli Friedmanf0a26492012-08-20 20:55:45 +00001731 const ArrayType *AT = getType()->getAsArrayTypeUnsafe();
1732 if (!AT || !AT->getElementType()->isIntegerType())
Richard Smithfe587202012-04-15 02:50:59 +00001733 return false;
Eli Friedmanf0a26492012-08-20 20:55:45 +00001734 const Expr *Init = getInit(0)->IgnoreParens();
Richard Smithfe587202012-04-15 02:50:59 +00001735 return isa<StringLiteral>(Init) || isa<ObjCEncodeExpr>(Init);
1736}
1737
Ted Kremenekc4ba51f2010-11-09 02:11:40 +00001738SourceRange InitListExpr::getSourceRange() const {
1739 if (SyntacticForm)
1740 return SyntacticForm->getSourceRange();
1741 SourceLocation Beg = LBraceLoc, End = RBraceLoc;
1742 if (Beg.isInvalid()) {
1743 // Find the first non-null initializer.
1744 for (InitExprsTy::const_iterator I = InitExprs.begin(),
1745 E = InitExprs.end();
1746 I != E; ++I) {
1747 if (Stmt *S = *I) {
1748 Beg = S->getLocStart();
1749 break;
1750 }
1751 }
1752 }
1753 if (End.isInvalid()) {
1754 // Find the first non-null initializer from the end.
1755 for (InitExprsTy::const_reverse_iterator I = InitExprs.rbegin(),
1756 E = InitExprs.rend();
1757 I != E; ++I) {
1758 if (Stmt *S = *I) {
1759 End = S->getSourceRange().getEnd();
1760 break;
1761 }
1762 }
1763 }
1764 return SourceRange(Beg, End);
1765}
1766
Steve Naroffbfdcae62008-09-04 15:31:07 +00001767/// getFunctionType - Return the underlying function type for this block.
Steve Naroff4eb206b2008-09-03 18:15:37 +00001768///
John McCalla345edb2012-02-17 03:32:35 +00001769const FunctionProtoType *BlockExpr::getFunctionType() const {
1770 // The block pointer is never sugared, but the function type might be.
1771 return cast<BlockPointerType>(getType())
1772 ->getPointeeType()->castAs<FunctionProtoType>();
Steve Naroff4eb206b2008-09-03 18:15:37 +00001773}
1774
Mike Stump1eb44332009-09-09 15:08:12 +00001775SourceLocation BlockExpr::getCaretLocation() const {
1776 return TheBlock->getCaretLocation();
Steve Naroff56ee6892008-10-08 17:01:13 +00001777}
Mike Stump1eb44332009-09-09 15:08:12 +00001778const Stmt *BlockExpr::getBody() const {
Douglas Gregor72971342009-04-18 00:02:19 +00001779 return TheBlock->getBody();
1780}
Mike Stump1eb44332009-09-09 15:08:12 +00001781Stmt *BlockExpr::getBody() {
1782 return TheBlock->getBody();
Douglas Gregor72971342009-04-18 00:02:19 +00001783}
Steve Naroff56ee6892008-10-08 17:01:13 +00001784
1785
Reid Spencer5f016e22007-07-11 17:01:13 +00001786//===----------------------------------------------------------------------===//
1787// Generic Expression Routines
1788//===----------------------------------------------------------------------===//
1789
Chris Lattner026dc962009-02-14 07:37:35 +00001790/// isUnusedResultAWarning - Return true if this immediate expression should
1791/// be warned about if the result is unused. If so, fill in Loc and Ranges
1792/// with location to warn on and the source range[s] to report with the
1793/// warning.
Eli Friedmana6115062012-05-24 00:47:05 +00001794bool Expr::isUnusedResultAWarning(const Expr *&WarnE, SourceLocation &Loc,
1795 SourceRange &R1, SourceRange &R2,
1796 ASTContext &Ctx) const {
Anders Carlssonffce2df2009-05-15 23:10:19 +00001797 // Don't warn if the expr is type dependent. The type could end up
1798 // instantiating to void.
1799 if (isTypeDependent())
1800 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001801
Reid Spencer5f016e22007-07-11 17:01:13 +00001802 switch (getStmtClass()) {
1803 default:
John McCall0faede62010-03-12 07:11:26 +00001804 if (getType()->isVoidType())
1805 return false;
Eli Friedmana6115062012-05-24 00:47:05 +00001806 WarnE = this;
Chris Lattner026dc962009-02-14 07:37:35 +00001807 Loc = getExprLoc();
1808 R1 = getSourceRange();
1809 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001810 case ParenExprClass:
Chris Lattner026dc962009-02-14 07:37:35 +00001811 return cast<ParenExpr>(this)->getSubExpr()->
Eli Friedmana6115062012-05-24 00:47:05 +00001812 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Peter Collingbournef111d932011-04-15 00:35:48 +00001813 case GenericSelectionExprClass:
1814 return cast<GenericSelectionExpr>(this)->getResultExpr()->
Eli Friedmana6115062012-05-24 00:47:05 +00001815 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Reid Spencer5f016e22007-07-11 17:01:13 +00001816 case UnaryOperatorClass: {
1817 const UnaryOperator *UO = cast<UnaryOperator>(this);
Mike Stump1eb44332009-09-09 15:08:12 +00001818
Reid Spencer5f016e22007-07-11 17:01:13 +00001819 switch (UO->getOpcode()) {
Eli Friedmana6115062012-05-24 00:47:05 +00001820 case UO_Plus:
1821 case UO_Minus:
1822 case UO_AddrOf:
1823 case UO_Not:
1824 case UO_LNot:
1825 case UO_Deref:
1826 break;
John McCall2de56d12010-08-25 11:45:40 +00001827 case UO_PostInc:
1828 case UO_PostDec:
1829 case UO_PreInc:
1830 case UO_PreDec: // ++/--
Chris Lattner026dc962009-02-14 07:37:35 +00001831 return false; // Not a warning.
John McCall2de56d12010-08-25 11:45:40 +00001832 case UO_Real:
1833 case UO_Imag:
Reid Spencer5f016e22007-07-11 17:01:13 +00001834 // accessing a piece of a volatile complex is a side-effect.
Mike Stumpdf317bf2009-11-03 23:25:48 +00001835 if (Ctx.getCanonicalType(UO->getSubExpr()->getType())
1836 .isVolatileQualified())
Chris Lattner026dc962009-02-14 07:37:35 +00001837 return false;
1838 break;
John McCall2de56d12010-08-25 11:45:40 +00001839 case UO_Extension:
Eli Friedmana6115062012-05-24 00:47:05 +00001840 return UO->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Reid Spencer5f016e22007-07-11 17:01:13 +00001841 }
Eli Friedmana6115062012-05-24 00:47:05 +00001842 WarnE = this;
Chris Lattner026dc962009-02-14 07:37:35 +00001843 Loc = UO->getOperatorLoc();
1844 R1 = UO->getSubExpr()->getSourceRange();
1845 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001846 }
Chris Lattnere7716e62007-12-01 06:07:34 +00001847 case BinaryOperatorClass: {
Chris Lattner026dc962009-02-14 07:37:35 +00001848 const BinaryOperator *BO = cast<BinaryOperator>(this);
Ted Kremenekc46a2462010-04-07 18:49:21 +00001849 switch (BO->getOpcode()) {
1850 default:
1851 break;
Argyrios Kyrtzidis25973452010-06-30 10:53:14 +00001852 // Consider the RHS of comma for side effects. LHS was checked by
1853 // Sema::CheckCommaOperands.
John McCall2de56d12010-08-25 11:45:40 +00001854 case BO_Comma:
Ted Kremenekc46a2462010-04-07 18:49:21 +00001855 // ((foo = <blah>), 0) is an idiom for hiding the result (and
1856 // lvalue-ness) of an assignment written in a macro.
1857 if (IntegerLiteral *IE =
1858 dyn_cast<IntegerLiteral>(BO->getRHS()->IgnoreParens()))
1859 if (IE->getValue() == 0)
1860 return false;
Eli Friedmana6115062012-05-24 00:47:05 +00001861 return BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Argyrios Kyrtzidis25973452010-06-30 10:53:14 +00001862 // Consider '||', '&&' to have side effects if the LHS or RHS does.
John McCall2de56d12010-08-25 11:45:40 +00001863 case BO_LAnd:
1864 case BO_LOr:
Eli Friedmana6115062012-05-24 00:47:05 +00001865 if (!BO->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx) ||
1866 !BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx))
Argyrios Kyrtzidis25973452010-06-30 10:53:14 +00001867 return false;
1868 break;
John McCallbf0ee352010-02-16 04:10:53 +00001869 }
Chris Lattner026dc962009-02-14 07:37:35 +00001870 if (BO->isAssignmentOp())
1871 return false;
Eli Friedmana6115062012-05-24 00:47:05 +00001872 WarnE = this;
Chris Lattner026dc962009-02-14 07:37:35 +00001873 Loc = BO->getOperatorLoc();
1874 R1 = BO->getLHS()->getSourceRange();
1875 R2 = BO->getRHS()->getSourceRange();
1876 return true;
Chris Lattnere7716e62007-12-01 06:07:34 +00001877 }
Chris Lattnereb14fe82007-08-25 02:00:02 +00001878 case CompoundAssignOperatorClass:
Douglas Gregorc6dfe192010-05-08 22:41:50 +00001879 case VAArgExprClass:
Eli Friedman276b0612011-10-11 02:20:01 +00001880 case AtomicExprClass:
Chris Lattner026dc962009-02-14 07:37:35 +00001881 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001882
Fariborz Jahanianab38e4b2007-12-01 19:58:28 +00001883 case ConditionalOperatorClass: {
Ted Kremenekfb7cb352011-03-01 20:34:48 +00001884 // If only one of the LHS or RHS is a warning, the operator might
1885 // be being used for control flow. Only warn if both the LHS and
1886 // RHS are warnings.
Fariborz Jahanianab38e4b2007-12-01 19:58:28 +00001887 const ConditionalOperator *Exp = cast<ConditionalOperator>(this);
Eli Friedmana6115062012-05-24 00:47:05 +00001888 if (!Exp->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx))
Ted Kremenekfb7cb352011-03-01 20:34:48 +00001889 return false;
1890 if (!Exp->getLHS())
Chris Lattner026dc962009-02-14 07:37:35 +00001891 return true;
Eli Friedmana6115062012-05-24 00:47:05 +00001892 return Exp->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Fariborz Jahanianab38e4b2007-12-01 19:58:28 +00001893 }
1894
Reid Spencer5f016e22007-07-11 17:01:13 +00001895 case MemberExprClass:
Eli Friedmana6115062012-05-24 00:47:05 +00001896 WarnE = this;
Chris Lattner026dc962009-02-14 07:37:35 +00001897 Loc = cast<MemberExpr>(this)->getMemberLoc();
1898 R1 = SourceRange(Loc, Loc);
1899 R2 = cast<MemberExpr>(this)->getBase()->getSourceRange();
1900 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001901
Reid Spencer5f016e22007-07-11 17:01:13 +00001902 case ArraySubscriptExprClass:
Eli Friedmana6115062012-05-24 00:47:05 +00001903 WarnE = this;
Chris Lattner026dc962009-02-14 07:37:35 +00001904 Loc = cast<ArraySubscriptExpr>(this)->getRBracketLoc();
1905 R1 = cast<ArraySubscriptExpr>(this)->getLHS()->getSourceRange();
1906 R2 = cast<ArraySubscriptExpr>(this)->getRHS()->getSourceRange();
1907 return true;
Eli Friedman211f6ad2008-05-27 15:24:04 +00001908
Chandler Carruth9b106832011-08-17 09:49:44 +00001909 case CXXOperatorCallExprClass: {
1910 // We warn about operator== and operator!= even when user-defined operator
1911 // overloads as there is no reasonable way to define these such that they
1912 // have non-trivial, desirable side-effects. See the -Wunused-comparison
1913 // warning: these operators are commonly typo'ed, and so warning on them
1914 // provides additional value as well. If this list is updated,
1915 // DiagnoseUnusedComparison should be as well.
1916 const CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(this);
1917 if (Op->getOperator() == OO_EqualEqual ||
Matt Beaumont-Gay6e521832011-09-19 18:51:20 +00001918 Op->getOperator() == OO_ExclaimEqual) {
Eli Friedmana6115062012-05-24 00:47:05 +00001919 WarnE = this;
Matt Beaumont-Gay6e521832011-09-19 18:51:20 +00001920 Loc = Op->getOperatorLoc();
1921 R1 = Op->getSourceRange();
Chandler Carruth9b106832011-08-17 09:49:44 +00001922 return true;
Matt Beaumont-Gay6e521832011-09-19 18:51:20 +00001923 }
Chandler Carruth9b106832011-08-17 09:49:44 +00001924
1925 // Fallthrough for generic call handling.
1926 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001927 case CallExprClass:
Richard Smith9fcce652012-03-07 08:35:16 +00001928 case CXXMemberCallExprClass:
1929 case UserDefinedLiteralClass: {
Chris Lattner026dc962009-02-14 07:37:35 +00001930 // If this is a direct call, get the callee.
1931 const CallExpr *CE = cast<CallExpr>(this);
Nuno Lopesd20254f2009-12-20 23:11:08 +00001932 if (const Decl *FD = CE->getCalleeDecl()) {
Chris Lattner026dc962009-02-14 07:37:35 +00001933 // If the callee has attribute pure, const, or warn_unused_result, warn
1934 // about it. void foo() { strlen("bar"); } should warn.
Chris Lattnerbc8d42c2009-10-13 04:53:48 +00001935 //
1936 // Note: If new cases are added here, DiagnoseUnusedExprResult should be
1937 // updated to match for QoI.
1938 if (FD->getAttr<WarnUnusedResultAttr>() ||
1939 FD->getAttr<PureAttr>() || FD->getAttr<ConstAttr>()) {
Eli Friedmana6115062012-05-24 00:47:05 +00001940 WarnE = this;
Chris Lattnerbc8d42c2009-10-13 04:53:48 +00001941 Loc = CE->getCallee()->getLocStart();
1942 R1 = CE->getCallee()->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001943
Chris Lattnerbc8d42c2009-10-13 04:53:48 +00001944 if (unsigned NumArgs = CE->getNumArgs())
1945 R2 = SourceRange(CE->getArg(0)->getLocStart(),
1946 CE->getArg(NumArgs-1)->getLocEnd());
1947 return true;
1948 }
Chris Lattner026dc962009-02-14 07:37:35 +00001949 }
1950 return false;
1951 }
Anders Carlsson58beed92009-11-17 17:11:23 +00001952
Matt Beaumont-Gay84c3b972012-10-23 06:15:26 +00001953 // If we don't know precisely what we're looking at, let's not warn.
1954 case UnresolvedLookupExprClass:
1955 case CXXUnresolvedConstructExprClass:
1956 return false;
1957
Anders Carlsson58beed92009-11-17 17:11:23 +00001958 case CXXTemporaryObjectExprClass:
1959 case CXXConstructExprClass:
1960 return false;
1961
Fariborz Jahanianf0317742010-03-30 18:22:15 +00001962 case ObjCMessageExprClass: {
1963 const ObjCMessageExpr *ME = cast<ObjCMessageExpr>(this);
David Blaikie4e4d0842012-03-11 07:00:24 +00001964 if (Ctx.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00001965 ME->isInstanceMessage() &&
1966 !ME->getType()->isVoidType() &&
1967 ME->getSelector().getIdentifierInfoForSlot(0) &&
1968 ME->getSelector().getIdentifierInfoForSlot(0)
1969 ->getName().startswith("init")) {
Eli Friedmana6115062012-05-24 00:47:05 +00001970 WarnE = this;
John McCallf85e1932011-06-15 23:02:42 +00001971 Loc = getExprLoc();
1972 R1 = ME->getSourceRange();
1973 return true;
1974 }
1975
Fariborz Jahanianf0317742010-03-30 18:22:15 +00001976 const ObjCMethodDecl *MD = ME->getMethodDecl();
1977 if (MD && MD->getAttr<WarnUnusedResultAttr>()) {
Eli Friedmana6115062012-05-24 00:47:05 +00001978 WarnE = this;
Fariborz Jahanianf0317742010-03-30 18:22:15 +00001979 Loc = getExprLoc();
1980 return true;
1981 }
Chris Lattner026dc962009-02-14 07:37:35 +00001982 return false;
Fariborz Jahanianf0317742010-03-30 18:22:15 +00001983 }
Mike Stump1eb44332009-09-09 15:08:12 +00001984
John McCall12f78a62010-12-02 01:19:52 +00001985 case ObjCPropertyRefExprClass:
Eli Friedmana6115062012-05-24 00:47:05 +00001986 WarnE = this;
Chris Lattner5e94a0d2009-08-16 16:51:50 +00001987 Loc = getExprLoc();
1988 R1 = getSourceRange();
Chris Lattnera50089e2009-08-16 16:45:18 +00001989 return true;
John McCall12f78a62010-12-02 01:19:52 +00001990
John McCall4b9c2d22011-11-06 09:01:30 +00001991 case PseudoObjectExprClass: {
1992 const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this);
1993
1994 // Only complain about things that have the form of a getter.
1995 if (isa<UnaryOperator>(PO->getSyntacticForm()) ||
1996 isa<BinaryOperator>(PO->getSyntacticForm()))
1997 return false;
1998
Eli Friedmana6115062012-05-24 00:47:05 +00001999 WarnE = this;
John McCall4b9c2d22011-11-06 09:01:30 +00002000 Loc = getExprLoc();
2001 R1 = getSourceRange();
2002 return true;
2003 }
2004
Chris Lattner611b2ec2008-07-26 19:51:01 +00002005 case StmtExprClass: {
2006 // Statement exprs don't logically have side effects themselves, but are
2007 // sometimes used in macros in ways that give them a type that is unused.
2008 // For example ({ blah; foo(); }) will end up with a type if foo has a type.
2009 // however, if the result of the stmt expr is dead, we don't want to emit a
2010 // warning.
2011 const CompoundStmt *CS = cast<StmtExpr>(this)->getSubStmt();
Argyrios Kyrtzidisd2827af2010-09-19 21:21:10 +00002012 if (!CS->body_empty()) {
Chris Lattner611b2ec2008-07-26 19:51:01 +00002013 if (const Expr *E = dyn_cast<Expr>(CS->body_back()))
Eli Friedmana6115062012-05-24 00:47:05 +00002014 return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Argyrios Kyrtzidisd2827af2010-09-19 21:21:10 +00002015 if (const LabelStmt *Label = dyn_cast<LabelStmt>(CS->body_back()))
2016 if (const Expr *E = dyn_cast<Expr>(Label->getSubStmt()))
Eli Friedmana6115062012-05-24 00:47:05 +00002017 return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Argyrios Kyrtzidisd2827af2010-09-19 21:21:10 +00002018 }
Mike Stump1eb44332009-09-09 15:08:12 +00002019
John McCall0faede62010-03-12 07:11:26 +00002020 if (getType()->isVoidType())
2021 return false;
Eli Friedmana6115062012-05-24 00:47:05 +00002022 WarnE = this;
Chris Lattner026dc962009-02-14 07:37:35 +00002023 Loc = cast<StmtExpr>(this)->getLParenLoc();
2024 R1 = getSourceRange();
2025 return true;
Chris Lattner611b2ec2008-07-26 19:51:01 +00002026 }
Eli Friedman63199172012-09-24 23:02:26 +00002027 case CXXFunctionalCastExprClass:
Eli Friedmana6115062012-05-24 00:47:05 +00002028 case CStyleCastExprClass: {
Eli Friedman4059da82012-05-24 21:05:41 +00002029 // Ignore an explicit cast to void unless the operand is a non-trivial
Eli Friedmana6115062012-05-24 00:47:05 +00002030 // volatile lvalue.
Eli Friedman4059da82012-05-24 21:05:41 +00002031 const CastExpr *CE = cast<CastExpr>(this);
Eli Friedmana6115062012-05-24 00:47:05 +00002032 if (CE->getCastKind() == CK_ToVoid) {
2033 if (CE->getSubExpr()->isGLValue() &&
Eli Friedman4059da82012-05-24 21:05:41 +00002034 CE->getSubExpr()->getType().isVolatileQualified()) {
2035 const DeclRefExpr *DRE =
2036 dyn_cast<DeclRefExpr>(CE->getSubExpr()->IgnoreParens());
2037 if (!(DRE && isa<VarDecl>(DRE->getDecl()) &&
2038 cast<VarDecl>(DRE->getDecl())->hasLocalStorage())) {
2039 return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc,
2040 R1, R2, Ctx);
2041 }
2042 }
Chris Lattnerfb846642009-07-28 18:25:28 +00002043 return false;
Eli Friedmana6115062012-05-24 00:47:05 +00002044 }
Eli Friedman4059da82012-05-24 21:05:41 +00002045
Eli Friedmana6115062012-05-24 00:47:05 +00002046 // If this is a cast to a constructor conversion, check the operand.
Anders Carlsson58beed92009-11-17 17:11:23 +00002047 // Otherwise, the result of the cast is unused.
Eli Friedmana6115062012-05-24 00:47:05 +00002048 if (CE->getCastKind() == CK_ConstructorConversion)
2049 return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Eli Friedman4059da82012-05-24 21:05:41 +00002050
Eli Friedmana6115062012-05-24 00:47:05 +00002051 WarnE = this;
Eli Friedman4059da82012-05-24 21:05:41 +00002052 if (const CXXFunctionalCastExpr *CXXCE =
2053 dyn_cast<CXXFunctionalCastExpr>(this)) {
2054 Loc = CXXCE->getTypeBeginLoc();
2055 R1 = CXXCE->getSubExpr()->getSourceRange();
2056 } else {
2057 const CStyleCastExpr *CStyleCE = cast<CStyleCastExpr>(this);
2058 Loc = CStyleCE->getLParenLoc();
2059 R1 = CStyleCE->getSubExpr()->getSourceRange();
2060 }
Chris Lattner026dc962009-02-14 07:37:35 +00002061 return true;
Anders Carlsson58beed92009-11-17 17:11:23 +00002062 }
Eli Friedmana6115062012-05-24 00:47:05 +00002063 case ImplicitCastExprClass: {
2064 const CastExpr *ICE = cast<ImplicitCastExpr>(this);
Eli Friedman4be1f472008-05-19 21:24:43 +00002065
Eli Friedmana6115062012-05-24 00:47:05 +00002066 // lvalue-to-rvalue conversion on a volatile lvalue is a side-effect.
2067 if (ICE->getCastKind() == CK_LValueToRValue &&
2068 ICE->getSubExpr()->getType().isVolatileQualified())
2069 return false;
2070
2071 return ICE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2072 }
Chris Lattner04421082008-04-08 04:40:51 +00002073 case CXXDefaultArgExprClass:
Mike Stumpdf317bf2009-11-03 23:25:48 +00002074 return (cast<CXXDefaultArgExpr>(this)
Eli Friedmana6115062012-05-24 00:47:05 +00002075 ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002076
2077 case CXXNewExprClass:
2078 // FIXME: In theory, there might be new expressions that don't have side
2079 // effects (e.g. a placement new with an uninitialized POD).
2080 case CXXDeleteExprClass:
Chris Lattner026dc962009-02-14 07:37:35 +00002081 return false;
Anders Carlsson2d46eb22009-08-16 04:11:06 +00002082 case CXXBindTemporaryExprClass:
Mike Stumpdf317bf2009-11-03 23:25:48 +00002083 return (cast<CXXBindTemporaryExpr>(this)
Eli Friedmana6115062012-05-24 00:47:05 +00002084 ->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
John McCall4765fa02010-12-06 08:20:24 +00002085 case ExprWithCleanupsClass:
2086 return (cast<ExprWithCleanups>(this)
Eli Friedmana6115062012-05-24 00:47:05 +00002087 ->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002088 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002089}
2090
Fariborz Jahanian44baa8a2009-02-22 18:40:18 +00002091/// isOBJCGCCandidate - Check if an expression is objc gc'able.
Fariborz Jahanian7f4f86a2009-09-08 23:38:54 +00002092/// returns true, if it is; false otherwise.
Fariborz Jahanian102e3902009-06-01 21:29:32 +00002093bool Expr::isOBJCGCCandidate(ASTContext &Ctx) const {
Peter Collingbournef111d932011-04-15 00:35:48 +00002094 const Expr *E = IgnoreParens();
2095 switch (E->getStmtClass()) {
Fariborz Jahanian44baa8a2009-02-22 18:40:18 +00002096 default:
2097 return false;
2098 case ObjCIvarRefExprClass:
2099 return true;
Fariborz Jahanian207c5212009-02-23 18:59:50 +00002100 case Expr::UnaryOperatorClass:
Peter Collingbournef111d932011-04-15 00:35:48 +00002101 return cast<UnaryOperator>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
Fariborz Jahanian44baa8a2009-02-22 18:40:18 +00002102 case ImplicitCastExprClass:
Peter Collingbournef111d932011-04-15 00:35:48 +00002103 return cast<ImplicitCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
Douglas Gregor03e80032011-06-21 17:03:29 +00002104 case MaterializeTemporaryExprClass:
2105 return cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr()
2106 ->isOBJCGCCandidate(Ctx);
Fariborz Jahanian06b89122009-05-05 23:28:21 +00002107 case CStyleCastExprClass:
Peter Collingbournef111d932011-04-15 00:35:48 +00002108 return cast<CStyleCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
Douglas Gregora2813ce2009-10-23 18:54:35 +00002109 case DeclRefExprClass: {
John McCallf4b88a42012-03-10 09:33:50 +00002110 const Decl *D = cast<DeclRefExpr>(E)->getDecl();
Fariborz Jahaniane3f83492011-09-23 18:57:30 +00002111
Fariborz Jahanian102e3902009-06-01 21:29:32 +00002112 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2113 if (VD->hasGlobalStorage())
2114 return true;
2115 QualType T = VD->getType();
Fariborz Jahanian59a53fa2009-09-16 18:09:18 +00002116 // dereferencing to a pointer is always a gc'able candidate,
2117 // unless it is __weak.
Daniel Dunbar7e88a602009-09-17 06:31:17 +00002118 return T->isPointerType() &&
John McCall0953e762009-09-24 19:53:00 +00002119 (Ctx.getObjCGCAttrKind(T) != Qualifiers::Weak);
Fariborz Jahanian102e3902009-06-01 21:29:32 +00002120 }
Fariborz Jahanian44baa8a2009-02-22 18:40:18 +00002121 return false;
2122 }
Douglas Gregor83f6faf2009-08-31 23:41:50 +00002123 case MemberExprClass: {
Peter Collingbournef111d932011-04-15 00:35:48 +00002124 const MemberExpr *M = cast<MemberExpr>(E);
Fariborz Jahanian102e3902009-06-01 21:29:32 +00002125 return M->getBase()->isOBJCGCCandidate(Ctx);
Fariborz Jahanian44baa8a2009-02-22 18:40:18 +00002126 }
2127 case ArraySubscriptExprClass:
Peter Collingbournef111d932011-04-15 00:35:48 +00002128 return cast<ArraySubscriptExpr>(E)->getBase()->isOBJCGCCandidate(Ctx);
Fariborz Jahanian44baa8a2009-02-22 18:40:18 +00002129 }
2130}
Sebastian Redl369e51f2010-09-10 20:55:33 +00002131
Argyrios Kyrtzidis11ab7902010-11-01 18:49:26 +00002132bool Expr::isBoundMemberFunction(ASTContext &Ctx) const {
2133 if (isTypeDependent())
2134 return false;
John McCall7eb0a9e2010-11-24 05:12:34 +00002135 return ClassifyLValue(Ctx) == Expr::LV_MemberFunction;
Argyrios Kyrtzidis11ab7902010-11-01 18:49:26 +00002136}
2137
John McCall864c0412011-04-26 20:42:42 +00002138QualType Expr::findBoundMemberType(const Expr *expr) {
John McCalle0a22d02011-10-18 21:02:43 +00002139 assert(expr->hasPlaceholderType(BuiltinType::BoundMember));
John McCall864c0412011-04-26 20:42:42 +00002140
2141 // Bound member expressions are always one of these possibilities:
2142 // x->m x.m x->*y x.*y
2143 // (possibly parenthesized)
2144
2145 expr = expr->IgnoreParens();
2146 if (const MemberExpr *mem = dyn_cast<MemberExpr>(expr)) {
2147 assert(isa<CXXMethodDecl>(mem->getMemberDecl()));
2148 return mem->getMemberDecl()->getType();
2149 }
2150
2151 if (const BinaryOperator *op = dyn_cast<BinaryOperator>(expr)) {
2152 QualType type = op->getRHS()->getType()->castAs<MemberPointerType>()
2153 ->getPointeeType();
2154 assert(type->isFunctionType());
2155 return type;
2156 }
2157
2158 assert(isa<UnresolvedMemberExpr>(expr));
2159 return QualType();
2160}
2161
Ted Kremenek4e99a5f2008-01-17 16:57:34 +00002162Expr* Expr::IgnoreParens() {
2163 Expr* E = this;
Abramo Bagnarab9eb35c2010-10-15 07:51:18 +00002164 while (true) {
2165 if (ParenExpr* P = dyn_cast<ParenExpr>(E)) {
2166 E = P->getSubExpr();
2167 continue;
2168 }
2169 if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) {
2170 if (P->getOpcode() == UO_Extension) {
2171 E = P->getSubExpr();
2172 continue;
2173 }
2174 }
Peter Collingbournef111d932011-04-15 00:35:48 +00002175 if (GenericSelectionExpr* P = dyn_cast<GenericSelectionExpr>(E)) {
2176 if (!P->isResultDependent()) {
2177 E = P->getResultExpr();
2178 continue;
2179 }
2180 }
Abramo Bagnarab9eb35c2010-10-15 07:51:18 +00002181 return E;
2182 }
Ted Kremenek4e99a5f2008-01-17 16:57:34 +00002183}
2184
Chris Lattner56f34942008-02-13 01:02:39 +00002185/// IgnoreParenCasts - Ignore parentheses and casts. Strip off any ParenExpr
2186/// or CastExprs or ImplicitCastExprs, returning their operand.
2187Expr *Expr::IgnoreParenCasts() {
2188 Expr *E = this;
2189 while (true) {
Abramo Bagnarab9eb35c2010-10-15 07:51:18 +00002190 if (ParenExpr* P = dyn_cast<ParenExpr>(E)) {
Chris Lattner56f34942008-02-13 01:02:39 +00002191 E = P->getSubExpr();
Abramo Bagnarab9eb35c2010-10-15 07:51:18 +00002192 continue;
2193 }
2194 if (CastExpr *P = dyn_cast<CastExpr>(E)) {
Chris Lattner56f34942008-02-13 01:02:39 +00002195 E = P->getSubExpr();
Abramo Bagnarab9eb35c2010-10-15 07:51:18 +00002196 continue;
2197 }
2198 if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) {
2199 if (P->getOpcode() == UO_Extension) {
2200 E = P->getSubExpr();
2201 continue;
2202 }
2203 }
Peter Collingbournef111d932011-04-15 00:35:48 +00002204 if (GenericSelectionExpr* P = dyn_cast<GenericSelectionExpr>(E)) {
2205 if (!P->isResultDependent()) {
2206 E = P->getResultExpr();
2207 continue;
2208 }
2209 }
Douglas Gregor03e80032011-06-21 17:03:29 +00002210 if (MaterializeTemporaryExpr *Materialize
2211 = dyn_cast<MaterializeTemporaryExpr>(E)) {
2212 E = Materialize->GetTemporaryExpr();
2213 continue;
2214 }
Douglas Gregorc0244c52011-09-08 17:56:33 +00002215 if (SubstNonTypeTemplateParmExpr *NTTP
2216 = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2217 E = NTTP->getReplacement();
2218 continue;
2219 }
Abramo Bagnarab9eb35c2010-10-15 07:51:18 +00002220 return E;
Chris Lattner56f34942008-02-13 01:02:39 +00002221 }
2222}
2223
John McCall9c5d70c2010-12-04 08:24:19 +00002224/// IgnoreParenLValueCasts - Ignore parentheses and lvalue-to-rvalue
2225/// casts. This is intended purely as a temporary workaround for code
2226/// that hasn't yet been rewritten to do the right thing about those
2227/// casts, and may disappear along with the last internal use.
John McCallf6a16482010-12-04 03:47:34 +00002228Expr *Expr::IgnoreParenLValueCasts() {
2229 Expr *E = this;
John McCall9c5d70c2010-12-04 08:24:19 +00002230 while (true) {
John McCallf6a16482010-12-04 03:47:34 +00002231 if (ParenExpr *P = dyn_cast<ParenExpr>(E)) {
2232 E = P->getSubExpr();
2233 continue;
John McCall9c5d70c2010-12-04 08:24:19 +00002234 } else if (CastExpr *P = dyn_cast<CastExpr>(E)) {
John McCallf6a16482010-12-04 03:47:34 +00002235 if (P->getCastKind() == CK_LValueToRValue) {
2236 E = P->getSubExpr();
2237 continue;
2238 }
John McCall9c5d70c2010-12-04 08:24:19 +00002239 } else if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) {
2240 if (P->getOpcode() == UO_Extension) {
2241 E = P->getSubExpr();
2242 continue;
2243 }
Peter Collingbournef111d932011-04-15 00:35:48 +00002244 } else if (GenericSelectionExpr* P = dyn_cast<GenericSelectionExpr>(E)) {
2245 if (!P->isResultDependent()) {
2246 E = P->getResultExpr();
2247 continue;
2248 }
Douglas Gregor03e80032011-06-21 17:03:29 +00002249 } else if (MaterializeTemporaryExpr *Materialize
2250 = dyn_cast<MaterializeTemporaryExpr>(E)) {
2251 E = Materialize->GetTemporaryExpr();
2252 continue;
Douglas Gregorc0244c52011-09-08 17:56:33 +00002253 } else if (SubstNonTypeTemplateParmExpr *NTTP
2254 = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2255 E = NTTP->getReplacement();
2256 continue;
John McCallf6a16482010-12-04 03:47:34 +00002257 }
2258 break;
2259 }
2260 return E;
2261}
Rafael Espindola632fbaa2012-06-28 01:56:38 +00002262
2263Expr *Expr::ignoreParenBaseCasts() {
2264 Expr *E = this;
2265 while (true) {
2266 if (ParenExpr *P = dyn_cast<ParenExpr>(E)) {
2267 E = P->getSubExpr();
2268 continue;
2269 }
2270 if (CastExpr *CE = dyn_cast<CastExpr>(E)) {
2271 if (CE->getCastKind() == CK_DerivedToBase ||
2272 CE->getCastKind() == CK_UncheckedDerivedToBase ||
2273 CE->getCastKind() == CK_NoOp) {
2274 E = CE->getSubExpr();
2275 continue;
2276 }
2277 }
2278
2279 return E;
2280 }
2281}
2282
John McCall2fc46bf2010-05-05 22:59:52 +00002283Expr *Expr::IgnoreParenImpCasts() {
2284 Expr *E = this;
2285 while (true) {
Abramo Bagnarab9eb35c2010-10-15 07:51:18 +00002286 if (ParenExpr *P = dyn_cast<ParenExpr>(E)) {
John McCall2fc46bf2010-05-05 22:59:52 +00002287 E = P->getSubExpr();
Abramo Bagnarab9eb35c2010-10-15 07:51:18 +00002288 continue;
2289 }
2290 if (ImplicitCastExpr *P = dyn_cast<ImplicitCastExpr>(E)) {
John McCall2fc46bf2010-05-05 22:59:52 +00002291 E = P->getSubExpr();
Abramo Bagnarab9eb35c2010-10-15 07:51:18 +00002292 continue;
2293 }
2294 if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) {
2295 if (P->getOpcode() == UO_Extension) {
2296 E = P->getSubExpr();
2297 continue;
2298 }
2299 }
Peter Collingbournef111d932011-04-15 00:35:48 +00002300 if (GenericSelectionExpr* P = dyn_cast<GenericSelectionExpr>(E)) {
2301 if (!P->isResultDependent()) {
2302 E = P->getResultExpr();
2303 continue;
2304 }
2305 }
Douglas Gregor03e80032011-06-21 17:03:29 +00002306 if (MaterializeTemporaryExpr *Materialize
2307 = dyn_cast<MaterializeTemporaryExpr>(E)) {
2308 E = Materialize->GetTemporaryExpr();
2309 continue;
2310 }
Douglas Gregorc0244c52011-09-08 17:56:33 +00002311 if (SubstNonTypeTemplateParmExpr *NTTP
2312 = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2313 E = NTTP->getReplacement();
2314 continue;
2315 }
Abramo Bagnarab9eb35c2010-10-15 07:51:18 +00002316 return E;
John McCall2fc46bf2010-05-05 22:59:52 +00002317 }
2318}
2319
Hans Wennborg2f072b42011-06-09 17:06:51 +00002320Expr *Expr::IgnoreConversionOperator() {
2321 if (CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(this)) {
Chandler Carruth14d251c2011-06-21 17:22:09 +00002322 if (MCE->getMethodDecl() && isa<CXXConversionDecl>(MCE->getMethodDecl()))
Hans Wennborg2f072b42011-06-09 17:06:51 +00002323 return MCE->getImplicitObjectArgument();
2324 }
2325 return this;
2326}
2327
Chris Lattnerecdd8412009-03-13 17:28:01 +00002328/// IgnoreParenNoopCasts - Ignore parentheses and casts that do not change the
2329/// value (including ptr->int casts of the same size). Strip off any
2330/// ParenExpr or CastExprs, returning their operand.
2331Expr *Expr::IgnoreParenNoopCasts(ASTContext &Ctx) {
2332 Expr *E = this;
2333 while (true) {
2334 if (ParenExpr *P = dyn_cast<ParenExpr>(E)) {
2335 E = P->getSubExpr();
2336 continue;
2337 }
Mike Stump1eb44332009-09-09 15:08:12 +00002338
Chris Lattnerecdd8412009-03-13 17:28:01 +00002339 if (CastExpr *P = dyn_cast<CastExpr>(E)) {
2340 // We ignore integer <-> casts that are of the same width, ptr<->ptr and
Douglas Gregor2ade35e2010-06-16 00:17:44 +00002341 // ptr<->int casts of the same width. We also ignore all identity casts.
Chris Lattnerecdd8412009-03-13 17:28:01 +00002342 Expr *SE = P->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00002343
Chris Lattnerecdd8412009-03-13 17:28:01 +00002344 if (Ctx.hasSameUnqualifiedType(E->getType(), SE->getType())) {
2345 E = SE;
2346 continue;
2347 }
Mike Stump1eb44332009-09-09 15:08:12 +00002348
Abramo Bagnarab9eb35c2010-10-15 07:51:18 +00002349 if ((E->getType()->isPointerType() ||
Douglas Gregor9d3347a2010-06-16 00:35:25 +00002350 E->getType()->isIntegralType(Ctx)) &&
Abramo Bagnarab9eb35c2010-10-15 07:51:18 +00002351 (SE->getType()->isPointerType() ||
Douglas Gregor9d3347a2010-06-16 00:35:25 +00002352 SE->getType()->isIntegralType(Ctx)) &&
Chris Lattnerecdd8412009-03-13 17:28:01 +00002353 Ctx.getTypeSize(E->getType()) == Ctx.getTypeSize(SE->getType())) {
2354 E = SE;
2355 continue;
2356 }
2357 }
Mike Stump1eb44332009-09-09 15:08:12 +00002358
Abramo Bagnarab9eb35c2010-10-15 07:51:18 +00002359 if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) {
2360 if (P->getOpcode() == UO_Extension) {
2361 E = P->getSubExpr();
2362 continue;
2363 }
2364 }
2365
Peter Collingbournef111d932011-04-15 00:35:48 +00002366 if (GenericSelectionExpr* P = dyn_cast<GenericSelectionExpr>(E)) {
2367 if (!P->isResultDependent()) {
2368 E = P->getResultExpr();
2369 continue;
2370 }
2371 }
2372
Douglas Gregorc0244c52011-09-08 17:56:33 +00002373 if (SubstNonTypeTemplateParmExpr *NTTP
2374 = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2375 E = NTTP->getReplacement();
2376 continue;
2377 }
2378
Chris Lattnerecdd8412009-03-13 17:28:01 +00002379 return E;
2380 }
2381}
2382
Douglas Gregor6eef5192009-12-14 19:27:10 +00002383bool Expr::isDefaultArgument() const {
2384 const Expr *E = this;
Douglas Gregor03e80032011-06-21 17:03:29 +00002385 if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
2386 E = M->GetTemporaryExpr();
2387
Douglas Gregor6eef5192009-12-14 19:27:10 +00002388 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
2389 E = ICE->getSubExprAsWritten();
Sean Huntc3021132010-05-05 15:23:54 +00002390
Douglas Gregor6eef5192009-12-14 19:27:10 +00002391 return isa<CXXDefaultArgExpr>(E);
2392}
Chris Lattnerecdd8412009-03-13 17:28:01 +00002393
Douglas Gregor2f599792010-04-02 18:24:57 +00002394/// \brief Skip over any no-op casts and any temporary-binding
2395/// expressions.
Anders Carlssonf8b30152010-11-28 16:40:49 +00002396static const Expr *skipTemporaryBindingsNoOpCastsAndParens(const Expr *E) {
Douglas Gregor03e80032011-06-21 17:03:29 +00002397 if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
2398 E = M->GetTemporaryExpr();
2399
Douglas Gregor2f599792010-04-02 18:24:57 +00002400 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall2de56d12010-08-25 11:45:40 +00002401 if (ICE->getCastKind() == CK_NoOp)
Douglas Gregor2f599792010-04-02 18:24:57 +00002402 E = ICE->getSubExpr();
2403 else
2404 break;
2405 }
2406
2407 while (const CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
2408 E = BE->getSubExpr();
2409
2410 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall2de56d12010-08-25 11:45:40 +00002411 if (ICE->getCastKind() == CK_NoOp)
Douglas Gregor2f599792010-04-02 18:24:57 +00002412 E = ICE->getSubExpr();
2413 else
2414 break;
2415 }
Anders Carlssonf8b30152010-11-28 16:40:49 +00002416
2417 return E->IgnoreParens();
Douglas Gregor2f599792010-04-02 18:24:57 +00002418}
2419
John McCall558d2ab2010-09-15 10:14:12 +00002420/// isTemporaryObject - Determines if this expression produces a
2421/// temporary of the given class type.
2422bool Expr::isTemporaryObject(ASTContext &C, const CXXRecordDecl *TempTy) const {
2423 if (!C.hasSameUnqualifiedType(getType(), C.getTypeDeclType(TempTy)))
2424 return false;
2425
Anders Carlssonf8b30152010-11-28 16:40:49 +00002426 const Expr *E = skipTemporaryBindingsNoOpCastsAndParens(this);
Douglas Gregor2f599792010-04-02 18:24:57 +00002427
John McCall58277b52010-09-15 20:59:13 +00002428 // Temporaries are by definition pr-values of class type.
Fariborz Jahaniandb148be2010-09-27 17:30:38 +00002429 if (!E->Classify(C).isPRValue()) {
2430 // In this context, property reference is a message call and is pr-value.
John McCall12f78a62010-12-02 01:19:52 +00002431 if (!isa<ObjCPropertyRefExpr>(E))
Fariborz Jahaniandb148be2010-09-27 17:30:38 +00002432 return false;
2433 }
Douglas Gregor2f599792010-04-02 18:24:57 +00002434
John McCall19e60ad2010-09-16 06:57:56 +00002435 // Black-list a few cases which yield pr-values of class type that don't
2436 // refer to temporaries of that type:
2437
2438 // - implicit derived-to-base conversions
John McCall558d2ab2010-09-15 10:14:12 +00002439 if (isa<ImplicitCastExpr>(E)) {
2440 switch (cast<ImplicitCastExpr>(E)->getCastKind()) {
2441 case CK_DerivedToBase:
2442 case CK_UncheckedDerivedToBase:
2443 return false;
2444 default:
2445 break;
2446 }
Douglas Gregor2f599792010-04-02 18:24:57 +00002447 }
2448
John McCall19e60ad2010-09-16 06:57:56 +00002449 // - member expressions (all)
2450 if (isa<MemberExpr>(E))
2451 return false;
2452
Eli Friedman32f498a2012-06-15 23:51:06 +00002453 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E))
2454 if (BO->isPtrMemOp())
2455 return false;
2456
John McCall56ca35d2011-02-17 10:25:35 +00002457 // - opaque values (all)
2458 if (isa<OpaqueValueExpr>(E))
2459 return false;
2460
John McCall558d2ab2010-09-15 10:14:12 +00002461 return true;
Douglas Gregor2f599792010-04-02 18:24:57 +00002462}
2463
Douglas Gregor75e85042011-03-02 21:06:53 +00002464bool Expr::isImplicitCXXThis() const {
2465 const Expr *E = this;
2466
2467 // Strip away parentheses and casts we don't care about.
2468 while (true) {
2469 if (const ParenExpr *Paren = dyn_cast<ParenExpr>(E)) {
2470 E = Paren->getSubExpr();
2471 continue;
2472 }
2473
2474 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2475 if (ICE->getCastKind() == CK_NoOp ||
2476 ICE->getCastKind() == CK_LValueToRValue ||
2477 ICE->getCastKind() == CK_DerivedToBase ||
2478 ICE->getCastKind() == CK_UncheckedDerivedToBase) {
2479 E = ICE->getSubExpr();
2480 continue;
2481 }
2482 }
2483
2484 if (const UnaryOperator* UnOp = dyn_cast<UnaryOperator>(E)) {
2485 if (UnOp->getOpcode() == UO_Extension) {
2486 E = UnOp->getSubExpr();
2487 continue;
2488 }
2489 }
2490
Douglas Gregor03e80032011-06-21 17:03:29 +00002491 if (const MaterializeTemporaryExpr *M
2492 = dyn_cast<MaterializeTemporaryExpr>(E)) {
2493 E = M->GetTemporaryExpr();
2494 continue;
2495 }
2496
Douglas Gregor75e85042011-03-02 21:06:53 +00002497 break;
2498 }
2499
2500 if (const CXXThisExpr *This = dyn_cast<CXXThisExpr>(E))
2501 return This->isImplicit();
2502
2503 return false;
2504}
2505
Douglas Gregor898574e2008-12-05 23:32:09 +00002506/// hasAnyTypeDependentArguments - Determines if any of the expressions
2507/// in Exprs is type-dependent.
Ahmed Charles13a140c2012-02-25 11:00:22 +00002508bool Expr::hasAnyTypeDependentArguments(llvm::ArrayRef<Expr *> Exprs) {
2509 for (unsigned I = 0; I < Exprs.size(); ++I)
Douglas Gregor898574e2008-12-05 23:32:09 +00002510 if (Exprs[I]->isTypeDependent())
2511 return true;
2512
2513 return false;
2514}
2515
John McCall4204f072010-08-02 21:13:48 +00002516bool Expr::isConstantInitializer(ASTContext &Ctx, bool IsForRef) const {
Eli Friedmanc39dc9a2009-01-25 03:12:18 +00002517 // This function is attempting whether an expression is an initializer
2518 // which can be evaluated at compile-time. isEvaluatable handles most
2519 // of the cases, but it can't deal with some initializer-specific
2520 // expressions, and it can't deal with aggregates; we deal with those here,
2521 // and fall back to isEvaluatable for the other cases.
2522
John McCall4204f072010-08-02 21:13:48 +00002523 // If we ever capture reference-binding directly in the AST, we can
2524 // kill the second parameter.
2525
2526 if (IsForRef) {
2527 EvalResult Result;
2528 return EvaluateAsLValue(Result, Ctx) && !Result.HasSideEffects;
2529 }
Eli Friedman1f4a6db2009-02-20 02:36:22 +00002530
Anders Carlssone8a32b82008-11-24 05:23:59 +00002531 switch (getStmtClass()) {
Eli Friedmanc39dc9a2009-01-25 03:12:18 +00002532 default: break;
Richard Smith4ec40892011-12-09 06:47:34 +00002533 case IntegerLiteralClass:
2534 case FloatingLiteralClass:
Anders Carlssone8a32b82008-11-24 05:23:59 +00002535 case StringLiteralClass:
Steve Naroff14108da2009-07-10 23:34:53 +00002536 case ObjCStringLiteralClass:
Chris Lattnereaf2bb82009-02-24 22:18:39 +00002537 case ObjCEncodeExprClass:
Anders Carlssone8a32b82008-11-24 05:23:59 +00002538 return true;
John McCallb4b9b152010-08-01 21:51:45 +00002539 case CXXTemporaryObjectExprClass:
2540 case CXXConstructExprClass: {
2541 const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
John McCall4204f072010-08-02 21:13:48 +00002542
2543 // Only if it's
Richard Smith180f4792011-11-10 06:34:14 +00002544 if (CE->getConstructor()->isTrivial()) {
2545 // 1) an application of the trivial default constructor or
2546 if (!CE->getNumArgs()) return true;
John McCall4204f072010-08-02 21:13:48 +00002547
Richard Smith180f4792011-11-10 06:34:14 +00002548 // 2) an elidable trivial copy construction of an operand which is
2549 // itself a constant initializer. Note that we consider the
2550 // operand on its own, *not* as a reference binding.
2551 if (CE->isElidable() &&
2552 CE->getArg(0)->isConstantInitializer(Ctx, false))
2553 return true;
2554 }
2555
2556 // 3) a foldable constexpr constructor.
2557 break;
John McCallb4b9b152010-08-01 21:51:45 +00002558 }
Nate Begeman59b5da62009-01-18 03:20:47 +00002559 case CompoundLiteralExprClass: {
Eli Friedman1f4a6db2009-02-20 02:36:22 +00002560 // This handles gcc's extension that allows global initializers like
2561 // "struct x {int x;} x = (struct x) {};".
2562 // FIXME: This accepts other cases it shouldn't!
Nate Begeman59b5da62009-01-18 03:20:47 +00002563 const Expr *Exp = cast<CompoundLiteralExpr>(this)->getInitializer();
John McCall4204f072010-08-02 21:13:48 +00002564 return Exp->isConstantInitializer(Ctx, false);
Nate Begeman59b5da62009-01-18 03:20:47 +00002565 }
Anders Carlssone8a32b82008-11-24 05:23:59 +00002566 case InitListExprClass: {
Eli Friedman1f4a6db2009-02-20 02:36:22 +00002567 // FIXME: This doesn't deal with fields with reference types correctly.
2568 // FIXME: This incorrectly allows pointers cast to integers to be assigned
2569 // to bitfields.
Anders Carlssone8a32b82008-11-24 05:23:59 +00002570 const InitListExpr *Exp = cast<InitListExpr>(this);
2571 unsigned numInits = Exp->getNumInits();
2572 for (unsigned i = 0; i < numInits; i++) {
John McCall4204f072010-08-02 21:13:48 +00002573 if (!Exp->getInit(i)->isConstantInitializer(Ctx, false))
Anders Carlssone8a32b82008-11-24 05:23:59 +00002574 return false;
2575 }
Eli Friedmanc39dc9a2009-01-25 03:12:18 +00002576 return true;
Anders Carlssone8a32b82008-11-24 05:23:59 +00002577 }
Douglas Gregor3498bdb2009-01-29 17:44:32 +00002578 case ImplicitValueInitExprClass:
2579 return true;
Chris Lattner3ae9f482009-10-13 07:14:16 +00002580 case ParenExprClass:
John McCall4204f072010-08-02 21:13:48 +00002581 return cast<ParenExpr>(this)->getSubExpr()
2582 ->isConstantInitializer(Ctx, IsForRef);
Peter Collingbournef111d932011-04-15 00:35:48 +00002583 case GenericSelectionExprClass:
2584 if (cast<GenericSelectionExpr>(this)->isResultDependent())
2585 return false;
2586 return cast<GenericSelectionExpr>(this)->getResultExpr()
2587 ->isConstantInitializer(Ctx, IsForRef);
Abramo Bagnara5cadfab2010-09-27 07:13:32 +00002588 case ChooseExprClass:
2589 return cast<ChooseExpr>(this)->getChosenSubExpr(Ctx)
2590 ->isConstantInitializer(Ctx, IsForRef);
Eli Friedmanc39dc9a2009-01-25 03:12:18 +00002591 case UnaryOperatorClass: {
2592 const UnaryOperator* Exp = cast<UnaryOperator>(this);
John McCall2de56d12010-08-25 11:45:40 +00002593 if (Exp->getOpcode() == UO_Extension)
John McCall4204f072010-08-02 21:13:48 +00002594 return Exp->getSubExpr()->isConstantInitializer(Ctx, false);
Eli Friedmanc39dc9a2009-01-25 03:12:18 +00002595 break;
2596 }
John McCall4204f072010-08-02 21:13:48 +00002597 case CXXFunctionalCastExprClass:
John McCallb4b9b152010-08-01 21:51:45 +00002598 case CXXStaticCastExprClass:
Chris Lattner81045d82009-04-21 05:19:11 +00002599 case ImplicitCastExprClass:
Richard Smithd62ca372011-12-06 22:44:34 +00002600 case CStyleCastExprClass: {
2601 const CastExpr *CE = cast<CastExpr>(this);
2602
David Chisnall7a7ee302012-01-16 17:27:18 +00002603 // If we're promoting an integer to an _Atomic type then this is constant
2604 // if the integer is constant. We also need to check the converse in case
2605 // someone does something like:
2606 //
2607 // int a = (_Atomic(int))42;
2608 //
2609 // I doubt anyone would write code like this directly, but it's quite
2610 // possible as the result of macro expansions.
2611 if (CE->getCastKind() == CK_NonAtomicToAtomic ||
2612 CE->getCastKind() == CK_AtomicToNonAtomic)
2613 return CE->getSubExpr()->isConstantInitializer(Ctx, false);
2614
Richard Smithd62ca372011-12-06 22:44:34 +00002615 // Handle bitcasts of vector constants.
2616 if (getType()->isVectorType() && CE->getCastKind() == CK_BitCast)
2617 return CE->getSubExpr()->isConstantInitializer(Ctx, false);
2618
Eli Friedman6bd97192011-12-21 00:43:02 +00002619 // Handle misc casts we want to ignore.
2620 // FIXME: Is it really safe to ignore all these?
2621 if (CE->getCastKind() == CK_NoOp ||
2622 CE->getCastKind() == CK_LValueToRValue ||
2623 CE->getCastKind() == CK_ToUnion ||
2624 CE->getCastKind() == CK_ConstructorConversion)
Richard Smithd62ca372011-12-06 22:44:34 +00002625 return CE->getSubExpr()->isConstantInitializer(Ctx, false);
2626
Eli Friedmanc39dc9a2009-01-25 03:12:18 +00002627 break;
Richard Smithd62ca372011-12-06 22:44:34 +00002628 }
Douglas Gregor03e80032011-06-21 17:03:29 +00002629 case MaterializeTemporaryExprClass:
Chris Lattner5f9e2722011-07-23 10:55:15 +00002630 return cast<MaterializeTemporaryExpr>(this)->GetTemporaryExpr()
Douglas Gregor03e80032011-06-21 17:03:29 +00002631 ->isConstantInitializer(Ctx, false);
Anders Carlssone8a32b82008-11-24 05:23:59 +00002632 }
Eli Friedmanc39dc9a2009-01-25 03:12:18 +00002633 return isEvaluatable(Ctx);
Steve Naroff38374b02007-09-02 20:30:18 +00002634}
2635
Richard Smith8ae4ec22012-08-07 04:16:51 +00002636bool Expr::HasSideEffects(const ASTContext &Ctx) const {
2637 if (isInstantiationDependent())
2638 return true;
2639
2640 switch (getStmtClass()) {
2641 case NoStmtClass:
2642 #define ABSTRACT_STMT(Type)
2643 #define STMT(Type, Base) case Type##Class:
2644 #define EXPR(Type, Base)
2645 #include "clang/AST/StmtNodes.inc"
2646 llvm_unreachable("unexpected Expr kind");
2647
2648 case DependentScopeDeclRefExprClass:
2649 case CXXUnresolvedConstructExprClass:
2650 case CXXDependentScopeMemberExprClass:
2651 case UnresolvedLookupExprClass:
2652 case UnresolvedMemberExprClass:
2653 case PackExpansionExprClass:
2654 case SubstNonTypeTemplateParmPackExprClass:
Richard Smith9a4db032012-09-12 00:56:43 +00002655 case FunctionParmPackExprClass:
Richard Smith8ae4ec22012-08-07 04:16:51 +00002656 llvm_unreachable("shouldn't see dependent / unresolved nodes here");
2657
Richard Smith60b70382012-08-07 05:18:29 +00002658 case DeclRefExprClass:
2659 case ObjCIvarRefExprClass:
Richard Smith8ae4ec22012-08-07 04:16:51 +00002660 case PredefinedExprClass:
2661 case IntegerLiteralClass:
2662 case FloatingLiteralClass:
2663 case ImaginaryLiteralClass:
2664 case StringLiteralClass:
2665 case CharacterLiteralClass:
2666 case OffsetOfExprClass:
2667 case ImplicitValueInitExprClass:
2668 case UnaryExprOrTypeTraitExprClass:
2669 case AddrLabelExprClass:
2670 case GNUNullExprClass:
2671 case CXXBoolLiteralExprClass:
2672 case CXXNullPtrLiteralExprClass:
2673 case CXXThisExprClass:
2674 case CXXScalarValueInitExprClass:
2675 case TypeTraitExprClass:
2676 case UnaryTypeTraitExprClass:
2677 case BinaryTypeTraitExprClass:
2678 case ArrayTypeTraitExprClass:
2679 case ExpressionTraitExprClass:
2680 case CXXNoexceptExprClass:
2681 case SizeOfPackExprClass:
2682 case ObjCStringLiteralClass:
2683 case ObjCEncodeExprClass:
2684 case ObjCBoolLiteralExprClass:
2685 case CXXUuidofExprClass:
2686 case OpaqueValueExprClass:
2687 // These never have a side-effect.
2688 return false;
2689
2690 case CallExprClass:
2691 case CompoundAssignOperatorClass:
2692 case VAArgExprClass:
2693 case AtomicExprClass:
2694 case StmtExprClass:
2695 case CXXOperatorCallExprClass:
2696 case CXXMemberCallExprClass:
2697 case UserDefinedLiteralClass:
2698 case CXXThrowExprClass:
2699 case CXXNewExprClass:
2700 case CXXDeleteExprClass:
2701 case ExprWithCleanupsClass:
2702 case CXXBindTemporaryExprClass:
2703 case BlockExprClass:
2704 case CUDAKernelCallExprClass:
2705 // These always have a side-effect.
2706 return true;
2707
2708 case ParenExprClass:
2709 case ArraySubscriptExprClass:
2710 case MemberExprClass:
2711 case ConditionalOperatorClass:
2712 case BinaryConditionalOperatorClass:
Richard Smith8ae4ec22012-08-07 04:16:51 +00002713 case CompoundLiteralExprClass:
2714 case ExtVectorElementExprClass:
2715 case DesignatedInitExprClass:
2716 case ParenListExprClass:
Richard Smith8ae4ec22012-08-07 04:16:51 +00002717 case CXXPseudoDestructorExprClass:
2718 case SubstNonTypeTemplateParmExprClass:
2719 case MaterializeTemporaryExprClass:
2720 case ShuffleVectorExprClass:
2721 case AsTypeExprClass:
2722 // These have a side-effect if any subexpression does.
2723 break;
2724
Richard Smith60b70382012-08-07 05:18:29 +00002725 case UnaryOperatorClass:
2726 if (cast<UnaryOperator>(this)->isIncrementDecrementOp())
Richard Smith8ae4ec22012-08-07 04:16:51 +00002727 return true;
2728 break;
Richard Smith8ae4ec22012-08-07 04:16:51 +00002729
2730 case BinaryOperatorClass:
2731 if (cast<BinaryOperator>(this)->isAssignmentOp())
2732 return true;
2733 break;
2734
Richard Smith8ae4ec22012-08-07 04:16:51 +00002735 case InitListExprClass:
2736 // FIXME: The children for an InitListExpr doesn't include the array filler.
2737 if (const Expr *E = cast<InitListExpr>(this)->getArrayFiller())
2738 if (E->HasSideEffects(Ctx))
2739 return true;
2740 break;
2741
2742 case GenericSelectionExprClass:
2743 return cast<GenericSelectionExpr>(this)->getResultExpr()->
2744 HasSideEffects(Ctx);
2745
2746 case ChooseExprClass:
2747 return cast<ChooseExpr>(this)->getChosenSubExpr(Ctx)->HasSideEffects(Ctx);
2748
2749 case CXXDefaultArgExprClass:
2750 return cast<CXXDefaultArgExpr>(this)->getExpr()->HasSideEffects(Ctx);
2751
2752 case CXXDynamicCastExprClass: {
2753 // A dynamic_cast expression has side-effects if it can throw.
2754 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(this);
2755 if (DCE->getTypeAsWritten()->isReferenceType() &&
2756 DCE->getCastKind() == CK_Dynamic)
2757 return true;
Richard Smith60b70382012-08-07 05:18:29 +00002758 } // Fall through.
2759 case ImplicitCastExprClass:
2760 case CStyleCastExprClass:
2761 case CXXStaticCastExprClass:
2762 case CXXReinterpretCastExprClass:
2763 case CXXConstCastExprClass:
2764 case CXXFunctionalCastExprClass: {
2765 const CastExpr *CE = cast<CastExpr>(this);
2766 if (CE->getCastKind() == CK_LValueToRValue &&
2767 CE->getSubExpr()->getType().isVolatileQualified())
2768 return true;
Richard Smith8ae4ec22012-08-07 04:16:51 +00002769 break;
2770 }
2771
Richard Smith0d729102012-08-13 20:08:14 +00002772 case CXXTypeidExprClass:
2773 // typeid might throw if its subexpression is potentially-evaluated, so has
2774 // side-effects in that case whether or not its subexpression does.
2775 return cast<CXXTypeidExpr>(this)->isPotentiallyEvaluated();
Richard Smith8ae4ec22012-08-07 04:16:51 +00002776
2777 case CXXConstructExprClass:
2778 case CXXTemporaryObjectExprClass: {
2779 const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
Richard Smith60b70382012-08-07 05:18:29 +00002780 if (!CE->getConstructor()->isTrivial())
Richard Smith8ae4ec22012-08-07 04:16:51 +00002781 return true;
Richard Smith60b70382012-08-07 05:18:29 +00002782 // A trivial constructor does not add any side-effects of its own. Just look
2783 // at its arguments.
Richard Smith8ae4ec22012-08-07 04:16:51 +00002784 break;
2785 }
2786
2787 case LambdaExprClass: {
2788 const LambdaExpr *LE = cast<LambdaExpr>(this);
2789 for (LambdaExpr::capture_iterator I = LE->capture_begin(),
2790 E = LE->capture_end(); I != E; ++I)
2791 if (I->getCaptureKind() == LCK_ByCopy)
2792 // FIXME: Only has a side-effect if the variable is volatile or if
2793 // the copy would invoke a non-trivial copy constructor.
2794 return true;
2795 return false;
2796 }
2797
2798 case PseudoObjectExprClass: {
2799 // Only look for side-effects in the semantic form, and look past
2800 // OpaqueValueExpr bindings in that form.
2801 const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this);
2802 for (PseudoObjectExpr::const_semantics_iterator I = PO->semantics_begin(),
2803 E = PO->semantics_end();
2804 I != E; ++I) {
2805 const Expr *Subexpr = *I;
2806 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Subexpr))
2807 Subexpr = OVE->getSourceExpr();
2808 if (Subexpr->HasSideEffects(Ctx))
2809 return true;
2810 }
2811 return false;
2812 }
2813
2814 case ObjCBoxedExprClass:
2815 case ObjCArrayLiteralClass:
2816 case ObjCDictionaryLiteralClass:
2817 case ObjCMessageExprClass:
2818 case ObjCSelectorExprClass:
2819 case ObjCProtocolExprClass:
2820 case ObjCPropertyRefExprClass:
2821 case ObjCIsaExprClass:
2822 case ObjCIndirectCopyRestoreExprClass:
2823 case ObjCSubscriptRefExprClass:
2824 case ObjCBridgedCastExprClass:
2825 // FIXME: Classify these cases better.
2826 return true;
2827 }
2828
2829 // Recurse to children.
2830 for (const_child_range SubStmts = children(); SubStmts; ++SubStmts)
2831 if (const Stmt *S = *SubStmts)
2832 if (cast<Expr>(S)->HasSideEffects(Ctx))
2833 return true;
2834
2835 return false;
2836}
2837
Douglas Gregor25d0a0f2012-02-23 07:33:15 +00002838namespace {
2839 /// \brief Look for a call to a non-trivial function within an expression.
2840 class NonTrivialCallFinder : public EvaluatedExprVisitor<NonTrivialCallFinder>
2841 {
2842 typedef EvaluatedExprVisitor<NonTrivialCallFinder> Inherited;
2843
2844 bool NonTrivial;
2845
2846 public:
2847 explicit NonTrivialCallFinder(ASTContext &Context)
Douglas Gregorb11e5252012-02-23 07:44:18 +00002848 : Inherited(Context), NonTrivial(false) { }
Douglas Gregor25d0a0f2012-02-23 07:33:15 +00002849
2850 bool hasNonTrivialCall() const { return NonTrivial; }
2851
2852 void VisitCallExpr(CallExpr *E) {
2853 if (CXXMethodDecl *Method
2854 = dyn_cast_or_null<CXXMethodDecl>(E->getCalleeDecl())) {
2855 if (Method->isTrivial()) {
2856 // Recurse to children of the call.
2857 Inherited::VisitStmt(E);
2858 return;
2859 }
2860 }
2861
2862 NonTrivial = true;
2863 }
2864
2865 void VisitCXXConstructExpr(CXXConstructExpr *E) {
2866 if (E->getConstructor()->isTrivial()) {
2867 // Recurse to children of the call.
2868 Inherited::VisitStmt(E);
2869 return;
2870 }
2871
2872 NonTrivial = true;
2873 }
2874
2875 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
2876 if (E->getTemporary()->getDestructor()->isTrivial()) {
2877 Inherited::VisitStmt(E);
2878 return;
2879 }
2880
2881 NonTrivial = true;
2882 }
2883 };
2884}
2885
2886bool Expr::hasNonTrivialCall(ASTContext &Ctx) {
2887 NonTrivialCallFinder Finder(Ctx);
2888 Finder.Visit(this);
2889 return Finder.hasNonTrivialCall();
2890}
2891
Chandler Carruth82214a82011-02-18 23:54:50 +00002892/// isNullPointerConstant - C99 6.3.2.3p3 - Return whether this is a null
2893/// pointer constant or not, as well as the specific kind of constant detected.
2894/// Null pointer constants can be integer constant expressions with the
2895/// value zero, casts of zero to void*, nullptr (C++0X), or __null
2896/// (a GNU extension).
2897Expr::NullPointerConstantKind
2898Expr::isNullPointerConstant(ASTContext &Ctx,
2899 NullPointerConstantValueDependence NPC) const {
Douglas Gregorce940492009-09-25 04:25:58 +00002900 if (isValueDependent()) {
2901 switch (NPC) {
2902 case NPC_NeverValueDependent:
David Blaikieb219cfc2011-09-23 05:06:16 +00002903 llvm_unreachable("Unexpected value dependent expression!");
Douglas Gregorce940492009-09-25 04:25:58 +00002904 case NPC_ValueDependentIsNull:
Chandler Carruth82214a82011-02-18 23:54:50 +00002905 if (isTypeDependent() || getType()->isIntegralType(Ctx))
David Blaikie50800fc2012-08-08 17:33:31 +00002906 return NPCK_ZeroExpression;
Chandler Carruth82214a82011-02-18 23:54:50 +00002907 else
2908 return NPCK_NotNull;
Sean Huntc3021132010-05-05 15:23:54 +00002909
Douglas Gregorce940492009-09-25 04:25:58 +00002910 case NPC_ValueDependentIsNotNull:
Chandler Carruth82214a82011-02-18 23:54:50 +00002911 return NPCK_NotNull;
Douglas Gregorce940492009-09-25 04:25:58 +00002912 }
2913 }
Daniel Dunbarf515b222009-09-18 08:46:16 +00002914
Sebastian Redl07779722008-10-31 14:43:28 +00002915 // Strip off a cast to void*, if it exists. Except in C++.
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002916 if (const ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(this)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002917 if (!Ctx.getLangOpts().CPlusPlus) {
Sebastian Redl07779722008-10-31 14:43:28 +00002918 // Check that it is a cast to void*.
Ted Kremenek6217b802009-07-29 21:53:49 +00002919 if (const PointerType *PT = CE->getType()->getAs<PointerType>()) {
Sebastian Redl07779722008-10-31 14:43:28 +00002920 QualType Pointee = PT->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00002921 if (!Pointee.hasQualifiers() &&
Sebastian Redl07779722008-10-31 14:43:28 +00002922 Pointee->isVoidType() && // to void*
2923 CE->getSubExpr()->getType()->isIntegerType()) // from int.
Douglas Gregorce940492009-09-25 04:25:58 +00002924 return CE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
Sebastian Redl07779722008-10-31 14:43:28 +00002925 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002926 }
Steve Naroffaa58f002008-01-14 16:10:57 +00002927 } else if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(this)) {
2928 // Ignore the ImplicitCastExpr type entirely.
Douglas Gregorce940492009-09-25 04:25:58 +00002929 return ICE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
Steve Naroffaa58f002008-01-14 16:10:57 +00002930 } else if (const ParenExpr *PE = dyn_cast<ParenExpr>(this)) {
2931 // Accept ((void*)0) as a null pointer constant, as many other
2932 // implementations do.
Douglas Gregorce940492009-09-25 04:25:58 +00002933 return PE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
Peter Collingbournef111d932011-04-15 00:35:48 +00002934 } else if (const GenericSelectionExpr *GE =
2935 dyn_cast<GenericSelectionExpr>(this)) {
2936 return GE->getResultExpr()->isNullPointerConstant(Ctx, NPC);
Mike Stump1eb44332009-09-09 15:08:12 +00002937 } else if (const CXXDefaultArgExpr *DefaultArg
Chris Lattner8123a952008-04-10 02:22:51 +00002938 = dyn_cast<CXXDefaultArgExpr>(this)) {
Chris Lattner04421082008-04-08 04:40:51 +00002939 // See through default argument expressions
Douglas Gregorce940492009-09-25 04:25:58 +00002940 return DefaultArg->getExpr()->isNullPointerConstant(Ctx, NPC);
Douglas Gregor2d8b2732008-11-29 04:51:27 +00002941 } else if (isa<GNUNullExpr>(this)) {
2942 // The GNU __null extension is always a null pointer constant.
Chandler Carruth82214a82011-02-18 23:54:50 +00002943 return NPCK_GNUNull;
Douglas Gregor03e80032011-06-21 17:03:29 +00002944 } else if (const MaterializeTemporaryExpr *M
2945 = dyn_cast<MaterializeTemporaryExpr>(this)) {
2946 return M->GetTemporaryExpr()->isNullPointerConstant(Ctx, NPC);
John McCall4b9c2d22011-11-06 09:01:30 +00002947 } else if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(this)) {
2948 if (const Expr *Source = OVE->getSourceExpr())
2949 return Source->isNullPointerConstant(Ctx, NPC);
Steve Naroffaaffbf72008-01-14 02:53:34 +00002950 }
Douglas Gregor2d8b2732008-11-29 04:51:27 +00002951
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002952 // C++0x nullptr_t is always a null pointer constant.
2953 if (getType()->isNullPtrType())
Chandler Carruth82214a82011-02-18 23:54:50 +00002954 return NPCK_CXX0X_nullptr;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002955
Fariborz Jahanianff3a0782010-09-27 22:42:37 +00002956 if (const RecordType *UT = getType()->getAsUnionType())
2957 if (UT && UT->getDecl()->hasAttr<TransparentUnionAttr>())
2958 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(this)){
2959 const Expr *InitExpr = CLE->getInitializer();
2960 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(InitExpr))
2961 return ILE->getInit(0)->isNullPointerConstant(Ctx, NPC);
2962 }
Steve Naroffaa58f002008-01-14 16:10:57 +00002963 // This expression must be an integer type.
Sean Huntc3021132010-05-05 15:23:54 +00002964 if (!getType()->isIntegerType() ||
David Blaikie4e4d0842012-03-11 07:00:24 +00002965 (Ctx.getLangOpts().CPlusPlus && getType()->isEnumeralType()))
Chandler Carruth82214a82011-02-18 23:54:50 +00002966 return NPCK_NotNull;
Mike Stump1eb44332009-09-09 15:08:12 +00002967
Reid Spencer5f016e22007-07-11 17:01:13 +00002968 // If we have an integer constant expression, we need to *evaluate* it and
Richard Smith70488e22012-02-14 21:38:30 +00002969 // test for the value 0. Don't use the C++11 constant expression semantics
2970 // for this, for now; once the dust settles on core issue 903, we might only
2971 // allow a literal 0 here in C++11 mode.
David Blaikie4e4d0842012-03-11 07:00:24 +00002972 if (Ctx.getLangOpts().CPlusPlus0x) {
Richard Smith70488e22012-02-14 21:38:30 +00002973 if (!isCXX98IntegralConstantExpr(Ctx))
2974 return NPCK_NotNull;
2975 } else {
2976 if (!isIntegerConstantExpr(Ctx))
2977 return NPCK_NotNull;
2978 }
Chandler Carruth82214a82011-02-18 23:54:50 +00002979
David Blaikie50800fc2012-08-08 17:33:31 +00002980 if (EvaluateKnownConstInt(Ctx) != 0)
2981 return NPCK_NotNull;
2982
2983 if (isa<IntegerLiteral>(this))
2984 return NPCK_ZeroLiteral;
2985 return NPCK_ZeroExpression;
Reid Spencer5f016e22007-07-11 17:01:13 +00002986}
Steve Naroff31a45842007-07-28 23:10:27 +00002987
John McCallf6a16482010-12-04 03:47:34 +00002988/// \brief If this expression is an l-value for an Objective C
2989/// property, find the underlying property reference expression.
2990const ObjCPropertyRefExpr *Expr::getObjCProperty() const {
2991 const Expr *E = this;
2992 while (true) {
2993 assert((E->getValueKind() == VK_LValue &&
2994 E->getObjectKind() == OK_ObjCProperty) &&
2995 "expression is not a property reference");
2996 E = E->IgnoreParenCasts();
2997 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2998 if (BO->getOpcode() == BO_Comma) {
2999 E = BO->getRHS();
3000 continue;
3001 }
3002 }
3003
3004 break;
3005 }
3006
3007 return cast<ObjCPropertyRefExpr>(E);
3008}
3009
Anna Zaksbbff82f2012-10-01 20:34:04 +00003010bool Expr::isObjCSelfExpr() const {
3011 const Expr *E = IgnoreParenImpCasts();
3012
3013 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
3014 if (!DRE)
3015 return false;
3016
3017 const ImplicitParamDecl *Param = dyn_cast<ImplicitParamDecl>(DRE->getDecl());
3018 if (!Param)
3019 return false;
3020
3021 const ObjCMethodDecl *M = dyn_cast<ObjCMethodDecl>(Param->getDeclContext());
3022 if (!M)
3023 return false;
3024
3025 return M->getSelfDecl() == Param;
3026}
3027
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003028FieldDecl *Expr::getBitField() {
Douglas Gregor6f4a69a2009-07-06 15:38:40 +00003029 Expr *E = this->IgnoreParens();
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003030
Douglas Gregorde4b1d82010-01-29 19:14:02 +00003031 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCallf6a16482010-12-04 03:47:34 +00003032 if (ICE->getCastKind() == CK_LValueToRValue ||
3033 (ICE->getValueKind() != VK_RValue && ICE->getCastKind() == CK_NoOp))
Douglas Gregorde4b1d82010-01-29 19:14:02 +00003034 E = ICE->getSubExpr()->IgnoreParens();
3035 else
3036 break;
3037 }
3038
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003039 if (MemberExpr *MemRef = dyn_cast<MemberExpr>(E))
Douglas Gregor86f19402008-12-20 23:49:58 +00003040 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemRef->getMemberDecl()))
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003041 if (Field->isBitField())
3042 return Field;
3043
Argyrios Kyrtzidis0f279e72010-10-30 19:52:22 +00003044 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E))
3045 if (FieldDecl *Field = dyn_cast<FieldDecl>(DeclRef->getDecl()))
3046 if (Field->isBitField())
3047 return Field;
3048
Eli Friedman42068e92011-07-13 02:05:57 +00003049 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(E)) {
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003050 if (BinOp->isAssignmentOp() && BinOp->getLHS())
3051 return BinOp->getLHS()->getBitField();
3052
Eli Friedman42068e92011-07-13 02:05:57 +00003053 if (BinOp->getOpcode() == BO_Comma && BinOp->getRHS())
3054 return BinOp->getRHS()->getBitField();
3055 }
3056
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003057 return 0;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003058}
3059
Anders Carlsson09380262010-01-31 17:18:49 +00003060bool Expr::refersToVectorElement() const {
3061 const Expr *E = this->IgnoreParens();
Sean Huntc3021132010-05-05 15:23:54 +00003062
Anders Carlsson09380262010-01-31 17:18:49 +00003063 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall5baba9d2010-08-25 10:28:54 +00003064 if (ICE->getValueKind() != VK_RValue &&
John McCall2de56d12010-08-25 11:45:40 +00003065 ICE->getCastKind() == CK_NoOp)
Anders Carlsson09380262010-01-31 17:18:49 +00003066 E = ICE->getSubExpr()->IgnoreParens();
3067 else
3068 break;
3069 }
Sean Huntc3021132010-05-05 15:23:54 +00003070
Anders Carlsson09380262010-01-31 17:18:49 +00003071 if (const ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(E))
3072 return ASE->getBase()->getType()->isVectorType();
3073
3074 if (isa<ExtVectorElementExpr>(E))
3075 return true;
3076
3077 return false;
3078}
3079
Chris Lattner2140e902009-02-16 22:14:05 +00003080/// isArrow - Return true if the base expression is a pointer to vector,
3081/// return false if the base expression is a vector.
3082bool ExtVectorElementExpr::isArrow() const {
3083 return getBase()->getType()->isPointerType();
3084}
3085
Nate Begeman213541a2008-04-18 23:10:10 +00003086unsigned ExtVectorElementExpr::getNumElements() const {
John McCall183700f2009-09-21 23:43:11 +00003087 if (const VectorType *VT = getType()->getAs<VectorType>())
Nate Begeman8a997642008-05-09 06:41:27 +00003088 return VT->getNumElements();
3089 return 1;
Chris Lattner4d0ac882007-08-03 16:00:20 +00003090}
3091
Nate Begeman8a997642008-05-09 06:41:27 +00003092/// containsDuplicateElements - Return true if any element access is repeated.
Nate Begeman213541a2008-04-18 23:10:10 +00003093bool ExtVectorElementExpr::containsDuplicateElements() const {
Daniel Dunbara2b34eb2009-10-18 02:09:09 +00003094 // FIXME: Refactor this code to an accessor on the AST node which returns the
3095 // "type" of component access, and share with code below and in Sema.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003096 StringRef Comp = Accessor->getName();
Nate Begeman190d6a22009-01-18 02:01:21 +00003097
3098 // Halving swizzles do not contain duplicate elements.
Daniel Dunbar15027422009-10-17 23:53:04 +00003099 if (Comp == "hi" || Comp == "lo" || Comp == "even" || Comp == "odd")
Nate Begeman190d6a22009-01-18 02:01:21 +00003100 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003101
Nate Begeman190d6a22009-01-18 02:01:21 +00003102 // Advance past s-char prefix on hex swizzles.
Daniel Dunbar15027422009-10-17 23:53:04 +00003103 if (Comp[0] == 's' || Comp[0] == 'S')
3104 Comp = Comp.substr(1);
Mike Stump1eb44332009-09-09 15:08:12 +00003105
Daniel Dunbar15027422009-10-17 23:53:04 +00003106 for (unsigned i = 0, e = Comp.size(); i != e; ++i)
Chris Lattner5f9e2722011-07-23 10:55:15 +00003107 if (Comp.substr(i + 1).find(Comp[i]) != StringRef::npos)
Steve Narofffec0b492007-07-30 03:29:09 +00003108 return true;
Daniel Dunbar15027422009-10-17 23:53:04 +00003109
Steve Narofffec0b492007-07-30 03:29:09 +00003110 return false;
3111}
Chris Lattnerb8f849d2007-08-02 23:36:59 +00003112
Nate Begeman8a997642008-05-09 06:41:27 +00003113/// getEncodedElementAccess - We encode the fields as a llvm ConstantArray.
Nate Begeman3b8d1162008-05-13 21:03:02 +00003114void ExtVectorElementExpr::getEncodedElementAccess(
Chris Lattner5f9e2722011-07-23 10:55:15 +00003115 SmallVectorImpl<unsigned> &Elts) const {
3116 StringRef Comp = Accessor->getName();
Daniel Dunbar4b55b242009-10-18 02:09:31 +00003117 if (Comp[0] == 's' || Comp[0] == 'S')
3118 Comp = Comp.substr(1);
Mike Stump1eb44332009-09-09 15:08:12 +00003119
Daniel Dunbar4b55b242009-10-18 02:09:31 +00003120 bool isHi = Comp == "hi";
3121 bool isLo = Comp == "lo";
3122 bool isEven = Comp == "even";
3123 bool isOdd = Comp == "odd";
Mike Stump1eb44332009-09-09 15:08:12 +00003124
Nate Begeman8a997642008-05-09 06:41:27 +00003125 for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
3126 uint64_t Index;
Mike Stump1eb44332009-09-09 15:08:12 +00003127
Nate Begeman8a997642008-05-09 06:41:27 +00003128 if (isHi)
3129 Index = e + i;
3130 else if (isLo)
3131 Index = i;
3132 else if (isEven)
3133 Index = 2 * i;
3134 else if (isOdd)
3135 Index = 2 * i + 1;
3136 else
Daniel Dunbar4b55b242009-10-18 02:09:31 +00003137 Index = ExtVectorType::getAccessorIdx(Comp[i]);
Chris Lattnerb8f849d2007-08-02 23:36:59 +00003138
Nate Begeman3b8d1162008-05-13 21:03:02 +00003139 Elts.push_back(Index);
Chris Lattnerb8f849d2007-08-02 23:36:59 +00003140 }
Nate Begeman8a997642008-05-09 06:41:27 +00003141}
3142
Douglas Gregor04badcf2010-04-21 00:45:42 +00003143ObjCMessageExpr::ObjCMessageExpr(QualType T,
John McCallf89e55a2010-11-18 06:31:45 +00003144 ExprValueKind VK,
Douglas Gregor04badcf2010-04-21 00:45:42 +00003145 SourceLocation LBracLoc,
3146 SourceLocation SuperLoc,
3147 bool IsInstanceSuper,
3148 QualType SuperType,
Sean Huntc3021132010-05-05 15:23:54 +00003149 Selector Sel,
Argyrios Kyrtzidis20718082011-10-03 06:36:51 +00003150 ArrayRef<SourceLocation> SelLocs,
3151 SelectorLocationsKind SelLocsK,
Douglas Gregor04badcf2010-04-21 00:45:42 +00003152 ObjCMethodDecl *Method,
Argyrios Kyrtzidis8d9ed792011-10-03 06:36:45 +00003153 ArrayRef<Expr *> Args,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00003154 SourceLocation RBracLoc,
3155 bool isImplicit)
John McCallf89e55a2010-11-18 06:31:45 +00003156 : Expr(ObjCMessageExprClass, T, VK, OK_Ordinary,
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00003157 /*TypeDependent=*/false, /*ValueDependent=*/false,
Douglas Gregor561f8122011-07-01 01:22:09 +00003158 /*InstantiationDependent=*/false,
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00003159 /*ContainsUnexpandedParameterPack=*/false),
Douglas Gregor04badcf2010-04-21 00:45:42 +00003160 SelectorOrMethod(reinterpret_cast<uintptr_t>(Method? Method
3161 : Sel.getAsOpaquePtr())),
Argyrios Kyrtzidisb994e6c2011-10-03 06:36:55 +00003162 Kind(IsInstanceSuper? SuperInstance : SuperClass),
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00003163 HasMethod(Method != 0), IsDelegateInitCall(false), IsImplicit(isImplicit),
3164 SuperLoc(SuperLoc), LBracLoc(LBracLoc), RBracLoc(RBracLoc)
Douglas Gregorc2350e52010-03-08 16:40:19 +00003165{
Argyrios Kyrtzidis20718082011-10-03 06:36:51 +00003166 initArgsAndSelLocs(Args, SelLocs, SelLocsK);
Douglas Gregor04badcf2010-04-21 00:45:42 +00003167 setReceiverPointer(SuperType.getAsOpaquePtr());
Ted Kremenek4df728e2008-06-24 15:50:53 +00003168}
3169
Douglas Gregor04badcf2010-04-21 00:45:42 +00003170ObjCMessageExpr::ObjCMessageExpr(QualType T,
John McCallf89e55a2010-11-18 06:31:45 +00003171 ExprValueKind VK,
Douglas Gregor04badcf2010-04-21 00:45:42 +00003172 SourceLocation LBracLoc,
3173 TypeSourceInfo *Receiver,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00003174 Selector Sel,
Argyrios Kyrtzidis20718082011-10-03 06:36:51 +00003175 ArrayRef<SourceLocation> SelLocs,
3176 SelectorLocationsKind SelLocsK,
Douglas Gregor04badcf2010-04-21 00:45:42 +00003177 ObjCMethodDecl *Method,
Argyrios Kyrtzidis8d9ed792011-10-03 06:36:45 +00003178 ArrayRef<Expr *> Args,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00003179 SourceLocation RBracLoc,
3180 bool isImplicit)
John McCallf89e55a2010-11-18 06:31:45 +00003181 : Expr(ObjCMessageExprClass, T, VK, OK_Ordinary, T->isDependentType(),
Douglas Gregor561f8122011-07-01 01:22:09 +00003182 T->isDependentType(), T->isInstantiationDependentType(),
3183 T->containsUnexpandedParameterPack()),
Douglas Gregor04badcf2010-04-21 00:45:42 +00003184 SelectorOrMethod(reinterpret_cast<uintptr_t>(Method? Method
3185 : Sel.getAsOpaquePtr())),
Argyrios Kyrtzidisb994e6c2011-10-03 06:36:55 +00003186 Kind(Class),
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00003187 HasMethod(Method != 0), IsDelegateInitCall(false), IsImplicit(isImplicit),
Argyrios Kyrtzidis20718082011-10-03 06:36:51 +00003188 LBracLoc(LBracLoc), RBracLoc(RBracLoc)
Douglas Gregor04badcf2010-04-21 00:45:42 +00003189{
Argyrios Kyrtzidis20718082011-10-03 06:36:51 +00003190 initArgsAndSelLocs(Args, SelLocs, SelLocsK);
Douglas Gregor04badcf2010-04-21 00:45:42 +00003191 setReceiverPointer(Receiver);
Ted Kremenek4df728e2008-06-24 15:50:53 +00003192}
3193
Douglas Gregor04badcf2010-04-21 00:45:42 +00003194ObjCMessageExpr::ObjCMessageExpr(QualType T,
John McCallf89e55a2010-11-18 06:31:45 +00003195 ExprValueKind VK,
Douglas Gregor04badcf2010-04-21 00:45:42 +00003196 SourceLocation LBracLoc,
3197 Expr *Receiver,
Sean Huntc3021132010-05-05 15:23:54 +00003198 Selector Sel,
Argyrios Kyrtzidis20718082011-10-03 06:36:51 +00003199 ArrayRef<SourceLocation> SelLocs,
3200 SelectorLocationsKind SelLocsK,
Douglas Gregor04badcf2010-04-21 00:45:42 +00003201 ObjCMethodDecl *Method,
Argyrios Kyrtzidis8d9ed792011-10-03 06:36:45 +00003202 ArrayRef<Expr *> Args,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00003203 SourceLocation RBracLoc,
3204 bool isImplicit)
John McCallf89e55a2010-11-18 06:31:45 +00003205 : Expr(ObjCMessageExprClass, T, VK, OK_Ordinary, Receiver->isTypeDependent(),
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00003206 Receiver->isTypeDependent(),
Douglas Gregor561f8122011-07-01 01:22:09 +00003207 Receiver->isInstantiationDependent(),
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00003208 Receiver->containsUnexpandedParameterPack()),
Douglas Gregor04badcf2010-04-21 00:45:42 +00003209 SelectorOrMethod(reinterpret_cast<uintptr_t>(Method? Method
3210 : Sel.getAsOpaquePtr())),
Argyrios Kyrtzidisb994e6c2011-10-03 06:36:55 +00003211 Kind(Instance),
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00003212 HasMethod(Method != 0), IsDelegateInitCall(false), IsImplicit(isImplicit),
Argyrios Kyrtzidis20718082011-10-03 06:36:51 +00003213 LBracLoc(LBracLoc), RBracLoc(RBracLoc)
Douglas Gregor04badcf2010-04-21 00:45:42 +00003214{
Argyrios Kyrtzidis20718082011-10-03 06:36:51 +00003215 initArgsAndSelLocs(Args, SelLocs, SelLocsK);
Douglas Gregor04badcf2010-04-21 00:45:42 +00003216 setReceiverPointer(Receiver);
Argyrios Kyrtzidis20718082011-10-03 06:36:51 +00003217}
3218
3219void ObjCMessageExpr::initArgsAndSelLocs(ArrayRef<Expr *> Args,
3220 ArrayRef<SourceLocation> SelLocs,
3221 SelectorLocationsKind SelLocsK) {
3222 setNumArgs(Args.size());
Douglas Gregoraa165f82011-01-03 19:04:46 +00003223 Expr **MyArgs = getArgs();
Argyrios Kyrtzidis8d9ed792011-10-03 06:36:45 +00003224 for (unsigned I = 0; I != Args.size(); ++I) {
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00003225 if (Args[I]->isTypeDependent())
3226 ExprBits.TypeDependent = true;
3227 if (Args[I]->isValueDependent())
3228 ExprBits.ValueDependent = true;
Douglas Gregor561f8122011-07-01 01:22:09 +00003229 if (Args[I]->isInstantiationDependent())
3230 ExprBits.InstantiationDependent = true;
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00003231 if (Args[I]->containsUnexpandedParameterPack())
3232 ExprBits.ContainsUnexpandedParameterPack = true;
3233
3234 MyArgs[I] = Args[I];
3235 }
Argyrios Kyrtzidis20718082011-10-03 06:36:51 +00003236
Benjamin Kramer19562c92012-02-20 00:20:48 +00003237 SelLocsKind = SelLocsK;
Argyrios Kyrtzidis0c6b8e32012-01-12 22:34:19 +00003238 if (!isImplicit()) {
Argyrios Kyrtzidis0c6b8e32012-01-12 22:34:19 +00003239 if (SelLocsK == SelLoc_NonStandard)
3240 std::copy(SelLocs.begin(), SelLocs.end(), getStoredSelLocs());
3241 }
Chris Lattner0389e6b2009-04-26 00:44:05 +00003242}
3243
Douglas Gregor04badcf2010-04-21 00:45:42 +00003244ObjCMessageExpr *ObjCMessageExpr::Create(ASTContext &Context, QualType T,
John McCallf89e55a2010-11-18 06:31:45 +00003245 ExprValueKind VK,
Douglas Gregor04badcf2010-04-21 00:45:42 +00003246 SourceLocation LBracLoc,
3247 SourceLocation SuperLoc,
3248 bool IsInstanceSuper,
3249 QualType SuperType,
Sean Huntc3021132010-05-05 15:23:54 +00003250 Selector Sel,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00003251 ArrayRef<SourceLocation> SelLocs,
Douglas Gregor04badcf2010-04-21 00:45:42 +00003252 ObjCMethodDecl *Method,
Argyrios Kyrtzidis8d9ed792011-10-03 06:36:45 +00003253 ArrayRef<Expr *> Args,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00003254 SourceLocation RBracLoc,
3255 bool isImplicit) {
3256 assert((!SelLocs.empty() || isImplicit) &&
3257 "No selector locs for non-implicit message");
3258 ObjCMessageExpr *Mem;
3259 SelectorLocationsKind SelLocsK = SelectorLocationsKind();
3260 if (isImplicit)
3261 Mem = alloc(Context, Args.size(), 0);
3262 else
3263 Mem = alloc(Context, Args, RBracLoc, SelLocs, Sel, SelLocsK);
John McCallf89e55a2010-11-18 06:31:45 +00003264 return new (Mem) ObjCMessageExpr(T, VK, LBracLoc, SuperLoc, IsInstanceSuper,
Argyrios Kyrtzidis20718082011-10-03 06:36:51 +00003265 SuperType, Sel, SelLocs, SelLocsK,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00003266 Method, Args, RBracLoc, isImplicit);
Douglas Gregor04badcf2010-04-21 00:45:42 +00003267}
3268
3269ObjCMessageExpr *ObjCMessageExpr::Create(ASTContext &Context, QualType T,
John McCallf89e55a2010-11-18 06:31:45 +00003270 ExprValueKind VK,
Douglas Gregor04badcf2010-04-21 00:45:42 +00003271 SourceLocation LBracLoc,
3272 TypeSourceInfo *Receiver,
Sean Huntc3021132010-05-05 15:23:54 +00003273 Selector Sel,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00003274 ArrayRef<SourceLocation> SelLocs,
Douglas Gregor04badcf2010-04-21 00:45:42 +00003275 ObjCMethodDecl *Method,
Argyrios Kyrtzidis8d9ed792011-10-03 06:36:45 +00003276 ArrayRef<Expr *> Args,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00003277 SourceLocation RBracLoc,
3278 bool isImplicit) {
3279 assert((!SelLocs.empty() || isImplicit) &&
3280 "No selector locs for non-implicit message");
3281 ObjCMessageExpr *Mem;
3282 SelectorLocationsKind SelLocsK = SelectorLocationsKind();
3283 if (isImplicit)
3284 Mem = alloc(Context, Args.size(), 0);
3285 else
3286 Mem = alloc(Context, Args, RBracLoc, SelLocs, Sel, SelLocsK);
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00003287 return new (Mem) ObjCMessageExpr(T, VK, LBracLoc, Receiver, Sel,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00003288 SelLocs, SelLocsK, Method, Args, RBracLoc,
3289 isImplicit);
Douglas Gregor04badcf2010-04-21 00:45:42 +00003290}
3291
3292ObjCMessageExpr *ObjCMessageExpr::Create(ASTContext &Context, QualType T,
John McCallf89e55a2010-11-18 06:31:45 +00003293 ExprValueKind VK,
Douglas Gregor04badcf2010-04-21 00:45:42 +00003294 SourceLocation LBracLoc,
3295 Expr *Receiver,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00003296 Selector Sel,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00003297 ArrayRef<SourceLocation> SelLocs,
Douglas Gregor04badcf2010-04-21 00:45:42 +00003298 ObjCMethodDecl *Method,
Argyrios Kyrtzidis8d9ed792011-10-03 06:36:45 +00003299 ArrayRef<Expr *> Args,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00003300 SourceLocation RBracLoc,
3301 bool isImplicit) {
3302 assert((!SelLocs.empty() || isImplicit) &&
3303 "No selector locs for non-implicit message");
3304 ObjCMessageExpr *Mem;
3305 SelectorLocationsKind SelLocsK = SelectorLocationsKind();
3306 if (isImplicit)
3307 Mem = alloc(Context, Args.size(), 0);
3308 else
3309 Mem = alloc(Context, Args, RBracLoc, SelLocs, Sel, SelLocsK);
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00003310 return new (Mem) ObjCMessageExpr(T, VK, LBracLoc, Receiver, Sel,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00003311 SelLocs, SelLocsK, Method, Args, RBracLoc,
3312 isImplicit);
Douglas Gregor04badcf2010-04-21 00:45:42 +00003313}
3314
Sean Huntc3021132010-05-05 15:23:54 +00003315ObjCMessageExpr *ObjCMessageExpr::CreateEmpty(ASTContext &Context,
Argyrios Kyrtzidis20718082011-10-03 06:36:51 +00003316 unsigned NumArgs,
3317 unsigned NumStoredSelLocs) {
3318 ObjCMessageExpr *Mem = alloc(Context, NumArgs, NumStoredSelLocs);
Douglas Gregor04badcf2010-04-21 00:45:42 +00003319 return new (Mem) ObjCMessageExpr(EmptyShell(), NumArgs);
3320}
Argyrios Kyrtzidise005d192010-12-10 20:08:30 +00003321
Argyrios Kyrtzidis20718082011-10-03 06:36:51 +00003322ObjCMessageExpr *ObjCMessageExpr::alloc(ASTContext &C,
3323 ArrayRef<Expr *> Args,
3324 SourceLocation RBraceLoc,
3325 ArrayRef<SourceLocation> SelLocs,
3326 Selector Sel,
3327 SelectorLocationsKind &SelLocsK) {
3328 SelLocsK = hasStandardSelectorLocs(Sel, SelLocs, Args, RBraceLoc);
3329 unsigned NumStoredSelLocs = (SelLocsK == SelLoc_NonStandard) ? SelLocs.size()
3330 : 0;
3331 return alloc(C, Args.size(), NumStoredSelLocs);
3332}
3333
3334ObjCMessageExpr *ObjCMessageExpr::alloc(ASTContext &C,
3335 unsigned NumArgs,
3336 unsigned NumStoredSelLocs) {
3337 unsigned Size = sizeof(ObjCMessageExpr) + sizeof(void *) +
3338 NumArgs * sizeof(Expr *) + NumStoredSelLocs * sizeof(SourceLocation);
3339 return (ObjCMessageExpr *)C.Allocate(Size,
3340 llvm::AlignOf<ObjCMessageExpr>::Alignment);
3341}
3342
3343void ObjCMessageExpr::getSelectorLocs(
3344 SmallVectorImpl<SourceLocation> &SelLocs) const {
3345 for (unsigned i = 0, e = getNumSelectorLocs(); i != e; ++i)
3346 SelLocs.push_back(getSelectorLoc(i));
3347}
3348
Argyrios Kyrtzidise005d192010-12-10 20:08:30 +00003349SourceRange ObjCMessageExpr::getReceiverRange() const {
3350 switch (getReceiverKind()) {
3351 case Instance:
3352 return getInstanceReceiver()->getSourceRange();
3353
3354 case Class:
3355 return getClassReceiverTypeInfo()->getTypeLoc().getSourceRange();
3356
3357 case SuperInstance:
3358 case SuperClass:
3359 return getSuperLoc();
3360 }
3361
David Blaikie30263482012-01-20 21:50:17 +00003362 llvm_unreachable("Invalid ReceiverKind!");
Argyrios Kyrtzidise005d192010-12-10 20:08:30 +00003363}
3364
Douglas Gregor04badcf2010-04-21 00:45:42 +00003365Selector ObjCMessageExpr::getSelector() const {
3366 if (HasMethod)
3367 return reinterpret_cast<const ObjCMethodDecl *>(SelectorOrMethod)
3368 ->getSelector();
Sean Huntc3021132010-05-05 15:23:54 +00003369 return Selector(SelectorOrMethod);
Douglas Gregor04badcf2010-04-21 00:45:42 +00003370}
3371
3372ObjCInterfaceDecl *ObjCMessageExpr::getReceiverInterface() const {
3373 switch (getReceiverKind()) {
3374 case Instance:
3375 if (const ObjCObjectPointerType *Ptr
3376 = getInstanceReceiver()->getType()->getAs<ObjCObjectPointerType>())
3377 return Ptr->getInterfaceDecl();
3378 break;
3379
3380 case Class:
John McCallc12c5bb2010-05-15 11:32:37 +00003381 if (const ObjCObjectType *Ty
3382 = getClassReceiver()->getAs<ObjCObjectType>())
3383 return Ty->getInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00003384 break;
3385
3386 case SuperInstance:
3387 if (const ObjCObjectPointerType *Ptr
3388 = getSuperType()->getAs<ObjCObjectPointerType>())
3389 return Ptr->getInterfaceDecl();
3390 break;
3391
3392 case SuperClass:
Argyrios Kyrtzidisee8a6ca2011-01-25 00:03:48 +00003393 if (const ObjCObjectType *Iface
3394 = getSuperType()->getAs<ObjCObjectType>())
3395 return Iface->getInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00003396 break;
3397 }
3398
3399 return 0;
Ted Kremenekeb3b3242010-02-11 22:41:21 +00003400}
Chris Lattner0389e6b2009-04-26 00:44:05 +00003401
Chris Lattner5f9e2722011-07-23 10:55:15 +00003402StringRef ObjCBridgedCastExpr::getBridgeKindName() const {
John McCallf85e1932011-06-15 23:02:42 +00003403 switch (getBridgeKind()) {
3404 case OBC_Bridge:
3405 return "__bridge";
3406 case OBC_BridgeTransfer:
3407 return "__bridge_transfer";
3408 case OBC_BridgeRetained:
3409 return "__bridge_retained";
3410 }
David Blaikie30263482012-01-20 21:50:17 +00003411
3412 llvm_unreachable("Invalid BridgeKind!");
John McCallf85e1932011-06-15 23:02:42 +00003413}
3414
Jay Foad4ba2a172011-01-12 09:06:06 +00003415bool ChooseExpr::isConditionTrue(const ASTContext &C) const {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003416 return getCond()->EvaluateKnownConstInt(C) != 0;
Chris Lattner27437ca2007-10-25 00:29:32 +00003417}
3418
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003419ShuffleVectorExpr::ShuffleVectorExpr(ASTContext &C, ArrayRef<Expr*> args,
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00003420 QualType Type, SourceLocation BLoc,
3421 SourceLocation RP)
3422 : Expr(ShuffleVectorExprClass, Type, VK_RValue, OK_Ordinary,
3423 Type->isDependentType(), Type->isDependentType(),
Douglas Gregor561f8122011-07-01 01:22:09 +00003424 Type->isInstantiationDependentType(),
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00003425 Type->containsUnexpandedParameterPack()),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003426 BuiltinLoc(BLoc), RParenLoc(RP), NumExprs(args.size())
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00003427{
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003428 SubExprs = new (C) Stmt*[args.size()];
3429 for (unsigned i = 0; i != args.size(); i++) {
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00003430 if (args[i]->isTypeDependent())
3431 ExprBits.TypeDependent = true;
3432 if (args[i]->isValueDependent())
3433 ExprBits.ValueDependent = true;
Douglas Gregor561f8122011-07-01 01:22:09 +00003434 if (args[i]->isInstantiationDependent())
3435 ExprBits.InstantiationDependent = true;
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00003436 if (args[i]->containsUnexpandedParameterPack())
3437 ExprBits.ContainsUnexpandedParameterPack = true;
3438
3439 SubExprs[i] = args[i];
3440 }
3441}
3442
Nate Begeman888376a2009-08-12 02:28:50 +00003443void ShuffleVectorExpr::setExprs(ASTContext &C, Expr ** Exprs,
3444 unsigned NumExprs) {
3445 if (SubExprs) C.Deallocate(SubExprs);
3446
3447 SubExprs = new (C) Stmt* [NumExprs];
Douglas Gregor94cd5d12009-04-16 00:01:45 +00003448 this->NumExprs = NumExprs;
3449 memcpy(SubExprs, Exprs, sizeof(Expr *) * NumExprs);
Mike Stump1eb44332009-09-09 15:08:12 +00003450}
Nate Begeman888376a2009-08-12 02:28:50 +00003451
Peter Collingbournef111d932011-04-15 00:35:48 +00003452GenericSelectionExpr::GenericSelectionExpr(ASTContext &Context,
3453 SourceLocation GenericLoc, Expr *ControllingExpr,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003454 ArrayRef<TypeSourceInfo*> AssocTypes,
3455 ArrayRef<Expr*> AssocExprs,
3456 SourceLocation DefaultLoc,
Peter Collingbournef111d932011-04-15 00:35:48 +00003457 SourceLocation RParenLoc,
3458 bool ContainsUnexpandedParameterPack,
3459 unsigned ResultIndex)
3460 : Expr(GenericSelectionExprClass,
3461 AssocExprs[ResultIndex]->getType(),
3462 AssocExprs[ResultIndex]->getValueKind(),
3463 AssocExprs[ResultIndex]->getObjectKind(),
3464 AssocExprs[ResultIndex]->isTypeDependent(),
3465 AssocExprs[ResultIndex]->isValueDependent(),
Douglas Gregor561f8122011-07-01 01:22:09 +00003466 AssocExprs[ResultIndex]->isInstantiationDependent(),
Peter Collingbournef111d932011-04-15 00:35:48 +00003467 ContainsUnexpandedParameterPack),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003468 AssocTypes(new (Context) TypeSourceInfo*[AssocTypes.size()]),
3469 SubExprs(new (Context) Stmt*[END_EXPR+AssocExprs.size()]),
3470 NumAssocs(AssocExprs.size()), ResultIndex(ResultIndex),
3471 GenericLoc(GenericLoc), DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
Peter Collingbournef111d932011-04-15 00:35:48 +00003472 SubExprs[CONTROLLING] = ControllingExpr;
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003473 assert(AssocTypes.size() == AssocExprs.size());
3474 std::copy(AssocTypes.begin(), AssocTypes.end(), this->AssocTypes);
3475 std::copy(AssocExprs.begin(), AssocExprs.end(), SubExprs+END_EXPR);
Peter Collingbournef111d932011-04-15 00:35:48 +00003476}
3477
3478GenericSelectionExpr::GenericSelectionExpr(ASTContext &Context,
3479 SourceLocation GenericLoc, Expr *ControllingExpr,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003480 ArrayRef<TypeSourceInfo*> AssocTypes,
3481 ArrayRef<Expr*> AssocExprs,
3482 SourceLocation DefaultLoc,
Peter Collingbournef111d932011-04-15 00:35:48 +00003483 SourceLocation RParenLoc,
3484 bool ContainsUnexpandedParameterPack)
3485 : Expr(GenericSelectionExprClass,
3486 Context.DependentTy,
3487 VK_RValue,
3488 OK_Ordinary,
Douglas Gregor561f8122011-07-01 01:22:09 +00003489 /*isTypeDependent=*/true,
3490 /*isValueDependent=*/true,
3491 /*isInstantiationDependent=*/true,
Peter Collingbournef111d932011-04-15 00:35:48 +00003492 ContainsUnexpandedParameterPack),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003493 AssocTypes(new (Context) TypeSourceInfo*[AssocTypes.size()]),
3494 SubExprs(new (Context) Stmt*[END_EXPR+AssocExprs.size()]),
3495 NumAssocs(AssocExprs.size()), ResultIndex(-1U), GenericLoc(GenericLoc),
3496 DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
Peter Collingbournef111d932011-04-15 00:35:48 +00003497 SubExprs[CONTROLLING] = ControllingExpr;
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003498 assert(AssocTypes.size() == AssocExprs.size());
3499 std::copy(AssocTypes.begin(), AssocTypes.end(), this->AssocTypes);
3500 std::copy(AssocExprs.begin(), AssocExprs.end(), SubExprs+END_EXPR);
Peter Collingbournef111d932011-04-15 00:35:48 +00003501}
3502
Ted Kremenek77ed8e42007-08-24 18:13:47 +00003503//===----------------------------------------------------------------------===//
Douglas Gregor05c13a32009-01-22 00:58:24 +00003504// DesignatedInitExpr
3505//===----------------------------------------------------------------------===//
3506
Chandler Carruthb1138242011-06-16 06:47:06 +00003507IdentifierInfo *DesignatedInitExpr::Designator::getFieldName() const {
Douglas Gregor05c13a32009-01-22 00:58:24 +00003508 assert(Kind == FieldDesignator && "Only valid on a field designator");
3509 if (Field.NameOrField & 0x01)
3510 return reinterpret_cast<IdentifierInfo *>(Field.NameOrField&~0x01);
3511 else
3512 return getField()->getIdentifier();
3513}
3514
Sean Huntc3021132010-05-05 15:23:54 +00003515DesignatedInitExpr::DesignatedInitExpr(ASTContext &C, QualType Ty,
Douglas Gregor319d57f2010-01-06 23:17:19 +00003516 unsigned NumDesignators,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00003517 const Designator *Designators,
Mike Stump1eb44332009-09-09 15:08:12 +00003518 SourceLocation EqualOrColonLoc,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00003519 bool GNUSyntax,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003520 ArrayRef<Expr*> IndexExprs,
Douglas Gregor9ea62762009-05-21 23:17:49 +00003521 Expr *Init)
Mike Stump1eb44332009-09-09 15:08:12 +00003522 : Expr(DesignatedInitExprClass, Ty,
John McCallf89e55a2010-11-18 06:31:45 +00003523 Init->getValueKind(), Init->getObjectKind(),
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00003524 Init->isTypeDependent(), Init->isValueDependent(),
Douglas Gregor561f8122011-07-01 01:22:09 +00003525 Init->isInstantiationDependent(),
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00003526 Init->containsUnexpandedParameterPack()),
Mike Stump1eb44332009-09-09 15:08:12 +00003527 EqualOrColonLoc(EqualOrColonLoc), GNUSyntax(GNUSyntax),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003528 NumDesignators(NumDesignators), NumSubExprs(IndexExprs.size() + 1) {
Douglas Gregor319d57f2010-01-06 23:17:19 +00003529 this->Designators = new (C) Designator[NumDesignators];
Douglas Gregor9ea62762009-05-21 23:17:49 +00003530
3531 // Record the initializer itself.
John McCall7502c1d2011-02-13 04:07:26 +00003532 child_range Child = children();
Douglas Gregor9ea62762009-05-21 23:17:49 +00003533 *Child++ = Init;
3534
3535 // Copy the designators and their subexpressions, computing
3536 // value-dependence along the way.
3537 unsigned IndexIdx = 0;
3538 for (unsigned I = 0; I != NumDesignators; ++I) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00003539 this->Designators[I] = Designators[I];
Douglas Gregor9ea62762009-05-21 23:17:49 +00003540
3541 if (this->Designators[I].isArrayDesignator()) {
3542 // Compute type- and value-dependence.
3543 Expr *Index = IndexExprs[IndexIdx];
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00003544 if (Index->isTypeDependent() || Index->isValueDependent())
3545 ExprBits.ValueDependent = true;
Douglas Gregor561f8122011-07-01 01:22:09 +00003546 if (Index->isInstantiationDependent())
3547 ExprBits.InstantiationDependent = true;
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00003548 // Propagate unexpanded parameter packs.
3549 if (Index->containsUnexpandedParameterPack())
3550 ExprBits.ContainsUnexpandedParameterPack = true;
Douglas Gregor9ea62762009-05-21 23:17:49 +00003551
3552 // Copy the index expressions into permanent storage.
3553 *Child++ = IndexExprs[IndexIdx++];
3554 } else if (this->Designators[I].isArrayRangeDesignator()) {
3555 // Compute type- and value-dependence.
3556 Expr *Start = IndexExprs[IndexIdx];
3557 Expr *End = IndexExprs[IndexIdx + 1];
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00003558 if (Start->isTypeDependent() || Start->isValueDependent() ||
Douglas Gregor561f8122011-07-01 01:22:09 +00003559 End->isTypeDependent() || End->isValueDependent()) {
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00003560 ExprBits.ValueDependent = true;
Douglas Gregor561f8122011-07-01 01:22:09 +00003561 ExprBits.InstantiationDependent = true;
3562 } else if (Start->isInstantiationDependent() ||
3563 End->isInstantiationDependent()) {
3564 ExprBits.InstantiationDependent = true;
3565 }
3566
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00003567 // Propagate unexpanded parameter packs.
3568 if (Start->containsUnexpandedParameterPack() ||
3569 End->containsUnexpandedParameterPack())
3570 ExprBits.ContainsUnexpandedParameterPack = true;
Douglas Gregor9ea62762009-05-21 23:17:49 +00003571
3572 // Copy the start/end expressions into permanent storage.
3573 *Child++ = IndexExprs[IndexIdx++];
3574 *Child++ = IndexExprs[IndexIdx++];
3575 }
3576 }
3577
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003578 assert(IndexIdx == IndexExprs.size() && "Wrong number of index expressions");
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00003579}
3580
Douglas Gregor05c13a32009-01-22 00:58:24 +00003581DesignatedInitExpr *
Mike Stump1eb44332009-09-09 15:08:12 +00003582DesignatedInitExpr::Create(ASTContext &C, Designator *Designators,
Douglas Gregor05c13a32009-01-22 00:58:24 +00003583 unsigned NumDesignators,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003584 ArrayRef<Expr*> IndexExprs,
Douglas Gregor05c13a32009-01-22 00:58:24 +00003585 SourceLocation ColonOrEqualLoc,
3586 bool UsesColonSyntax, Expr *Init) {
Steve Naroffc0ac4922009-01-27 23:20:32 +00003587 void *Mem = C.Allocate(sizeof(DesignatedInitExpr) +
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003588 sizeof(Stmt *) * (IndexExprs.size() + 1), 8);
Douglas Gregor319d57f2010-01-06 23:17:19 +00003589 return new (Mem) DesignatedInitExpr(C, C.VoidTy, NumDesignators, Designators,
Douglas Gregor9ea62762009-05-21 23:17:49 +00003590 ColonOrEqualLoc, UsesColonSyntax,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003591 IndexExprs, Init);
Douglas Gregor05c13a32009-01-22 00:58:24 +00003592}
3593
Mike Stump1eb44332009-09-09 15:08:12 +00003594DesignatedInitExpr *DesignatedInitExpr::CreateEmpty(ASTContext &C,
Douglas Gregord077d752009-04-16 00:55:48 +00003595 unsigned NumIndexExprs) {
3596 void *Mem = C.Allocate(sizeof(DesignatedInitExpr) +
3597 sizeof(Stmt *) * (NumIndexExprs + 1), 8);
3598 return new (Mem) DesignatedInitExpr(NumIndexExprs + 1);
3599}
3600
Douglas Gregor319d57f2010-01-06 23:17:19 +00003601void DesignatedInitExpr::setDesignators(ASTContext &C,
3602 const Designator *Desigs,
Douglas Gregord077d752009-04-16 00:55:48 +00003603 unsigned NumDesigs) {
Douglas Gregor319d57f2010-01-06 23:17:19 +00003604 Designators = new (C) Designator[NumDesigs];
Douglas Gregord077d752009-04-16 00:55:48 +00003605 NumDesignators = NumDesigs;
3606 for (unsigned I = 0; I != NumDesigs; ++I)
3607 Designators[I] = Desigs[I];
3608}
3609
Abramo Bagnara24f46742011-03-16 15:08:46 +00003610SourceRange DesignatedInitExpr::getDesignatorsSourceRange() const {
3611 DesignatedInitExpr *DIE = const_cast<DesignatedInitExpr*>(this);
3612 if (size() == 1)
3613 return DIE->getDesignator(0)->getSourceRange();
3614 return SourceRange(DIE->getDesignator(0)->getStartLocation(),
3615 DIE->getDesignator(size()-1)->getEndLocation());
3616}
3617
Douglas Gregor05c13a32009-01-22 00:58:24 +00003618SourceRange DesignatedInitExpr::getSourceRange() const {
3619 SourceLocation StartLoc;
Chris Lattnerd603eaa2009-02-16 22:33:34 +00003620 Designator &First =
3621 *const_cast<DesignatedInitExpr*>(this)->designators_begin();
Douglas Gregor05c13a32009-01-22 00:58:24 +00003622 if (First.isFieldDesignator()) {
Douglas Gregoreeae8f02009-03-28 00:41:23 +00003623 if (GNUSyntax)
Douglas Gregor05c13a32009-01-22 00:58:24 +00003624 StartLoc = SourceLocation::getFromRawEncoding(First.Field.FieldLoc);
3625 else
3626 StartLoc = SourceLocation::getFromRawEncoding(First.Field.DotLoc);
3627 } else
Chris Lattnerd603eaa2009-02-16 22:33:34 +00003628 StartLoc =
3629 SourceLocation::getFromRawEncoding(First.ArrayOrRange.LBracketLoc);
Douglas Gregor05c13a32009-01-22 00:58:24 +00003630 return SourceRange(StartLoc, getInit()->getSourceRange().getEnd());
3631}
3632
Douglas Gregor05c13a32009-01-22 00:58:24 +00003633Expr *DesignatedInitExpr::getArrayIndex(const Designator& D) {
3634 assert(D.Kind == Designator::ArrayDesignator && "Requires array designator");
3635 char* Ptr = static_cast<char*>(static_cast<void *>(this));
3636 Ptr += sizeof(DesignatedInitExpr);
Douglas Gregor05c13a32009-01-22 00:58:24 +00003637 Stmt **SubExprs = reinterpret_cast<Stmt**>(reinterpret_cast<void**>(Ptr));
3638 return cast<Expr>(*(SubExprs + D.ArrayOrRange.Index + 1));
3639}
3640
3641Expr *DesignatedInitExpr::getArrayRangeStart(const Designator& D) {
Mike Stump1eb44332009-09-09 15:08:12 +00003642 assert(D.Kind == Designator::ArrayRangeDesignator &&
Douglas Gregor05c13a32009-01-22 00:58:24 +00003643 "Requires array range designator");
3644 char* Ptr = static_cast<char*>(static_cast<void *>(this));
3645 Ptr += sizeof(DesignatedInitExpr);
Douglas Gregor05c13a32009-01-22 00:58:24 +00003646 Stmt **SubExprs = reinterpret_cast<Stmt**>(reinterpret_cast<void**>(Ptr));
3647 return cast<Expr>(*(SubExprs + D.ArrayOrRange.Index + 1));
3648}
3649
3650Expr *DesignatedInitExpr::getArrayRangeEnd(const Designator& D) {
Mike Stump1eb44332009-09-09 15:08:12 +00003651 assert(D.Kind == Designator::ArrayRangeDesignator &&
Douglas Gregor05c13a32009-01-22 00:58:24 +00003652 "Requires array range designator");
3653 char* Ptr = static_cast<char*>(static_cast<void *>(this));
3654 Ptr += sizeof(DesignatedInitExpr);
Douglas Gregor05c13a32009-01-22 00:58:24 +00003655 Stmt **SubExprs = reinterpret_cast<Stmt**>(reinterpret_cast<void**>(Ptr));
3656 return cast<Expr>(*(SubExprs + D.ArrayOrRange.Index + 2));
3657}
3658
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00003659/// \brief Replaces the designator at index @p Idx with the series
3660/// of designators in [First, Last).
Douglas Gregor319d57f2010-01-06 23:17:19 +00003661void DesignatedInitExpr::ExpandDesignator(ASTContext &C, unsigned Idx,
Mike Stump1eb44332009-09-09 15:08:12 +00003662 const Designator *First,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00003663 const Designator *Last) {
3664 unsigned NumNewDesignators = Last - First;
3665 if (NumNewDesignators == 0) {
3666 std::copy_backward(Designators + Idx + 1,
3667 Designators + NumDesignators,
3668 Designators + Idx);
3669 --NumNewDesignators;
3670 return;
3671 } else if (NumNewDesignators == 1) {
3672 Designators[Idx] = *First;
3673 return;
3674 }
3675
Mike Stump1eb44332009-09-09 15:08:12 +00003676 Designator *NewDesignators
Douglas Gregor319d57f2010-01-06 23:17:19 +00003677 = new (C) Designator[NumDesignators - 1 + NumNewDesignators];
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00003678 std::copy(Designators, Designators + Idx, NewDesignators);
3679 std::copy(First, Last, NewDesignators + Idx);
3680 std::copy(Designators + Idx + 1, Designators + NumDesignators,
3681 NewDesignators + Idx + NumNewDesignators);
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00003682 Designators = NewDesignators;
3683 NumDesignators = NumDesignators - 1 + NumNewDesignators;
3684}
3685
Mike Stump1eb44332009-09-09 15:08:12 +00003686ParenListExpr::ParenListExpr(ASTContext& C, SourceLocation lparenloc,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003687 ArrayRef<Expr*> exprs,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003688 SourceLocation rparenloc)
3689 : Expr(ParenListExprClass, QualType(), VK_RValue, OK_Ordinary,
Douglas Gregor561f8122011-07-01 01:22:09 +00003690 false, false, false, false),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003691 NumExprs(exprs.size()), LParenLoc(lparenloc), RParenLoc(rparenloc) {
3692 Exprs = new (C) Stmt*[exprs.size()];
3693 for (unsigned i = 0; i != exprs.size(); ++i) {
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00003694 if (exprs[i]->isTypeDependent())
3695 ExprBits.TypeDependent = true;
3696 if (exprs[i]->isValueDependent())
3697 ExprBits.ValueDependent = true;
Douglas Gregor561f8122011-07-01 01:22:09 +00003698 if (exprs[i]->isInstantiationDependent())
3699 ExprBits.InstantiationDependent = true;
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00003700 if (exprs[i]->containsUnexpandedParameterPack())
3701 ExprBits.ContainsUnexpandedParameterPack = true;
3702
Nate Begeman2ef13e52009-08-10 23:49:36 +00003703 Exprs[i] = exprs[i];
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00003704 }
Nate Begeman2ef13e52009-08-10 23:49:36 +00003705}
3706
John McCalle996ffd2011-02-16 08:02:54 +00003707const OpaqueValueExpr *OpaqueValueExpr::findInCopyConstruct(const Expr *e) {
3708 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(e))
3709 e = ewc->getSubExpr();
Douglas Gregor03e80032011-06-21 17:03:29 +00003710 if (const MaterializeTemporaryExpr *m = dyn_cast<MaterializeTemporaryExpr>(e))
3711 e = m->GetTemporaryExpr();
John McCalle996ffd2011-02-16 08:02:54 +00003712 e = cast<CXXConstructExpr>(e)->getArg(0);
3713 while (const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
3714 e = ice->getSubExpr();
3715 return cast<OpaqueValueExpr>(e);
3716}
3717
John McCall4b9c2d22011-11-06 09:01:30 +00003718PseudoObjectExpr *PseudoObjectExpr::Create(ASTContext &Context, EmptyShell sh,
3719 unsigned numSemanticExprs) {
3720 void *buffer = Context.Allocate(sizeof(PseudoObjectExpr) +
3721 (1 + numSemanticExprs) * sizeof(Expr*),
3722 llvm::alignOf<PseudoObjectExpr>());
3723 return new(buffer) PseudoObjectExpr(sh, numSemanticExprs);
3724}
3725
3726PseudoObjectExpr::PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs)
3727 : Expr(PseudoObjectExprClass, shell) {
3728 PseudoObjectExprBits.NumSubExprs = numSemanticExprs + 1;
3729}
3730
3731PseudoObjectExpr *PseudoObjectExpr::Create(ASTContext &C, Expr *syntax,
3732 ArrayRef<Expr*> semantics,
3733 unsigned resultIndex) {
3734 assert(syntax && "no syntactic expression!");
3735 assert(semantics.size() && "no semantic expressions!");
3736
3737 QualType type;
3738 ExprValueKind VK;
3739 if (resultIndex == NoResult) {
3740 type = C.VoidTy;
3741 VK = VK_RValue;
3742 } else {
3743 assert(resultIndex < semantics.size());
3744 type = semantics[resultIndex]->getType();
3745 VK = semantics[resultIndex]->getValueKind();
3746 assert(semantics[resultIndex]->getObjectKind() == OK_Ordinary);
3747 }
3748
3749 void *buffer = C.Allocate(sizeof(PseudoObjectExpr) +
3750 (1 + semantics.size()) * sizeof(Expr*),
3751 llvm::alignOf<PseudoObjectExpr>());
3752 return new(buffer) PseudoObjectExpr(type, VK, syntax, semantics,
3753 resultIndex);
3754}
3755
3756PseudoObjectExpr::PseudoObjectExpr(QualType type, ExprValueKind VK,
3757 Expr *syntax, ArrayRef<Expr*> semantics,
3758 unsigned resultIndex)
3759 : Expr(PseudoObjectExprClass, type, VK, OK_Ordinary,
3760 /*filled in at end of ctor*/ false, false, false, false) {
3761 PseudoObjectExprBits.NumSubExprs = semantics.size() + 1;
3762 PseudoObjectExprBits.ResultIndex = resultIndex + 1;
3763
3764 for (unsigned i = 0, e = semantics.size() + 1; i != e; ++i) {
3765 Expr *E = (i == 0 ? syntax : semantics[i-1]);
3766 getSubExprsBuffer()[i] = E;
3767
3768 if (E->isTypeDependent())
3769 ExprBits.TypeDependent = true;
3770 if (E->isValueDependent())
3771 ExprBits.ValueDependent = true;
3772 if (E->isInstantiationDependent())
3773 ExprBits.InstantiationDependent = true;
3774 if (E->containsUnexpandedParameterPack())
3775 ExprBits.ContainsUnexpandedParameterPack = true;
3776
3777 if (isa<OpaqueValueExpr>(E))
3778 assert(cast<OpaqueValueExpr>(E)->getSourceExpr() != 0 &&
3779 "opaque-value semantic expressions for pseudo-object "
3780 "operations must have sources");
3781 }
3782}
3783
Douglas Gregor05c13a32009-01-22 00:58:24 +00003784//===----------------------------------------------------------------------===//
Ted Kremenekce2fc3a2008-10-27 18:40:21 +00003785// ExprIterator.
3786//===----------------------------------------------------------------------===//
3787
3788Expr* ExprIterator::operator[](size_t idx) { return cast<Expr>(I[idx]); }
3789Expr* ExprIterator::operator*() const { return cast<Expr>(*I); }
3790Expr* ExprIterator::operator->() const { return cast<Expr>(*I); }
3791const Expr* ConstExprIterator::operator[](size_t idx) const {
3792 return cast<Expr>(I[idx]);
3793}
3794const Expr* ConstExprIterator::operator*() const { return cast<Expr>(*I); }
3795const Expr* ConstExprIterator::operator->() const { return cast<Expr>(*I); }
3796
3797//===----------------------------------------------------------------------===//
Ted Kremenek77ed8e42007-08-24 18:13:47 +00003798// Child Iterators for iterating over subexpressions/substatements
3799//===----------------------------------------------------------------------===//
3800
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003801// UnaryExprOrTypeTraitExpr
3802Stmt::child_range UnaryExprOrTypeTraitExpr::children() {
Sebastian Redl05189992008-11-11 17:56:53 +00003803 // If this is of a type and the type is a VLA type (and not a typedef), the
3804 // size expression of the VLA needs to be treated as an executable expression.
3805 // Why isn't this weirdness documented better in StmtIterator?
3806 if (isArgumentType()) {
John McCallf4c73712011-01-19 06:33:43 +00003807 if (const VariableArrayType* T = dyn_cast<VariableArrayType>(
Sebastian Redl05189992008-11-11 17:56:53 +00003808 getArgumentType().getTypePtr()))
John McCall63c00d72011-02-09 08:16:59 +00003809 return child_range(child_iterator(T), child_iterator());
3810 return child_range();
Sebastian Redl05189992008-11-11 17:56:53 +00003811 }
John McCall63c00d72011-02-09 08:16:59 +00003812 return child_range(&Argument.Ex, &Argument.Ex + 1);
Ted Kremenek9ac59282007-10-18 23:28:49 +00003813}
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00003814
Steve Naroff563477d2007-09-18 23:55:05 +00003815// ObjCMessageExpr
John McCall63c00d72011-02-09 08:16:59 +00003816Stmt::child_range ObjCMessageExpr::children() {
3817 Stmt **begin;
Douglas Gregor04badcf2010-04-21 00:45:42 +00003818 if (getReceiverKind() == Instance)
John McCall63c00d72011-02-09 08:16:59 +00003819 begin = reinterpret_cast<Stmt **>(this + 1);
3820 else
3821 begin = reinterpret_cast<Stmt **>(getArgs());
3822 return child_range(begin,
3823 reinterpret_cast<Stmt **>(getArgs() + getNumArgs()));
Steve Naroff563477d2007-09-18 23:55:05 +00003824}
3825
Ted Kremenekebcb57a2012-03-06 20:05:56 +00003826ObjCArrayLiteral::ObjCArrayLiteral(llvm::ArrayRef<Expr *> Elements,
3827 QualType T, ObjCMethodDecl *Method,
3828 SourceRange SR)
3829 : Expr(ObjCArrayLiteralClass, T, VK_RValue, OK_Ordinary,
3830 false, false, false, false),
3831 NumElements(Elements.size()), Range(SR), ArrayWithObjectsMethod(Method)
3832{
3833 Expr **SaveElements = getElements();
3834 for (unsigned I = 0, N = Elements.size(); I != N; ++I) {
3835 if (Elements[I]->isTypeDependent() || Elements[I]->isValueDependent())
3836 ExprBits.ValueDependent = true;
3837 if (Elements[I]->isInstantiationDependent())
3838 ExprBits.InstantiationDependent = true;
3839 if (Elements[I]->containsUnexpandedParameterPack())
3840 ExprBits.ContainsUnexpandedParameterPack = true;
3841
3842 SaveElements[I] = Elements[I];
3843 }
3844}
3845
3846ObjCArrayLiteral *ObjCArrayLiteral::Create(ASTContext &C,
3847 llvm::ArrayRef<Expr *> Elements,
3848 QualType T, ObjCMethodDecl * Method,
3849 SourceRange SR) {
3850 void *Mem = C.Allocate(sizeof(ObjCArrayLiteral)
3851 + Elements.size() * sizeof(Expr *));
3852 return new (Mem) ObjCArrayLiteral(Elements, T, Method, SR);
3853}
3854
3855ObjCArrayLiteral *ObjCArrayLiteral::CreateEmpty(ASTContext &C,
3856 unsigned NumElements) {
3857
3858 void *Mem = C.Allocate(sizeof(ObjCArrayLiteral)
3859 + NumElements * sizeof(Expr *));
3860 return new (Mem) ObjCArrayLiteral(EmptyShell(), NumElements);
3861}
3862
3863ObjCDictionaryLiteral::ObjCDictionaryLiteral(
3864 ArrayRef<ObjCDictionaryElement> VK,
3865 bool HasPackExpansions,
3866 QualType T, ObjCMethodDecl *method,
3867 SourceRange SR)
3868 : Expr(ObjCDictionaryLiteralClass, T, VK_RValue, OK_Ordinary, false, false,
3869 false, false),
3870 NumElements(VK.size()), HasPackExpansions(HasPackExpansions), Range(SR),
3871 DictWithObjectsMethod(method)
3872{
3873 KeyValuePair *KeyValues = getKeyValues();
3874 ExpansionData *Expansions = getExpansionData();
3875 for (unsigned I = 0; I < NumElements; I++) {
3876 if (VK[I].Key->isTypeDependent() || VK[I].Key->isValueDependent() ||
3877 VK[I].Value->isTypeDependent() || VK[I].Value->isValueDependent())
3878 ExprBits.ValueDependent = true;
3879 if (VK[I].Key->isInstantiationDependent() ||
3880 VK[I].Value->isInstantiationDependent())
3881 ExprBits.InstantiationDependent = true;
3882 if (VK[I].EllipsisLoc.isInvalid() &&
3883 (VK[I].Key->containsUnexpandedParameterPack() ||
3884 VK[I].Value->containsUnexpandedParameterPack()))
3885 ExprBits.ContainsUnexpandedParameterPack = true;
3886
3887 KeyValues[I].Key = VK[I].Key;
3888 KeyValues[I].Value = VK[I].Value;
3889 if (Expansions) {
3890 Expansions[I].EllipsisLoc = VK[I].EllipsisLoc;
3891 if (VK[I].NumExpansions)
3892 Expansions[I].NumExpansionsPlusOne = *VK[I].NumExpansions + 1;
3893 else
3894 Expansions[I].NumExpansionsPlusOne = 0;
3895 }
3896 }
3897}
3898
3899ObjCDictionaryLiteral *
3900ObjCDictionaryLiteral::Create(ASTContext &C,
3901 ArrayRef<ObjCDictionaryElement> VK,
3902 bool HasPackExpansions,
3903 QualType T, ObjCMethodDecl *method,
3904 SourceRange SR) {
3905 unsigned ExpansionsSize = 0;
3906 if (HasPackExpansions)
3907 ExpansionsSize = sizeof(ExpansionData) * VK.size();
3908
3909 void *Mem = C.Allocate(sizeof(ObjCDictionaryLiteral) +
3910 sizeof(KeyValuePair) * VK.size() + ExpansionsSize);
3911 return new (Mem) ObjCDictionaryLiteral(VK, HasPackExpansions, T, method, SR);
3912}
3913
3914ObjCDictionaryLiteral *
3915ObjCDictionaryLiteral::CreateEmpty(ASTContext &C, unsigned NumElements,
3916 bool HasPackExpansions) {
3917 unsigned ExpansionsSize = 0;
3918 if (HasPackExpansions)
3919 ExpansionsSize = sizeof(ExpansionData) * NumElements;
3920 void *Mem = C.Allocate(sizeof(ObjCDictionaryLiteral) +
3921 sizeof(KeyValuePair) * NumElements + ExpansionsSize);
3922 return new (Mem) ObjCDictionaryLiteral(EmptyShell(), NumElements,
3923 HasPackExpansions);
3924}
3925
3926ObjCSubscriptRefExpr *ObjCSubscriptRefExpr::Create(ASTContext &C,
3927 Expr *base,
3928 Expr *key, QualType T,
3929 ObjCMethodDecl *getMethod,
3930 ObjCMethodDecl *setMethod,
3931 SourceLocation RB) {
3932 void *Mem = C.Allocate(sizeof(ObjCSubscriptRefExpr));
3933 return new (Mem) ObjCSubscriptRefExpr(base, key, T, VK_LValue,
3934 OK_ObjCSubscript,
3935 getMethod, setMethod, RB);
3936}
Eli Friedmandfa64ba2011-10-14 22:48:56 +00003937
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003938AtomicExpr::AtomicExpr(SourceLocation BLoc, ArrayRef<Expr*> args,
Eli Friedmandfa64ba2011-10-14 22:48:56 +00003939 QualType t, AtomicOp op, SourceLocation RP)
3940 : Expr(AtomicExprClass, t, VK_RValue, OK_Ordinary,
3941 false, false, false, false),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003942 NumSubExprs(args.size()), BuiltinLoc(BLoc), RParenLoc(RP), Op(op)
Eli Friedmandfa64ba2011-10-14 22:48:56 +00003943{
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003944 assert(args.size() == getNumSubExprs(op) && "wrong number of subexpressions");
3945 for (unsigned i = 0; i != args.size(); i++) {
Eli Friedmandfa64ba2011-10-14 22:48:56 +00003946 if (args[i]->isTypeDependent())
3947 ExprBits.TypeDependent = true;
3948 if (args[i]->isValueDependent())
3949 ExprBits.ValueDependent = true;
3950 if (args[i]->isInstantiationDependent())
3951 ExprBits.InstantiationDependent = true;
3952 if (args[i]->containsUnexpandedParameterPack())
3953 ExprBits.ContainsUnexpandedParameterPack = true;
3954
3955 SubExprs[i] = args[i];
3956 }
3957}
Richard Smithe1b2abc2012-04-10 22:49:28 +00003958
3959unsigned AtomicExpr::getNumSubExprs(AtomicOp Op) {
3960 switch (Op) {
Richard Smithff34d402012-04-12 05:08:17 +00003961 case AO__c11_atomic_init:
3962 case AO__c11_atomic_load:
3963 case AO__atomic_load_n:
Richard Smithe1b2abc2012-04-10 22:49:28 +00003964 return 2;
Richard Smithff34d402012-04-12 05:08:17 +00003965
3966 case AO__c11_atomic_store:
3967 case AO__c11_atomic_exchange:
3968 case AO__atomic_load:
3969 case AO__atomic_store:
3970 case AO__atomic_store_n:
3971 case AO__atomic_exchange_n:
3972 case AO__c11_atomic_fetch_add:
3973 case AO__c11_atomic_fetch_sub:
3974 case AO__c11_atomic_fetch_and:
3975 case AO__c11_atomic_fetch_or:
3976 case AO__c11_atomic_fetch_xor:
3977 case AO__atomic_fetch_add:
3978 case AO__atomic_fetch_sub:
3979 case AO__atomic_fetch_and:
3980 case AO__atomic_fetch_or:
3981 case AO__atomic_fetch_xor:
Richard Smith51b92402012-04-13 06:31:38 +00003982 case AO__atomic_fetch_nand:
Richard Smithff34d402012-04-12 05:08:17 +00003983 case AO__atomic_add_fetch:
3984 case AO__atomic_sub_fetch:
3985 case AO__atomic_and_fetch:
3986 case AO__atomic_or_fetch:
3987 case AO__atomic_xor_fetch:
Richard Smith51b92402012-04-13 06:31:38 +00003988 case AO__atomic_nand_fetch:
Richard Smithe1b2abc2012-04-10 22:49:28 +00003989 return 3;
Richard Smithff34d402012-04-12 05:08:17 +00003990
3991 case AO__atomic_exchange:
3992 return 4;
3993
3994 case AO__c11_atomic_compare_exchange_strong:
3995 case AO__c11_atomic_compare_exchange_weak:
Richard Smithe1b2abc2012-04-10 22:49:28 +00003996 return 5;
Richard Smithff34d402012-04-12 05:08:17 +00003997
3998 case AO__atomic_compare_exchange:
3999 case AO__atomic_compare_exchange_n:
4000 return 6;
Richard Smithe1b2abc2012-04-10 22:49:28 +00004001 }
4002 llvm_unreachable("unknown atomic op");
4003}