blob: 71bbfdc3369f491cef5c18b9c7341ff87ba34134 [file] [log] [blame]
Chris Lattner1b926492006-08-23 06:42:10 +00001//===--- Expr.cpp - Expression AST Node Implementation --------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner1b926492006-08-23 06:42:10 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expr class and subclasses.
11//
12//===----------------------------------------------------------------------===//
13
Chris Lattner5c4664e2007-07-15 23:32:58 +000014#include "clang/AST/ASTContext.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000015#include "clang/AST/Attr.h"
Douglas Gregor9a657932008-10-21 23:43:52 +000016#include "clang/AST/DeclCXX.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000018#include "clang/AST/DeclTemplate.h"
Douglas Gregor1be329d2012-02-23 07:33:15 +000019#include "clang/AST/EvaluatedExprVisitor.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000020#include "clang/AST/Expr.h"
21#include "clang/AST/ExprCXX.h"
David Majnemerbed356a2013-11-06 23:31:56 +000022#include "clang/AST/Mangle.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000023#include "clang/AST/RecordLayout.h"
Chris Lattner5e9a8782006-11-04 06:21:51 +000024#include "clang/AST/StmtVisitor.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000025#include "clang/Basic/Builtins.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000026#include "clang/Basic/CharInfo.h"
Chris Lattnere925d612010-11-17 07:37:15 +000027#include "clang/Basic/SourceManager.h"
Chris Lattnera7944d82007-11-27 18:22:04 +000028#include "clang/Basic/TargetInfo.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000029#include "clang/Lex/Lexer.h"
30#include "clang/Lex/LiteralSupport.h"
31#include "clang/Sema/SemaDiagnostic.h"
Douglas Gregor0840cc02009-11-01 20:32:48 +000032#include "llvm/Support/ErrorHandling.h"
Anders Carlsson2fb08242009-09-08 18:24:21 +000033#include "llvm/Support/raw_ostream.h"
Douglas Gregord5846a12009-04-15 06:41:24 +000034#include <algorithm>
Eli Friedmanfcec6302011-11-01 02:23:42 +000035#include <cstring>
Chris Lattner1b926492006-08-23 06:42:10 +000036using namespace clang;
37
Rafael Espindolab7f5a9c2012-06-27 18:18:05 +000038const CXXRecordDecl *Expr::getBestDynamicClassType() const {
Rafael Espindolaecbe2e92012-06-28 01:56:38 +000039 const Expr *E = ignoreParenBaseCasts();
Rafael Espindola49e860b2012-06-26 17:45:31 +000040
41 QualType DerivedType = E->getType();
Rafael Espindola49e860b2012-06-26 17:45:31 +000042 if (const PointerType *PTy = DerivedType->getAs<PointerType>())
43 DerivedType = PTy->getPointeeType();
44
Rafael Espindola60a2bba2012-07-17 20:24:05 +000045 if (DerivedType->isDependentType())
Craig Topper36250ad2014-05-12 05:36:57 +000046 return nullptr;
Rafael Espindola60a2bba2012-07-17 20:24:05 +000047
Rafael Espindola49e860b2012-06-26 17:45:31 +000048 const RecordType *Ty = DerivedType->castAs<RecordType>();
Rafael Espindola49e860b2012-06-26 17:45:31 +000049 Decl *D = Ty->getDecl();
50 return cast<CXXRecordDecl>(D);
51}
52
Richard Smithf3fabd22013-06-03 00:17:11 +000053const Expr *Expr::skipRValueSubobjectAdjustments(
54 SmallVectorImpl<const Expr *> &CommaLHSs,
55 SmallVectorImpl<SubobjectAdjustment> &Adjustments) const {
Rafael Espindola9c006de2012-10-27 01:03:43 +000056 const Expr *E = this;
57 while (true) {
58 E = E->IgnoreParens();
59
60 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
61 if ((CE->getCastKind() == CK_DerivedToBase ||
62 CE->getCastKind() == CK_UncheckedDerivedToBase) &&
63 E->getType()->isRecordType()) {
64 E = CE->getSubExpr();
65 CXXRecordDecl *Derived
66 = cast<CXXRecordDecl>(E->getType()->getAs<RecordType>()->getDecl());
67 Adjustments.push_back(SubobjectAdjustment(CE, Derived));
68 continue;
69 }
70
71 if (CE->getCastKind() == CK_NoOp) {
72 E = CE->getSubExpr();
73 continue;
74 }
75 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
Richard Smith6b6f8aa2013-06-15 00:30:29 +000076 if (!ME->isArrow()) {
Rafael Espindola9c006de2012-10-27 01:03:43 +000077 assert(ME->getBase()->getType()->isRecordType());
78 if (FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
Richard Smith6b6f8aa2013-06-15 00:30:29 +000079 if (!Field->isBitField() && !Field->getType()->isReferenceType()) {
Richard Smith2d187902013-06-03 07:13:35 +000080 E = ME->getBase();
81 Adjustments.push_back(SubobjectAdjustment(Field));
82 continue;
83 }
Rafael Espindola9c006de2012-10-27 01:03:43 +000084 }
85 }
86 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
87 if (BO->isPtrMemOp()) {
Rafael Espindola973aa202012-11-01 14:32:20 +000088 assert(BO->getRHS()->isRValue());
Rafael Espindola9c006de2012-10-27 01:03:43 +000089 E = BO->getLHS();
90 const MemberPointerType *MPT =
91 BO->getRHS()->getType()->getAs<MemberPointerType>();
92 Adjustments.push_back(SubobjectAdjustment(MPT, BO->getRHS()));
Richard Smithf3fabd22013-06-03 00:17:11 +000093 continue;
94 } else if (BO->getOpcode() == BO_Comma) {
95 CommaLHSs.push_back(BO->getLHS());
96 E = BO->getRHS();
97 continue;
Rafael Espindola9c006de2012-10-27 01:03:43 +000098 }
99 }
100
101 // Nothing changed.
102 break;
103 }
104 return E;
105}
106
Chris Lattner4ebae652010-04-16 23:34:13 +0000107/// isKnownToHaveBooleanValue - Return true if this is an integer expression
108/// that is known to return 0 or 1. This happens for _Bool/bool expressions
109/// but also int expressions which are produced by things like comparisons in
110/// C.
111bool Expr::isKnownToHaveBooleanValue() const {
Peter Collingbourne91147592011-04-15 00:35:48 +0000112 const Expr *E = IgnoreParens();
113
Chris Lattner4ebae652010-04-16 23:34:13 +0000114 // If this value has _Bool type, it is obvious 0/1.
Peter Collingbourne91147592011-04-15 00:35:48 +0000115 if (E->getType()->isBooleanType()) return true;
Alexis Hunta8136cc2010-05-05 15:23:54 +0000116 // If this is a non-scalar-integer type, we don't care enough to try.
Peter Collingbourne91147592011-04-15 00:35:48 +0000117 if (!E->getType()->isIntegralOrEnumerationType()) return false;
Alexis Hunta8136cc2010-05-05 15:23:54 +0000118
Peter Collingbourne91147592011-04-15 00:35:48 +0000119 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
Chris Lattner4ebae652010-04-16 23:34:13 +0000120 switch (UO->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +0000121 case UO_Plus:
Chris Lattner4ebae652010-04-16 23:34:13 +0000122 return UO->getSubExpr()->isKnownToHaveBooleanValue();
Richard Trieu0f097742014-04-04 04:13:47 +0000123 case UO_LNot:
124 return true;
Chris Lattner4ebae652010-04-16 23:34:13 +0000125 default:
126 return false;
127 }
128 }
Alexis Hunta8136cc2010-05-05 15:23:54 +0000129
John McCall45d30c32010-06-12 01:56:02 +0000130 // Only look through implicit casts. If the user writes
131 // '(int) (a && b)' treat it as an arbitrary int.
Peter Collingbourne91147592011-04-15 00:35:48 +0000132 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Chris Lattner4ebae652010-04-16 23:34:13 +0000133 return CE->getSubExpr()->isKnownToHaveBooleanValue();
Alexis Hunta8136cc2010-05-05 15:23:54 +0000134
Peter Collingbourne91147592011-04-15 00:35:48 +0000135 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
Chris Lattner4ebae652010-04-16 23:34:13 +0000136 switch (BO->getOpcode()) {
137 default: return false;
John McCalle3027922010-08-25 11:45:40 +0000138 case BO_LT: // Relational operators.
139 case BO_GT:
140 case BO_LE:
141 case BO_GE:
142 case BO_EQ: // Equality operators.
143 case BO_NE:
144 case BO_LAnd: // AND operator.
145 case BO_LOr: // Logical OR operator.
Chris Lattner4ebae652010-04-16 23:34:13 +0000146 return true;
Alexis Hunta8136cc2010-05-05 15:23:54 +0000147
John McCalle3027922010-08-25 11:45:40 +0000148 case BO_And: // Bitwise AND operator.
149 case BO_Xor: // Bitwise XOR operator.
150 case BO_Or: // Bitwise OR operator.
Chris Lattner4ebae652010-04-16 23:34:13 +0000151 // Handle things like (x==2)|(y==12).
152 return BO->getLHS()->isKnownToHaveBooleanValue() &&
153 BO->getRHS()->isKnownToHaveBooleanValue();
Alexis Hunta8136cc2010-05-05 15:23:54 +0000154
John McCalle3027922010-08-25 11:45:40 +0000155 case BO_Comma:
156 case BO_Assign:
Chris Lattner4ebae652010-04-16 23:34:13 +0000157 return BO->getRHS()->isKnownToHaveBooleanValue();
158 }
159 }
Alexis Hunta8136cc2010-05-05 15:23:54 +0000160
Peter Collingbourne91147592011-04-15 00:35:48 +0000161 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
Chris Lattner4ebae652010-04-16 23:34:13 +0000162 return CO->getTrueExpr()->isKnownToHaveBooleanValue() &&
163 CO->getFalseExpr()->isKnownToHaveBooleanValue();
Alexis Hunta8136cc2010-05-05 15:23:54 +0000164
Chris Lattner4ebae652010-04-16 23:34:13 +0000165 return false;
166}
167
John McCallbd066782011-02-09 08:16:59 +0000168// Amusing macro metaprogramming hack: check whether a class provides
169// a more specific implementation of getExprLoc().
Daniel Dunbarb0ab5e92012-03-09 15:39:19 +0000170//
171// See also Stmt.cpp:{getLocStart(),getLocEnd()}.
John McCallbd066782011-02-09 08:16:59 +0000172namespace {
173 /// This implementation is used when a class provides a custom
174 /// implementation of getExprLoc.
175 template <class E, class T>
176 SourceLocation getExprLocImpl(const Expr *expr,
177 SourceLocation (T::*v)() const) {
178 return static_cast<const E*>(expr)->getExprLoc();
179 }
180
181 /// This implementation is used when a class doesn't provide
182 /// a custom implementation of getExprLoc. Overload resolution
183 /// should pick it over the implementation above because it's
184 /// more specialized according to function template partial ordering.
185 template <class E>
186 SourceLocation getExprLocImpl(const Expr *expr,
187 SourceLocation (Expr::*v)() const) {
Daniel Dunbarb0ab5e92012-03-09 15:39:19 +0000188 return static_cast<const E*>(expr)->getLocStart();
John McCallbd066782011-02-09 08:16:59 +0000189 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000190}
John McCallbd066782011-02-09 08:16:59 +0000191
192SourceLocation Expr::getExprLoc() const {
193 switch (getStmtClass()) {
194 case Stmt::NoStmtClass: llvm_unreachable("statement without class");
195#define ABSTRACT_STMT(type)
196#define STMT(type, base) \
Richard Smitha0cbfc92014-07-26 00:47:13 +0000197 case Stmt::type##Class: break;
John McCallbd066782011-02-09 08:16:59 +0000198#define EXPR(type, base) \
199 case Stmt::type##Class: return getExprLocImpl<type>(this, &type::getExprLoc);
200#include "clang/AST/StmtNodes.inc"
201 }
Richard Smitha0cbfc92014-07-26 00:47:13 +0000202 llvm_unreachable("unknown expression kind");
John McCallbd066782011-02-09 08:16:59 +0000203}
204
Chris Lattner0eedafe2006-08-24 04:56:27 +0000205//===----------------------------------------------------------------------===//
206// Primary Expressions.
207//===----------------------------------------------------------------------===//
208
Douglas Gregor678d76c2011-07-01 01:22:09 +0000209/// \brief Compute the type-, value-, and instantiation-dependence of a
210/// declaration reference
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000211/// based on the declaration being referenced.
Craig Topperce7167c2013-08-22 04:58:56 +0000212static void computeDeclRefDependence(const ASTContext &Ctx, NamedDecl *D,
213 QualType T, bool &TypeDependent,
Douglas Gregor678d76c2011-07-01 01:22:09 +0000214 bool &ValueDependent,
215 bool &InstantiationDependent) {
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000216 TypeDependent = false;
217 ValueDependent = false;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000218 InstantiationDependent = false;
Douglas Gregored6c7442009-11-23 11:41:28 +0000219
220 // (TD) C++ [temp.dep.expr]p3:
221 // An id-expression is type-dependent if it contains:
222 //
Richard Smithcfaa5a32014-10-17 02:46:42 +0000223 // and
Douglas Gregored6c7442009-11-23 11:41:28 +0000224 //
225 // (VD) C++ [temp.dep.constexpr]p2:
226 // An identifier is value-dependent if it is:
Richard Smithcfaa5a32014-10-17 02:46:42 +0000227
Douglas Gregored6c7442009-11-23 11:41:28 +0000228 // (TD) - an identifier that was declared with dependent type
229 // (VD) - a name declared with a dependent type,
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000230 if (T->isDependentType()) {
231 TypeDependent = true;
232 ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000233 InstantiationDependent = true;
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000234 return;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000235 } else if (T->isInstantiationDependentType()) {
236 InstantiationDependent = true;
Douglas Gregored6c7442009-11-23 11:41:28 +0000237 }
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000238
Douglas Gregored6c7442009-11-23 11:41:28 +0000239 // (TD) - a conversion-function-id that specifies a dependent type
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000240 if (D->getDeclName().getNameKind()
Douglas Gregor678d76c2011-07-01 01:22:09 +0000241 == DeclarationName::CXXConversionFunctionName) {
242 QualType T = D->getDeclName().getCXXNameType();
243 if (T->isDependentType()) {
244 TypeDependent = true;
245 ValueDependent = true;
246 InstantiationDependent = true;
247 return;
248 }
249
250 if (T->isInstantiationDependentType())
251 InstantiationDependent = true;
Douglas Gregored6c7442009-11-23 11:41:28 +0000252 }
Douglas Gregor678d76c2011-07-01 01:22:09 +0000253
Douglas Gregored6c7442009-11-23 11:41:28 +0000254 // (VD) - the name of a non-type template parameter,
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000255 if (isa<NonTypeTemplateParmDecl>(D)) {
256 ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000257 InstantiationDependent = true;
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000258 return;
259 }
260
Douglas Gregored6c7442009-11-23 11:41:28 +0000261 // (VD) - a constant with integral or enumeration type and is
262 // initialized with an expression that is value-dependent.
Richard Smithec8dcd22011-11-08 01:31:09 +0000263 // (VD) - a constant with literal type and is initialized with an
264 // expression that is value-dependent [C++11].
265 // (VD) - FIXME: Missing from the standard:
266 // - an entity with reference type and is initialized with an
267 // expression that is value-dependent [C++11]
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000268 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000269 if ((Ctx.getLangOpts().CPlusPlus11 ?
Richard Smithd9f663b2013-04-22 15:31:51 +0000270 Var->getType()->isLiteralType(Ctx) :
Richard Smithec8dcd22011-11-08 01:31:09 +0000271 Var->getType()->isIntegralOrEnumerationType()) &&
David Blaikief5697e52012-08-10 00:55:35 +0000272 (Var->getType().isConstQualified() ||
Richard Smithec8dcd22011-11-08 01:31:09 +0000273 Var->getType()->isReferenceType())) {
Sebastian Redl5ca79842010-02-01 20:16:42 +0000274 if (const Expr *Init = Var->getAnyInitializer())
Douglas Gregor678d76c2011-07-01 01:22:09 +0000275 if (Init->isValueDependent()) {
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000276 ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000277 InstantiationDependent = true;
278 }
Richard Smithec8dcd22011-11-08 01:31:09 +0000279 }
280
Douglas Gregor0e4de762010-05-11 08:41:30 +0000281 // (VD) - FIXME: Missing from the standard:
282 // - a member function or a static data member of the current
283 // instantiation
Richard Smithec8dcd22011-11-08 01:31:09 +0000284 if (Var->isStaticDataMember() &&
285 Var->getDeclContext()->isDependentContext()) {
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000286 ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000287 InstantiationDependent = true;
Richard Smith00f5d892013-11-14 22:40:45 +0000288 TypeSourceInfo *TInfo = Var->getFirstDecl()->getTypeSourceInfo();
289 if (TInfo->getType()->isIncompleteArrayType())
290 TypeDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000291 }
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000292
293 return;
294 }
295
Douglas Gregor0e4de762010-05-11 08:41:30 +0000296 // (VD) - FIXME: Missing from the standard:
297 // - a member function or a static data member of the current
298 // instantiation
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000299 if (isa<CXXMethodDecl>(D) && D->getDeclContext()->isDependentContext()) {
300 ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000301 InstantiationDependent = true;
Richard Smithec8dcd22011-11-08 01:31:09 +0000302 }
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000303}
Douglas Gregora6e053e2010-12-15 01:34:56 +0000304
Craig Topperce7167c2013-08-22 04:58:56 +0000305void DeclRefExpr::computeDependence(const ASTContext &Ctx) {
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000306 bool TypeDependent = false;
307 bool ValueDependent = false;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000308 bool InstantiationDependent = false;
Daniel Dunbar9d355812012-03-09 01:51:51 +0000309 computeDeclRefDependence(Ctx, getDecl(), getType(), TypeDependent,
310 ValueDependent, InstantiationDependent);
Richard Smithcfaa5a32014-10-17 02:46:42 +0000311
312 ExprBits.TypeDependent |= TypeDependent;
313 ExprBits.ValueDependent |= ValueDependent;
314 ExprBits.InstantiationDependent |= InstantiationDependent;
315
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000316 // Is the declaration a parameter pack?
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000317 if (getDecl()->isParameterPack())
Douglas Gregor3c6bd2a2011-01-05 21:11:38 +0000318 ExprBits.ContainsUnexpandedParameterPack = true;
Douglas Gregored6c7442009-11-23 11:41:28 +0000319}
320
Craig Topperce7167c2013-08-22 04:58:56 +0000321DeclRefExpr::DeclRefExpr(const ASTContext &Ctx,
Daniel Dunbar9d355812012-03-09 01:51:51 +0000322 NestedNameSpecifierLoc QualifierLoc,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000323 SourceLocation TemplateKWLoc,
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000324 ValueDecl *D, bool RefersToEnclosingVariableOrCapture,
John McCall113bee02012-03-10 09:33:50 +0000325 const DeclarationNameInfo &NameInfo,
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000326 NamedDecl *FoundD,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000327 const TemplateArgumentListInfo *TemplateArgs,
John McCall7decc9e2010-11-18 06:31:45 +0000328 QualType T, ExprValueKind VK)
Douglas Gregor678d76c2011-07-01 01:22:09 +0000329 : Expr(DeclRefExprClass, T, VK, OK_Ordinary, false, false, false, false),
Chandler Carruth0e439962011-05-01 21:29:53 +0000330 D(D), Loc(NameInfo.getLoc()), DNLoc(NameInfo.getInfo()) {
331 DeclRefExprBits.HasQualifier = QualifierLoc ? 1 : 0;
Richard Smithcfaa5a32014-10-17 02:46:42 +0000332 if (QualifierLoc) {
James Y Knighte7d82282015-12-29 18:15:14 +0000333 new (getTrailingObjects<NestedNameSpecifierLoc>())
334 NestedNameSpecifierLoc(QualifierLoc);
Richard Smithcfaa5a32014-10-17 02:46:42 +0000335 auto *NNS = QualifierLoc.getNestedNameSpecifier();
336 if (NNS->isInstantiationDependent())
337 ExprBits.InstantiationDependent = true;
338 if (NNS->containsUnexpandedParameterPack())
339 ExprBits.ContainsUnexpandedParameterPack = true;
340 }
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000341 DeclRefExprBits.HasFoundDecl = FoundD ? 1 : 0;
342 if (FoundD)
James Y Knighte7d82282015-12-29 18:15:14 +0000343 *getTrailingObjects<NamedDecl *>() = FoundD;
Abramo Bagnara7945c982012-01-27 09:46:47 +0000344 DeclRefExprBits.HasTemplateKWAndArgsInfo
345 = (TemplateArgs || TemplateKWLoc.isValid()) ? 1 : 0;
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000346 DeclRefExprBits.RefersToEnclosingVariableOrCapture =
347 RefersToEnclosingVariableOrCapture;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000348 if (TemplateArgs) {
349 bool Dependent = false;
350 bool InstantiationDependent = false;
351 bool ContainsUnexpandedParameterPack = false;
James Y Knighte7d82282015-12-29 18:15:14 +0000352 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
353 TemplateKWLoc, *TemplateArgs, getTrailingObjects<TemplateArgumentLoc>(),
354 Dependent, InstantiationDependent, ContainsUnexpandedParameterPack);
Richard Smithcfaa5a32014-10-17 02:46:42 +0000355 assert(!Dependent && "built a DeclRefExpr with dependent template args");
356 ExprBits.InstantiationDependent |= InstantiationDependent;
357 ExprBits.ContainsUnexpandedParameterPack |= ContainsUnexpandedParameterPack;
Abramo Bagnara7945c982012-01-27 09:46:47 +0000358 } else if (TemplateKWLoc.isValid()) {
James Y Knighte7d82282015-12-29 18:15:14 +0000359 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
360 TemplateKWLoc);
Douglas Gregor678d76c2011-07-01 01:22:09 +0000361 }
Benjamin Kramer138ef9c2011-10-10 12:54:05 +0000362 DeclRefExprBits.HadMultipleCandidates = 0;
363
Daniel Dunbar9d355812012-03-09 01:51:51 +0000364 computeDependence(Ctx);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000365}
366
Craig Topperce7167c2013-08-22 04:58:56 +0000367DeclRefExpr *DeclRefExpr::Create(const ASTContext &Context,
Douglas Gregorea972d32011-02-28 21:54:11 +0000368 NestedNameSpecifierLoc QualifierLoc,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000369 SourceLocation TemplateKWLoc,
John McCallce546572009-12-08 09:08:17 +0000370 ValueDecl *D,
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000371 bool RefersToEnclosingVariableOrCapture,
Douglas Gregor4bd90e52009-10-23 18:54:35 +0000372 SourceLocation NameLoc,
Douglas Gregored6c7442009-11-23 11:41:28 +0000373 QualType T,
John McCall7decc9e2010-11-18 06:31:45 +0000374 ExprValueKind VK,
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000375 NamedDecl *FoundD,
Douglas Gregored6c7442009-11-23 11:41:28 +0000376 const TemplateArgumentListInfo *TemplateArgs) {
Abramo Bagnara7945c982012-01-27 09:46:47 +0000377 return Create(Context, QualifierLoc, TemplateKWLoc, D,
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000378 RefersToEnclosingVariableOrCapture,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000379 DeclarationNameInfo(D->getDeclName(), NameLoc),
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000380 T, VK, FoundD, TemplateArgs);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000381}
382
Craig Topperce7167c2013-08-22 04:58:56 +0000383DeclRefExpr *DeclRefExpr::Create(const ASTContext &Context,
Douglas Gregorea972d32011-02-28 21:54:11 +0000384 NestedNameSpecifierLoc QualifierLoc,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000385 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000386 ValueDecl *D,
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000387 bool RefersToEnclosingVariableOrCapture,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000388 const DeclarationNameInfo &NameInfo,
389 QualType T,
John McCall7decc9e2010-11-18 06:31:45 +0000390 ExprValueKind VK,
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000391 NamedDecl *FoundD,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000392 const TemplateArgumentListInfo *TemplateArgs) {
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000393 // Filter out cases where the found Decl is the same as the value refenenced.
394 if (D == FoundD)
Craig Topper36250ad2014-05-12 05:36:57 +0000395 FoundD = nullptr;
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000396
James Y Knighte7d82282015-12-29 18:15:14 +0000397 bool HasTemplateKWAndArgsInfo = TemplateArgs || TemplateKWLoc.isValid();
398 std::size_t Size =
399 totalSizeToAlloc<NestedNameSpecifierLoc, NamedDecl *,
400 ASTTemplateKWAndArgsInfo, TemplateArgumentLoc>(
401 QualifierLoc ? 1 : 0, FoundD ? 1 : 0,
402 HasTemplateKWAndArgsInfo ? 1 : 0,
403 TemplateArgs ? TemplateArgs->size() : 0);
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000404
Chris Lattner5c0b4052010-10-30 05:14:06 +0000405 void *Mem = Context.Allocate(Size, llvm::alignOf<DeclRefExpr>());
Daniel Dunbar9d355812012-03-09 01:51:51 +0000406 return new (Mem) DeclRefExpr(Context, QualifierLoc, TemplateKWLoc, D,
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000407 RefersToEnclosingVariableOrCapture,
Daniel Dunbar9d355812012-03-09 01:51:51 +0000408 NameInfo, FoundD, TemplateArgs, T, VK);
Douglas Gregor4bd90e52009-10-23 18:54:35 +0000409}
410
Craig Topperce7167c2013-08-22 04:58:56 +0000411DeclRefExpr *DeclRefExpr::CreateEmpty(const ASTContext &Context,
Douglas Gregor87866ce2011-02-04 12:01:24 +0000412 bool HasQualifier,
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000413 bool HasFoundDecl,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000414 bool HasTemplateKWAndArgsInfo,
Argyrios Kyrtzidis1985bb32010-07-08 13:09:47 +0000415 unsigned NumTemplateArgs) {
James Y Knighte7d82282015-12-29 18:15:14 +0000416 assert(NumTemplateArgs == 0 || HasTemplateKWAndArgsInfo);
417 std::size_t Size =
418 totalSizeToAlloc<NestedNameSpecifierLoc, NamedDecl *,
419 ASTTemplateKWAndArgsInfo, TemplateArgumentLoc>(
420 HasQualifier ? 1 : 0, HasFoundDecl ? 1 : 0, HasTemplateKWAndArgsInfo,
421 NumTemplateArgs);
Chris Lattner5c0b4052010-10-30 05:14:06 +0000422 void *Mem = Context.Allocate(Size, llvm::alignOf<DeclRefExpr>());
Argyrios Kyrtzidis1985bb32010-07-08 13:09:47 +0000423 return new (Mem) DeclRefExpr(EmptyShell());
424}
425
Daniel Dunbarb507f272012-03-09 15:39:15 +0000426SourceLocation DeclRefExpr::getLocStart() const {
427 if (hasQualifier())
428 return getQualifierLoc().getBeginLoc();
429 return getNameInfo().getLocStart();
430}
431SourceLocation DeclRefExpr::getLocEnd() const {
432 if (hasExplicitTemplateArgs())
433 return getRAngleLoc();
434 return getNameInfo().getLocEnd();
435}
Douglas Gregor4bd90e52009-10-23 18:54:35 +0000436
Alexey Bataevec474782014-10-09 08:45:04 +0000437PredefinedExpr::PredefinedExpr(SourceLocation L, QualType FNTy, IdentType IT,
438 StringLiteral *SL)
439 : Expr(PredefinedExprClass, FNTy, VK_LValue, OK_Ordinary,
440 FNTy->isDependentType(), FNTy->isDependentType(),
441 FNTy->isInstantiationDependentType(),
442 /*ContainsUnexpandedParameterPack=*/false),
443 Loc(L), Type(IT), FnName(SL) {}
444
445StringLiteral *PredefinedExpr::getFunctionName() {
Alexey Bataev769562a2014-10-10 18:58:13 +0000446 return cast_or_null<StringLiteral>(FnName);
Alexey Bataevec474782014-10-09 08:45:04 +0000447}
448
449StringRef PredefinedExpr::getIdentTypeName(PredefinedExpr::IdentType IT) {
450 switch (IT) {
451 case Func:
452 return "__func__";
453 case Function:
454 return "__FUNCTION__";
455 case FuncDName:
456 return "__FUNCDNAME__";
457 case LFunction:
458 return "L__FUNCTION__";
459 case PrettyFunction:
460 return "__PRETTY_FUNCTION__";
461 case FuncSig:
462 return "__FUNCSIG__";
463 case PrettyFunctionNoVirtual:
464 break;
465 }
466 llvm_unreachable("Unknown ident type for PredefinedExpr");
467}
468
Anders Carlsson2fb08242009-09-08 18:24:21 +0000469// FIXME: Maybe this should use DeclPrinter with a special "print predefined
470// expr" policy instead.
Anders Carlsson5bd8d192010-02-11 18:20:28 +0000471std::string PredefinedExpr::ComputeName(IdentType IT, const Decl *CurrentDecl) {
472 ASTContext &Context = CurrentDecl->getASTContext();
473
David Majnemerbed356a2013-11-06 23:31:56 +0000474 if (IT == PredefinedExpr::FuncDName) {
475 if (const NamedDecl *ND = dyn_cast<NamedDecl>(CurrentDecl)) {
Ahmed Charlesb8984322014-03-07 20:03:18 +0000476 std::unique_ptr<MangleContext> MC;
David Majnemerbed356a2013-11-06 23:31:56 +0000477 MC.reset(Context.createMangleContext());
478
479 if (MC->shouldMangleDeclName(ND)) {
480 SmallString<256> Buffer;
481 llvm::raw_svector_ostream Out(Buffer);
482 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(ND))
483 MC->mangleCXXCtor(CD, Ctor_Base, Out);
484 else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(ND))
485 MC->mangleCXXDtor(DD, Dtor_Base, Out);
486 else
487 MC->mangleName(ND, Out);
488
David Majnemerbed356a2013-11-06 23:31:56 +0000489 if (!Buffer.empty() && Buffer.front() == '\01')
490 return Buffer.substr(1);
491 return Buffer.str();
492 } else
493 return ND->getIdentifier()->getName();
494 }
495 return "";
496 }
Alexey Bataevec474782014-10-09 08:45:04 +0000497 if (auto *BD = dyn_cast<BlockDecl>(CurrentDecl)) {
498 std::unique_ptr<MangleContext> MC;
499 MC.reset(Context.createMangleContext());
500 SmallString<256> Buffer;
501 llvm::raw_svector_ostream Out(Buffer);
502 auto DC = CurrentDecl->getDeclContext();
503 if (DC->isFileContext())
504 MC->mangleGlobalBlock(BD, /*ID*/ nullptr, Out);
505 else if (const auto *CD = dyn_cast<CXXConstructorDecl>(DC))
506 MC->mangleCtorBlock(CD, /*CT*/ Ctor_Complete, BD, Out);
507 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(DC))
508 MC->mangleDtorBlock(DD, /*DT*/ Dtor_Complete, BD, Out);
509 else
510 MC->mangleBlock(DC, BD, Out);
511 return Out.str();
512 }
Anders Carlsson2fb08242009-09-08 18:24:21 +0000513 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CurrentDecl)) {
Reid Kleckner52eddda2014-04-08 18:13:24 +0000514 if (IT != PrettyFunction && IT != PrettyFunctionNoVirtual && IT != FuncSig)
Anders Carlsson2fb08242009-09-08 18:24:21 +0000515 return FD->getNameAsString();
516
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000517 SmallString<256> Name;
Anders Carlsson2fb08242009-09-08 18:24:21 +0000518 llvm::raw_svector_ostream Out(Name);
519
520 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
Anders Carlsson5bd8d192010-02-11 18:20:28 +0000521 if (MD->isVirtual() && IT != PrettyFunctionNoVirtual)
Anders Carlsson2fb08242009-09-08 18:24:21 +0000522 Out << "virtual ";
Sam Weinig4e83bd22009-12-27 01:38:20 +0000523 if (MD->isStatic())
524 Out << "static ";
Anders Carlsson2fb08242009-09-08 18:24:21 +0000525 }
526
David Blaikiebbafb8a2012-03-11 07:00:24 +0000527 PrintingPolicy Policy(Context.getLangOpts());
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +0000528 std::string Proto;
Douglas Gregor11a434a2012-04-10 20:14:15 +0000529 llvm::raw_string_ostream POut(Proto);
Anders Carlsson2fb08242009-09-08 18:24:21 +0000530
Douglas Gregor11a434a2012-04-10 20:14:15 +0000531 const FunctionDecl *Decl = FD;
532 if (const FunctionDecl* Pattern = FD->getTemplateInstantiationPattern())
533 Decl = Pattern;
534 const FunctionType *AFT = Decl->getType()->getAs<FunctionType>();
Craig Topper36250ad2014-05-12 05:36:57 +0000535 const FunctionProtoType *FT = nullptr;
Anders Carlsson2fb08242009-09-08 18:24:21 +0000536 if (FD->hasWrittenPrototype())
537 FT = dyn_cast<FunctionProtoType>(AFT);
538
Reid Kleckner52eddda2014-04-08 18:13:24 +0000539 if (IT == FuncSig) {
540 switch (FT->getCallConv()) {
541 case CC_C: POut << "__cdecl "; break;
542 case CC_X86StdCall: POut << "__stdcall "; break;
543 case CC_X86FastCall: POut << "__fastcall "; break;
544 case CC_X86ThisCall: POut << "__thiscall "; break;
Reid Klecknerd7857f02014-10-24 17:42:17 +0000545 case CC_X86VectorCall: POut << "__vectorcall "; break;
Reid Kleckner52eddda2014-04-08 18:13:24 +0000546 // Only bother printing the conventions that MSVC knows about.
547 default: break;
548 }
549 }
550
551 FD->printQualifiedName(POut, Policy);
552
Douglas Gregor11a434a2012-04-10 20:14:15 +0000553 POut << "(";
Anders Carlsson2fb08242009-09-08 18:24:21 +0000554 if (FT) {
Douglas Gregor11a434a2012-04-10 20:14:15 +0000555 for (unsigned i = 0, e = Decl->getNumParams(); i != e; ++i) {
Anders Carlsson2fb08242009-09-08 18:24:21 +0000556 if (i) POut << ", ";
Argyrios Kyrtzidisa18347e2012-05-05 04:20:37 +0000557 POut << Decl->getParamDecl(i)->getType().stream(Policy);
Anders Carlsson2fb08242009-09-08 18:24:21 +0000558 }
559
560 if (FT->isVariadic()) {
561 if (FD->getNumParams()) POut << ", ";
562 POut << "...";
563 }
564 }
Douglas Gregor11a434a2012-04-10 20:14:15 +0000565 POut << ")";
Anders Carlsson2fb08242009-09-08 18:24:21 +0000566
Sam Weinig4e83bd22009-12-27 01:38:20 +0000567 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
Argyrios Kyrtzidis53e3d6d2012-12-14 19:44:11 +0000568 const FunctionType *FT = MD->getType()->castAs<FunctionType>();
David Blaikief5697e52012-08-10 00:55:35 +0000569 if (FT->isConst())
Douglas Gregor11a434a2012-04-10 20:14:15 +0000570 POut << " const";
David Blaikief5697e52012-08-10 00:55:35 +0000571 if (FT->isVolatile())
Douglas Gregor11a434a2012-04-10 20:14:15 +0000572 POut << " volatile";
573 RefQualifierKind Ref = MD->getRefQualifier();
574 if (Ref == RQ_LValue)
575 POut << " &";
576 else if (Ref == RQ_RValue)
577 POut << " &&";
Sam Weinig4e83bd22009-12-27 01:38:20 +0000578 }
579
Douglas Gregor11a434a2012-04-10 20:14:15 +0000580 typedef SmallVector<const ClassTemplateSpecializationDecl *, 8> SpecsTy;
581 SpecsTy Specs;
582 const DeclContext *Ctx = FD->getDeclContext();
583 while (Ctx && isa<NamedDecl>(Ctx)) {
584 const ClassTemplateSpecializationDecl *Spec
585 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx);
586 if (Spec && !Spec->isExplicitSpecialization())
587 Specs.push_back(Spec);
588 Ctx = Ctx->getParent();
589 }
590
591 std::string TemplateParams;
592 llvm::raw_string_ostream TOut(TemplateParams);
593 for (SpecsTy::reverse_iterator I = Specs.rbegin(), E = Specs.rend();
594 I != E; ++I) {
595 const TemplateParameterList *Params
596 = (*I)->getSpecializedTemplate()->getTemplateParameters();
597 const TemplateArgumentList &Args = (*I)->getTemplateArgs();
598 assert(Params->size() == Args.size());
599 for (unsigned i = 0, numParams = Params->size(); i != numParams; ++i) {
600 StringRef Param = Params->getParam(i)->getName();
601 if (Param.empty()) continue;
602 TOut << Param << " = ";
603 Args.get(i).print(Policy, TOut);
604 TOut << ", ";
605 }
606 }
607
608 FunctionTemplateSpecializationInfo *FSI
609 = FD->getTemplateSpecializationInfo();
610 if (FSI && !FSI->isExplicitSpecialization()) {
611 const TemplateParameterList* Params
612 = FSI->getTemplate()->getTemplateParameters();
613 const TemplateArgumentList* Args = FSI->TemplateArguments;
614 assert(Params->size() == Args->size());
615 for (unsigned i = 0, e = Params->size(); i != e; ++i) {
616 StringRef Param = Params->getParam(i)->getName();
617 if (Param.empty()) continue;
618 TOut << Param << " = ";
619 Args->get(i).print(Policy, TOut);
620 TOut << ", ";
621 }
622 }
623
624 TOut.flush();
625 if (!TemplateParams.empty()) {
626 // remove the trailing comma and space
627 TemplateParams.resize(TemplateParams.size() - 2);
628 POut << " [" << TemplateParams << "]";
629 }
630
631 POut.flush();
632
Benjamin Kramer90f54222013-08-21 11:45:27 +0000633 // Print "auto" for all deduced return types. This includes C++1y return
634 // type deduction and lambdas. For trailing return types resolve the
635 // decltype expression. Otherwise print the real type when this is
636 // not a constructor or destructor.
Alexey Bataevec474782014-10-09 08:45:04 +0000637 if (isa<CXXMethodDecl>(FD) &&
638 cast<CXXMethodDecl>(FD)->getParent()->isLambda())
Benjamin Kramer90f54222013-08-21 11:45:27 +0000639 Proto = "auto " + Proto;
Alp Toker314cc812014-01-25 16:55:45 +0000640 else if (FT && FT->getReturnType()->getAs<DecltypeType>())
641 FT->getReturnType()
642 ->getAs<DecltypeType>()
643 ->getUnderlyingType()
Benjamin Kramer90f54222013-08-21 11:45:27 +0000644 .getAsStringInternal(Proto, Policy);
645 else if (!isa<CXXConstructorDecl>(FD) && !isa<CXXDestructorDecl>(FD))
Alp Toker314cc812014-01-25 16:55:45 +0000646 AFT->getReturnType().getAsStringInternal(Proto, Policy);
Anders Carlsson2fb08242009-09-08 18:24:21 +0000647
648 Out << Proto;
649
Anders Carlsson2fb08242009-09-08 18:24:21 +0000650 return Name.str().str();
651 }
Wei Pan8d6b19a2013-08-26 14:27:34 +0000652 if (const CapturedDecl *CD = dyn_cast<CapturedDecl>(CurrentDecl)) {
653 for (const DeclContext *DC = CD->getParent(); DC; DC = DC->getParent())
654 // Skip to its enclosing function or method, but not its enclosing
655 // CapturedDecl.
656 if (DC->isFunctionOrMethod() && (DC->getDeclKind() != Decl::Captured)) {
657 const Decl *D = Decl::castFromDeclContext(DC);
658 return ComputeName(IT, D);
659 }
660 llvm_unreachable("CapturedDecl not inside a function or method");
661 }
Anders Carlsson2fb08242009-09-08 18:24:21 +0000662 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurrentDecl)) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000663 SmallString<256> Name;
Anders Carlsson2fb08242009-09-08 18:24:21 +0000664 llvm::raw_svector_ostream Out(Name);
665 Out << (MD->isInstanceMethod() ? '-' : '+');
666 Out << '[';
Ted Kremenek361ffd92010-03-18 21:23:08 +0000667
668 // For incorrect code, there might not be an ObjCInterfaceDecl. Do
669 // a null check to avoid a crash.
670 if (const ObjCInterfaceDecl *ID = MD->getClassInterface())
Benjamin Kramerb89514a2011-10-14 18:45:37 +0000671 Out << *ID;
Ted Kremenek361ffd92010-03-18 21:23:08 +0000672
Anders Carlsson2fb08242009-09-08 18:24:21 +0000673 if (const ObjCCategoryImplDecl *CID =
Benjamin Kramerb11416d2010-04-17 09:33:03 +0000674 dyn_cast<ObjCCategoryImplDecl>(MD->getDeclContext()))
Benjamin Kramer2f569922012-02-07 11:57:45 +0000675 Out << '(' << *CID << ')';
Benjamin Kramerb11416d2010-04-17 09:33:03 +0000676
Anders Carlsson2fb08242009-09-08 18:24:21 +0000677 Out << ' ';
Aaron Ballmanb190f972014-01-03 17:59:55 +0000678 MD->getSelector().print(Out);
Anders Carlsson2fb08242009-09-08 18:24:21 +0000679 Out << ']';
680
Anders Carlsson2fb08242009-09-08 18:24:21 +0000681 return Name.str().str();
682 }
683 if (isa<TranslationUnitDecl>(CurrentDecl) && IT == PrettyFunction) {
684 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
685 return "top level";
686 }
687 return "";
688}
689
Craig Topper37932912013-08-18 10:09:15 +0000690void APNumericStorage::setIntValue(const ASTContext &C,
691 const llvm::APInt &Val) {
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000692 if (hasAllocation())
693 C.Deallocate(pVal);
694
695 BitWidth = Val.getBitWidth();
696 unsigned NumWords = Val.getNumWords();
697 const uint64_t* Words = Val.getRawData();
698 if (NumWords > 1) {
699 pVal = new (C) uint64_t[NumWords];
700 std::copy(Words, Words + NumWords, pVal);
701 } else if (NumWords == 1)
702 VAL = Words[0];
703 else
704 VAL = 0;
705}
706
Craig Topper37932912013-08-18 10:09:15 +0000707IntegerLiteral::IntegerLiteral(const ASTContext &C, const llvm::APInt &V,
Benjamin Kramer1ea8e092012-07-04 17:04:04 +0000708 QualType type, SourceLocation l)
709 : Expr(IntegerLiteralClass, type, VK_RValue, OK_Ordinary, false, false,
710 false, false),
711 Loc(l) {
712 assert(type->isIntegerType() && "Illegal type in IntegerLiteral");
713 assert(V.getBitWidth() == C.getIntWidth(type) &&
714 "Integer type is not the correct size for constant.");
715 setValue(C, V);
716}
717
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000718IntegerLiteral *
Craig Topper37932912013-08-18 10:09:15 +0000719IntegerLiteral::Create(const ASTContext &C, const llvm::APInt &V,
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000720 QualType type, SourceLocation l) {
721 return new (C) IntegerLiteral(C, V, type, l);
722}
723
724IntegerLiteral *
Craig Topper37932912013-08-18 10:09:15 +0000725IntegerLiteral::Create(const ASTContext &C, EmptyShell Empty) {
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000726 return new (C) IntegerLiteral(Empty);
727}
728
Craig Topper37932912013-08-18 10:09:15 +0000729FloatingLiteral::FloatingLiteral(const ASTContext &C, const llvm::APFloat &V,
Benjamin Kramer1ea8e092012-07-04 17:04:04 +0000730 bool isexact, QualType Type, SourceLocation L)
731 : Expr(FloatingLiteralClass, Type, VK_RValue, OK_Ordinary, false, false,
732 false, false), Loc(L) {
Tim Northover178723a2013-01-22 09:46:51 +0000733 setSemantics(V.getSemantics());
Benjamin Kramer1ea8e092012-07-04 17:04:04 +0000734 FloatingLiteralBits.IsExact = isexact;
735 setValue(C, V);
736}
737
Craig Topper37932912013-08-18 10:09:15 +0000738FloatingLiteral::FloatingLiteral(const ASTContext &C, EmptyShell Empty)
Benjamin Kramer1ea8e092012-07-04 17:04:04 +0000739 : Expr(FloatingLiteralClass, Empty) {
Tim Northover178723a2013-01-22 09:46:51 +0000740 setRawSemantics(IEEEhalf);
Benjamin Kramer1ea8e092012-07-04 17:04:04 +0000741 FloatingLiteralBits.IsExact = false;
742}
743
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000744FloatingLiteral *
Craig Topper37932912013-08-18 10:09:15 +0000745FloatingLiteral::Create(const ASTContext &C, const llvm::APFloat &V,
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000746 bool isexact, QualType Type, SourceLocation L) {
747 return new (C) FloatingLiteral(C, V, isexact, Type, L);
748}
749
750FloatingLiteral *
Craig Topper37932912013-08-18 10:09:15 +0000751FloatingLiteral::Create(const ASTContext &C, EmptyShell Empty) {
Akira Hatanaka428f5b22012-01-10 22:40:09 +0000752 return new (C) FloatingLiteral(C, Empty);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000753}
754
Tim Northover178723a2013-01-22 09:46:51 +0000755const llvm::fltSemantics &FloatingLiteral::getSemantics() const {
756 switch(FloatingLiteralBits.Semantics) {
757 case IEEEhalf:
758 return llvm::APFloat::IEEEhalf;
759 case IEEEsingle:
760 return llvm::APFloat::IEEEsingle;
761 case IEEEdouble:
762 return llvm::APFloat::IEEEdouble;
763 case x87DoubleExtended:
764 return llvm::APFloat::x87DoubleExtended;
765 case IEEEquad:
766 return llvm::APFloat::IEEEquad;
767 case PPCDoubleDouble:
768 return llvm::APFloat::PPCDoubleDouble;
769 }
770 llvm_unreachable("Unrecognised floating semantics");
771}
772
773void FloatingLiteral::setSemantics(const llvm::fltSemantics &Sem) {
774 if (&Sem == &llvm::APFloat::IEEEhalf)
775 FloatingLiteralBits.Semantics = IEEEhalf;
776 else if (&Sem == &llvm::APFloat::IEEEsingle)
777 FloatingLiteralBits.Semantics = IEEEsingle;
778 else if (&Sem == &llvm::APFloat::IEEEdouble)
779 FloatingLiteralBits.Semantics = IEEEdouble;
780 else if (&Sem == &llvm::APFloat::x87DoubleExtended)
781 FloatingLiteralBits.Semantics = x87DoubleExtended;
782 else if (&Sem == &llvm::APFloat::IEEEquad)
783 FloatingLiteralBits.Semantics = IEEEquad;
784 else if (&Sem == &llvm::APFloat::PPCDoubleDouble)
785 FloatingLiteralBits.Semantics = PPCDoubleDouble;
786 else
787 llvm_unreachable("Unknown floating semantics");
788}
789
Chris Lattnera0173132008-06-07 22:13:43 +0000790/// getValueAsApproximateDouble - This returns the value as an inaccurate
791/// double. Note that this may cause loss of precision, but is useful for
792/// debugging dumps, etc.
793double FloatingLiteral::getValueAsApproximateDouble() const {
794 llvm::APFloat V = getValue();
Dale Johannesenc48814b2008-10-09 23:02:32 +0000795 bool ignored;
796 V.convert(llvm::APFloat::IEEEdouble, llvm::APFloat::rmNearestTiesToEven,
797 &ignored);
Chris Lattnera0173132008-06-07 22:13:43 +0000798 return V.convertToDouble();
799}
800
Nick Lewycky4ed84042012-02-24 09:07:53 +0000801int StringLiteral::mapCharByteWidth(TargetInfo const &target,StringKind k) {
Eli Friedman381f4312012-02-29 20:59:56 +0000802 int CharByteWidth = 0;
Nick Lewycky4ed84042012-02-24 09:07:53 +0000803 switch(k) {
Eli Friedmanfcec6302011-11-01 02:23:42 +0000804 case Ascii:
805 case UTF8:
Nick Lewycky4ed84042012-02-24 09:07:53 +0000806 CharByteWidth = target.getCharWidth();
Eli Friedmanfcec6302011-11-01 02:23:42 +0000807 break;
808 case Wide:
Nick Lewycky4ed84042012-02-24 09:07:53 +0000809 CharByteWidth = target.getWCharWidth();
Eli Friedmanfcec6302011-11-01 02:23:42 +0000810 break;
811 case UTF16:
Nick Lewycky4ed84042012-02-24 09:07:53 +0000812 CharByteWidth = target.getChar16Width();
Eli Friedmanfcec6302011-11-01 02:23:42 +0000813 break;
814 case UTF32:
Nick Lewycky4ed84042012-02-24 09:07:53 +0000815 CharByteWidth = target.getChar32Width();
Eli Friedman381f4312012-02-29 20:59:56 +0000816 break;
Eli Friedmanfcec6302011-11-01 02:23:42 +0000817 }
818 assert((CharByteWidth & 7) == 0 && "Assumes character size is byte multiple");
819 CharByteWidth /= 8;
Nick Lewycky4ed84042012-02-24 09:07:53 +0000820 assert((CharByteWidth==1 || CharByteWidth==2 || CharByteWidth==4)
Eli Friedmanfcec6302011-11-01 02:23:42 +0000821 && "character byte widths supported are 1, 2, and 4 only");
822 return CharByteWidth;
823}
824
Craig Topper37932912013-08-18 10:09:15 +0000825StringLiteral *StringLiteral::Create(const ASTContext &C, StringRef Str,
Douglas Gregorfb65e592011-07-27 05:40:30 +0000826 StringKind Kind, bool Pascal, QualType Ty,
Mike Stump11289f42009-09-09 15:08:12 +0000827 const SourceLocation *Loc,
Anders Carlssona3905812009-03-15 18:34:13 +0000828 unsigned NumStrs) {
Benjamin Kramercdac7612014-02-25 12:26:20 +0000829 assert(C.getAsConstantArrayType(Ty) &&
830 "StringLiteral must be of constant array type!");
831
Chris Lattnerf83b5af2009-02-18 06:40:38 +0000832 // Allocate enough space for the StringLiteral plus an array of locations for
833 // any concatenated string tokens.
834 void *Mem = C.Allocate(sizeof(StringLiteral)+
835 sizeof(SourceLocation)*(NumStrs-1),
Chris Lattner5c0b4052010-10-30 05:14:06 +0000836 llvm::alignOf<StringLiteral>());
Chris Lattnerf83b5af2009-02-18 06:40:38 +0000837 StringLiteral *SL = new (Mem) StringLiteral(Ty);
Mike Stump11289f42009-09-09 15:08:12 +0000838
Steve Naroffdf7855b2007-02-21 23:46:25 +0000839 // OPTIMIZE: could allocate this appended to the StringLiteral.
Eli Friedmanfcec6302011-11-01 02:23:42 +0000840 SL->setString(C,Str,Kind,Pascal);
841
Chris Lattnerf83b5af2009-02-18 06:40:38 +0000842 SL->TokLocs[0] = Loc[0];
843 SL->NumConcatenated = NumStrs;
Chris Lattnerd3e98952006-10-06 05:22:26 +0000844
Chris Lattner630970d2009-02-18 05:49:11 +0000845 if (NumStrs != 1)
Chris Lattnerf83b5af2009-02-18 06:40:38 +0000846 memcpy(&SL->TokLocs[1], Loc+1, sizeof(SourceLocation)*(NumStrs-1));
847 return SL;
Chris Lattner630970d2009-02-18 05:49:11 +0000848}
849
Craig Topper37932912013-08-18 10:09:15 +0000850StringLiteral *StringLiteral::CreateEmpty(const ASTContext &C,
851 unsigned NumStrs) {
Douglas Gregor958dfc92009-04-15 16:35:07 +0000852 void *Mem = C.Allocate(sizeof(StringLiteral)+
853 sizeof(SourceLocation)*(NumStrs-1),
Chris Lattner5c0b4052010-10-30 05:14:06 +0000854 llvm::alignOf<StringLiteral>());
Douglas Gregor958dfc92009-04-15 16:35:07 +0000855 StringLiteral *SL = new (Mem) StringLiteral(QualType());
Eli Friedmanfcec6302011-11-01 02:23:42 +0000856 SL->CharByteWidth = 0;
857 SL->Length = 0;
Douglas Gregor958dfc92009-04-15 16:35:07 +0000858 SL->NumConcatenated = NumStrs;
859 return SL;
860}
861
Alexander Kornienko540bacb2013-02-01 12:35:51 +0000862void StringLiteral::outputString(raw_ostream &OS) const {
Richard Trieudc355912012-06-13 20:25:24 +0000863 switch (getKind()) {
864 case Ascii: break; // no prefix.
865 case Wide: OS << 'L'; break;
866 case UTF8: OS << "u8"; break;
867 case UTF16: OS << 'u'; break;
868 case UTF32: OS << 'U'; break;
869 }
870 OS << '"';
871 static const char Hex[] = "0123456789ABCDEF";
872
873 unsigned LastSlashX = getLength();
874 for (unsigned I = 0, N = getLength(); I != N; ++I) {
875 switch (uint32_t Char = getCodeUnit(I)) {
876 default:
877 // FIXME: Convert UTF-8 back to codepoints before rendering.
878
879 // Convert UTF-16 surrogate pairs back to codepoints before rendering.
880 // Leave invalid surrogates alone; we'll use \x for those.
881 if (getKind() == UTF16 && I != N - 1 && Char >= 0xd800 &&
882 Char <= 0xdbff) {
883 uint32_t Trail = getCodeUnit(I + 1);
884 if (Trail >= 0xdc00 && Trail <= 0xdfff) {
885 Char = 0x10000 + ((Char - 0xd800) << 10) + (Trail - 0xdc00);
886 ++I;
887 }
888 }
889
890 if (Char > 0xff) {
891 // If this is a wide string, output characters over 0xff using \x
892 // escapes. Otherwise, this is a UTF-16 or UTF-32 string, and Char is a
893 // codepoint: use \x escapes for invalid codepoints.
894 if (getKind() == Wide ||
895 (Char >= 0xd800 && Char <= 0xdfff) || Char >= 0x110000) {
896 // FIXME: Is this the best way to print wchar_t?
897 OS << "\\x";
898 int Shift = 28;
899 while ((Char >> Shift) == 0)
900 Shift -= 4;
901 for (/**/; Shift >= 0; Shift -= 4)
902 OS << Hex[(Char >> Shift) & 15];
903 LastSlashX = I;
904 break;
905 }
906
907 if (Char > 0xffff)
908 OS << "\\U00"
909 << Hex[(Char >> 20) & 15]
910 << Hex[(Char >> 16) & 15];
911 else
912 OS << "\\u";
913 OS << Hex[(Char >> 12) & 15]
914 << Hex[(Char >> 8) & 15]
915 << Hex[(Char >> 4) & 15]
916 << Hex[(Char >> 0) & 15];
917 break;
918 }
919
920 // If we used \x... for the previous character, and this character is a
921 // hexadecimal digit, prevent it being slurped as part of the \x.
922 if (LastSlashX + 1 == I) {
923 switch (Char) {
924 case '0': case '1': case '2': case '3': case '4':
925 case '5': case '6': case '7': case '8': case '9':
926 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
927 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
928 OS << "\"\"";
929 }
930 }
931
932 assert(Char <= 0xff &&
933 "Characters above 0xff should already have been handled.");
934
Jordan Rosea7d03842013-02-08 22:30:41 +0000935 if (isPrintable(Char))
Richard Trieudc355912012-06-13 20:25:24 +0000936 OS << (char)Char;
937 else // Output anything hard as an octal escape.
938 OS << '\\'
939 << (char)('0' + ((Char >> 6) & 7))
940 << (char)('0' + ((Char >> 3) & 7))
941 << (char)('0' + ((Char >> 0) & 7));
942 break;
943 // Handle some common non-printable cases to make dumps prettier.
944 case '\\': OS << "\\\\"; break;
945 case '"': OS << "\\\""; break;
946 case '\n': OS << "\\n"; break;
947 case '\t': OS << "\\t"; break;
948 case '\a': OS << "\\a"; break;
949 case '\b': OS << "\\b"; break;
950 }
951 }
952 OS << '"';
953}
954
Craig Topper37932912013-08-18 10:09:15 +0000955void StringLiteral::setString(const ASTContext &C, StringRef Str,
Eli Friedmanfcec6302011-11-01 02:23:42 +0000956 StringKind Kind, bool IsPascal) {
957 //FIXME: we assume that the string data comes from a target that uses the same
958 // code unit size and endianess for the type of string.
959 this->Kind = Kind;
960 this->IsPascal = IsPascal;
961
Nick Lewycky4ed84042012-02-24 09:07:53 +0000962 CharByteWidth = mapCharByteWidth(C.getTargetInfo(),Kind);
Eli Friedmanfcec6302011-11-01 02:23:42 +0000963 assert((Str.size()%CharByteWidth == 0)
964 && "size of data must be multiple of CharByteWidth");
965 Length = Str.size()/CharByteWidth;
966
967 switch(CharByteWidth) {
968 case 1: {
969 char *AStrData = new (C) char[Length];
Argyrios Kyrtzidis61710892012-09-14 21:17:41 +0000970 std::memcpy(AStrData,Str.data(),Length*sizeof(*AStrData));
Eli Friedmanfcec6302011-11-01 02:23:42 +0000971 StrData.asChar = AStrData;
972 break;
973 }
974 case 2: {
975 uint16_t *AStrData = new (C) uint16_t[Length];
Argyrios Kyrtzidis61710892012-09-14 21:17:41 +0000976 std::memcpy(AStrData,Str.data(),Length*sizeof(*AStrData));
Eli Friedmanfcec6302011-11-01 02:23:42 +0000977 StrData.asUInt16 = AStrData;
978 break;
979 }
980 case 4: {
981 uint32_t *AStrData = new (C) uint32_t[Length];
Argyrios Kyrtzidis61710892012-09-14 21:17:41 +0000982 std::memcpy(AStrData,Str.data(),Length*sizeof(*AStrData));
Eli Friedmanfcec6302011-11-01 02:23:42 +0000983 StrData.asUInt32 = AStrData;
984 break;
985 }
986 default:
Davide Italiano04839a52016-01-30 08:03:54 +0000987 llvm_unreachable("unsupported CharByteWidth");
Eli Friedmanfcec6302011-11-01 02:23:42 +0000988 }
Douglas Gregor958dfc92009-04-15 16:35:07 +0000989}
990
Chris Lattnere925d612010-11-17 07:37:15 +0000991/// getLocationOfByte - Return a source location that points to the specified
992/// byte of this string literal.
993///
994/// Strings are amazingly complex. They can be formed from multiple tokens and
995/// can have escape sequences in them in addition to the usual trigraph and
996/// escaped newline business. This routine handles this complexity.
997///
Richard Smithefb116f2015-12-10 01:11:47 +0000998/// The *StartToken sets the first token to be searched in this function and
999/// the *StartTokenByteOffset is the byte offset of the first token. Before
1000/// returning, it updates the *StartToken to the TokNo of the token being found
1001/// and sets *StartTokenByteOffset to the byte offset of the token in the
1002/// string.
1003/// Using these two parameters can reduce the time complexity from O(n^2) to
1004/// O(n) if one wants to get the location of byte for all the tokens in a
1005/// string.
1006///
1007SourceLocation
1008StringLiteral::getLocationOfByte(unsigned ByteNo, const SourceManager &SM,
1009 const LangOptions &Features,
1010 const TargetInfo &Target, unsigned *StartToken,
1011 unsigned *StartTokenByteOffset) const {
Richard Smith4060f772012-06-13 05:37:23 +00001012 assert((Kind == StringLiteral::Ascii || Kind == StringLiteral::UTF8) &&
1013 "Only narrow string literals are currently supported");
Douglas Gregorfb65e592011-07-27 05:40:30 +00001014
Chris Lattnere925d612010-11-17 07:37:15 +00001015 // Loop over all of the tokens in this string until we find the one that
1016 // contains the byte we're looking for.
1017 unsigned TokNo = 0;
Richard Smithefb116f2015-12-10 01:11:47 +00001018 unsigned StringOffset = 0;
1019 if (StartToken)
1020 TokNo = *StartToken;
1021 if (StartTokenByteOffset) {
1022 StringOffset = *StartTokenByteOffset;
1023 ByteNo -= StringOffset;
1024 }
Chris Lattnere925d612010-11-17 07:37:15 +00001025 while (1) {
1026 assert(TokNo < getNumConcatenated() && "Invalid byte number!");
1027 SourceLocation StrTokLoc = getStrTokenLoc(TokNo);
1028
1029 // Get the spelling of the string so that we can get the data that makes up
1030 // the string literal, not the identifier for the macro it is potentially
1031 // expanded through.
1032 SourceLocation StrTokSpellingLoc = SM.getSpellingLoc(StrTokLoc);
Richard Smithefb116f2015-12-10 01:11:47 +00001033
Chris Lattnere925d612010-11-17 07:37:15 +00001034 // Re-lex the token to get its length and original spelling.
Richard Smithefb116f2015-12-10 01:11:47 +00001035 std::pair<FileID, unsigned> LocInfo =
1036 SM.getDecomposedLoc(StrTokSpellingLoc);
Chris Lattnere925d612010-11-17 07:37:15 +00001037 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001038 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
Richard Smithefb116f2015-12-10 01:11:47 +00001039 if (Invalid) {
1040 if (StartTokenByteOffset != nullptr)
1041 *StartTokenByteOffset = StringOffset;
1042 if (StartToken != nullptr)
1043 *StartToken = TokNo;
Chris Lattnere925d612010-11-17 07:37:15 +00001044 return StrTokSpellingLoc;
Richard Smithefb116f2015-12-10 01:11:47 +00001045 }
1046
Chris Lattnere925d612010-11-17 07:37:15 +00001047 const char *StrData = Buffer.data()+LocInfo.second;
1048
Chris Lattnere925d612010-11-17 07:37:15 +00001049 // Create a lexer starting at the beginning of this token.
Argyrios Kyrtzidis45f51182012-05-11 21:39:18 +00001050 Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), Features,
1051 Buffer.begin(), StrData, Buffer.end());
Chris Lattnere925d612010-11-17 07:37:15 +00001052 Token TheTok;
1053 TheLexer.LexFromRawLexer(TheTok);
1054
1055 // Use the StringLiteralParser to compute the length of the string in bytes.
Craig Topper9d5583e2014-06-26 04:58:39 +00001056 StringLiteralParser SLP(TheTok, SM, Features, Target);
Chris Lattnere925d612010-11-17 07:37:15 +00001057 unsigned TokNumBytes = SLP.GetStringLength();
1058
1059 // If the byte is in this token, return the location of the byte.
1060 if (ByteNo < TokNumBytes ||
Hans Wennborg77d1abe2011-06-30 20:17:41 +00001061 (ByteNo == TokNumBytes && TokNo == getNumConcatenated() - 1)) {
Richard Smithefb116f2015-12-10 01:11:47 +00001062 unsigned Offset = SLP.getOffsetOfStringByte(TheTok, ByteNo);
1063
Chris Lattnere925d612010-11-17 07:37:15 +00001064 // Now that we know the offset of the token in the spelling, use the
1065 // preprocessor to get the offset in the original source.
Richard Smithefb116f2015-12-10 01:11:47 +00001066 if (StartTokenByteOffset != nullptr)
1067 *StartTokenByteOffset = StringOffset;
1068 if (StartToken != nullptr)
1069 *StartToken = TokNo;
Chris Lattnere925d612010-11-17 07:37:15 +00001070 return Lexer::AdvanceToTokenCharacter(StrTokLoc, Offset, SM, Features);
1071 }
Richard Smithefb116f2015-12-10 01:11:47 +00001072
Chris Lattnere925d612010-11-17 07:37:15 +00001073 // Move to the next string token.
Richard Smithefb116f2015-12-10 01:11:47 +00001074 StringOffset += TokNumBytes;
Chris Lattnere925d612010-11-17 07:37:15 +00001075 ++TokNo;
1076 ByteNo -= TokNumBytes;
1077 }
1078}
1079
1080
1081
Chris Lattner1b926492006-08-23 06:42:10 +00001082/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1083/// corresponds to, e.g. "sizeof" or "[pre]++".
David Blaikie1d202a62012-10-08 01:11:04 +00001084StringRef UnaryOperator::getOpcodeStr(Opcode Op) {
Chris Lattner1b926492006-08-23 06:42:10 +00001085 switch (Op) {
Etienne Bergeron5356d962016-05-12 20:58:56 +00001086#define UNARY_OPERATION(Name, Spelling) case UO_##Name: return Spelling;
1087#include "clang/AST/OperationKinds.def"
Chris Lattner1b926492006-08-23 06:42:10 +00001088 }
David Blaikief47fa302012-01-17 02:30:50 +00001089 llvm_unreachable("Unknown unary operator");
Chris Lattner1b926492006-08-23 06:42:10 +00001090}
1091
John McCalle3027922010-08-25 11:45:40 +00001092UnaryOperatorKind
Douglas Gregor084d8552009-03-13 23:49:33 +00001093UnaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix) {
1094 switch (OO) {
David Blaikie83d382b2011-09-23 05:06:16 +00001095 default: llvm_unreachable("No unary operator for overloaded function");
John McCalle3027922010-08-25 11:45:40 +00001096 case OO_PlusPlus: return Postfix ? UO_PostInc : UO_PreInc;
1097 case OO_MinusMinus: return Postfix ? UO_PostDec : UO_PreDec;
1098 case OO_Amp: return UO_AddrOf;
1099 case OO_Star: return UO_Deref;
1100 case OO_Plus: return UO_Plus;
1101 case OO_Minus: return UO_Minus;
1102 case OO_Tilde: return UO_Not;
1103 case OO_Exclaim: return UO_LNot;
Richard Smith9f690bd2015-10-27 06:02:45 +00001104 case OO_Coawait: return UO_Coawait;
Douglas Gregor084d8552009-03-13 23:49:33 +00001105 }
1106}
1107
1108OverloadedOperatorKind UnaryOperator::getOverloadedOperator(Opcode Opc) {
1109 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00001110 case UO_PostInc: case UO_PreInc: return OO_PlusPlus;
1111 case UO_PostDec: case UO_PreDec: return OO_MinusMinus;
1112 case UO_AddrOf: return OO_Amp;
1113 case UO_Deref: return OO_Star;
1114 case UO_Plus: return OO_Plus;
1115 case UO_Minus: return OO_Minus;
1116 case UO_Not: return OO_Tilde;
1117 case UO_LNot: return OO_Exclaim;
Richard Smith9f690bd2015-10-27 06:02:45 +00001118 case UO_Coawait: return OO_Coawait;
Douglas Gregor084d8552009-03-13 23:49:33 +00001119 default: return OO_None;
1120 }
1121}
1122
1123
Chris Lattner0eedafe2006-08-24 04:56:27 +00001124//===----------------------------------------------------------------------===//
1125// Postfix Operators.
1126//===----------------------------------------------------------------------===//
Chris Lattnere165d942006-08-24 04:40:38 +00001127
Justin Lebarf8bdacb2016-01-14 23:31:30 +00001128CallExpr::CallExpr(const ASTContext &C, StmtClass SC, Expr *fn,
1129 ArrayRef<Expr *> preargs, ArrayRef<Expr *> args, QualType t,
Craig Topper37932912013-08-18 10:09:15 +00001130 ExprValueKind VK, SourceLocation rparenloc)
Justin Lebarf8bdacb2016-01-14 23:31:30 +00001131 : Expr(SC, t, VK, OK_Ordinary, fn->isTypeDependent(),
1132 fn->isValueDependent(), fn->isInstantiationDependent(),
1133 fn->containsUnexpandedParameterPack()),
1134 NumArgs(args.size()) {
Mike Stump11289f42009-09-09 15:08:12 +00001135
Justin Lebarf8bdacb2016-01-14 23:31:30 +00001136 unsigned NumPreArgs = preargs.size();
1137 SubExprs = new (C) Stmt *[args.size()+PREARGS_START+NumPreArgs];
Douglas Gregor993603d2008-11-14 16:09:21 +00001138 SubExprs[FN] = fn;
Justin Lebarf8bdacb2016-01-14 23:31:30 +00001139 for (unsigned i = 0; i != NumPreArgs; ++i) {
1140 updateDependenciesFromArg(preargs[i]);
1141 SubExprs[i+PREARGS_START] = preargs[i];
1142 }
Benjamin Kramerc215e762012-08-24 11:54:20 +00001143 for (unsigned i = 0; i != args.size(); ++i) {
Justin Lebarf8bdacb2016-01-14 23:31:30 +00001144 updateDependenciesFromArg(args[i]);
Peter Collingbourne3a347252011-02-08 21:18:02 +00001145 SubExprs[i+PREARGS_START+NumPreArgs] = args[i];
Douglas Gregora6e053e2010-12-15 01:34:56 +00001146 }
Ted Kremenekd7b4f402009-02-09 20:51:47 +00001147
Peter Collingbourne3a347252011-02-08 21:18:02 +00001148 CallExprBits.NumPreArgs = NumPreArgs;
Douglas Gregor993603d2008-11-14 16:09:21 +00001149 RParenLoc = rparenloc;
1150}
Nate Begeman1e36a852008-01-17 17:46:27 +00001151
Justin Lebarf8bdacb2016-01-14 23:31:30 +00001152CallExpr::CallExpr(const ASTContext &C, StmtClass SC, Expr *fn,
1153 ArrayRef<Expr *> args, QualType t, ExprValueKind VK,
1154 SourceLocation rparenloc)
1155 : CallExpr(C, SC, fn, ArrayRef<Expr *>(), args, t, VK, rparenloc) {}
1156
Benjamin Kramerf04f98d2015-03-06 14:15:57 +00001157CallExpr::CallExpr(const ASTContext &C, Expr *fn, ArrayRef<Expr *> args,
John McCall7decc9e2010-11-18 06:31:45 +00001158 QualType t, ExprValueKind VK, SourceLocation rparenloc)
Justin Lebarf8bdacb2016-01-14 23:31:30 +00001159 : CallExpr(C, CallExprClass, fn, ArrayRef<Expr *>(), args, t, VK, rparenloc) {
Chris Lattnere165d942006-08-24 04:40:38 +00001160}
1161
Craig Topper37932912013-08-18 10:09:15 +00001162CallExpr::CallExpr(const ASTContext &C, StmtClass SC, EmptyShell Empty)
Benjamin Kramerf04f98d2015-03-06 14:15:57 +00001163 : CallExpr(C, SC, /*NumPreArgs=*/0, Empty) {}
Peter Collingbourne3a347252011-02-08 21:18:02 +00001164
Craig Topper37932912013-08-18 10:09:15 +00001165CallExpr::CallExpr(const ASTContext &C, StmtClass SC, unsigned NumPreArgs,
Peter Collingbourne3a347252011-02-08 21:18:02 +00001166 EmptyShell Empty)
Craig Topper36250ad2014-05-12 05:36:57 +00001167 : Expr(SC, Empty), SubExprs(nullptr), NumArgs(0) {
Peter Collingbourne3a347252011-02-08 21:18:02 +00001168 // FIXME: Why do we allocate this?
Justin Lebarf8bdacb2016-01-14 23:31:30 +00001169 SubExprs = new (C) Stmt*[PREARGS_START+NumPreArgs]();
Peter Collingbourne3a347252011-02-08 21:18:02 +00001170 CallExprBits.NumPreArgs = NumPreArgs;
Douglas Gregore20a2e52009-04-15 17:43:59 +00001171}
1172
Justin Lebarf8bdacb2016-01-14 23:31:30 +00001173void CallExpr::updateDependenciesFromArg(Expr *Arg) {
1174 if (Arg->isTypeDependent())
1175 ExprBits.TypeDependent = true;
1176 if (Arg->isValueDependent())
1177 ExprBits.ValueDependent = true;
1178 if (Arg->isInstantiationDependent())
1179 ExprBits.InstantiationDependent = true;
1180 if (Arg->containsUnexpandedParameterPack())
1181 ExprBits.ContainsUnexpandedParameterPack = true;
1182}
1183
Nuno Lopes518e3702009-12-20 23:11:08 +00001184Decl *CallExpr::getCalleeDecl() {
John McCalle3ca8eb2011-09-13 23:08:34 +00001185 Expr *CEE = getCallee()->IgnoreParenImpCasts();
Douglas Gregore0e96302011-09-06 21:41:04 +00001186
1187 while (SubstNonTypeTemplateParmExpr *NTTP
1188 = dyn_cast<SubstNonTypeTemplateParmExpr>(CEE)) {
1189 CEE = NTTP->getReplacement()->IgnoreParenCasts();
1190 }
1191
Sebastian Redl2b1832e2010-09-10 20:55:30 +00001192 // If we're calling a dereference, look at the pointer instead.
1193 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CEE)) {
1194 if (BO->isPtrMemOp())
1195 CEE = BO->getRHS()->IgnoreParenCasts();
1196 } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(CEE)) {
1197 if (UO->getOpcode() == UO_Deref)
1198 CEE = UO->getSubExpr()->IgnoreParenCasts();
1199 }
Chris Lattner52301912009-07-17 15:46:27 +00001200 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CEE))
Nuno Lopes518e3702009-12-20 23:11:08 +00001201 return DRE->getDecl();
Nuno Lopesc095b532009-12-24 00:28:18 +00001202 if (MemberExpr *ME = dyn_cast<MemberExpr>(CEE))
1203 return ME->getMemberDecl();
Zhongxing Xu3c8fa972009-07-17 07:29:51 +00001204
Craig Topper36250ad2014-05-12 05:36:57 +00001205 return nullptr;
Zhongxing Xu3c8fa972009-07-17 07:29:51 +00001206}
1207
Nuno Lopes518e3702009-12-20 23:11:08 +00001208FunctionDecl *CallExpr::getDirectCallee() {
Chris Lattner3a6af3d2009-12-21 01:10:56 +00001209 return dyn_cast_or_null<FunctionDecl>(getCalleeDecl());
Nuno Lopes518e3702009-12-20 23:11:08 +00001210}
1211
Chris Lattnere4407ed2007-12-28 05:25:02 +00001212/// setNumArgs - This changes the number of arguments present in this call.
1213/// Any orphaned expressions are deleted by this, and any new operands are set
1214/// to null.
Craig Topper37932912013-08-18 10:09:15 +00001215void CallExpr::setNumArgs(const ASTContext& C, unsigned NumArgs) {
Chris Lattnere4407ed2007-12-28 05:25:02 +00001216 // No change, just return.
1217 if (NumArgs == getNumArgs()) return;
Mike Stump11289f42009-09-09 15:08:12 +00001218
Chris Lattnere4407ed2007-12-28 05:25:02 +00001219 // If shrinking # arguments, just delete the extras and forgot them.
1220 if (NumArgs < getNumArgs()) {
Chris Lattnere4407ed2007-12-28 05:25:02 +00001221 this->NumArgs = NumArgs;
1222 return;
1223 }
1224
1225 // Otherwise, we are growing the # arguments. New an bigger argument array.
Peter Collingbourne3a347252011-02-08 21:18:02 +00001226 unsigned NumPreArgs = getNumPreArgs();
1227 Stmt **NewSubExprs = new (C) Stmt*[NumArgs+PREARGS_START+NumPreArgs];
Chris Lattnere4407ed2007-12-28 05:25:02 +00001228 // Copy over args.
Peter Collingbourne3a347252011-02-08 21:18:02 +00001229 for (unsigned i = 0; i != getNumArgs()+PREARGS_START+NumPreArgs; ++i)
Chris Lattnere4407ed2007-12-28 05:25:02 +00001230 NewSubExprs[i] = SubExprs[i];
1231 // Null out new args.
Peter Collingbourne3a347252011-02-08 21:18:02 +00001232 for (unsigned i = getNumArgs()+PREARGS_START+NumPreArgs;
1233 i != NumArgs+PREARGS_START+NumPreArgs; ++i)
Craig Topper36250ad2014-05-12 05:36:57 +00001234 NewSubExprs[i] = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001235
Douglas Gregorba6e5572009-04-17 21:46:47 +00001236 if (SubExprs) C.Deallocate(SubExprs);
Chris Lattnere4407ed2007-12-28 05:25:02 +00001237 SubExprs = NewSubExprs;
1238 this->NumArgs = NumArgs;
1239}
1240
Alp Tokera724cff2013-12-28 21:59:02 +00001241/// getBuiltinCallee - If this is a call to a builtin, return the builtin ID. If
Chris Lattner01ff98a2008-10-06 05:00:53 +00001242/// not, return 0.
Alp Tokera724cff2013-12-28 21:59:02 +00001243unsigned CallExpr::getBuiltinCallee() const {
Steve Narofff6e3b3292008-01-31 01:07:12 +00001244 // All simple function calls (e.g. func()) are implicitly cast to pointer to
Mike Stump11289f42009-09-09 15:08:12 +00001245 // function. As a result, we try and obtain the DeclRefExpr from the
Steve Narofff6e3b3292008-01-31 01:07:12 +00001246 // ImplicitCastExpr.
1247 const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(getCallee());
1248 if (!ICE) // FIXME: deal with more complex calls (e.g. (func)(), (*func)()).
Chris Lattner01ff98a2008-10-06 05:00:53 +00001249 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001250
Steve Narofff6e3b3292008-01-31 01:07:12 +00001251 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr());
1252 if (!DRE)
Chris Lattner01ff98a2008-10-06 05:00:53 +00001253 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001254
Anders Carlssonfbcf6762008-01-31 02:13:57 +00001255 const FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
1256 if (!FDecl)
Chris Lattner01ff98a2008-10-06 05:00:53 +00001257 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001258
Douglas Gregor9eb16ea2008-11-21 15:30:19 +00001259 if (!FDecl->getIdentifier())
1260 return 0;
1261
Douglas Gregor15fc9562009-09-12 00:22:50 +00001262 return FDecl->getBuiltinID();
Chris Lattner01ff98a2008-10-06 05:00:53 +00001263}
Anders Carlssonfbcf6762008-01-31 02:13:57 +00001264
Scott Douglass503fc392015-06-10 13:53:15 +00001265bool CallExpr::isUnevaluatedBuiltinCall(const ASTContext &Ctx) const {
Alp Tokera724cff2013-12-28 21:59:02 +00001266 if (unsigned BI = getBuiltinCallee())
Richard Smith5011a002013-01-17 23:46:04 +00001267 return Ctx.BuiltinInfo.isUnevaluated(BI);
1268 return false;
1269}
1270
David Majnemerced8bdf2015-02-25 17:36:15 +00001271QualType CallExpr::getCallReturnType(const ASTContext &Ctx) const {
1272 const Expr *Callee = getCallee();
1273 QualType CalleeType = Callee->getType();
1274 if (const auto *FnTypePtr = CalleeType->getAs<PointerType>()) {
Anders Carlsson00a27592009-05-26 04:57:27 +00001275 CalleeType = FnTypePtr->getPointeeType();
David Majnemerced8bdf2015-02-25 17:36:15 +00001276 } else if (const auto *BPT = CalleeType->getAs<BlockPointerType>()) {
Anders Carlsson00a27592009-05-26 04:57:27 +00001277 CalleeType = BPT->getPointeeType();
David Majnemerced8bdf2015-02-25 17:36:15 +00001278 } else if (CalleeType->isSpecificPlaceholderType(BuiltinType::BoundMember)) {
1279 if (isa<CXXPseudoDestructorExpr>(Callee->IgnoreParens()))
1280 return Ctx.VoidTy;
1281
John McCall0009fcc2011-04-26 20:42:42 +00001282 // This should never be overloaded and so should never return null.
David Majnemerced8bdf2015-02-25 17:36:15 +00001283 CalleeType = Expr::findBoundMemberType(Callee);
1284 }
1285
John McCall0009fcc2011-04-26 20:42:42 +00001286 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00001287 return FnType->getReturnType();
Anders Carlsson00a27592009-05-26 04:57:27 +00001288}
Chris Lattner01ff98a2008-10-06 05:00:53 +00001289
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001290SourceLocation CallExpr::getLocStart() const {
1291 if (isa<CXXOperatorCallExpr>(this))
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00001292 return cast<CXXOperatorCallExpr>(this)->getLocStart();
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001293
1294 SourceLocation begin = getCallee()->getLocStart();
Keno Fischer070db172014-08-15 01:39:12 +00001295 if (begin.isInvalid() && getNumArgs() > 0 && getArg(0))
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001296 begin = getArg(0)->getLocStart();
1297 return begin;
1298}
1299SourceLocation CallExpr::getLocEnd() const {
1300 if (isa<CXXOperatorCallExpr>(this))
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00001301 return cast<CXXOperatorCallExpr>(this)->getLocEnd();
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001302
1303 SourceLocation end = getRParenLoc();
Keno Fischer070db172014-08-15 01:39:12 +00001304 if (end.isInvalid() && getNumArgs() > 0 && getArg(getNumArgs() - 1))
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001305 end = getArg(getNumArgs() - 1)->getLocEnd();
1306 return end;
1307}
John McCall701417a2011-02-21 06:23:05 +00001308
Craig Topper37932912013-08-18 10:09:15 +00001309OffsetOfExpr *OffsetOfExpr::Create(const ASTContext &C, QualType type,
Douglas Gregor882211c2010-04-28 22:16:22 +00001310 SourceLocation OperatorLoc,
Alexis Hunta8136cc2010-05-05 15:23:54 +00001311 TypeSourceInfo *tsi,
Benjamin Kramerc215e762012-08-24 11:54:20 +00001312 ArrayRef<OffsetOfNode> comps,
1313 ArrayRef<Expr*> exprs,
Douglas Gregor882211c2010-04-28 22:16:22 +00001314 SourceLocation RParenLoc) {
James Y Knight7281c352015-12-29 22:31:18 +00001315 void *Mem = C.Allocate(
1316 totalSizeToAlloc<OffsetOfNode, Expr *>(comps.size(), exprs.size()));
Douglas Gregor882211c2010-04-28 22:16:22 +00001317
Benjamin Kramerc215e762012-08-24 11:54:20 +00001318 return new (Mem) OffsetOfExpr(C, type, OperatorLoc, tsi, comps, exprs,
1319 RParenLoc);
Douglas Gregor882211c2010-04-28 22:16:22 +00001320}
1321
Craig Topper37932912013-08-18 10:09:15 +00001322OffsetOfExpr *OffsetOfExpr::CreateEmpty(const ASTContext &C,
Douglas Gregor882211c2010-04-28 22:16:22 +00001323 unsigned numComps, unsigned numExprs) {
James Y Knight7281c352015-12-29 22:31:18 +00001324 void *Mem =
1325 C.Allocate(totalSizeToAlloc<OffsetOfNode, Expr *>(numComps, numExprs));
Douglas Gregor882211c2010-04-28 22:16:22 +00001326 return new (Mem) OffsetOfExpr(numComps, numExprs);
1327}
1328
Craig Topper37932912013-08-18 10:09:15 +00001329OffsetOfExpr::OffsetOfExpr(const ASTContext &C, QualType type,
Douglas Gregor882211c2010-04-28 22:16:22 +00001330 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
Benjamin Kramerc215e762012-08-24 11:54:20 +00001331 ArrayRef<OffsetOfNode> comps, ArrayRef<Expr*> exprs,
Douglas Gregor882211c2010-04-28 22:16:22 +00001332 SourceLocation RParenLoc)
John McCall7decc9e2010-11-18 06:31:45 +00001333 : Expr(OffsetOfExprClass, type, VK_RValue, OK_Ordinary,
1334 /*TypeDependent=*/false,
Douglas Gregora6e053e2010-12-15 01:34:56 +00001335 /*ValueDependent=*/tsi->getType()->isDependentType(),
Douglas Gregor678d76c2011-07-01 01:22:09 +00001336 tsi->getType()->isInstantiationDependentType(),
Douglas Gregora6e053e2010-12-15 01:34:56 +00001337 tsi->getType()->containsUnexpandedParameterPack()),
Alexis Hunta8136cc2010-05-05 15:23:54 +00001338 OperatorLoc(OperatorLoc), RParenLoc(RParenLoc), TSInfo(tsi),
Benjamin Kramerc215e762012-08-24 11:54:20 +00001339 NumComps(comps.size()), NumExprs(exprs.size())
Douglas Gregor882211c2010-04-28 22:16:22 +00001340{
Benjamin Kramerc215e762012-08-24 11:54:20 +00001341 for (unsigned i = 0; i != comps.size(); ++i) {
1342 setComponent(i, comps[i]);
Douglas Gregor882211c2010-04-28 22:16:22 +00001343 }
Alexis Hunta8136cc2010-05-05 15:23:54 +00001344
Benjamin Kramerc215e762012-08-24 11:54:20 +00001345 for (unsigned i = 0; i != exprs.size(); ++i) {
1346 if (exprs[i]->isTypeDependent() || exprs[i]->isValueDependent())
Douglas Gregora6e053e2010-12-15 01:34:56 +00001347 ExprBits.ValueDependent = true;
Benjamin Kramerc215e762012-08-24 11:54:20 +00001348 if (exprs[i]->containsUnexpandedParameterPack())
Douglas Gregora6e053e2010-12-15 01:34:56 +00001349 ExprBits.ContainsUnexpandedParameterPack = true;
1350
Benjamin Kramerc215e762012-08-24 11:54:20 +00001351 setIndexExpr(i, exprs[i]);
Douglas Gregor882211c2010-04-28 22:16:22 +00001352 }
1353}
1354
James Y Knight7281c352015-12-29 22:31:18 +00001355IdentifierInfo *OffsetOfNode::getFieldName() const {
Douglas Gregor882211c2010-04-28 22:16:22 +00001356 assert(getKind() == Field || getKind() == Identifier);
1357 if (getKind() == Field)
1358 return getField()->getIdentifier();
Alexis Hunta8136cc2010-05-05 15:23:54 +00001359
Douglas Gregor882211c2010-04-28 22:16:22 +00001360 return reinterpret_cast<IdentifierInfo *> (Data & ~(uintptr_t)Mask);
1361}
1362
David Majnemer10fd83d2015-01-15 10:04:14 +00001363UnaryExprOrTypeTraitExpr::UnaryExprOrTypeTraitExpr(
1364 UnaryExprOrTypeTrait ExprKind, Expr *E, QualType resultType,
1365 SourceLocation op, SourceLocation rp)
1366 : Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_RValue, OK_Ordinary,
1367 false, // Never type-dependent (C++ [temp.dep.expr]p3).
1368 // Value-dependent if the argument is type-dependent.
1369 E->isTypeDependent(), E->isInstantiationDependent(),
1370 E->containsUnexpandedParameterPack()),
1371 OpLoc(op), RParenLoc(rp) {
1372 UnaryExprOrTypeTraitExprBits.Kind = ExprKind;
1373 UnaryExprOrTypeTraitExprBits.IsType = false;
1374 Argument.Ex = E;
1375
1376 // Check to see if we are in the situation where alignof(decl) should be
1377 // dependent because decl's alignment is dependent.
1378 if (ExprKind == UETT_AlignOf) {
1379 if (!isValueDependent() || !isInstantiationDependent()) {
1380 E = E->IgnoreParens();
1381
1382 const ValueDecl *D = nullptr;
1383 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
1384 D = DRE->getDecl();
1385 else if (const auto *ME = dyn_cast<MemberExpr>(E))
1386 D = ME->getMemberDecl();
1387
1388 if (D) {
1389 for (const auto *I : D->specific_attrs<AlignedAttr>()) {
1390 if (I->isAlignmentDependent()) {
1391 setValueDependent(true);
1392 setInstantiationDependent(true);
1393 break;
1394 }
1395 }
1396 }
1397 }
1398 }
1399}
1400
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00001401MemberExpr *MemberExpr::Create(
1402 const ASTContext &C, Expr *base, bool isarrow, SourceLocation OperatorLoc,
1403 NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,
1404 ValueDecl *memberdecl, DeclAccessPair founddecl,
1405 DeclarationNameInfo nameinfo, const TemplateArgumentListInfo *targs,
1406 QualType ty, ExprValueKind vk, ExprObjectKind ok) {
John McCall16df1e52010-03-30 21:47:33 +00001407
Douglas Gregorea972d32011-02-28 21:54:11 +00001408 bool hasQualOrFound = (QualifierLoc ||
John McCalla8ae2222010-04-06 21:38:20 +00001409 founddecl.getDecl() != memberdecl ||
1410 founddecl.getAccess() != memberdecl->getAccess());
Mike Stump11289f42009-09-09 15:08:12 +00001411
James Y Knighte7d82282015-12-29 18:15:14 +00001412 bool HasTemplateKWAndArgsInfo = targs || TemplateKWLoc.isValid();
1413 std::size_t Size =
1414 totalSizeToAlloc<MemberExprNameQualifier, ASTTemplateKWAndArgsInfo,
1415 TemplateArgumentLoc>(hasQualOrFound ? 1 : 0,
1416 HasTemplateKWAndArgsInfo ? 1 : 0,
1417 targs ? targs->size() : 0);
Mike Stump11289f42009-09-09 15:08:12 +00001418
Chris Lattner5c0b4052010-10-30 05:14:06 +00001419 void *Mem = C.Allocate(Size, llvm::alignOf<MemberExpr>());
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00001420 MemberExpr *E = new (Mem)
1421 MemberExpr(base, isarrow, OperatorLoc, memberdecl, nameinfo, ty, vk, ok);
John McCall16df1e52010-03-30 21:47:33 +00001422
1423 if (hasQualOrFound) {
Douglas Gregorea972d32011-02-28 21:54:11 +00001424 // FIXME: Wrong. We should be looking at the member declaration we found.
1425 if (QualifierLoc && QualifierLoc.getNestedNameSpecifier()->isDependent()) {
John McCall16df1e52010-03-30 21:47:33 +00001426 E->setValueDependent(true);
1427 E->setTypeDependent(true);
Douglas Gregor678d76c2011-07-01 01:22:09 +00001428 E->setInstantiationDependent(true);
1429 }
1430 else if (QualifierLoc &&
1431 QualifierLoc.getNestedNameSpecifier()->isInstantiationDependent())
1432 E->setInstantiationDependent(true);
1433
John McCall16df1e52010-03-30 21:47:33 +00001434 E->HasQualifierOrFoundDecl = true;
1435
James Y Knighte7d82282015-12-29 18:15:14 +00001436 MemberExprNameQualifier *NQ =
1437 E->getTrailingObjects<MemberExprNameQualifier>();
Douglas Gregorea972d32011-02-28 21:54:11 +00001438 NQ->QualifierLoc = QualifierLoc;
John McCall16df1e52010-03-30 21:47:33 +00001439 NQ->FoundDecl = founddecl;
1440 }
1441
Abramo Bagnara7945c982012-01-27 09:46:47 +00001442 E->HasTemplateKWAndArgsInfo = (targs || TemplateKWLoc.isValid());
1443
John McCall16df1e52010-03-30 21:47:33 +00001444 if (targs) {
Douglas Gregor678d76c2011-07-01 01:22:09 +00001445 bool Dependent = false;
1446 bool InstantiationDependent = false;
1447 bool ContainsUnexpandedParameterPack = false;
James Y Knighte7d82282015-12-29 18:15:14 +00001448 E->getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
1449 TemplateKWLoc, *targs, E->getTrailingObjects<TemplateArgumentLoc>(),
1450 Dependent, InstantiationDependent, ContainsUnexpandedParameterPack);
Douglas Gregor678d76c2011-07-01 01:22:09 +00001451 if (InstantiationDependent)
1452 E->setInstantiationDependent(true);
Abramo Bagnara7945c982012-01-27 09:46:47 +00001453 } else if (TemplateKWLoc.isValid()) {
James Y Knighte7d82282015-12-29 18:15:14 +00001454 E->getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
1455 TemplateKWLoc);
John McCall16df1e52010-03-30 21:47:33 +00001456 }
1457
1458 return E;
Douglas Gregorf405d7e2009-08-31 23:41:50 +00001459}
1460
Daniel Dunbarb507f272012-03-09 15:39:15 +00001461SourceLocation MemberExpr::getLocStart() const {
Douglas Gregor25b7e052011-03-02 21:06:53 +00001462 if (isImplicitAccess()) {
1463 if (hasQualifier())
Daniel Dunbarb507f272012-03-09 15:39:15 +00001464 return getQualifierLoc().getBeginLoc();
1465 return MemberLoc;
Douglas Gregor25b7e052011-03-02 21:06:53 +00001466 }
Abramo Bagnara7945c982012-01-27 09:46:47 +00001467
Daniel Dunbarb507f272012-03-09 15:39:15 +00001468 // FIXME: We don't want this to happen. Rather, we should be able to
1469 // detect all kinds of implicit accesses more cleanly.
1470 SourceLocation BaseStartLoc = getBase()->getLocStart();
1471 if (BaseStartLoc.isValid())
1472 return BaseStartLoc;
1473 return MemberLoc;
1474}
1475SourceLocation MemberExpr::getLocEnd() const {
Abramo Bagnara9b836fb2012-11-08 13:52:58 +00001476 SourceLocation EndLoc = getMemberNameInfo().getEndLoc();
Daniel Dunbarb507f272012-03-09 15:39:15 +00001477 if (hasExplicitTemplateArgs())
Abramo Bagnara9b836fb2012-11-08 13:52:58 +00001478 EndLoc = getRAngleLoc();
1479 else if (EndLoc.isInvalid())
1480 EndLoc = getBase()->getLocEnd();
1481 return EndLoc;
Douglas Gregor25b7e052011-03-02 21:06:53 +00001482}
1483
Alp Tokerc1086762013-12-07 13:51:35 +00001484bool CastExpr::CastConsistency() const {
John McCall9320b872011-09-09 05:25:32 +00001485 switch (getCastKind()) {
1486 case CK_DerivedToBase:
1487 case CK_UncheckedDerivedToBase:
1488 case CK_DerivedToBaseMemberPointer:
1489 case CK_BaseToDerived:
1490 case CK_BaseToDerivedMemberPointer:
1491 assert(!path_empty() && "Cast kind should have a base path!");
1492 break;
1493
1494 case CK_CPointerToObjCPointerCast:
1495 assert(getType()->isObjCObjectPointerType());
1496 assert(getSubExpr()->getType()->isPointerType());
1497 goto CheckNoBasePath;
1498
1499 case CK_BlockPointerToObjCPointerCast:
1500 assert(getType()->isObjCObjectPointerType());
1501 assert(getSubExpr()->getType()->isBlockPointerType());
1502 goto CheckNoBasePath;
1503
John McCallc62bb392012-02-15 01:22:51 +00001504 case CK_ReinterpretMemberPointer:
1505 assert(getType()->isMemberPointerType());
1506 assert(getSubExpr()->getType()->isMemberPointerType());
1507 goto CheckNoBasePath;
1508
John McCall9320b872011-09-09 05:25:32 +00001509 case CK_BitCast:
1510 // Arbitrary casts to C pointer types count as bitcasts.
1511 // Otherwise, we should only have block and ObjC pointer casts
1512 // here if they stay within the type kind.
1513 if (!getType()->isPointerType()) {
1514 assert(getType()->isObjCObjectPointerType() ==
1515 getSubExpr()->getType()->isObjCObjectPointerType());
1516 assert(getType()->isBlockPointerType() ==
1517 getSubExpr()->getType()->isBlockPointerType());
1518 }
1519 goto CheckNoBasePath;
1520
1521 case CK_AnyPointerToBlockPointerCast:
1522 assert(getType()->isBlockPointerType());
1523 assert(getSubExpr()->getType()->isAnyPointerType() &&
1524 !getSubExpr()->getType()->isBlockPointerType());
1525 goto CheckNoBasePath;
1526
Douglas Gregored90df32012-02-22 05:02:47 +00001527 case CK_CopyAndAutoreleaseBlockObject:
1528 assert(getType()->isBlockPointerType());
1529 assert(getSubExpr()->getType()->isBlockPointerType());
1530 goto CheckNoBasePath;
Eli Friedman34866c72012-08-31 00:14:07 +00001531
1532 case CK_FunctionToPointerDecay:
1533 assert(getType()->isPointerType());
1534 assert(getSubExpr()->getType()->isFunctionType());
1535 goto CheckNoBasePath;
1536
David Tweede1468322013-12-11 13:39:46 +00001537 case CK_AddressSpaceConversion:
1538 assert(getType()->isPointerType());
1539 assert(getSubExpr()->getType()->isPointerType());
1540 assert(getType()->getPointeeType().getAddressSpace() !=
1541 getSubExpr()->getType()->getPointeeType().getAddressSpace());
John McCall9320b872011-09-09 05:25:32 +00001542 // These should not have an inheritance path.
1543 case CK_Dynamic:
1544 case CK_ToUnion:
1545 case CK_ArrayToPointerDecay:
John McCall9320b872011-09-09 05:25:32 +00001546 case CK_NullToMemberPointer:
1547 case CK_NullToPointer:
1548 case CK_ConstructorConversion:
1549 case CK_IntegralToPointer:
1550 case CK_PointerToIntegral:
1551 case CK_ToVoid:
1552 case CK_VectorSplat:
1553 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +00001554 case CK_BooleanToSignedIntegral:
John McCall9320b872011-09-09 05:25:32 +00001555 case CK_IntegralToFloating:
1556 case CK_FloatingToIntegral:
1557 case CK_FloatingCast:
1558 case CK_ObjCObjectLValueCast:
1559 case CK_FloatingRealToComplex:
1560 case CK_FloatingComplexToReal:
1561 case CK_FloatingComplexCast:
1562 case CK_FloatingComplexToIntegralComplex:
1563 case CK_IntegralRealToComplex:
1564 case CK_IntegralComplexToReal:
1565 case CK_IntegralComplexCast:
1566 case CK_IntegralComplexToFloatingComplex:
John McCall2d637d22011-09-10 06:18:15 +00001567 case CK_ARCProduceObject:
1568 case CK_ARCConsumeObject:
1569 case CK_ARCReclaimReturnedObject:
1570 case CK_ARCExtendBlockObject:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001571 case CK_ZeroToOCLEvent:
John McCall9320b872011-09-09 05:25:32 +00001572 assert(!getType()->isBooleanType() && "unheralded conversion to bool");
1573 goto CheckNoBasePath;
1574
1575 case CK_Dependent:
1576 case CK_LValueToRValue:
John McCall9320b872011-09-09 05:25:32 +00001577 case CK_NoOp:
David Chisnallfa35df62012-01-16 17:27:18 +00001578 case CK_AtomicToNonAtomic:
1579 case CK_NonAtomicToAtomic:
John McCall9320b872011-09-09 05:25:32 +00001580 case CK_PointerToBoolean:
1581 case CK_IntegralToBoolean:
1582 case CK_FloatingToBoolean:
1583 case CK_MemberPointerToBoolean:
1584 case CK_FloatingComplexToBoolean:
1585 case CK_IntegralComplexToBoolean:
1586 case CK_LValueBitCast: // -> bool&
1587 case CK_UserDefinedConversion: // operator bool()
Eli Friedman34866c72012-08-31 00:14:07 +00001588 case CK_BuiltinFnToFnPtr:
John McCall9320b872011-09-09 05:25:32 +00001589 CheckNoBasePath:
1590 assert(path_empty() && "Cast kind should not have a base path!");
1591 break;
1592 }
Alp Tokerc1086762013-12-07 13:51:35 +00001593 return true;
John McCall9320b872011-09-09 05:25:32 +00001594}
1595
Anders Carlsson496335e2009-09-03 00:59:21 +00001596const char *CastExpr::getCastKindName() const {
1597 switch (getCastKind()) {
Etienne Bergeron5356d962016-05-12 20:58:56 +00001598#define CAST_OPERATION(Name) case CK_##Name: return #Name;
1599#include "clang/AST/OperationKinds.def"
Anders Carlsson496335e2009-09-03 00:59:21 +00001600 }
John McCallc5e62b42010-11-13 09:02:35 +00001601 llvm_unreachable("Unhandled cast kind!");
Anders Carlsson496335e2009-09-03 00:59:21 +00001602}
1603
Douglas Gregord196a582009-12-14 19:27:10 +00001604Expr *CastExpr::getSubExprAsWritten() {
Craig Topper36250ad2014-05-12 05:36:57 +00001605 Expr *SubExpr = nullptr;
Douglas Gregord196a582009-12-14 19:27:10 +00001606 CastExpr *E = this;
1607 do {
1608 SubExpr = E->getSubExpr();
Douglas Gregorfe314812011-06-21 17:03:29 +00001609
1610 // Skip through reference binding to temporary.
1611 if (MaterializeTemporaryExpr *Materialize
1612 = dyn_cast<MaterializeTemporaryExpr>(SubExpr))
1613 SubExpr = Materialize->GetTemporaryExpr();
1614
Douglas Gregord196a582009-12-14 19:27:10 +00001615 // Skip any temporary bindings; they're implicit.
1616 if (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(SubExpr))
1617 SubExpr = Binder->getSubExpr();
Alexis Hunta8136cc2010-05-05 15:23:54 +00001618
Douglas Gregord196a582009-12-14 19:27:10 +00001619 // Conversions by constructor and conversion functions have a
1620 // subexpression describing the call; strip it off.
John McCalle3027922010-08-25 11:45:40 +00001621 if (E->getCastKind() == CK_ConstructorConversion)
Douglas Gregord196a582009-12-14 19:27:10 +00001622 SubExpr = cast<CXXConstructExpr>(SubExpr)->getArg(0);
Manman Ren8abc2e52016-02-02 22:23:03 +00001623 else if (E->getCastKind() == CK_UserDefinedConversion) {
1624 assert((isa<CXXMemberCallExpr>(SubExpr) ||
1625 isa<BlockExpr>(SubExpr)) &&
1626 "Unexpected SubExpr for CK_UserDefinedConversion.");
1627 if (isa<CXXMemberCallExpr>(SubExpr))
1628 SubExpr = cast<CXXMemberCallExpr>(SubExpr)->getImplicitObjectArgument();
1629 }
Alexis Hunta8136cc2010-05-05 15:23:54 +00001630
Douglas Gregord196a582009-12-14 19:27:10 +00001631 // If the subexpression we're left with is an implicit cast, look
1632 // through that, too.
Alexis Hunta8136cc2010-05-05 15:23:54 +00001633 } while ((E = dyn_cast<ImplicitCastExpr>(SubExpr)));
1634
Douglas Gregord196a582009-12-14 19:27:10 +00001635 return SubExpr;
1636}
1637
John McCallcf142162010-08-07 06:22:56 +00001638CXXBaseSpecifier **CastExpr::path_buffer() {
1639 switch (getStmtClass()) {
1640#define ABSTRACT_STMT(x)
James Y Knight1d75c5e2015-12-30 02:27:28 +00001641#define CASTEXPR(Type, Base) \
1642 case Stmt::Type##Class: \
1643 return static_cast<Type *>(this)->getTrailingObjects<CXXBaseSpecifier *>();
John McCallcf142162010-08-07 06:22:56 +00001644#define STMT(Type, Base)
1645#include "clang/AST/StmtNodes.inc"
1646 default:
1647 llvm_unreachable("non-cast expressions not possible here");
John McCallcf142162010-08-07 06:22:56 +00001648 }
1649}
1650
Craig Topper37932912013-08-18 10:09:15 +00001651ImplicitCastExpr *ImplicitCastExpr::Create(const ASTContext &C, QualType T,
John McCallcf142162010-08-07 06:22:56 +00001652 CastKind Kind, Expr *Operand,
1653 const CXXCastPath *BasePath,
John McCall2536c6d2010-08-25 10:28:54 +00001654 ExprValueKind VK) {
John McCallcf142162010-08-07 06:22:56 +00001655 unsigned PathSize = (BasePath ? BasePath->size() : 0);
James Y Knight1d75c5e2015-12-30 02:27:28 +00001656 void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
John McCallcf142162010-08-07 06:22:56 +00001657 ImplicitCastExpr *E =
John McCall2536c6d2010-08-25 10:28:54 +00001658 new (Buffer) ImplicitCastExpr(T, Kind, Operand, PathSize, VK);
James Y Knight1d75c5e2015-12-30 02:27:28 +00001659 if (PathSize)
1660 std::uninitialized_copy_n(BasePath->data(), BasePath->size(),
1661 E->getTrailingObjects<CXXBaseSpecifier *>());
John McCallcf142162010-08-07 06:22:56 +00001662 return E;
1663}
1664
Craig Topper37932912013-08-18 10:09:15 +00001665ImplicitCastExpr *ImplicitCastExpr::CreateEmpty(const ASTContext &C,
John McCallcf142162010-08-07 06:22:56 +00001666 unsigned PathSize) {
James Y Knight1d75c5e2015-12-30 02:27:28 +00001667 void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
John McCallcf142162010-08-07 06:22:56 +00001668 return new (Buffer) ImplicitCastExpr(EmptyShell(), PathSize);
1669}
1670
1671
Craig Topper37932912013-08-18 10:09:15 +00001672CStyleCastExpr *CStyleCastExpr::Create(const ASTContext &C, QualType T,
John McCall7decc9e2010-11-18 06:31:45 +00001673 ExprValueKind VK, CastKind K, Expr *Op,
John McCallcf142162010-08-07 06:22:56 +00001674 const CXXCastPath *BasePath,
1675 TypeSourceInfo *WrittenTy,
1676 SourceLocation L, SourceLocation R) {
1677 unsigned PathSize = (BasePath ? BasePath->size() : 0);
James Y Knight1d75c5e2015-12-30 02:27:28 +00001678 void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
John McCallcf142162010-08-07 06:22:56 +00001679 CStyleCastExpr *E =
John McCall7decc9e2010-11-18 06:31:45 +00001680 new (Buffer) CStyleCastExpr(T, VK, K, Op, PathSize, WrittenTy, L, R);
James Y Knight1d75c5e2015-12-30 02:27:28 +00001681 if (PathSize)
1682 std::uninitialized_copy_n(BasePath->data(), BasePath->size(),
1683 E->getTrailingObjects<CXXBaseSpecifier *>());
John McCallcf142162010-08-07 06:22:56 +00001684 return E;
1685}
1686
Craig Topper37932912013-08-18 10:09:15 +00001687CStyleCastExpr *CStyleCastExpr::CreateEmpty(const ASTContext &C,
1688 unsigned PathSize) {
James Y Knight1d75c5e2015-12-30 02:27:28 +00001689 void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
John McCallcf142162010-08-07 06:22:56 +00001690 return new (Buffer) CStyleCastExpr(EmptyShell(), PathSize);
1691}
1692
Chris Lattner1b926492006-08-23 06:42:10 +00001693/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1694/// corresponds to, e.g. "<<=".
David Blaikie1d202a62012-10-08 01:11:04 +00001695StringRef BinaryOperator::getOpcodeStr(Opcode Op) {
Chris Lattner1b926492006-08-23 06:42:10 +00001696 switch (Op) {
Etienne Bergeron5356d962016-05-12 20:58:56 +00001697#define BINARY_OPERATION(Name, Spelling) case BO_##Name: return Spelling;
1698#include "clang/AST/OperationKinds.def"
Chris Lattner1b926492006-08-23 06:42:10 +00001699 }
David Blaikiee4d798f2012-01-20 21:50:17 +00001700 llvm_unreachable("Invalid OpCode!");
Chris Lattner1b926492006-08-23 06:42:10 +00001701}
Steve Naroff47500512007-04-19 23:00:49 +00001702
John McCalle3027922010-08-25 11:45:40 +00001703BinaryOperatorKind
Douglas Gregor1baf54e2009-03-13 18:40:31 +00001704BinaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO) {
1705 switch (OO) {
David Blaikie83d382b2011-09-23 05:06:16 +00001706 default: llvm_unreachable("Not an overloadable binary operator");
John McCalle3027922010-08-25 11:45:40 +00001707 case OO_Plus: return BO_Add;
1708 case OO_Minus: return BO_Sub;
1709 case OO_Star: return BO_Mul;
1710 case OO_Slash: return BO_Div;
1711 case OO_Percent: return BO_Rem;
1712 case OO_Caret: return BO_Xor;
1713 case OO_Amp: return BO_And;
1714 case OO_Pipe: return BO_Or;
1715 case OO_Equal: return BO_Assign;
1716 case OO_Less: return BO_LT;
1717 case OO_Greater: return BO_GT;
1718 case OO_PlusEqual: return BO_AddAssign;
1719 case OO_MinusEqual: return BO_SubAssign;
1720 case OO_StarEqual: return BO_MulAssign;
1721 case OO_SlashEqual: return BO_DivAssign;
1722 case OO_PercentEqual: return BO_RemAssign;
1723 case OO_CaretEqual: return BO_XorAssign;
1724 case OO_AmpEqual: return BO_AndAssign;
1725 case OO_PipeEqual: return BO_OrAssign;
1726 case OO_LessLess: return BO_Shl;
1727 case OO_GreaterGreater: return BO_Shr;
1728 case OO_LessLessEqual: return BO_ShlAssign;
1729 case OO_GreaterGreaterEqual: return BO_ShrAssign;
1730 case OO_EqualEqual: return BO_EQ;
1731 case OO_ExclaimEqual: return BO_NE;
1732 case OO_LessEqual: return BO_LE;
1733 case OO_GreaterEqual: return BO_GE;
1734 case OO_AmpAmp: return BO_LAnd;
1735 case OO_PipePipe: return BO_LOr;
1736 case OO_Comma: return BO_Comma;
1737 case OO_ArrowStar: return BO_PtrMemI;
Douglas Gregor1baf54e2009-03-13 18:40:31 +00001738 }
1739}
1740
1741OverloadedOperatorKind BinaryOperator::getOverloadedOperator(Opcode Opc) {
1742 static const OverloadedOperatorKind OverOps[] = {
1743 /* .* Cannot be overloaded */OO_None, OO_ArrowStar,
1744 OO_Star, OO_Slash, OO_Percent,
1745 OO_Plus, OO_Minus,
1746 OO_LessLess, OO_GreaterGreater,
1747 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
1748 OO_EqualEqual, OO_ExclaimEqual,
1749 OO_Amp,
1750 OO_Caret,
1751 OO_Pipe,
1752 OO_AmpAmp,
1753 OO_PipePipe,
1754 OO_Equal, OO_StarEqual,
1755 OO_SlashEqual, OO_PercentEqual,
1756 OO_PlusEqual, OO_MinusEqual,
1757 OO_LessLessEqual, OO_GreaterGreaterEqual,
1758 OO_AmpEqual, OO_CaretEqual,
1759 OO_PipeEqual,
1760 OO_Comma
1761 };
1762 return OverOps[Opc];
1763}
1764
Craig Topper37932912013-08-18 10:09:15 +00001765InitListExpr::InitListExpr(const ASTContext &C, SourceLocation lbraceloc,
Benjamin Kramerc215e762012-08-24 11:54:20 +00001766 ArrayRef<Expr*> initExprs, SourceLocation rbraceloc)
Douglas Gregora6e053e2010-12-15 01:34:56 +00001767 : Expr(InitListExprClass, QualType(), VK_RValue, OK_Ordinary, false, false,
Douglas Gregor678d76c2011-07-01 01:22:09 +00001768 false, false),
Benjamin Kramerc215e762012-08-24 11:54:20 +00001769 InitExprs(C, initExprs.size()),
Craig Topper36250ad2014-05-12 05:36:57 +00001770 LBraceLoc(lbraceloc), RBraceLoc(rbraceloc), AltForm(nullptr, true)
Sebastian Redlc83ed822012-02-17 08:42:25 +00001771{
1772 sawArrayRangeDesignator(false);
Benjamin Kramerc215e762012-08-24 11:54:20 +00001773 for (unsigned I = 0; I != initExprs.size(); ++I) {
Ted Kremenek013041e2010-02-19 01:50:18 +00001774 if (initExprs[I]->isTypeDependent())
John McCall925b16622010-10-26 08:39:16 +00001775 ExprBits.TypeDependent = true;
Ted Kremenek013041e2010-02-19 01:50:18 +00001776 if (initExprs[I]->isValueDependent())
John McCall925b16622010-10-26 08:39:16 +00001777 ExprBits.ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +00001778 if (initExprs[I]->isInstantiationDependent())
1779 ExprBits.InstantiationDependent = true;
Douglas Gregora6e053e2010-12-15 01:34:56 +00001780 if (initExprs[I]->containsUnexpandedParameterPack())
1781 ExprBits.ContainsUnexpandedParameterPack = true;
Douglas Gregordeebf6e2009-11-19 23:25:22 +00001782 }
Alexis Hunta8136cc2010-05-05 15:23:54 +00001783
Benjamin Kramerc215e762012-08-24 11:54:20 +00001784 InitExprs.insert(C, InitExprs.end(), initExprs.begin(), initExprs.end());
Anders Carlsson4692db02007-08-31 04:56:16 +00001785}
Chris Lattner1ec5f562007-06-27 05:38:08 +00001786
Craig Topper37932912013-08-18 10:09:15 +00001787void InitListExpr::reserveInits(const ASTContext &C, unsigned NumInits) {
Ted Kremenek013041e2010-02-19 01:50:18 +00001788 if (NumInits > InitExprs.size())
Ted Kremenekac034612010-04-13 23:39:13 +00001789 InitExprs.reserve(C, NumInits);
Douglas Gregor6d00c992009-03-20 23:58:33 +00001790}
1791
Craig Topper37932912013-08-18 10:09:15 +00001792void InitListExpr::resizeInits(const ASTContext &C, unsigned NumInits) {
Craig Topper36250ad2014-05-12 05:36:57 +00001793 InitExprs.resize(C, NumInits, nullptr);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001794}
1795
Craig Topper37932912013-08-18 10:09:15 +00001796Expr *InitListExpr::updateInit(const ASTContext &C, unsigned Init, Expr *expr) {
Ted Kremenek013041e2010-02-19 01:50:18 +00001797 if (Init >= InitExprs.size()) {
Craig Topper36250ad2014-05-12 05:36:57 +00001798 InitExprs.insert(C, InitExprs.end(), Init - InitExprs.size() + 1, nullptr);
Richard Smithc275da62013-12-06 01:27:24 +00001799 setInit(Init, expr);
Craig Topper36250ad2014-05-12 05:36:57 +00001800 return nullptr;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001801 }
Mike Stump11289f42009-09-09 15:08:12 +00001802
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001803 Expr *Result = cast_or_null<Expr>(InitExprs[Init]);
Richard Smithc275da62013-12-06 01:27:24 +00001804 setInit(Init, expr);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001805 return Result;
1806}
1807
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +00001808void InitListExpr::setArrayFiller(Expr *filler) {
Argyrios Kyrtzidisd4590a5d2011-10-21 23:02:22 +00001809 assert(!hasArrayFiller() && "Filler already set!");
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +00001810 ArrayFillerOrUnionFieldInit = filler;
1811 // Fill out any "holes" in the array due to designated initializers.
1812 Expr **inits = getInits();
1813 for (unsigned i = 0, e = getNumInits(); i != e; ++i)
Craig Topper36250ad2014-05-12 05:36:57 +00001814 if (inits[i] == nullptr)
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +00001815 inits[i] = filler;
1816}
1817
Richard Smith9ec1e482012-04-15 02:50:59 +00001818bool InitListExpr::isStringLiteralInit() const {
1819 if (getNumInits() != 1)
1820 return false;
Eli Friedmancf4ab082012-08-20 20:55:45 +00001821 const ArrayType *AT = getType()->getAsArrayTypeUnsafe();
1822 if (!AT || !AT->getElementType()->isIntegerType())
Richard Smith9ec1e482012-04-15 02:50:59 +00001823 return false;
Ted Kremenek256bd962014-01-19 06:31:34 +00001824 // It is possible for getInit() to return null.
1825 const Expr *Init = getInit(0);
1826 if (!Init)
1827 return false;
1828 Init = Init->IgnoreParens();
Richard Smith9ec1e482012-04-15 02:50:59 +00001829 return isa<StringLiteral>(Init) || isa<ObjCEncodeExpr>(Init);
1830}
1831
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00001832SourceLocation InitListExpr::getLocStart() const {
Abramo Bagnara8d16bd42012-11-08 18:41:43 +00001833 if (InitListExpr *SyntacticForm = getSyntacticForm())
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00001834 return SyntacticForm->getLocStart();
1835 SourceLocation Beg = LBraceLoc;
Ted Kremenek16e6026f2010-11-09 02:11:40 +00001836 if (Beg.isInvalid()) {
1837 // Find the first non-null initializer.
1838 for (InitExprsTy::const_iterator I = InitExprs.begin(),
1839 E = InitExprs.end();
1840 I != E; ++I) {
1841 if (Stmt *S = *I) {
1842 Beg = S->getLocStart();
1843 break;
1844 }
1845 }
1846 }
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00001847 return Beg;
1848}
1849
1850SourceLocation InitListExpr::getLocEnd() const {
1851 if (InitListExpr *SyntacticForm = getSyntacticForm())
1852 return SyntacticForm->getLocEnd();
1853 SourceLocation End = RBraceLoc;
Ted Kremenek16e6026f2010-11-09 02:11:40 +00001854 if (End.isInvalid()) {
1855 // Find the first non-null initializer from the end.
1856 for (InitExprsTy::const_reverse_iterator I = InitExprs.rbegin(),
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00001857 E = InitExprs.rend();
1858 I != E; ++I) {
Ted Kremenek16e6026f2010-11-09 02:11:40 +00001859 if (Stmt *S = *I) {
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00001860 End = S->getLocEnd();
Ted Kremenek16e6026f2010-11-09 02:11:40 +00001861 break;
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00001862 }
Ted Kremenek16e6026f2010-11-09 02:11:40 +00001863 }
1864 }
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00001865 return End;
Ted Kremenek16e6026f2010-11-09 02:11:40 +00001866}
1867
Steve Naroff991e99d2008-09-04 15:31:07 +00001868/// getFunctionType - Return the underlying function type for this block.
Steve Naroffc540d662008-09-03 18:15:37 +00001869///
John McCallc833dea2012-02-17 03:32:35 +00001870const FunctionProtoType *BlockExpr::getFunctionType() const {
1871 // The block pointer is never sugared, but the function type might be.
1872 return cast<BlockPointerType>(getType())
1873 ->getPointeeType()->castAs<FunctionProtoType>();
Steve Naroffc540d662008-09-03 18:15:37 +00001874}
1875
Mike Stump11289f42009-09-09 15:08:12 +00001876SourceLocation BlockExpr::getCaretLocation() const {
1877 return TheBlock->getCaretLocation();
Steve Naroff415d3d52008-10-08 17:01:13 +00001878}
Mike Stump11289f42009-09-09 15:08:12 +00001879const Stmt *BlockExpr::getBody() const {
Douglas Gregore3dcb2d2009-04-18 00:02:19 +00001880 return TheBlock->getBody();
1881}
Mike Stump11289f42009-09-09 15:08:12 +00001882Stmt *BlockExpr::getBody() {
1883 return TheBlock->getBody();
Douglas Gregore3dcb2d2009-04-18 00:02:19 +00001884}
Steve Naroff415d3d52008-10-08 17:01:13 +00001885
1886
Chris Lattner1ec5f562007-06-27 05:38:08 +00001887//===----------------------------------------------------------------------===//
1888// Generic Expression Routines
1889//===----------------------------------------------------------------------===//
1890
Chris Lattner237f2752009-02-14 07:37:35 +00001891/// isUnusedResultAWarning - Return true if this immediate expression should
1892/// be warned about if the result is unused. If so, fill in Loc and Ranges
1893/// with location to warn on and the source range[s] to report with the
1894/// warning.
Eli Friedmanc11535c2012-05-24 00:47:05 +00001895bool Expr::isUnusedResultAWarning(const Expr *&WarnE, SourceLocation &Loc,
1896 SourceRange &R1, SourceRange &R2,
1897 ASTContext &Ctx) const {
Anders Carlsson789e2cc2009-05-15 23:10:19 +00001898 // Don't warn if the expr is type dependent. The type could end up
1899 // instantiating to void.
1900 if (isTypeDependent())
1901 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001902
Chris Lattner1ec5f562007-06-27 05:38:08 +00001903 switch (getStmtClass()) {
1904 default:
John McCallc493a732010-03-12 07:11:26 +00001905 if (getType()->isVoidType())
1906 return false;
Eli Friedmanc11535c2012-05-24 00:47:05 +00001907 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00001908 Loc = getExprLoc();
1909 R1 = getSourceRange();
1910 return true;
Chris Lattner1ec5f562007-06-27 05:38:08 +00001911 case ParenExprClass:
Chris Lattner237f2752009-02-14 07:37:35 +00001912 return cast<ParenExpr>(this)->getSubExpr()->
Eli Friedmanc11535c2012-05-24 00:47:05 +00001913 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00001914 case GenericSelectionExprClass:
1915 return cast<GenericSelectionExpr>(this)->getResultExpr()->
Eli Friedmanc11535c2012-05-24 00:47:05 +00001916 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Eli Friedman75807f22013-07-20 00:40:58 +00001917 case ChooseExprClass:
1918 return cast<ChooseExpr>(this)->getChosenSubExpr()->
1919 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Chris Lattner1ec5f562007-06-27 05:38:08 +00001920 case UnaryOperatorClass: {
1921 const UnaryOperator *UO = cast<UnaryOperator>(this);
Mike Stump11289f42009-09-09 15:08:12 +00001922
Chris Lattner1ec5f562007-06-27 05:38:08 +00001923 switch (UO->getOpcode()) {
Eli Friedmanc11535c2012-05-24 00:47:05 +00001924 case UO_Plus:
1925 case UO_Minus:
1926 case UO_AddrOf:
1927 case UO_Not:
1928 case UO_LNot:
1929 case UO_Deref:
1930 break;
Richard Smith9f690bd2015-10-27 06:02:45 +00001931 case UO_Coawait:
1932 // This is just the 'operator co_await' call inside the guts of a
1933 // dependent co_await call.
John McCalle3027922010-08-25 11:45:40 +00001934 case UO_PostInc:
1935 case UO_PostDec:
1936 case UO_PreInc:
1937 case UO_PreDec: // ++/--
Chris Lattner237f2752009-02-14 07:37:35 +00001938 return false; // Not a warning.
John McCalle3027922010-08-25 11:45:40 +00001939 case UO_Real:
1940 case UO_Imag:
Chris Lattnera44d1162007-06-27 05:58:59 +00001941 // accessing a piece of a volatile complex is a side-effect.
Mike Stump53f9ded2009-11-03 23:25:48 +00001942 if (Ctx.getCanonicalType(UO->getSubExpr()->getType())
1943 .isVolatileQualified())
Chris Lattner237f2752009-02-14 07:37:35 +00001944 return false;
1945 break;
John McCalle3027922010-08-25 11:45:40 +00001946 case UO_Extension:
Eli Friedmanc11535c2012-05-24 00:47:05 +00001947 return UO->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Chris Lattner1ec5f562007-06-27 05:38:08 +00001948 }
Eli Friedmanc11535c2012-05-24 00:47:05 +00001949 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00001950 Loc = UO->getOperatorLoc();
1951 R1 = UO->getSubExpr()->getSourceRange();
1952 return true;
Chris Lattner1ec5f562007-06-27 05:38:08 +00001953 }
Chris Lattnerae7a8342007-12-01 06:07:34 +00001954 case BinaryOperatorClass: {
Chris Lattner237f2752009-02-14 07:37:35 +00001955 const BinaryOperator *BO = cast<BinaryOperator>(this);
Ted Kremenek43a9c962010-04-07 18:49:21 +00001956 switch (BO->getOpcode()) {
1957 default:
1958 break;
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00001959 // Consider the RHS of comma for side effects. LHS was checked by
1960 // Sema::CheckCommaOperands.
John McCalle3027922010-08-25 11:45:40 +00001961 case BO_Comma:
Ted Kremenek43a9c962010-04-07 18:49:21 +00001962 // ((foo = <blah>), 0) is an idiom for hiding the result (and
1963 // lvalue-ness) of an assignment written in a macro.
1964 if (IntegerLiteral *IE =
1965 dyn_cast<IntegerLiteral>(BO->getRHS()->IgnoreParens()))
1966 if (IE->getValue() == 0)
1967 return false;
Eli Friedmanc11535c2012-05-24 00:47:05 +00001968 return BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00001969 // Consider '||', '&&' to have side effects if the LHS or RHS does.
John McCalle3027922010-08-25 11:45:40 +00001970 case BO_LAnd:
1971 case BO_LOr:
Eli Friedmanc11535c2012-05-24 00:47:05 +00001972 if (!BO->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx) ||
1973 !BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx))
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00001974 return false;
1975 break;
John McCall1e3715a2010-02-16 04:10:53 +00001976 }
Chris Lattner237f2752009-02-14 07:37:35 +00001977 if (BO->isAssignmentOp())
1978 return false;
Eli Friedmanc11535c2012-05-24 00:47:05 +00001979 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00001980 Loc = BO->getOperatorLoc();
1981 R1 = BO->getLHS()->getSourceRange();
1982 R2 = BO->getRHS()->getSourceRange();
1983 return true;
Chris Lattnerae7a8342007-12-01 06:07:34 +00001984 }
Chris Lattner86928112007-08-25 02:00:02 +00001985 case CompoundAssignOperatorClass:
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00001986 case VAArgExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001987 case AtomicExprClass:
Chris Lattner237f2752009-02-14 07:37:35 +00001988 return false;
Chris Lattner1ec5f562007-06-27 05:38:08 +00001989
Fariborz Jahanian9fac54d2007-12-01 19:58:28 +00001990 case ConditionalOperatorClass: {
Ted Kremeneke96dad92011-03-01 20:34:48 +00001991 // If only one of the LHS or RHS is a warning, the operator might
1992 // be being used for control flow. Only warn if both the LHS and
1993 // RHS are warnings.
Fariborz Jahanian9fac54d2007-12-01 19:58:28 +00001994 const ConditionalOperator *Exp = cast<ConditionalOperator>(this);
Eli Friedmanc11535c2012-05-24 00:47:05 +00001995 if (!Exp->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx))
Ted Kremeneke96dad92011-03-01 20:34:48 +00001996 return false;
1997 if (!Exp->getLHS())
Chris Lattner237f2752009-02-14 07:37:35 +00001998 return true;
Eli Friedmanc11535c2012-05-24 00:47:05 +00001999 return Exp->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Fariborz Jahanian9fac54d2007-12-01 19:58:28 +00002000 }
2001
Chris Lattnera44d1162007-06-27 05:58:59 +00002002 case MemberExprClass:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002003 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002004 Loc = cast<MemberExpr>(this)->getMemberLoc();
2005 R1 = SourceRange(Loc, Loc);
2006 R2 = cast<MemberExpr>(this)->getBase()->getSourceRange();
2007 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002008
Chris Lattner1ec5f562007-06-27 05:38:08 +00002009 case ArraySubscriptExprClass:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002010 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002011 Loc = cast<ArraySubscriptExpr>(this)->getRBracketLoc();
2012 R1 = cast<ArraySubscriptExpr>(this)->getLHS()->getSourceRange();
2013 R2 = cast<ArraySubscriptExpr>(this)->getRHS()->getSourceRange();
2014 return true;
Eli Friedman824f8c12008-05-27 15:24:04 +00002015
Chandler Carruth46339472011-08-17 09:49:44 +00002016 case CXXOperatorCallExprClass: {
Richard Trieu99e1c952014-03-11 03:11:08 +00002017 // Warn about operator ==,!=,<,>,<=, and >= even when user-defined operator
Chandler Carruth46339472011-08-17 09:49:44 +00002018 // overloads as there is no reasonable way to define these such that they
2019 // have non-trivial, desirable side-effects. See the -Wunused-comparison
Richard Trieu99e1c952014-03-11 03:11:08 +00002020 // warning: operators == and != are commonly typo'ed, and so warning on them
Chandler Carruth46339472011-08-17 09:49:44 +00002021 // provides additional value as well. If this list is updated,
2022 // DiagnoseUnusedComparison should be as well.
2023 const CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(this);
Richard Trieu99e1c952014-03-11 03:11:08 +00002024 switch (Op->getOperator()) {
2025 default:
2026 break;
2027 case OO_EqualEqual:
2028 case OO_ExclaimEqual:
2029 case OO_Less:
2030 case OO_Greater:
2031 case OO_GreaterEqual:
2032 case OO_LessEqual:
David Majnemerced8bdf2015-02-25 17:36:15 +00002033 if (Op->getCallReturnType(Ctx)->isReferenceType() ||
2034 Op->getCallReturnType(Ctx)->isVoidType())
Richard Trieu161132b2014-05-14 23:22:10 +00002035 break;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002036 WarnE = this;
Matt Beaumont-Gaydcaacaa2011-09-19 18:51:20 +00002037 Loc = Op->getOperatorLoc();
2038 R1 = Op->getSourceRange();
Chandler Carruth46339472011-08-17 09:49:44 +00002039 return true;
Matt Beaumont-Gaydcaacaa2011-09-19 18:51:20 +00002040 }
Chandler Carruth46339472011-08-17 09:49:44 +00002041
2042 // Fallthrough for generic call handling.
2043 }
Chris Lattner1ec5f562007-06-27 05:38:08 +00002044 case CallExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00002045 case CXXMemberCallExprClass:
2046 case UserDefinedLiteralClass: {
Chris Lattner237f2752009-02-14 07:37:35 +00002047 // If this is a direct call, get the callee.
2048 const CallExpr *CE = cast<CallExpr>(this);
Nuno Lopes518e3702009-12-20 23:11:08 +00002049 if (const Decl *FD = CE->getCalleeDecl()) {
Kaelyn Takata0a2e84c2015-04-09 19:43:04 +00002050 const FunctionDecl *Func = dyn_cast<FunctionDecl>(FD);
2051 bool HasWarnUnusedResultAttr = Func ? Func->hasUnusedResultAttr()
2052 : FD->hasAttr<WarnUnusedResultAttr>();
2053
Chris Lattner237f2752009-02-14 07:37:35 +00002054 // If the callee has attribute pure, const, or warn_unused_result, warn
2055 // about it. void foo() { strlen("bar"); } should warn.
Chris Lattner1a6babf2009-10-13 04:53:48 +00002056 //
2057 // Note: If new cases are added here, DiagnoseUnusedExprResult should be
2058 // updated to match for QoI.
Kaelyn Takata0a2e84c2015-04-09 19:43:04 +00002059 if (HasWarnUnusedResultAttr ||
Aaron Ballman9ead1242013-12-19 02:39:40 +00002060 FD->hasAttr<PureAttr>() || FD->hasAttr<ConstAttr>()) {
Eli Friedmanc11535c2012-05-24 00:47:05 +00002061 WarnE = this;
Chris Lattner1a6babf2009-10-13 04:53:48 +00002062 Loc = CE->getCallee()->getLocStart();
2063 R1 = CE->getCallee()->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002064
Chris Lattner1a6babf2009-10-13 04:53:48 +00002065 if (unsigned NumArgs = CE->getNumArgs())
2066 R2 = SourceRange(CE->getArg(0)->getLocStart(),
2067 CE->getArg(NumArgs-1)->getLocEnd());
2068 return true;
2069 }
Chris Lattner237f2752009-02-14 07:37:35 +00002070 }
2071 return false;
2072 }
Anders Carlsson6aa50392009-11-17 17:11:23 +00002073
Matt Beaumont-Gayabf836c2012-10-23 06:15:26 +00002074 // If we don't know precisely what we're looking at, let's not warn.
2075 case UnresolvedLookupExprClass:
2076 case CXXUnresolvedConstructExprClass:
2077 return false;
2078
Anders Carlsson6aa50392009-11-17 17:11:23 +00002079 case CXXTemporaryObjectExprClass:
Lubos Lunak1f490f32013-07-21 13:15:58 +00002080 case CXXConstructExprClass: {
2081 if (const CXXRecordDecl *Type = getType()->getAsCXXRecordDecl()) {
2082 if (Type->hasAttr<WarnUnusedAttr>()) {
2083 WarnE = this;
2084 Loc = getLocStart();
2085 R1 = getSourceRange();
2086 return true;
2087 }
2088 }
Anders Carlsson6aa50392009-11-17 17:11:23 +00002089 return false;
Lubos Lunak1f490f32013-07-21 13:15:58 +00002090 }
Anders Carlsson6aa50392009-11-17 17:11:23 +00002091
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +00002092 case ObjCMessageExprClass: {
2093 const ObjCMessageExpr *ME = cast<ObjCMessageExpr>(this);
David Blaikiebbafb8a2012-03-11 07:00:24 +00002094 if (Ctx.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00002095 ME->isInstanceMessage() &&
2096 !ME->getType()->isVoidType() &&
Jean-Daniel Dupas06028a52013-07-19 20:25:56 +00002097 ME->getMethodFamily() == OMF_init) {
Eli Friedmanc11535c2012-05-24 00:47:05 +00002098 WarnE = this;
John McCall31168b02011-06-15 23:02:42 +00002099 Loc = getExprLoc();
2100 R1 = ME->getSourceRange();
2101 return true;
2102 }
2103
Fariborz Jahanianac6b4ef2014-07-18 22:59:10 +00002104 if (const ObjCMethodDecl *MD = ME->getMethodDecl())
Fariborz Jahanianb0553e22015-02-16 23:49:44 +00002105 if (MD->hasAttr<WarnUnusedResultAttr>()) {
Fariborz Jahanianac6b4ef2014-07-18 22:59:10 +00002106 WarnE = this;
2107 Loc = getExprLoc();
2108 return true;
2109 }
2110
Chris Lattner237f2752009-02-14 07:37:35 +00002111 return false;
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +00002112 }
Mike Stump11289f42009-09-09 15:08:12 +00002113
John McCallb7bd14f2010-12-02 01:19:52 +00002114 case ObjCPropertyRefExprClass:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002115 WarnE = this;
Chris Lattnerd37f61c2009-08-16 16:51:50 +00002116 Loc = getExprLoc();
2117 R1 = getSourceRange();
Chris Lattnerd8b800a2009-08-16 16:45:18 +00002118 return true;
John McCallb7bd14f2010-12-02 01:19:52 +00002119
John McCallfe96e0b2011-11-06 09:01:30 +00002120 case PseudoObjectExprClass: {
2121 const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this);
2122
2123 // Only complain about things that have the form of a getter.
2124 if (isa<UnaryOperator>(PO->getSyntacticForm()) ||
2125 isa<BinaryOperator>(PO->getSyntacticForm()))
2126 return false;
2127
Eli Friedmanc11535c2012-05-24 00:47:05 +00002128 WarnE = this;
John McCallfe96e0b2011-11-06 09:01:30 +00002129 Loc = getExprLoc();
2130 R1 = getSourceRange();
2131 return true;
2132 }
2133
Chris Lattner944d3062008-07-26 19:51:01 +00002134 case StmtExprClass: {
2135 // Statement exprs don't logically have side effects themselves, but are
2136 // sometimes used in macros in ways that give them a type that is unused.
2137 // For example ({ blah; foo(); }) will end up with a type if foo has a type.
2138 // however, if the result of the stmt expr is dead, we don't want to emit a
2139 // warning.
2140 const CompoundStmt *CS = cast<StmtExpr>(this)->getSubStmt();
Argyrios Kyrtzidis90963412010-09-19 21:21:10 +00002141 if (!CS->body_empty()) {
Chris Lattner944d3062008-07-26 19:51:01 +00002142 if (const Expr *E = dyn_cast<Expr>(CS->body_back()))
Eli Friedmanc11535c2012-05-24 00:47:05 +00002143 return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Argyrios Kyrtzidis90963412010-09-19 21:21:10 +00002144 if (const LabelStmt *Label = dyn_cast<LabelStmt>(CS->body_back()))
2145 if (const Expr *E = dyn_cast<Expr>(Label->getSubStmt()))
Eli Friedmanc11535c2012-05-24 00:47:05 +00002146 return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Argyrios Kyrtzidis90963412010-09-19 21:21:10 +00002147 }
Mike Stump11289f42009-09-09 15:08:12 +00002148
John McCallc493a732010-03-12 07:11:26 +00002149 if (getType()->isVoidType())
2150 return false;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002151 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002152 Loc = cast<StmtExpr>(this)->getLParenLoc();
2153 R1 = getSourceRange();
2154 return true;
Chris Lattner944d3062008-07-26 19:51:01 +00002155 }
Eli Friedmanbdd57532012-09-24 23:02:26 +00002156 case CXXFunctionalCastExprClass:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002157 case CStyleCastExprClass: {
Eli Friedmanf92f6452012-05-24 21:05:41 +00002158 // Ignore an explicit cast to void unless the operand is a non-trivial
Eli Friedmanc11535c2012-05-24 00:47:05 +00002159 // volatile lvalue.
Eli Friedmanf92f6452012-05-24 21:05:41 +00002160 const CastExpr *CE = cast<CastExpr>(this);
Eli Friedmanc11535c2012-05-24 00:47:05 +00002161 if (CE->getCastKind() == CK_ToVoid) {
2162 if (CE->getSubExpr()->isGLValue() &&
Eli Friedmanf92f6452012-05-24 21:05:41 +00002163 CE->getSubExpr()->getType().isVolatileQualified()) {
2164 const DeclRefExpr *DRE =
2165 dyn_cast<DeclRefExpr>(CE->getSubExpr()->IgnoreParens());
2166 if (!(DRE && isa<VarDecl>(DRE->getDecl()) &&
2167 cast<VarDecl>(DRE->getDecl())->hasLocalStorage())) {
2168 return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc,
2169 R1, R2, Ctx);
2170 }
2171 }
Chris Lattner2706a552009-07-28 18:25:28 +00002172 return false;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002173 }
Eli Friedmanf92f6452012-05-24 21:05:41 +00002174
Eli Friedmanc11535c2012-05-24 00:47:05 +00002175 // If this is a cast to a constructor conversion, check the operand.
Anders Carlsson6aa50392009-11-17 17:11:23 +00002176 // Otherwise, the result of the cast is unused.
Eli Friedmanc11535c2012-05-24 00:47:05 +00002177 if (CE->getCastKind() == CK_ConstructorConversion)
2178 return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Eli Friedmanf92f6452012-05-24 21:05:41 +00002179
Eli Friedmanc11535c2012-05-24 00:47:05 +00002180 WarnE = this;
Eli Friedmanf92f6452012-05-24 21:05:41 +00002181 if (const CXXFunctionalCastExpr *CXXCE =
2182 dyn_cast<CXXFunctionalCastExpr>(this)) {
Eli Friedman89fe0d52013-08-15 22:02:56 +00002183 Loc = CXXCE->getLocStart();
Eli Friedmanf92f6452012-05-24 21:05:41 +00002184 R1 = CXXCE->getSubExpr()->getSourceRange();
2185 } else {
2186 const CStyleCastExpr *CStyleCE = cast<CStyleCastExpr>(this);
2187 Loc = CStyleCE->getLParenLoc();
2188 R1 = CStyleCE->getSubExpr()->getSourceRange();
2189 }
Chris Lattner237f2752009-02-14 07:37:35 +00002190 return true;
Anders Carlsson6aa50392009-11-17 17:11:23 +00002191 }
Eli Friedmanc11535c2012-05-24 00:47:05 +00002192 case ImplicitCastExprClass: {
2193 const CastExpr *ICE = cast<ImplicitCastExpr>(this);
Eli Friedmanca8da1d2008-05-19 21:24:43 +00002194
Eli Friedmanc11535c2012-05-24 00:47:05 +00002195 // lvalue-to-rvalue conversion on a volatile lvalue is a side-effect.
2196 if (ICE->getCastKind() == CK_LValueToRValue &&
2197 ICE->getSubExpr()->getType().isVolatileQualified())
2198 return false;
2199
2200 return ICE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2201 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002202 case CXXDefaultArgExprClass:
Mike Stump53f9ded2009-11-03 23:25:48 +00002203 return (cast<CXXDefaultArgExpr>(this)
Eli Friedmanc11535c2012-05-24 00:47:05 +00002204 ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
Richard Smith852c9db2013-04-20 22:23:05 +00002205 case CXXDefaultInitExprClass:
2206 return (cast<CXXDefaultInitExpr>(this)
2207 ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
Sebastian Redlbd150f42008-11-21 19:14:01 +00002208
2209 case CXXNewExprClass:
2210 // FIXME: In theory, there might be new expressions that don't have side
2211 // effects (e.g. a placement new with an uninitialized POD).
2212 case CXXDeleteExprClass:
Chris Lattner237f2752009-02-14 07:37:35 +00002213 return false;
Anders Carlssone80ccac2009-08-16 04:11:06 +00002214 case CXXBindTemporaryExprClass:
Mike Stump53f9ded2009-11-03 23:25:48 +00002215 return (cast<CXXBindTemporaryExpr>(this)
Eli Friedmanc11535c2012-05-24 00:47:05 +00002216 ->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
John McCall5d413782010-12-06 08:20:24 +00002217 case ExprWithCleanupsClass:
2218 return (cast<ExprWithCleanups>(this)
Eli Friedmanc11535c2012-05-24 00:47:05 +00002219 ->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
Sebastian Redlbd150f42008-11-21 19:14:01 +00002220 }
Chris Lattner1ec5f562007-06-27 05:38:08 +00002221}
2222
Fariborz Jahanian07735332009-02-22 18:40:18 +00002223/// isOBJCGCCandidate - Check if an expression is objc gc'able.
Fariborz Jahanian063c7722009-09-08 23:38:54 +00002224/// returns true, if it is; false otherwise.
Fariborz Jahanianc6d98002009-06-01 21:29:32 +00002225bool Expr::isOBJCGCCandidate(ASTContext &Ctx) const {
Peter Collingbourne91147592011-04-15 00:35:48 +00002226 const Expr *E = IgnoreParens();
2227 switch (E->getStmtClass()) {
Fariborz Jahanian07735332009-02-22 18:40:18 +00002228 default:
2229 return false;
2230 case ObjCIvarRefExprClass:
2231 return true;
Fariborz Jahanian392124c2009-02-23 18:59:50 +00002232 case Expr::UnaryOperatorClass:
Peter Collingbourne91147592011-04-15 00:35:48 +00002233 return cast<UnaryOperator>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
Fariborz Jahanian07735332009-02-22 18:40:18 +00002234 case ImplicitCastExprClass:
Peter Collingbourne91147592011-04-15 00:35:48 +00002235 return cast<ImplicitCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
Douglas Gregorfe314812011-06-21 17:03:29 +00002236 case MaterializeTemporaryExprClass:
2237 return cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr()
2238 ->isOBJCGCCandidate(Ctx);
Fariborz Jahaniana16904b2009-05-05 23:28:21 +00002239 case CStyleCastExprClass:
Peter Collingbourne91147592011-04-15 00:35:48 +00002240 return cast<CStyleCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002241 case DeclRefExprClass: {
John McCall113bee02012-03-10 09:33:50 +00002242 const Decl *D = cast<DeclRefExpr>(E)->getDecl();
Fariborz Jahanianc367b8f2011-09-23 18:57:30 +00002243
Fariborz Jahanianc6d98002009-06-01 21:29:32 +00002244 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2245 if (VD->hasGlobalStorage())
2246 return true;
2247 QualType T = VD->getType();
Fariborz Jahaniancceedbf2009-09-16 18:09:18 +00002248 // dereferencing to a pointer is always a gc'able candidate,
2249 // unless it is __weak.
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00002250 return T->isPointerType() &&
John McCall8ccfcb52009-09-24 19:53:00 +00002251 (Ctx.getObjCGCAttrKind(T) != Qualifiers::Weak);
Fariborz Jahanianc6d98002009-06-01 21:29:32 +00002252 }
Fariborz Jahanian07735332009-02-22 18:40:18 +00002253 return false;
2254 }
Douglas Gregorf405d7e2009-08-31 23:41:50 +00002255 case MemberExprClass: {
Peter Collingbourne91147592011-04-15 00:35:48 +00002256 const MemberExpr *M = cast<MemberExpr>(E);
Fariborz Jahanianc6d98002009-06-01 21:29:32 +00002257 return M->getBase()->isOBJCGCCandidate(Ctx);
Fariborz Jahanian07735332009-02-22 18:40:18 +00002258 }
2259 case ArraySubscriptExprClass:
Peter Collingbourne91147592011-04-15 00:35:48 +00002260 return cast<ArraySubscriptExpr>(E)->getBase()->isOBJCGCCandidate(Ctx);
Fariborz Jahanian07735332009-02-22 18:40:18 +00002261 }
2262}
Sebastian Redlce354af2010-09-10 20:55:33 +00002263
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +00002264bool Expr::isBoundMemberFunction(ASTContext &Ctx) const {
2265 if (isTypeDependent())
2266 return false;
John McCall086a4642010-11-24 05:12:34 +00002267 return ClassifyLValue(Ctx) == Expr::LV_MemberFunction;
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +00002268}
2269
John McCall0009fcc2011-04-26 20:42:42 +00002270QualType Expr::findBoundMemberType(const Expr *expr) {
John McCalle314e272011-10-18 21:02:43 +00002271 assert(expr->hasPlaceholderType(BuiltinType::BoundMember));
John McCall0009fcc2011-04-26 20:42:42 +00002272
2273 // Bound member expressions are always one of these possibilities:
2274 // x->m x.m x->*y x.*y
2275 // (possibly parenthesized)
2276
2277 expr = expr->IgnoreParens();
2278 if (const MemberExpr *mem = dyn_cast<MemberExpr>(expr)) {
2279 assert(isa<CXXMethodDecl>(mem->getMemberDecl()));
2280 return mem->getMemberDecl()->getType();
2281 }
2282
2283 if (const BinaryOperator *op = dyn_cast<BinaryOperator>(expr)) {
2284 QualType type = op->getRHS()->getType()->castAs<MemberPointerType>()
2285 ->getPointeeType();
2286 assert(type->isFunctionType());
2287 return type;
2288 }
2289
David Majnemerced8bdf2015-02-25 17:36:15 +00002290 assert(isa<UnresolvedMemberExpr>(expr) || isa<CXXPseudoDestructorExpr>(expr));
John McCall0009fcc2011-04-26 20:42:42 +00002291 return QualType();
2292}
2293
Ted Kremenekfff70962008-01-17 16:57:34 +00002294Expr* Expr::IgnoreParens() {
2295 Expr* E = this;
Abramo Bagnara932e3932010-10-15 07:51:18 +00002296 while (true) {
2297 if (ParenExpr* P = dyn_cast<ParenExpr>(E)) {
2298 E = P->getSubExpr();
2299 continue;
2300 }
2301 if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) {
2302 if (P->getOpcode() == UO_Extension) {
2303 E = P->getSubExpr();
2304 continue;
2305 }
2306 }
Peter Collingbourne91147592011-04-15 00:35:48 +00002307 if (GenericSelectionExpr* P = dyn_cast<GenericSelectionExpr>(E)) {
2308 if (!P->isResultDependent()) {
2309 E = P->getResultExpr();
2310 continue;
2311 }
2312 }
Eli Friedman75807f22013-07-20 00:40:58 +00002313 if (ChooseExpr* P = dyn_cast<ChooseExpr>(E)) {
2314 if (!P->isConditionDependent()) {
2315 E = P->getChosenSubExpr();
2316 continue;
2317 }
2318 }
Abramo Bagnara932e3932010-10-15 07:51:18 +00002319 return E;
2320 }
Ted Kremenekfff70962008-01-17 16:57:34 +00002321}
2322
Chris Lattnerf2660962008-02-13 01:02:39 +00002323/// IgnoreParenCasts - Ignore parentheses and casts. Strip off any ParenExpr
2324/// or CastExprs or ImplicitCastExprs, returning their operand.
2325Expr *Expr::IgnoreParenCasts() {
2326 Expr *E = this;
2327 while (true) {
Eli Friedman75807f22013-07-20 00:40:58 +00002328 E = E->IgnoreParens();
Abramo Bagnara932e3932010-10-15 07:51:18 +00002329 if (CastExpr *P = dyn_cast<CastExpr>(E)) {
Chris Lattnerf2660962008-02-13 01:02:39 +00002330 E = P->getSubExpr();
Abramo Bagnara932e3932010-10-15 07:51:18 +00002331 continue;
2332 }
Douglas Gregorfe314812011-06-21 17:03:29 +00002333 if (MaterializeTemporaryExpr *Materialize
2334 = dyn_cast<MaterializeTemporaryExpr>(E)) {
2335 E = Materialize->GetTemporaryExpr();
2336 continue;
2337 }
Douglas Gregor6a40b082011-09-08 17:56:33 +00002338 if (SubstNonTypeTemplateParmExpr *NTTP
2339 = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2340 E = NTTP->getReplacement();
2341 continue;
2342 }
Abramo Bagnara932e3932010-10-15 07:51:18 +00002343 return E;
Chris Lattnerf2660962008-02-13 01:02:39 +00002344 }
2345}
2346
Ted Kremenek6f375e52014-04-16 07:26:09 +00002347Expr *Expr::IgnoreCasts() {
2348 Expr *E = this;
2349 while (true) {
2350 if (CastExpr *P = dyn_cast<CastExpr>(E)) {
2351 E = P->getSubExpr();
2352 continue;
2353 }
2354 if (MaterializeTemporaryExpr *Materialize
2355 = dyn_cast<MaterializeTemporaryExpr>(E)) {
2356 E = Materialize->GetTemporaryExpr();
2357 continue;
2358 }
2359 if (SubstNonTypeTemplateParmExpr *NTTP
2360 = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2361 E = NTTP->getReplacement();
2362 continue;
2363 }
2364 return E;
2365 }
2366}
2367
John McCall5a4ce8b2010-12-04 08:24:19 +00002368/// IgnoreParenLValueCasts - Ignore parentheses and lvalue-to-rvalue
2369/// casts. This is intended purely as a temporary workaround for code
2370/// that hasn't yet been rewritten to do the right thing about those
2371/// casts, and may disappear along with the last internal use.
John McCall34376a62010-12-04 03:47:34 +00002372Expr *Expr::IgnoreParenLValueCasts() {
2373 Expr *E = this;
John McCall5a4ce8b2010-12-04 08:24:19 +00002374 while (true) {
Eli Friedman75807f22013-07-20 00:40:58 +00002375 E = E->IgnoreParens();
2376 if (CastExpr *P = dyn_cast<CastExpr>(E)) {
John McCall34376a62010-12-04 03:47:34 +00002377 if (P->getCastKind() == CK_LValueToRValue) {
2378 E = P->getSubExpr();
2379 continue;
2380 }
Douglas Gregorfe314812011-06-21 17:03:29 +00002381 } else if (MaterializeTemporaryExpr *Materialize
2382 = dyn_cast<MaterializeTemporaryExpr>(E)) {
2383 E = Materialize->GetTemporaryExpr();
2384 continue;
Douglas Gregor6a40b082011-09-08 17:56:33 +00002385 } else if (SubstNonTypeTemplateParmExpr *NTTP
2386 = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2387 E = NTTP->getReplacement();
2388 continue;
John McCall34376a62010-12-04 03:47:34 +00002389 }
2390 break;
2391 }
2392 return E;
2393}
Rafael Espindolaecbe2e92012-06-28 01:56:38 +00002394
2395Expr *Expr::ignoreParenBaseCasts() {
2396 Expr *E = this;
2397 while (true) {
Eli Friedman75807f22013-07-20 00:40:58 +00002398 E = E->IgnoreParens();
Rafael Espindolaecbe2e92012-06-28 01:56:38 +00002399 if (CastExpr *CE = dyn_cast<CastExpr>(E)) {
2400 if (CE->getCastKind() == CK_DerivedToBase ||
2401 CE->getCastKind() == CK_UncheckedDerivedToBase ||
2402 CE->getCastKind() == CK_NoOp) {
2403 E = CE->getSubExpr();
2404 continue;
2405 }
2406 }
2407
2408 return E;
2409 }
2410}
2411
John McCalleebc8322010-05-05 22:59:52 +00002412Expr *Expr::IgnoreParenImpCasts() {
2413 Expr *E = this;
2414 while (true) {
Eli Friedman75807f22013-07-20 00:40:58 +00002415 E = E->IgnoreParens();
Abramo Bagnara932e3932010-10-15 07:51:18 +00002416 if (ImplicitCastExpr *P = dyn_cast<ImplicitCastExpr>(E)) {
John McCalleebc8322010-05-05 22:59:52 +00002417 E = P->getSubExpr();
Abramo Bagnara932e3932010-10-15 07:51:18 +00002418 continue;
2419 }
Douglas Gregorfe314812011-06-21 17:03:29 +00002420 if (MaterializeTemporaryExpr *Materialize
2421 = dyn_cast<MaterializeTemporaryExpr>(E)) {
2422 E = Materialize->GetTemporaryExpr();
2423 continue;
2424 }
Douglas Gregor6a40b082011-09-08 17:56:33 +00002425 if (SubstNonTypeTemplateParmExpr *NTTP
2426 = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2427 E = NTTP->getReplacement();
2428 continue;
2429 }
Abramo Bagnara932e3932010-10-15 07:51:18 +00002430 return E;
John McCalleebc8322010-05-05 22:59:52 +00002431 }
2432}
2433
Hans Wennborgde2e67e2011-06-09 17:06:51 +00002434Expr *Expr::IgnoreConversionOperator() {
2435 if (CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(this)) {
Chandler Carruth4352b0b2011-06-21 17:22:09 +00002436 if (MCE->getMethodDecl() && isa<CXXConversionDecl>(MCE->getMethodDecl()))
Hans Wennborgde2e67e2011-06-09 17:06:51 +00002437 return MCE->getImplicitObjectArgument();
2438 }
2439 return this;
2440}
2441
Chris Lattneref26c772009-03-13 17:28:01 +00002442/// IgnoreParenNoopCasts - Ignore parentheses and casts that do not change the
2443/// value (including ptr->int casts of the same size). Strip off any
2444/// ParenExpr or CastExprs, returning their operand.
2445Expr *Expr::IgnoreParenNoopCasts(ASTContext &Ctx) {
2446 Expr *E = this;
2447 while (true) {
Eli Friedman75807f22013-07-20 00:40:58 +00002448 E = E->IgnoreParens();
Mike Stump11289f42009-09-09 15:08:12 +00002449
Chris Lattneref26c772009-03-13 17:28:01 +00002450 if (CastExpr *P = dyn_cast<CastExpr>(E)) {
2451 // We ignore integer <-> casts that are of the same width, ptr<->ptr and
Douglas Gregorb90df602010-06-16 00:17:44 +00002452 // ptr<->int casts of the same width. We also ignore all identity casts.
Chris Lattneref26c772009-03-13 17:28:01 +00002453 Expr *SE = P->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002454
Chris Lattneref26c772009-03-13 17:28:01 +00002455 if (Ctx.hasSameUnqualifiedType(E->getType(), SE->getType())) {
2456 E = SE;
2457 continue;
2458 }
Mike Stump11289f42009-09-09 15:08:12 +00002459
Abramo Bagnara932e3932010-10-15 07:51:18 +00002460 if ((E->getType()->isPointerType() ||
Douglas Gregor6972a622010-06-16 00:35:25 +00002461 E->getType()->isIntegralType(Ctx)) &&
Abramo Bagnara932e3932010-10-15 07:51:18 +00002462 (SE->getType()->isPointerType() ||
Douglas Gregor6972a622010-06-16 00:35:25 +00002463 SE->getType()->isIntegralType(Ctx)) &&
Chris Lattneref26c772009-03-13 17:28:01 +00002464 Ctx.getTypeSize(E->getType()) == Ctx.getTypeSize(SE->getType())) {
2465 E = SE;
2466 continue;
2467 }
2468 }
Mike Stump11289f42009-09-09 15:08:12 +00002469
Douglas Gregor6a40b082011-09-08 17:56:33 +00002470 if (SubstNonTypeTemplateParmExpr *NTTP
2471 = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2472 E = NTTP->getReplacement();
2473 continue;
2474 }
2475
Chris Lattneref26c772009-03-13 17:28:01 +00002476 return E;
2477 }
2478}
2479
Douglas Gregord196a582009-12-14 19:27:10 +00002480bool Expr::isDefaultArgument() const {
2481 const Expr *E = this;
Douglas Gregorfe314812011-06-21 17:03:29 +00002482 if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
2483 E = M->GetTemporaryExpr();
2484
Douglas Gregord196a582009-12-14 19:27:10 +00002485 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
2486 E = ICE->getSubExprAsWritten();
Alexis Hunta8136cc2010-05-05 15:23:54 +00002487
Douglas Gregord196a582009-12-14 19:27:10 +00002488 return isa<CXXDefaultArgExpr>(E);
2489}
Chris Lattneref26c772009-03-13 17:28:01 +00002490
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002491/// \brief Skip over any no-op casts and any temporary-binding
2492/// expressions.
Anders Carlsson66bbf502010-11-28 16:40:49 +00002493static const Expr *skipTemporaryBindingsNoOpCastsAndParens(const Expr *E) {
Douglas Gregorfe314812011-06-21 17:03:29 +00002494 if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
2495 E = M->GetTemporaryExpr();
2496
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002497 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCalle3027922010-08-25 11:45:40 +00002498 if (ICE->getCastKind() == CK_NoOp)
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002499 E = ICE->getSubExpr();
2500 else
2501 break;
2502 }
2503
2504 while (const CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
2505 E = BE->getSubExpr();
2506
2507 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCalle3027922010-08-25 11:45:40 +00002508 if (ICE->getCastKind() == CK_NoOp)
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002509 E = ICE->getSubExpr();
2510 else
2511 break;
2512 }
Anders Carlsson66bbf502010-11-28 16:40:49 +00002513
2514 return E->IgnoreParens();
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002515}
2516
John McCall7a626f62010-09-15 10:14:12 +00002517/// isTemporaryObject - Determines if this expression produces a
2518/// temporary of the given class type.
2519bool Expr::isTemporaryObject(ASTContext &C, const CXXRecordDecl *TempTy) const {
2520 if (!C.hasSameUnqualifiedType(getType(), C.getTypeDeclType(TempTy)))
2521 return false;
2522
Anders Carlsson66bbf502010-11-28 16:40:49 +00002523 const Expr *E = skipTemporaryBindingsNoOpCastsAndParens(this);
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002524
John McCall02dc8c72010-09-15 20:59:13 +00002525 // Temporaries are by definition pr-values of class type.
Fariborz Jahanian30e8d582010-09-27 17:30:38 +00002526 if (!E->Classify(C).isPRValue()) {
2527 // In this context, property reference is a message call and is pr-value.
John McCallb7bd14f2010-12-02 01:19:52 +00002528 if (!isa<ObjCPropertyRefExpr>(E))
Fariborz Jahanian30e8d582010-09-27 17:30:38 +00002529 return false;
2530 }
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002531
John McCallf4ee1dd2010-09-16 06:57:56 +00002532 // Black-list a few cases which yield pr-values of class type that don't
2533 // refer to temporaries of that type:
2534
2535 // - implicit derived-to-base conversions
John McCall7a626f62010-09-15 10:14:12 +00002536 if (isa<ImplicitCastExpr>(E)) {
2537 switch (cast<ImplicitCastExpr>(E)->getCastKind()) {
2538 case CK_DerivedToBase:
2539 case CK_UncheckedDerivedToBase:
2540 return false;
2541 default:
2542 break;
2543 }
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002544 }
2545
John McCallf4ee1dd2010-09-16 06:57:56 +00002546 // - member expressions (all)
2547 if (isa<MemberExpr>(E))
2548 return false;
2549
Eli Friedman13ffdd82012-06-15 23:51:06 +00002550 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E))
2551 if (BO->isPtrMemOp())
2552 return false;
2553
John McCallc07a0c72011-02-17 10:25:35 +00002554 // - opaque values (all)
2555 if (isa<OpaqueValueExpr>(E))
2556 return false;
2557
John McCall7a626f62010-09-15 10:14:12 +00002558 return true;
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002559}
2560
Douglas Gregor25b7e052011-03-02 21:06:53 +00002561bool Expr::isImplicitCXXThis() const {
2562 const Expr *E = this;
2563
2564 // Strip away parentheses and casts we don't care about.
2565 while (true) {
2566 if (const ParenExpr *Paren = dyn_cast<ParenExpr>(E)) {
2567 E = Paren->getSubExpr();
2568 continue;
2569 }
2570
2571 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2572 if (ICE->getCastKind() == CK_NoOp ||
2573 ICE->getCastKind() == CK_LValueToRValue ||
2574 ICE->getCastKind() == CK_DerivedToBase ||
2575 ICE->getCastKind() == CK_UncheckedDerivedToBase) {
2576 E = ICE->getSubExpr();
2577 continue;
2578 }
2579 }
2580
2581 if (const UnaryOperator* UnOp = dyn_cast<UnaryOperator>(E)) {
2582 if (UnOp->getOpcode() == UO_Extension) {
2583 E = UnOp->getSubExpr();
2584 continue;
2585 }
2586 }
2587
Douglas Gregorfe314812011-06-21 17:03:29 +00002588 if (const MaterializeTemporaryExpr *M
2589 = dyn_cast<MaterializeTemporaryExpr>(E)) {
2590 E = M->GetTemporaryExpr();
2591 continue;
2592 }
2593
Douglas Gregor25b7e052011-03-02 21:06:53 +00002594 break;
2595 }
2596
2597 if (const CXXThisExpr *This = dyn_cast<CXXThisExpr>(E))
2598 return This->isImplicit();
2599
2600 return false;
2601}
2602
Douglas Gregor4619e432008-12-05 23:32:09 +00002603/// hasAnyTypeDependentArguments - Determines if any of the expressions
2604/// in Exprs is type-dependent.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002605bool Expr::hasAnyTypeDependentArguments(ArrayRef<Expr *> Exprs) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002606 for (unsigned I = 0; I < Exprs.size(); ++I)
Douglas Gregor4619e432008-12-05 23:32:09 +00002607 if (Exprs[I]->isTypeDependent())
2608 return true;
2609
2610 return false;
2611}
2612
Abramo Bagnara847c6602014-05-22 19:20:46 +00002613bool Expr::isConstantInitializer(ASTContext &Ctx, bool IsForRef,
2614 const Expr **Culprit) const {
Eli Friedman384da272009-01-25 03:12:18 +00002615 // This function is attempting whether an expression is an initializer
Eli Friedman4c27ac22013-07-16 22:40:53 +00002616 // which can be evaluated at compile-time. It very closely parallels
2617 // ConstExprEmitter in CGExprConstant.cpp; if they don't match, it
2618 // will lead to unexpected results. Like ConstExprEmitter, it falls back
2619 // to isEvaluatable most of the time.
2620 //
John McCall8b0f4ff2010-08-02 21:13:48 +00002621 // If we ever capture reference-binding directly in the AST, we can
2622 // kill the second parameter.
2623
2624 if (IsForRef) {
2625 EvalResult Result;
Abramo Bagnara847c6602014-05-22 19:20:46 +00002626 if (EvaluateAsLValue(Result, Ctx) && !Result.HasSideEffects)
2627 return true;
2628 if (Culprit)
2629 *Culprit = this;
2630 return false;
John McCall8b0f4ff2010-08-02 21:13:48 +00002631 }
Eli Friedmancf7cbe72009-02-20 02:36:22 +00002632
Anders Carlssona7c5eb72008-11-24 05:23:59 +00002633 switch (getStmtClass()) {
Eli Friedman384da272009-01-25 03:12:18 +00002634 default: break;
Anders Carlssona7c5eb72008-11-24 05:23:59 +00002635 case StringLiteralClass:
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00002636 case ObjCEncodeExprClass:
Anders Carlssona7c5eb72008-11-24 05:23:59 +00002637 return true;
John McCall81c9cea2010-08-01 21:51:45 +00002638 case CXXTemporaryObjectExprClass:
2639 case CXXConstructExprClass: {
2640 const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
John McCall8b0f4ff2010-08-02 21:13:48 +00002641
Eli Friedman4c27ac22013-07-16 22:40:53 +00002642 if (CE->getConstructor()->isTrivial() &&
2643 CE->getConstructor()->getParent()->hasTrivialDestructor()) {
2644 // Trivial default constructor
Richard Smithd62306a2011-11-10 06:34:14 +00002645 if (!CE->getNumArgs()) return true;
John McCall8b0f4ff2010-08-02 21:13:48 +00002646
Eli Friedman4c27ac22013-07-16 22:40:53 +00002647 // Trivial copy constructor
2648 assert(CE->getNumArgs() == 1 && "trivial ctor with > 1 argument");
Abramo Bagnara847c6602014-05-22 19:20:46 +00002649 return CE->getArg(0)->isConstantInitializer(Ctx, false, Culprit);
Richard Smithd62306a2011-11-10 06:34:14 +00002650 }
2651
Richard Smithd62306a2011-11-10 06:34:14 +00002652 break;
John McCall81c9cea2010-08-01 21:51:45 +00002653 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002654 case CompoundLiteralExprClass: {
Eli Friedmancf7cbe72009-02-20 02:36:22 +00002655 // This handles gcc's extension that allows global initializers like
2656 // "struct x {int x;} x = (struct x) {};".
2657 // FIXME: This accepts other cases it shouldn't!
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002658 const Expr *Exp = cast<CompoundLiteralExpr>(this)->getInitializer();
Abramo Bagnara847c6602014-05-22 19:20:46 +00002659 return Exp->isConstantInitializer(Ctx, false, Culprit);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002660 }
Yunzhong Gaocb779302015-06-10 00:27:52 +00002661 case DesignatedInitUpdateExprClass: {
2662 const DesignatedInitUpdateExpr *DIUE = cast<DesignatedInitUpdateExpr>(this);
2663 return DIUE->getBase()->isConstantInitializer(Ctx, false, Culprit) &&
2664 DIUE->getUpdater()->isConstantInitializer(Ctx, false, Culprit);
2665 }
Anders Carlssona7c5eb72008-11-24 05:23:59 +00002666 case InitListExprClass: {
Eli Friedman4c27ac22013-07-16 22:40:53 +00002667 const InitListExpr *ILE = cast<InitListExpr>(this);
2668 if (ILE->getType()->isArrayType()) {
2669 unsigned numInits = ILE->getNumInits();
2670 for (unsigned i = 0; i < numInits; i++) {
Abramo Bagnara847c6602014-05-22 19:20:46 +00002671 if (!ILE->getInit(i)->isConstantInitializer(Ctx, false, Culprit))
Eli Friedman4c27ac22013-07-16 22:40:53 +00002672 return false;
2673 }
2674 return true;
Anders Carlssona7c5eb72008-11-24 05:23:59 +00002675 }
Eli Friedman4c27ac22013-07-16 22:40:53 +00002676
2677 if (ILE->getType()->isRecordType()) {
2678 unsigned ElementNo = 0;
2679 RecordDecl *RD = ILE->getType()->getAs<RecordType>()->getDecl();
Hans Wennborga302cd92014-08-21 16:06:57 +00002680 for (const auto *Field : RD->fields()) {
Eli Friedman4c27ac22013-07-16 22:40:53 +00002681 // If this is a union, skip all the fields that aren't being initialized.
Hans Wennborga302cd92014-08-21 16:06:57 +00002682 if (RD->isUnion() && ILE->getInitializedFieldInUnion() != Field)
Eli Friedman4c27ac22013-07-16 22:40:53 +00002683 continue;
2684
2685 // Don't emit anonymous bitfields, they just affect layout.
2686 if (Field->isUnnamedBitfield())
2687 continue;
2688
2689 if (ElementNo < ILE->getNumInits()) {
2690 const Expr *Elt = ILE->getInit(ElementNo++);
2691 if (Field->isBitField()) {
2692 // Bitfields have to evaluate to an integer.
2693 llvm::APSInt ResultTmp;
Abramo Bagnara847c6602014-05-22 19:20:46 +00002694 if (!Elt->EvaluateAsInt(ResultTmp, Ctx)) {
2695 if (Culprit)
2696 *Culprit = Elt;
Eli Friedman4c27ac22013-07-16 22:40:53 +00002697 return false;
Abramo Bagnara847c6602014-05-22 19:20:46 +00002698 }
Eli Friedman4c27ac22013-07-16 22:40:53 +00002699 } else {
2700 bool RefType = Field->getType()->isReferenceType();
Abramo Bagnara847c6602014-05-22 19:20:46 +00002701 if (!Elt->isConstantInitializer(Ctx, RefType, Culprit))
Eli Friedman4c27ac22013-07-16 22:40:53 +00002702 return false;
2703 }
2704 }
2705 }
2706 return true;
2707 }
2708
2709 break;
Anders Carlssona7c5eb72008-11-24 05:23:59 +00002710 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00002711 case ImplicitValueInitExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00002712 case NoInitExprClass:
Douglas Gregor0202cb42009-01-29 17:44:32 +00002713 return true;
Chris Lattner3eb172a2009-10-13 07:14:16 +00002714 case ParenExprClass:
John McCall8b0f4ff2010-08-02 21:13:48 +00002715 return cast<ParenExpr>(this)->getSubExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00002716 ->isConstantInitializer(Ctx, IsForRef, Culprit);
Peter Collingbourne91147592011-04-15 00:35:48 +00002717 case GenericSelectionExprClass:
Peter Collingbourne91147592011-04-15 00:35:48 +00002718 return cast<GenericSelectionExpr>(this)->getResultExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00002719 ->isConstantInitializer(Ctx, IsForRef, Culprit);
Abramo Bagnarab59a5b62010-09-27 07:13:32 +00002720 case ChooseExprClass:
Abramo Bagnara847c6602014-05-22 19:20:46 +00002721 if (cast<ChooseExpr>(this)->isConditionDependent()) {
2722 if (Culprit)
2723 *Culprit = this;
Eli Friedman75807f22013-07-20 00:40:58 +00002724 return false;
Abramo Bagnara847c6602014-05-22 19:20:46 +00002725 }
Eli Friedman75807f22013-07-20 00:40:58 +00002726 return cast<ChooseExpr>(this)->getChosenSubExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00002727 ->isConstantInitializer(Ctx, IsForRef, Culprit);
Eli Friedman384da272009-01-25 03:12:18 +00002728 case UnaryOperatorClass: {
2729 const UnaryOperator* Exp = cast<UnaryOperator>(this);
John McCalle3027922010-08-25 11:45:40 +00002730 if (Exp->getOpcode() == UO_Extension)
Abramo Bagnara847c6602014-05-22 19:20:46 +00002731 return Exp->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
Eli Friedman384da272009-01-25 03:12:18 +00002732 break;
2733 }
John McCall8b0f4ff2010-08-02 21:13:48 +00002734 case CXXFunctionalCastExprClass:
John McCall81c9cea2010-08-01 21:51:45 +00002735 case CXXStaticCastExprClass:
Chris Lattner1f02e052009-04-21 05:19:11 +00002736 case ImplicitCastExprClass:
Eli Friedman4c27ac22013-07-16 22:40:53 +00002737 case CStyleCastExprClass:
2738 case ObjCBridgedCastExprClass:
2739 case CXXDynamicCastExprClass:
2740 case CXXReinterpretCastExprClass:
2741 case CXXConstCastExprClass: {
Richard Smith161f09a2011-12-06 22:44:34 +00002742 const CastExpr *CE = cast<CastExpr>(this);
2743
Eli Friedman13ec75b2011-12-21 00:43:02 +00002744 // Handle misc casts we want to ignore.
Eli Friedman13ec75b2011-12-21 00:43:02 +00002745 if (CE->getCastKind() == CK_NoOp ||
2746 CE->getCastKind() == CK_LValueToRValue ||
2747 CE->getCastKind() == CK_ToUnion ||
Eli Friedman4c27ac22013-07-16 22:40:53 +00002748 CE->getCastKind() == CK_ConstructorConversion ||
2749 CE->getCastKind() == CK_NonAtomicToAtomic ||
2750 CE->getCastKind() == CK_AtomicToNonAtomic)
Abramo Bagnara847c6602014-05-22 19:20:46 +00002751 return CE->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
Richard Smith161f09a2011-12-06 22:44:34 +00002752
Eli Friedman384da272009-01-25 03:12:18 +00002753 break;
Richard Smith161f09a2011-12-06 22:44:34 +00002754 }
Douglas Gregorfe314812011-06-21 17:03:29 +00002755 case MaterializeTemporaryExprClass:
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002756 return cast<MaterializeTemporaryExpr>(this)->GetTemporaryExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00002757 ->isConstantInitializer(Ctx, false, Culprit);
Eli Friedman4c27ac22013-07-16 22:40:53 +00002758
2759 case SubstNonTypeTemplateParmExprClass:
2760 return cast<SubstNonTypeTemplateParmExpr>(this)->getReplacement()
Abramo Bagnara847c6602014-05-22 19:20:46 +00002761 ->isConstantInitializer(Ctx, false, Culprit);
Eli Friedman4c27ac22013-07-16 22:40:53 +00002762 case CXXDefaultArgExprClass:
2763 return cast<CXXDefaultArgExpr>(this)->getExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00002764 ->isConstantInitializer(Ctx, false, Culprit);
Eli Friedman4c27ac22013-07-16 22:40:53 +00002765 case CXXDefaultInitExprClass:
2766 return cast<CXXDefaultInitExpr>(this)->getExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00002767 ->isConstantInitializer(Ctx, false, Culprit);
Anders Carlssona7c5eb72008-11-24 05:23:59 +00002768 }
Richard Smithce8eca52015-12-08 03:21:47 +00002769 // Allow certain forms of UB in constant initializers: signed integer
2770 // overflow and floating-point division by zero. We'll give a warning on
2771 // these, but they're common enough that we have to accept them.
2772 if (isEvaluatable(Ctx, SE_AllowUndefinedBehavior))
Abramo Bagnara847c6602014-05-22 19:20:46 +00002773 return true;
2774 if (Culprit)
2775 *Culprit = this;
2776 return false;
Steve Naroffb03f5942007-09-02 20:30:18 +00002777}
2778
Scott Douglasscc013592015-06-10 15:18:23 +00002779namespace {
2780 /// \brief Look for any side effects within a Stmt.
2781 class SideEffectFinder : public ConstEvaluatedExprVisitor<SideEffectFinder> {
2782 typedef ConstEvaluatedExprVisitor<SideEffectFinder> Inherited;
2783 const bool IncludePossibleEffects;
2784 bool HasSideEffects;
2785
2786 public:
2787 explicit SideEffectFinder(const ASTContext &Context, bool IncludePossible)
2788 : Inherited(Context),
2789 IncludePossibleEffects(IncludePossible), HasSideEffects(false) { }
2790
2791 bool hasSideEffects() const { return HasSideEffects; }
2792
2793 void VisitExpr(const Expr *E) {
2794 if (!HasSideEffects &&
2795 E->HasSideEffects(Context, IncludePossibleEffects))
2796 HasSideEffects = true;
2797 }
2798 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002799}
Scott Douglasscc013592015-06-10 15:18:23 +00002800
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00002801bool Expr::HasSideEffects(const ASTContext &Ctx,
2802 bool IncludePossibleEffects) const {
2803 // In circumstances where we care about definite side effects instead of
2804 // potential side effects, we want to ignore expressions that are part of a
2805 // macro expansion as a potential side effect.
2806 if (!IncludePossibleEffects && getExprLoc().isMacroID())
2807 return false;
2808
Richard Smith0421ce72012-08-07 04:16:51 +00002809 if (isInstantiationDependent())
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00002810 return IncludePossibleEffects;
Richard Smith0421ce72012-08-07 04:16:51 +00002811
2812 switch (getStmtClass()) {
2813 case NoStmtClass:
2814 #define ABSTRACT_STMT(Type)
2815 #define STMT(Type, Base) case Type##Class:
2816 #define EXPR(Type, Base)
2817 #include "clang/AST/StmtNodes.inc"
2818 llvm_unreachable("unexpected Expr kind");
2819
2820 case DependentScopeDeclRefExprClass:
2821 case CXXUnresolvedConstructExprClass:
2822 case CXXDependentScopeMemberExprClass:
2823 case UnresolvedLookupExprClass:
2824 case UnresolvedMemberExprClass:
2825 case PackExpansionExprClass:
2826 case SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +00002827 case FunctionParmPackExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +00002828 case TypoExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +00002829 case CXXFoldExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00002830 llvm_unreachable("shouldn't see dependent / unresolved nodes here");
2831
Richard Smitha33e4fe2012-08-07 05:18:29 +00002832 case DeclRefExprClass:
2833 case ObjCIvarRefExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00002834 case PredefinedExprClass:
2835 case IntegerLiteralClass:
2836 case FloatingLiteralClass:
2837 case ImaginaryLiteralClass:
2838 case StringLiteralClass:
2839 case CharacterLiteralClass:
2840 case OffsetOfExprClass:
2841 case ImplicitValueInitExprClass:
2842 case UnaryExprOrTypeTraitExprClass:
2843 case AddrLabelExprClass:
2844 case GNUNullExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00002845 case NoInitExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00002846 case CXXBoolLiteralExprClass:
2847 case CXXNullPtrLiteralExprClass:
2848 case CXXThisExprClass:
2849 case CXXScalarValueInitExprClass:
2850 case TypeTraitExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00002851 case ArrayTypeTraitExprClass:
2852 case ExpressionTraitExprClass:
2853 case CXXNoexceptExprClass:
2854 case SizeOfPackExprClass:
2855 case ObjCStringLiteralClass:
2856 case ObjCEncodeExprClass:
2857 case ObjCBoolLiteralExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +00002858 case ObjCAvailabilityCheckExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00002859 case CXXUuidofExprClass:
2860 case OpaqueValueExprClass:
2861 // These never have a side-effect.
2862 return false;
2863
2864 case CallExprClass:
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00002865 case CXXOperatorCallExprClass:
2866 case CXXMemberCallExprClass:
2867 case CUDAKernelCallExprClass:
Michael Kupersteinaed5ccd2015-04-06 13:22:01 +00002868 case UserDefinedLiteralClass: {
2869 // We don't know a call definitely has side effects, except for calls
2870 // to pure/const functions that definitely don't.
2871 // If the call itself is considered side-effect free, check the operands.
2872 const Decl *FD = cast<CallExpr>(this)->getCalleeDecl();
2873 bool IsPure = FD && (FD->hasAttr<ConstAttr>() || FD->hasAttr<PureAttr>());
2874 if (IsPure || !IncludePossibleEffects)
2875 break;
2876 return true;
2877 }
2878
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00002879 case BlockExprClass:
2880 case CXXBindTemporaryExprClass:
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00002881 if (!IncludePossibleEffects)
2882 break;
2883 return true;
2884
John McCall5e77d762013-04-16 07:28:30 +00002885 case MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +00002886 case MSPropertySubscriptExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00002887 case CompoundAssignOperatorClass:
2888 case VAArgExprClass:
2889 case AtomicExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00002890 case CXXThrowExprClass:
2891 case CXXNewExprClass:
2892 case CXXDeleteExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +00002893 case CoawaitExprClass:
2894 case CoyieldExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00002895 // These always have a side-effect.
2896 return true;
2897
Scott Douglasscc013592015-06-10 15:18:23 +00002898 case StmtExprClass: {
2899 // StmtExprs have a side-effect if any substatement does.
2900 SideEffectFinder Finder(Ctx, IncludePossibleEffects);
2901 Finder.Visit(cast<StmtExpr>(this)->getSubStmt());
2902 return Finder.hasSideEffects();
2903 }
2904
Tim Shen4a05bb82016-06-21 20:29:17 +00002905 case ExprWithCleanupsClass:
2906 if (IncludePossibleEffects)
2907 if (cast<ExprWithCleanups>(this)->cleanupsHaveSideEffects())
2908 return true;
2909 break;
2910
Richard Smith0421ce72012-08-07 04:16:51 +00002911 case ParenExprClass:
2912 case ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +00002913 case OMPArraySectionExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00002914 case MemberExprClass:
2915 case ConditionalOperatorClass:
2916 case BinaryConditionalOperatorClass:
Richard Smith0421ce72012-08-07 04:16:51 +00002917 case CompoundLiteralExprClass:
2918 case ExtVectorElementExprClass:
2919 case DesignatedInitExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00002920 case DesignatedInitUpdateExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00002921 case ParenListExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00002922 case CXXPseudoDestructorExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +00002923 case CXXStdInitializerListExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00002924 case SubstNonTypeTemplateParmExprClass:
2925 case MaterializeTemporaryExprClass:
2926 case ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +00002927 case ConvertVectorExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00002928 case AsTypeExprClass:
2929 // These have a side-effect if any subexpression does.
2930 break;
2931
Richard Smitha33e4fe2012-08-07 05:18:29 +00002932 case UnaryOperatorClass:
2933 if (cast<UnaryOperator>(this)->isIncrementDecrementOp())
Richard Smith0421ce72012-08-07 04:16:51 +00002934 return true;
2935 break;
Richard Smith0421ce72012-08-07 04:16:51 +00002936
2937 case BinaryOperatorClass:
2938 if (cast<BinaryOperator>(this)->isAssignmentOp())
2939 return true;
2940 break;
2941
Richard Smith0421ce72012-08-07 04:16:51 +00002942 case InitListExprClass:
2943 // FIXME: The children for an InitListExpr doesn't include the array filler.
2944 if (const Expr *E = cast<InitListExpr>(this)->getArrayFiller())
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00002945 if (E->HasSideEffects(Ctx, IncludePossibleEffects))
Richard Smith0421ce72012-08-07 04:16:51 +00002946 return true;
2947 break;
2948
2949 case GenericSelectionExprClass:
2950 return cast<GenericSelectionExpr>(this)->getResultExpr()->
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00002951 HasSideEffects(Ctx, IncludePossibleEffects);
Richard Smith0421ce72012-08-07 04:16:51 +00002952
2953 case ChooseExprClass:
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00002954 return cast<ChooseExpr>(this)->getChosenSubExpr()->HasSideEffects(
2955 Ctx, IncludePossibleEffects);
Richard Smith0421ce72012-08-07 04:16:51 +00002956
2957 case CXXDefaultArgExprClass:
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00002958 return cast<CXXDefaultArgExpr>(this)->getExpr()->HasSideEffects(
2959 Ctx, IncludePossibleEffects);
Richard Smith0421ce72012-08-07 04:16:51 +00002960
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002961 case CXXDefaultInitExprClass: {
2962 const FieldDecl *FD = cast<CXXDefaultInitExpr>(this)->getField();
2963 if (const Expr *E = FD->getInClassInitializer())
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00002964 return E->HasSideEffects(Ctx, IncludePossibleEffects);
Richard Smith852c9db2013-04-20 22:23:05 +00002965 // If we've not yet parsed the initializer, assume it has side-effects.
2966 return true;
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002967 }
Richard Smith852c9db2013-04-20 22:23:05 +00002968
Richard Smith0421ce72012-08-07 04:16:51 +00002969 case CXXDynamicCastExprClass: {
2970 // A dynamic_cast expression has side-effects if it can throw.
2971 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(this);
2972 if (DCE->getTypeAsWritten()->isReferenceType() &&
2973 DCE->getCastKind() == CK_Dynamic)
2974 return true;
Richard Smitha33e4fe2012-08-07 05:18:29 +00002975 } // Fall through.
2976 case ImplicitCastExprClass:
2977 case CStyleCastExprClass:
2978 case CXXStaticCastExprClass:
2979 case CXXReinterpretCastExprClass:
2980 case CXXConstCastExprClass:
2981 case CXXFunctionalCastExprClass: {
Aaron Ballman409af502015-01-03 17:00:12 +00002982 // While volatile reads are side-effecting in both C and C++, we treat them
2983 // as having possible (not definite) side-effects. This allows idiomatic
2984 // code to behave without warning, such as sizeof(*v) for a volatile-
2985 // qualified pointer.
2986 if (!IncludePossibleEffects)
2987 break;
2988
Richard Smitha33e4fe2012-08-07 05:18:29 +00002989 const CastExpr *CE = cast<CastExpr>(this);
2990 if (CE->getCastKind() == CK_LValueToRValue &&
2991 CE->getSubExpr()->getType().isVolatileQualified())
2992 return true;
Richard Smith0421ce72012-08-07 04:16:51 +00002993 break;
2994 }
2995
Richard Smithef8bf432012-08-13 20:08:14 +00002996 case CXXTypeidExprClass:
2997 // typeid might throw if its subexpression is potentially-evaluated, so has
2998 // side-effects in that case whether or not its subexpression does.
2999 return cast<CXXTypeidExpr>(this)->isPotentiallyEvaluated();
Richard Smith0421ce72012-08-07 04:16:51 +00003000
3001 case CXXConstructExprClass:
3002 case CXXTemporaryObjectExprClass: {
3003 const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003004 if (!CE->getConstructor()->isTrivial() && IncludePossibleEffects)
Richard Smith0421ce72012-08-07 04:16:51 +00003005 return true;
Richard Smitha33e4fe2012-08-07 05:18:29 +00003006 // A trivial constructor does not add any side-effects of its own. Just look
3007 // at its arguments.
Richard Smith0421ce72012-08-07 04:16:51 +00003008 break;
3009 }
3010
Richard Smith5179eb72016-06-28 19:03:57 +00003011 case CXXInheritedCtorInitExprClass: {
3012 const auto *ICIE = cast<CXXInheritedCtorInitExpr>(this);
3013 if (!ICIE->getConstructor()->isTrivial() && IncludePossibleEffects)
3014 return true;
3015 break;
3016 }
3017
Richard Smith0421ce72012-08-07 04:16:51 +00003018 case LambdaExprClass: {
3019 const LambdaExpr *LE = cast<LambdaExpr>(this);
3020 for (LambdaExpr::capture_iterator I = LE->capture_begin(),
3021 E = LE->capture_end(); I != E; ++I)
3022 if (I->getCaptureKind() == LCK_ByCopy)
3023 // FIXME: Only has a side-effect if the variable is volatile or if
3024 // the copy would invoke a non-trivial copy constructor.
3025 return true;
3026 return false;
3027 }
3028
3029 case PseudoObjectExprClass: {
3030 // Only look for side-effects in the semantic form, and look past
3031 // OpaqueValueExpr bindings in that form.
3032 const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this);
3033 for (PseudoObjectExpr::const_semantics_iterator I = PO->semantics_begin(),
3034 E = PO->semantics_end();
3035 I != E; ++I) {
3036 const Expr *Subexpr = *I;
3037 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Subexpr))
3038 Subexpr = OVE->getSourceExpr();
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003039 if (Subexpr->HasSideEffects(Ctx, IncludePossibleEffects))
Richard Smith0421ce72012-08-07 04:16:51 +00003040 return true;
3041 }
3042 return false;
3043 }
3044
3045 case ObjCBoxedExprClass:
3046 case ObjCArrayLiteralClass:
3047 case ObjCDictionaryLiteralClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003048 case ObjCSelectorExprClass:
3049 case ObjCProtocolExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003050 case ObjCIsaExprClass:
3051 case ObjCIndirectCopyRestoreExprClass:
3052 case ObjCSubscriptRefExprClass:
3053 case ObjCBridgedCastExprClass:
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003054 case ObjCMessageExprClass:
3055 case ObjCPropertyRefExprClass:
3056 // FIXME: Classify these cases better.
3057 if (IncludePossibleEffects)
3058 return true;
3059 break;
Richard Smith0421ce72012-08-07 04:16:51 +00003060 }
3061
3062 // Recurse to children.
Benjamin Kramer642f1732015-07-02 21:03:14 +00003063 for (const Stmt *SubStmt : children())
3064 if (SubStmt &&
3065 cast<Expr>(SubStmt)->HasSideEffects(Ctx, IncludePossibleEffects))
3066 return true;
Richard Smith0421ce72012-08-07 04:16:51 +00003067
3068 return false;
3069}
3070
Douglas Gregor1be329d2012-02-23 07:33:15 +00003071namespace {
3072 /// \brief Look for a call to a non-trivial function within an expression.
Scott Douglass503fc392015-06-10 13:53:15 +00003073 class NonTrivialCallFinder : public ConstEvaluatedExprVisitor<NonTrivialCallFinder>
Douglas Gregor1be329d2012-02-23 07:33:15 +00003074 {
Scott Douglass503fc392015-06-10 13:53:15 +00003075 typedef ConstEvaluatedExprVisitor<NonTrivialCallFinder> Inherited;
3076
Douglas Gregor1be329d2012-02-23 07:33:15 +00003077 bool NonTrivial;
3078
3079 public:
Scott Douglass503fc392015-06-10 13:53:15 +00003080 explicit NonTrivialCallFinder(const ASTContext &Context)
Douglas Gregor6427a5e2012-02-23 07:44:18 +00003081 : Inherited(Context), NonTrivial(false) { }
Douglas Gregor1be329d2012-02-23 07:33:15 +00003082
3083 bool hasNonTrivialCall() const { return NonTrivial; }
Scott Douglass503fc392015-06-10 13:53:15 +00003084
3085 void VisitCallExpr(const CallExpr *E) {
3086 if (const CXXMethodDecl *Method
3087 = dyn_cast_or_null<const CXXMethodDecl>(E->getCalleeDecl())) {
Douglas Gregor1be329d2012-02-23 07:33:15 +00003088 if (Method->isTrivial()) {
3089 // Recurse to children of the call.
3090 Inherited::VisitStmt(E);
3091 return;
3092 }
3093 }
3094
3095 NonTrivial = true;
3096 }
Scott Douglass503fc392015-06-10 13:53:15 +00003097
3098 void VisitCXXConstructExpr(const CXXConstructExpr *E) {
Douglas Gregor1be329d2012-02-23 07:33:15 +00003099 if (E->getConstructor()->isTrivial()) {
3100 // Recurse to children of the call.
3101 Inherited::VisitStmt(E);
3102 return;
3103 }
3104
3105 NonTrivial = true;
3106 }
Scott Douglass503fc392015-06-10 13:53:15 +00003107
3108 void VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
Douglas Gregor1be329d2012-02-23 07:33:15 +00003109 if (E->getTemporary()->getDestructor()->isTrivial()) {
3110 Inherited::VisitStmt(E);
3111 return;
3112 }
3113
3114 NonTrivial = true;
3115 }
3116 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003117}
Douglas Gregor1be329d2012-02-23 07:33:15 +00003118
Scott Douglass503fc392015-06-10 13:53:15 +00003119bool Expr::hasNonTrivialCall(const ASTContext &Ctx) const {
Douglas Gregor1be329d2012-02-23 07:33:15 +00003120 NonTrivialCallFinder Finder(Ctx);
3121 Finder.Visit(this);
3122 return Finder.hasNonTrivialCall();
3123}
3124
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003125/// isNullPointerConstant - C99 6.3.2.3p3 - Return whether this is a null
3126/// pointer constant or not, as well as the specific kind of constant detected.
3127/// Null pointer constants can be integer constant expressions with the
3128/// value zero, casts of zero to void*, nullptr (C++0X), or __null
3129/// (a GNU extension).
3130Expr::NullPointerConstantKind
3131Expr::isNullPointerConstant(ASTContext &Ctx,
3132 NullPointerConstantValueDependence NPC) const {
Reid Klecknera5eef142013-11-12 02:22:34 +00003133 if (isValueDependent() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00003134 (!Ctx.getLangOpts().CPlusPlus11 || Ctx.getLangOpts().MSVCCompat)) {
Douglas Gregor56751b52009-09-25 04:25:58 +00003135 switch (NPC) {
3136 case NPC_NeverValueDependent:
David Blaikie83d382b2011-09-23 05:06:16 +00003137 llvm_unreachable("Unexpected value dependent expression!");
Douglas Gregor56751b52009-09-25 04:25:58 +00003138 case NPC_ValueDependentIsNull:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003139 if (isTypeDependent() || getType()->isIntegralType(Ctx))
David Blaikie1c7c8f72012-08-08 17:33:31 +00003140 return NPCK_ZeroExpression;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003141 else
3142 return NPCK_NotNull;
Alexis Hunta8136cc2010-05-05 15:23:54 +00003143
Douglas Gregor56751b52009-09-25 04:25:58 +00003144 case NPC_ValueDependentIsNotNull:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003145 return NPCK_NotNull;
Douglas Gregor56751b52009-09-25 04:25:58 +00003146 }
3147 }
Daniel Dunbarebc51402009-09-18 08:46:16 +00003148
Sebastian Redl72b8aef2008-10-31 14:43:28 +00003149 // Strip off a cast to void*, if it exists. Except in C++.
Argyrios Kyrtzidis3bab3d22008-08-18 23:01:59 +00003150 if (const ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(this)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003151 if (!Ctx.getLangOpts().CPlusPlus) {
Sebastian Redl72b8aef2008-10-31 14:43:28 +00003152 // Check that it is a cast to void*.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003153 if (const PointerType *PT = CE->getType()->getAs<PointerType>()) {
Sebastian Redl72b8aef2008-10-31 14:43:28 +00003154 QualType Pointee = PT->getPointeeType();
Anastasia Stulova2446b8b2015-12-11 17:41:19 +00003155 Qualifiers Q = Pointee.getQualifiers();
3156 // In OpenCL v2.0 generic address space acts as a placeholder
3157 // and should be ignored.
3158 bool IsASValid = true;
3159 if (Ctx.getLangOpts().OpenCLVersion >= 200) {
3160 if (Pointee.getAddressSpace() == LangAS::opencl_generic)
3161 Q.removeAddressSpace();
3162 else
3163 IsASValid = false;
3164 }
3165
3166 if (IsASValid && !Q.hasQualifiers() &&
3167 Pointee->isVoidType() && // to void*
3168 CE->getSubExpr()->getType()->isIntegerType()) // from int.
Douglas Gregor56751b52009-09-25 04:25:58 +00003169 return CE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
Sebastian Redl72b8aef2008-10-31 14:43:28 +00003170 }
Steve Naroffada7d422007-05-20 17:54:12 +00003171 }
Steve Naroff4871fe02008-01-14 16:10:57 +00003172 } else if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(this)) {
3173 // Ignore the ImplicitCastExpr type entirely.
Douglas Gregor56751b52009-09-25 04:25:58 +00003174 return ICE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
Steve Naroff4871fe02008-01-14 16:10:57 +00003175 } else if (const ParenExpr *PE = dyn_cast<ParenExpr>(this)) {
3176 // Accept ((void*)0) as a null pointer constant, as many other
3177 // implementations do.
Douglas Gregor56751b52009-09-25 04:25:58 +00003178 return PE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
Peter Collingbourne91147592011-04-15 00:35:48 +00003179 } else if (const GenericSelectionExpr *GE =
3180 dyn_cast<GenericSelectionExpr>(this)) {
Eli Friedman75807f22013-07-20 00:40:58 +00003181 if (GE->isResultDependent())
3182 return NPCK_NotNull;
Peter Collingbourne91147592011-04-15 00:35:48 +00003183 return GE->getResultExpr()->isNullPointerConstant(Ctx, NPC);
Eli Friedman75807f22013-07-20 00:40:58 +00003184 } else if (const ChooseExpr *CE = dyn_cast<ChooseExpr>(this)) {
3185 if (CE->isConditionDependent())
3186 return NPCK_NotNull;
3187 return CE->getChosenSubExpr()->isNullPointerConstant(Ctx, NPC);
Mike Stump11289f42009-09-09 15:08:12 +00003188 } else if (const CXXDefaultArgExpr *DefaultArg
Chris Lattner58258242008-04-10 02:22:51 +00003189 = dyn_cast<CXXDefaultArgExpr>(this)) {
Richard Smith852c9db2013-04-20 22:23:05 +00003190 // See through default argument expressions.
Douglas Gregor56751b52009-09-25 04:25:58 +00003191 return DefaultArg->getExpr()->isNullPointerConstant(Ctx, NPC);
Richard Smith852c9db2013-04-20 22:23:05 +00003192 } else if (const CXXDefaultInitExpr *DefaultInit
3193 = dyn_cast<CXXDefaultInitExpr>(this)) {
3194 // See through default initializer expressions.
3195 return DefaultInit->getExpr()->isNullPointerConstant(Ctx, NPC);
Douglas Gregor3be4b122008-11-29 04:51:27 +00003196 } else if (isa<GNUNullExpr>(this)) {
3197 // The GNU __null extension is always a null pointer constant.
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003198 return NPCK_GNUNull;
Douglas Gregorfe314812011-06-21 17:03:29 +00003199 } else if (const MaterializeTemporaryExpr *M
3200 = dyn_cast<MaterializeTemporaryExpr>(this)) {
3201 return M->GetTemporaryExpr()->isNullPointerConstant(Ctx, NPC);
John McCallfe96e0b2011-11-06 09:01:30 +00003202 } else if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(this)) {
3203 if (const Expr *Source = OVE->getSourceExpr())
3204 return Source->isNullPointerConstant(Ctx, NPC);
Steve Naroff09035312008-01-14 02:53:34 +00003205 }
Douglas Gregor3be4b122008-11-29 04:51:27 +00003206
Richard Smith89645bc2013-01-02 12:01:23 +00003207 // C++11 nullptr_t is always a null pointer constant.
Sebastian Redl576fd422009-05-10 18:38:11 +00003208 if (getType()->isNullPtrType())
Richard Smith89645bc2013-01-02 12:01:23 +00003209 return NPCK_CXX11_nullptr;
Sebastian Redl576fd422009-05-10 18:38:11 +00003210
Fariborz Jahanian3567c422010-09-27 22:42:37 +00003211 if (const RecordType *UT = getType()->getAsUnionType())
Richard Smith4055de42013-06-13 02:46:14 +00003212 if (!Ctx.getLangOpts().CPlusPlus11 &&
3213 UT && UT->getDecl()->hasAttr<TransparentUnionAttr>())
Fariborz Jahanian3567c422010-09-27 22:42:37 +00003214 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(this)){
3215 const Expr *InitExpr = CLE->getInitializer();
3216 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(InitExpr))
3217 return ILE->getInit(0)->isNullPointerConstant(Ctx, NPC);
3218 }
Steve Naroff4871fe02008-01-14 16:10:57 +00003219 // This expression must be an integer type.
Alexis Hunta8136cc2010-05-05 15:23:54 +00003220 if (!getType()->isIntegerType() ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00003221 (Ctx.getLangOpts().CPlusPlus && getType()->isEnumeralType()))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003222 return NPCK_NotNull;
Mike Stump11289f42009-09-09 15:08:12 +00003223
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003224 if (Ctx.getLangOpts().CPlusPlus11) {
Richard Smith4055de42013-06-13 02:46:14 +00003225 // C++11 [conv.ptr]p1: A null pointer constant is an integer literal with
3226 // value zero or a prvalue of type std::nullptr_t.
Reid Klecknera5eef142013-11-12 02:22:34 +00003227 // Microsoft mode permits C++98 rules reflecting MSVC behavior.
Richard Smith4055de42013-06-13 02:46:14 +00003228 const IntegerLiteral *Lit = dyn_cast<IntegerLiteral>(this);
Reid Klecknera5eef142013-11-12 02:22:34 +00003229 if (Lit && !Lit->getValue())
3230 return NPCK_ZeroLiteral;
Alp Tokerbfa39342014-01-14 12:51:41 +00003231 else if (!Ctx.getLangOpts().MSVCCompat || !isCXX98IntegralConstantExpr(Ctx))
Reid Klecknera5eef142013-11-12 02:22:34 +00003232 return NPCK_NotNull;
Richard Smith98a0a492012-02-14 21:38:30 +00003233 } else {
Richard Smith4055de42013-06-13 02:46:14 +00003234 // If we have an integer constant expression, we need to *evaluate* it and
3235 // test for the value 0.
Richard Smith98a0a492012-02-14 21:38:30 +00003236 if (!isIntegerConstantExpr(Ctx))
3237 return NPCK_NotNull;
3238 }
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003239
David Blaikie1c7c8f72012-08-08 17:33:31 +00003240 if (EvaluateKnownConstInt(Ctx) != 0)
3241 return NPCK_NotNull;
3242
3243 if (isa<IntegerLiteral>(this))
3244 return NPCK_ZeroLiteral;
3245 return NPCK_ZeroExpression;
Steve Naroff218bc2b2007-05-04 21:54:46 +00003246}
Steve Narofff7a5da12007-07-28 23:10:27 +00003247
John McCall34376a62010-12-04 03:47:34 +00003248/// \brief If this expression is an l-value for an Objective C
3249/// property, find the underlying property reference expression.
3250const ObjCPropertyRefExpr *Expr::getObjCProperty() const {
3251 const Expr *E = this;
3252 while (true) {
3253 assert((E->getValueKind() == VK_LValue &&
3254 E->getObjectKind() == OK_ObjCProperty) &&
3255 "expression is not a property reference");
3256 E = E->IgnoreParenCasts();
3257 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3258 if (BO->getOpcode() == BO_Comma) {
3259 E = BO->getRHS();
3260 continue;
3261 }
3262 }
3263
3264 break;
3265 }
3266
3267 return cast<ObjCPropertyRefExpr>(E);
3268}
3269
Anna Zaks97c7ce32012-10-01 20:34:04 +00003270bool Expr::isObjCSelfExpr() const {
3271 const Expr *E = IgnoreParenImpCasts();
3272
3273 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
3274 if (!DRE)
3275 return false;
3276
3277 const ImplicitParamDecl *Param = dyn_cast<ImplicitParamDecl>(DRE->getDecl());
3278 if (!Param)
3279 return false;
3280
3281 const ObjCMethodDecl *M = dyn_cast<ObjCMethodDecl>(Param->getDeclContext());
3282 if (!M)
3283 return false;
3284
3285 return M->getSelfDecl() == Param;
3286}
3287
John McCalld25db7e2013-05-06 21:39:12 +00003288FieldDecl *Expr::getSourceBitField() {
Douglas Gregor19623dc2009-07-06 15:38:40 +00003289 Expr *E = this->IgnoreParens();
Douglas Gregor71235ec2009-05-02 02:18:30 +00003290
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003291 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall34376a62010-12-04 03:47:34 +00003292 if (ICE->getCastKind() == CK_LValueToRValue ||
3293 (ICE->getValueKind() != VK_RValue && ICE->getCastKind() == CK_NoOp))
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003294 E = ICE->getSubExpr()->IgnoreParens();
3295 else
3296 break;
3297 }
3298
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003299 if (MemberExpr *MemRef = dyn_cast<MemberExpr>(E))
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00003300 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemRef->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00003301 if (Field->isBitField())
3302 return Field;
3303
John McCalld25db7e2013-05-06 21:39:12 +00003304 if (ObjCIvarRefExpr *IvarRef = dyn_cast<ObjCIvarRefExpr>(E))
3305 if (FieldDecl *Ivar = dyn_cast<FieldDecl>(IvarRef->getDecl()))
3306 if (Ivar->isBitField())
3307 return Ivar;
3308
Argyrios Kyrtzidisd3f00542010-10-30 19:52:22 +00003309 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E))
3310 if (FieldDecl *Field = dyn_cast<FieldDecl>(DeclRef->getDecl()))
3311 if (Field->isBitField())
3312 return Field;
3313
Eli Friedman609ada22011-07-13 02:05:57 +00003314 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(E)) {
Douglas Gregor71235ec2009-05-02 02:18:30 +00003315 if (BinOp->isAssignmentOp() && BinOp->getLHS())
John McCalld25db7e2013-05-06 21:39:12 +00003316 return BinOp->getLHS()->getSourceBitField();
Douglas Gregor71235ec2009-05-02 02:18:30 +00003317
Eli Friedman609ada22011-07-13 02:05:57 +00003318 if (BinOp->getOpcode() == BO_Comma && BinOp->getRHS())
John McCalld25db7e2013-05-06 21:39:12 +00003319 return BinOp->getRHS()->getSourceBitField();
Eli Friedman609ada22011-07-13 02:05:57 +00003320 }
3321
Richard Smith5b571672014-09-24 23:55:00 +00003322 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E))
3323 if (UnOp->isPrefix() && UnOp->isIncrementDecrementOp())
3324 return UnOp->getSubExpr()->getSourceBitField();
3325
Craig Topper36250ad2014-05-12 05:36:57 +00003326 return nullptr;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003327}
3328
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003329bool Expr::refersToVectorElement() const {
3330 const Expr *E = this->IgnoreParens();
Alexis Hunta8136cc2010-05-05 15:23:54 +00003331
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003332 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall2536c6d2010-08-25 10:28:54 +00003333 if (ICE->getValueKind() != VK_RValue &&
John McCalle3027922010-08-25 11:45:40 +00003334 ICE->getCastKind() == CK_NoOp)
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003335 E = ICE->getSubExpr()->IgnoreParens();
3336 else
3337 break;
3338 }
Alexis Hunta8136cc2010-05-05 15:23:54 +00003339
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003340 if (const ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(E))
3341 return ASE->getBase()->getType()->isVectorType();
3342
3343 if (isa<ExtVectorElementExpr>(E))
3344 return true;
3345
3346 return false;
3347}
3348
Andrey Bokhankod9eab9c2015-08-03 10:38:10 +00003349bool Expr::refersToGlobalRegisterVar() const {
3350 const Expr *E = this->IgnoreParenImpCasts();
3351
3352 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
3353 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
3354 if (VD->getStorageClass() == SC_Register &&
3355 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
3356 return true;
3357
3358 return false;
3359}
3360
Chris Lattnerb8211f62009-02-16 22:14:05 +00003361/// isArrow - Return true if the base expression is a pointer to vector,
3362/// return false if the base expression is a vector.
3363bool ExtVectorElementExpr::isArrow() const {
3364 return getBase()->getType()->isPointerType();
3365}
3366
Nate Begemance4d7fc2008-04-18 23:10:10 +00003367unsigned ExtVectorElementExpr::getNumElements() const {
John McCall9dd450b2009-09-21 23:43:11 +00003368 if (const VectorType *VT = getType()->getAs<VectorType>())
Nate Begemanf322eab2008-05-09 06:41:27 +00003369 return VT->getNumElements();
3370 return 1;
Chris Lattner177bd452007-08-03 16:00:20 +00003371}
3372
Nate Begemanf322eab2008-05-09 06:41:27 +00003373/// containsDuplicateElements - Return true if any element access is repeated.
Nate Begemance4d7fc2008-04-18 23:10:10 +00003374bool ExtVectorElementExpr::containsDuplicateElements() const {
Daniel Dunbarcb2a0562009-10-18 02:09:09 +00003375 // FIXME: Refactor this code to an accessor on the AST node which returns the
3376 // "type" of component access, and share with code below and in Sema.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003377 StringRef Comp = Accessor->getName();
Nate Begeman7e5185b2009-01-18 02:01:21 +00003378
3379 // Halving swizzles do not contain duplicate elements.
Daniel Dunbar125c9c92009-10-17 23:53:04 +00003380 if (Comp == "hi" || Comp == "lo" || Comp == "even" || Comp == "odd")
Nate Begeman7e5185b2009-01-18 02:01:21 +00003381 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003382
Nate Begeman7e5185b2009-01-18 02:01:21 +00003383 // Advance past s-char prefix on hex swizzles.
Daniel Dunbar125c9c92009-10-17 23:53:04 +00003384 if (Comp[0] == 's' || Comp[0] == 'S')
3385 Comp = Comp.substr(1);
Mike Stump11289f42009-09-09 15:08:12 +00003386
Daniel Dunbar125c9c92009-10-17 23:53:04 +00003387 for (unsigned i = 0, e = Comp.size(); i != e; ++i)
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003388 if (Comp.substr(i + 1).find(Comp[i]) != StringRef::npos)
Steve Naroff0d595ca2007-07-30 03:29:09 +00003389 return true;
Daniel Dunbar125c9c92009-10-17 23:53:04 +00003390
Steve Naroff0d595ca2007-07-30 03:29:09 +00003391 return false;
3392}
Chris Lattner885b4952007-08-02 23:36:59 +00003393
Nate Begemanf322eab2008-05-09 06:41:27 +00003394/// getEncodedElementAccess - We encode the fields as a llvm ConstantArray.
Nate Begemand3862152008-05-13 21:03:02 +00003395void ExtVectorElementExpr::getEncodedElementAccess(
Benjamin Kramer99383102015-07-28 16:25:32 +00003396 SmallVectorImpl<uint32_t> &Elts) const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003397 StringRef Comp = Accessor->getName();
Pirama Arumuga Nainar98eaa622016-07-22 18:49:43 +00003398 bool isNumericAccessor = false;
3399 if (Comp[0] == 's' || Comp[0] == 'S') {
Daniel Dunbarce5a0b32009-10-18 02:09:31 +00003400 Comp = Comp.substr(1);
Pirama Arumuga Nainar98eaa622016-07-22 18:49:43 +00003401 isNumericAccessor = true;
3402 }
Mike Stump11289f42009-09-09 15:08:12 +00003403
Daniel Dunbarce5a0b32009-10-18 02:09:31 +00003404 bool isHi = Comp == "hi";
3405 bool isLo = Comp == "lo";
3406 bool isEven = Comp == "even";
3407 bool isOdd = Comp == "odd";
Mike Stump11289f42009-09-09 15:08:12 +00003408
Nate Begemanf322eab2008-05-09 06:41:27 +00003409 for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
3410 uint64_t Index;
Mike Stump11289f42009-09-09 15:08:12 +00003411
Nate Begemanf322eab2008-05-09 06:41:27 +00003412 if (isHi)
3413 Index = e + i;
3414 else if (isLo)
3415 Index = i;
3416 else if (isEven)
3417 Index = 2 * i;
3418 else if (isOdd)
3419 Index = 2 * i + 1;
3420 else
Pirama Arumuga Nainar98eaa622016-07-22 18:49:43 +00003421 Index = ExtVectorType::getAccessorIdx(Comp[i], isNumericAccessor);
Chris Lattner885b4952007-08-02 23:36:59 +00003422
Nate Begemand3862152008-05-13 21:03:02 +00003423 Elts.push_back(Index);
Chris Lattner885b4952007-08-02 23:36:59 +00003424 }
Nate Begemanf322eab2008-05-09 06:41:27 +00003425}
3426
Craig Topper37932912013-08-18 10:09:15 +00003427ShuffleVectorExpr::ShuffleVectorExpr(const ASTContext &C, ArrayRef<Expr*> args,
Douglas Gregora6e053e2010-12-15 01:34:56 +00003428 QualType Type, SourceLocation BLoc,
3429 SourceLocation RP)
3430 : Expr(ShuffleVectorExprClass, Type, VK_RValue, OK_Ordinary,
3431 Type->isDependentType(), Type->isDependentType(),
Douglas Gregor678d76c2011-07-01 01:22:09 +00003432 Type->isInstantiationDependentType(),
Douglas Gregora6e053e2010-12-15 01:34:56 +00003433 Type->containsUnexpandedParameterPack()),
Benjamin Kramerc215e762012-08-24 11:54:20 +00003434 BuiltinLoc(BLoc), RParenLoc(RP), NumExprs(args.size())
Douglas Gregora6e053e2010-12-15 01:34:56 +00003435{
Benjamin Kramerc215e762012-08-24 11:54:20 +00003436 SubExprs = new (C) Stmt*[args.size()];
3437 for (unsigned i = 0; i != args.size(); i++) {
Douglas Gregora6e053e2010-12-15 01:34:56 +00003438 if (args[i]->isTypeDependent())
3439 ExprBits.TypeDependent = true;
3440 if (args[i]->isValueDependent())
3441 ExprBits.ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003442 if (args[i]->isInstantiationDependent())
3443 ExprBits.InstantiationDependent = true;
Douglas Gregora6e053e2010-12-15 01:34:56 +00003444 if (args[i]->containsUnexpandedParameterPack())
3445 ExprBits.ContainsUnexpandedParameterPack = true;
3446
3447 SubExprs[i] = args[i];
3448 }
3449}
3450
Craig Topper37932912013-08-18 10:09:15 +00003451void ShuffleVectorExpr::setExprs(const ASTContext &C, ArrayRef<Expr *> Exprs) {
Nate Begeman48745922009-08-12 02:28:50 +00003452 if (SubExprs) C.Deallocate(SubExprs);
3453
Dmitri Gribenko674eaa22013-05-10 00:43:44 +00003454 this->NumExprs = Exprs.size();
Dmitri Gribenko48d6daf2013-05-10 17:30:13 +00003455 SubExprs = new (C) Stmt*[NumExprs];
Dmitri Gribenko674eaa22013-05-10 00:43:44 +00003456 memcpy(SubExprs, Exprs.data(), sizeof(Expr *) * Exprs.size());
Mike Stump11289f42009-09-09 15:08:12 +00003457}
Nate Begeman48745922009-08-12 02:28:50 +00003458
Craig Topper37932912013-08-18 10:09:15 +00003459GenericSelectionExpr::GenericSelectionExpr(const ASTContext &Context,
Peter Collingbourne91147592011-04-15 00:35:48 +00003460 SourceLocation GenericLoc, Expr *ControllingExpr,
Benjamin Kramerc215e762012-08-24 11:54:20 +00003461 ArrayRef<TypeSourceInfo*> AssocTypes,
3462 ArrayRef<Expr*> AssocExprs,
3463 SourceLocation DefaultLoc,
Peter Collingbourne91147592011-04-15 00:35:48 +00003464 SourceLocation RParenLoc,
3465 bool ContainsUnexpandedParameterPack,
3466 unsigned ResultIndex)
3467 : Expr(GenericSelectionExprClass,
3468 AssocExprs[ResultIndex]->getType(),
3469 AssocExprs[ResultIndex]->getValueKind(),
3470 AssocExprs[ResultIndex]->getObjectKind(),
3471 AssocExprs[ResultIndex]->isTypeDependent(),
3472 AssocExprs[ResultIndex]->isValueDependent(),
Douglas Gregor678d76c2011-07-01 01:22:09 +00003473 AssocExprs[ResultIndex]->isInstantiationDependent(),
Peter Collingbourne91147592011-04-15 00:35:48 +00003474 ContainsUnexpandedParameterPack),
Benjamin Kramerc215e762012-08-24 11:54:20 +00003475 AssocTypes(new (Context) TypeSourceInfo*[AssocTypes.size()]),
3476 SubExprs(new (Context) Stmt*[END_EXPR+AssocExprs.size()]),
3477 NumAssocs(AssocExprs.size()), ResultIndex(ResultIndex),
3478 GenericLoc(GenericLoc), DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
Peter Collingbourne91147592011-04-15 00:35:48 +00003479 SubExprs[CONTROLLING] = ControllingExpr;
Benjamin Kramerc215e762012-08-24 11:54:20 +00003480 assert(AssocTypes.size() == AssocExprs.size());
3481 std::copy(AssocTypes.begin(), AssocTypes.end(), this->AssocTypes);
3482 std::copy(AssocExprs.begin(), AssocExprs.end(), SubExprs+END_EXPR);
Peter Collingbourne91147592011-04-15 00:35:48 +00003483}
3484
Craig Topper37932912013-08-18 10:09:15 +00003485GenericSelectionExpr::GenericSelectionExpr(const ASTContext &Context,
Peter Collingbourne91147592011-04-15 00:35:48 +00003486 SourceLocation GenericLoc, Expr *ControllingExpr,
Benjamin Kramerc215e762012-08-24 11:54:20 +00003487 ArrayRef<TypeSourceInfo*> AssocTypes,
3488 ArrayRef<Expr*> AssocExprs,
3489 SourceLocation DefaultLoc,
Peter Collingbourne91147592011-04-15 00:35:48 +00003490 SourceLocation RParenLoc,
3491 bool ContainsUnexpandedParameterPack)
3492 : Expr(GenericSelectionExprClass,
3493 Context.DependentTy,
3494 VK_RValue,
3495 OK_Ordinary,
Douglas Gregor678d76c2011-07-01 01:22:09 +00003496 /*isTypeDependent=*/true,
3497 /*isValueDependent=*/true,
3498 /*isInstantiationDependent=*/true,
Peter Collingbourne91147592011-04-15 00:35:48 +00003499 ContainsUnexpandedParameterPack),
Benjamin Kramerc215e762012-08-24 11:54:20 +00003500 AssocTypes(new (Context) TypeSourceInfo*[AssocTypes.size()]),
3501 SubExprs(new (Context) Stmt*[END_EXPR+AssocExprs.size()]),
3502 NumAssocs(AssocExprs.size()), ResultIndex(-1U), GenericLoc(GenericLoc),
3503 DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
Peter Collingbourne91147592011-04-15 00:35:48 +00003504 SubExprs[CONTROLLING] = ControllingExpr;
Benjamin Kramerc215e762012-08-24 11:54:20 +00003505 assert(AssocTypes.size() == AssocExprs.size());
3506 std::copy(AssocTypes.begin(), AssocTypes.end(), this->AssocTypes);
3507 std::copy(AssocExprs.begin(), AssocExprs.end(), SubExprs+END_EXPR);
Peter Collingbourne91147592011-04-15 00:35:48 +00003508}
3509
Ted Kremenek85e92ec2007-08-24 18:13:47 +00003510//===----------------------------------------------------------------------===//
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003511// DesignatedInitExpr
3512//===----------------------------------------------------------------------===//
3513
Chandler Carruth631abd92011-06-16 06:47:06 +00003514IdentifierInfo *DesignatedInitExpr::Designator::getFieldName() const {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003515 assert(Kind == FieldDesignator && "Only valid on a field designator");
3516 if (Field.NameOrField & 0x01)
3517 return reinterpret_cast<IdentifierInfo *>(Field.NameOrField&~0x01);
3518 else
3519 return getField()->getIdentifier();
3520}
3521
Craig Topper37932912013-08-18 10:09:15 +00003522DesignatedInitExpr::DesignatedInitExpr(const ASTContext &C, QualType Ty,
David Majnemerf7e36092016-06-23 00:15:04 +00003523 llvm::ArrayRef<Designator> Designators,
Mike Stump11289f42009-09-09 15:08:12 +00003524 SourceLocation EqualOrColonLoc,
Douglas Gregord5846a12009-04-15 06:41:24 +00003525 bool GNUSyntax,
Benjamin Kramerc215e762012-08-24 11:54:20 +00003526 ArrayRef<Expr*> IndexExprs,
Douglas Gregorca1aeec2009-05-21 23:17:49 +00003527 Expr *Init)
Mike Stump11289f42009-09-09 15:08:12 +00003528 : Expr(DesignatedInitExprClass, Ty,
John McCall7decc9e2010-11-18 06:31:45 +00003529 Init->getValueKind(), Init->getObjectKind(),
Douglas Gregora6e053e2010-12-15 01:34:56 +00003530 Init->isTypeDependent(), Init->isValueDependent(),
Douglas Gregor678d76c2011-07-01 01:22:09 +00003531 Init->isInstantiationDependent(),
Douglas Gregora6e053e2010-12-15 01:34:56 +00003532 Init->containsUnexpandedParameterPack()),
Mike Stump11289f42009-09-09 15:08:12 +00003533 EqualOrColonLoc(EqualOrColonLoc), GNUSyntax(GNUSyntax),
David Majnemerf7e36092016-06-23 00:15:04 +00003534 NumDesignators(Designators.size()), NumSubExprs(IndexExprs.size() + 1) {
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00003535 this->Designators = new (C) Designator[NumDesignators];
Douglas Gregorca1aeec2009-05-21 23:17:49 +00003536
3537 // Record the initializer itself.
Benjamin Kramer5733e352015-07-18 17:09:36 +00003538 child_iterator Child = child_begin();
Douglas Gregorca1aeec2009-05-21 23:17:49 +00003539 *Child++ = Init;
3540
3541 // Copy the designators and their subexpressions, computing
3542 // value-dependence along the way.
3543 unsigned IndexIdx = 0;
3544 for (unsigned I = 0; I != NumDesignators; ++I) {
Douglas Gregord5846a12009-04-15 06:41:24 +00003545 this->Designators[I] = Designators[I];
Douglas Gregorca1aeec2009-05-21 23:17:49 +00003546
3547 if (this->Designators[I].isArrayDesignator()) {
3548 // Compute type- and value-dependence.
3549 Expr *Index = IndexExprs[IndexIdx];
Douglas Gregora6e053e2010-12-15 01:34:56 +00003550 if (Index->isTypeDependent() || Index->isValueDependent())
David Majnemer4f217682015-01-09 01:39:09 +00003551 ExprBits.TypeDependent = ExprBits.ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003552 if (Index->isInstantiationDependent())
3553 ExprBits.InstantiationDependent = true;
Douglas Gregora6e053e2010-12-15 01:34:56 +00003554 // Propagate unexpanded parameter packs.
3555 if (Index->containsUnexpandedParameterPack())
3556 ExprBits.ContainsUnexpandedParameterPack = true;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00003557
3558 // Copy the index expressions into permanent storage.
3559 *Child++ = IndexExprs[IndexIdx++];
3560 } else if (this->Designators[I].isArrayRangeDesignator()) {
3561 // Compute type- and value-dependence.
3562 Expr *Start = IndexExprs[IndexIdx];
3563 Expr *End = IndexExprs[IndexIdx + 1];
Douglas Gregora6e053e2010-12-15 01:34:56 +00003564 if (Start->isTypeDependent() || Start->isValueDependent() ||
Douglas Gregor678d76c2011-07-01 01:22:09 +00003565 End->isTypeDependent() || End->isValueDependent()) {
David Majnemer4f217682015-01-09 01:39:09 +00003566 ExprBits.TypeDependent = ExprBits.ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003567 ExprBits.InstantiationDependent = true;
3568 } else if (Start->isInstantiationDependent() ||
3569 End->isInstantiationDependent()) {
3570 ExprBits.InstantiationDependent = true;
3571 }
3572
Douglas Gregora6e053e2010-12-15 01:34:56 +00003573 // Propagate unexpanded parameter packs.
3574 if (Start->containsUnexpandedParameterPack() ||
3575 End->containsUnexpandedParameterPack())
3576 ExprBits.ContainsUnexpandedParameterPack = true;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00003577
3578 // Copy the start/end expressions into permanent storage.
3579 *Child++ = IndexExprs[IndexIdx++];
3580 *Child++ = IndexExprs[IndexIdx++];
3581 }
3582 }
3583
Benjamin Kramerc215e762012-08-24 11:54:20 +00003584 assert(IndexIdx == IndexExprs.size() && "Wrong number of index expressions");
Douglas Gregord5846a12009-04-15 06:41:24 +00003585}
3586
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003587DesignatedInitExpr *
David Majnemerf7e36092016-06-23 00:15:04 +00003588DesignatedInitExpr::Create(const ASTContext &C,
3589 llvm::ArrayRef<Designator> Designators,
Benjamin Kramerc215e762012-08-24 11:54:20 +00003590 ArrayRef<Expr*> IndexExprs,
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003591 SourceLocation ColonOrEqualLoc,
3592 bool UsesColonSyntax, Expr *Init) {
James Y Knighte00a67e2015-12-31 04:18:25 +00003593 void *Mem = C.Allocate(totalSizeToAlloc<Stmt *>(IndexExprs.size() + 1),
James Y Knight53c76162015-07-17 18:21:37 +00003594 llvm::alignOf<DesignatedInitExpr>());
David Majnemerf7e36092016-06-23 00:15:04 +00003595 return new (Mem) DesignatedInitExpr(C, C.VoidTy, Designators,
Douglas Gregorca1aeec2009-05-21 23:17:49 +00003596 ColonOrEqualLoc, UsesColonSyntax,
Benjamin Kramerc215e762012-08-24 11:54:20 +00003597 IndexExprs, Init);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003598}
3599
Craig Topper37932912013-08-18 10:09:15 +00003600DesignatedInitExpr *DesignatedInitExpr::CreateEmpty(const ASTContext &C,
Douglas Gregor38676d52009-04-16 00:55:48 +00003601 unsigned NumIndexExprs) {
James Y Knighte00a67e2015-12-31 04:18:25 +00003602 void *Mem = C.Allocate(totalSizeToAlloc<Stmt *>(NumIndexExprs + 1),
3603 llvm::alignOf<DesignatedInitExpr>());
Douglas Gregor38676d52009-04-16 00:55:48 +00003604 return new (Mem) DesignatedInitExpr(NumIndexExprs + 1);
3605}
3606
Craig Topper37932912013-08-18 10:09:15 +00003607void DesignatedInitExpr::setDesignators(const ASTContext &C,
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00003608 const Designator *Desigs,
Douglas Gregor38676d52009-04-16 00:55:48 +00003609 unsigned NumDesigs) {
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00003610 Designators = new (C) Designator[NumDesigs];
Douglas Gregor38676d52009-04-16 00:55:48 +00003611 NumDesignators = NumDesigs;
3612 for (unsigned I = 0; I != NumDesigs; ++I)
3613 Designators[I] = Desigs[I];
3614}
3615
Abramo Bagnara22f8cd72011-03-16 15:08:46 +00003616SourceRange DesignatedInitExpr::getDesignatorsSourceRange() const {
3617 DesignatedInitExpr *DIE = const_cast<DesignatedInitExpr*>(this);
3618 if (size() == 1)
3619 return DIE->getDesignator(0)->getSourceRange();
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00003620 return SourceRange(DIE->getDesignator(0)->getLocStart(),
3621 DIE->getDesignator(size()-1)->getLocEnd());
Abramo Bagnara22f8cd72011-03-16 15:08:46 +00003622}
3623
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00003624SourceLocation DesignatedInitExpr::getLocStart() const {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003625 SourceLocation StartLoc;
David Majnemerf7e36092016-06-23 00:15:04 +00003626 auto *DIE = const_cast<DesignatedInitExpr *>(this);
3627 Designator &First = *DIE->getDesignator(0);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003628 if (First.isFieldDesignator()) {
Douglas Gregor5c7c9cb2009-03-28 00:41:23 +00003629 if (GNUSyntax)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003630 StartLoc = SourceLocation::getFromRawEncoding(First.Field.FieldLoc);
3631 else
3632 StartLoc = SourceLocation::getFromRawEncoding(First.Field.DotLoc);
3633 } else
Chris Lattner8ba22472009-02-16 22:33:34 +00003634 StartLoc =
3635 SourceLocation::getFromRawEncoding(First.ArrayOrRange.LBracketLoc);
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00003636 return StartLoc;
3637}
3638
3639SourceLocation DesignatedInitExpr::getLocEnd() const {
3640 return getInit()->getLocEnd();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003641}
3642
Dmitri Gribenkod06f7ff2013-01-26 15:15:52 +00003643Expr *DesignatedInitExpr::getArrayIndex(const Designator& D) const {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003644 assert(D.Kind == Designator::ArrayDesignator && "Requires array designator");
James Y Knighte00a67e2015-12-31 04:18:25 +00003645 return getSubExpr(D.ArrayOrRange.Index + 1);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003646}
3647
Dmitri Gribenkod06f7ff2013-01-26 15:15:52 +00003648Expr *DesignatedInitExpr::getArrayRangeStart(const Designator &D) const {
Mike Stump11289f42009-09-09 15:08:12 +00003649 assert(D.Kind == Designator::ArrayRangeDesignator &&
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003650 "Requires array range designator");
James Y Knighte00a67e2015-12-31 04:18:25 +00003651 return getSubExpr(D.ArrayOrRange.Index + 1);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003652}
3653
Dmitri Gribenkod06f7ff2013-01-26 15:15:52 +00003654Expr *DesignatedInitExpr::getArrayRangeEnd(const Designator &D) const {
Mike Stump11289f42009-09-09 15:08:12 +00003655 assert(D.Kind == Designator::ArrayRangeDesignator &&
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003656 "Requires array range designator");
James Y Knighte00a67e2015-12-31 04:18:25 +00003657 return getSubExpr(D.ArrayOrRange.Index + 2);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003658}
3659
Douglas Gregord5846a12009-04-15 06:41:24 +00003660/// \brief Replaces the designator at index @p Idx with the series
3661/// of designators in [First, Last).
Craig Topper37932912013-08-18 10:09:15 +00003662void DesignatedInitExpr::ExpandDesignator(const ASTContext &C, unsigned Idx,
Mike Stump11289f42009-09-09 15:08:12 +00003663 const Designator *First,
Douglas Gregord5846a12009-04-15 06:41:24 +00003664 const Designator *Last) {
3665 unsigned NumNewDesignators = Last - First;
3666 if (NumNewDesignators == 0) {
3667 std::copy_backward(Designators + Idx + 1,
3668 Designators + NumDesignators,
3669 Designators + Idx);
3670 --NumNewDesignators;
3671 return;
3672 } else if (NumNewDesignators == 1) {
3673 Designators[Idx] = *First;
3674 return;
3675 }
3676
Mike Stump11289f42009-09-09 15:08:12 +00003677 Designator *NewDesignators
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00003678 = new (C) Designator[NumDesignators - 1 + NumNewDesignators];
Douglas Gregord5846a12009-04-15 06:41:24 +00003679 std::copy(Designators, Designators + Idx, NewDesignators);
3680 std::copy(First, Last, NewDesignators + Idx);
3681 std::copy(Designators + Idx + 1, Designators + NumDesignators,
3682 NewDesignators + Idx + NumNewDesignators);
Douglas Gregord5846a12009-04-15 06:41:24 +00003683 Designators = NewDesignators;
3684 NumDesignators = NumDesignators - 1 + NumNewDesignators;
3685}
3686
Yunzhong Gaocb779302015-06-10 00:27:52 +00003687DesignatedInitUpdateExpr::DesignatedInitUpdateExpr(const ASTContext &C,
3688 SourceLocation lBraceLoc, Expr *baseExpr, SourceLocation rBraceLoc)
3689 : Expr(DesignatedInitUpdateExprClass, baseExpr->getType(), VK_RValue,
3690 OK_Ordinary, false, false, false, false) {
3691 BaseAndUpdaterExprs[0] = baseExpr;
3692
3693 InitListExpr *ILE = new (C) InitListExpr(C, lBraceLoc, None, rBraceLoc);
3694 ILE->setType(baseExpr->getType());
3695 BaseAndUpdaterExprs[1] = ILE;
3696}
3697
3698SourceLocation DesignatedInitUpdateExpr::getLocStart() const {
3699 return getBase()->getLocStart();
3700}
3701
3702SourceLocation DesignatedInitUpdateExpr::getLocEnd() const {
3703 return getBase()->getLocEnd();
3704}
3705
Craig Topper37932912013-08-18 10:09:15 +00003706ParenListExpr::ParenListExpr(const ASTContext& C, SourceLocation lparenloc,
Benjamin Kramerc215e762012-08-24 11:54:20 +00003707 ArrayRef<Expr*> exprs,
Sebastian Redla9351792012-02-11 23:51:47 +00003708 SourceLocation rparenloc)
3709 : Expr(ParenListExprClass, QualType(), VK_RValue, OK_Ordinary,
Douglas Gregor678d76c2011-07-01 01:22:09 +00003710 false, false, false, false),
Benjamin Kramerc215e762012-08-24 11:54:20 +00003711 NumExprs(exprs.size()), LParenLoc(lparenloc), RParenLoc(rparenloc) {
3712 Exprs = new (C) Stmt*[exprs.size()];
3713 for (unsigned i = 0; i != exprs.size(); ++i) {
Douglas Gregora6e053e2010-12-15 01:34:56 +00003714 if (exprs[i]->isTypeDependent())
3715 ExprBits.TypeDependent = true;
3716 if (exprs[i]->isValueDependent())
3717 ExprBits.ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003718 if (exprs[i]->isInstantiationDependent())
3719 ExprBits.InstantiationDependent = true;
Douglas Gregora6e053e2010-12-15 01:34:56 +00003720 if (exprs[i]->containsUnexpandedParameterPack())
3721 ExprBits.ContainsUnexpandedParameterPack = true;
3722
Nate Begeman5ec4b312009-08-10 23:49:36 +00003723 Exprs[i] = exprs[i];
Douglas Gregora6e053e2010-12-15 01:34:56 +00003724 }
Nate Begeman5ec4b312009-08-10 23:49:36 +00003725}
3726
John McCall1bf58462011-02-16 08:02:54 +00003727const OpaqueValueExpr *OpaqueValueExpr::findInCopyConstruct(const Expr *e) {
3728 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(e))
3729 e = ewc->getSubExpr();
Douglas Gregorfe314812011-06-21 17:03:29 +00003730 if (const MaterializeTemporaryExpr *m = dyn_cast<MaterializeTemporaryExpr>(e))
3731 e = m->GetTemporaryExpr();
John McCall1bf58462011-02-16 08:02:54 +00003732 e = cast<CXXConstructExpr>(e)->getArg(0);
3733 while (const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
3734 e = ice->getSubExpr();
3735 return cast<OpaqueValueExpr>(e);
3736}
3737
Craig Topper37932912013-08-18 10:09:15 +00003738PseudoObjectExpr *PseudoObjectExpr::Create(const ASTContext &Context,
3739 EmptyShell sh,
John McCallfe96e0b2011-11-06 09:01:30 +00003740 unsigned numSemanticExprs) {
James Y Knighte00a67e2015-12-31 04:18:25 +00003741 void *buffer =
3742 Context.Allocate(totalSizeToAlloc<Expr *>(1 + numSemanticExprs),
3743 llvm::alignOf<PseudoObjectExpr>());
John McCallfe96e0b2011-11-06 09:01:30 +00003744 return new(buffer) PseudoObjectExpr(sh, numSemanticExprs);
3745}
3746
3747PseudoObjectExpr::PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs)
3748 : Expr(PseudoObjectExprClass, shell) {
3749 PseudoObjectExprBits.NumSubExprs = numSemanticExprs + 1;
3750}
3751
Craig Topper37932912013-08-18 10:09:15 +00003752PseudoObjectExpr *PseudoObjectExpr::Create(const ASTContext &C, Expr *syntax,
John McCallfe96e0b2011-11-06 09:01:30 +00003753 ArrayRef<Expr*> semantics,
3754 unsigned resultIndex) {
3755 assert(syntax && "no syntactic expression!");
3756 assert(semantics.size() && "no semantic expressions!");
3757
3758 QualType type;
3759 ExprValueKind VK;
3760 if (resultIndex == NoResult) {
3761 type = C.VoidTy;
3762 VK = VK_RValue;
3763 } else {
3764 assert(resultIndex < semantics.size());
3765 type = semantics[resultIndex]->getType();
3766 VK = semantics[resultIndex]->getValueKind();
3767 assert(semantics[resultIndex]->getObjectKind() == OK_Ordinary);
3768 }
3769
James Y Knighte00a67e2015-12-31 04:18:25 +00003770 void *buffer = C.Allocate(totalSizeToAlloc<Expr *>(semantics.size() + 1),
John McCallfe96e0b2011-11-06 09:01:30 +00003771 llvm::alignOf<PseudoObjectExpr>());
3772 return new(buffer) PseudoObjectExpr(type, VK, syntax, semantics,
3773 resultIndex);
3774}
3775
3776PseudoObjectExpr::PseudoObjectExpr(QualType type, ExprValueKind VK,
3777 Expr *syntax, ArrayRef<Expr*> semantics,
3778 unsigned resultIndex)
3779 : Expr(PseudoObjectExprClass, type, VK, OK_Ordinary,
3780 /*filled in at end of ctor*/ false, false, false, false) {
3781 PseudoObjectExprBits.NumSubExprs = semantics.size() + 1;
3782 PseudoObjectExprBits.ResultIndex = resultIndex + 1;
3783
3784 for (unsigned i = 0, e = semantics.size() + 1; i != e; ++i) {
3785 Expr *E = (i == 0 ? syntax : semantics[i-1]);
3786 getSubExprsBuffer()[i] = E;
3787
3788 if (E->isTypeDependent())
3789 ExprBits.TypeDependent = true;
3790 if (E->isValueDependent())
3791 ExprBits.ValueDependent = true;
3792 if (E->isInstantiationDependent())
3793 ExprBits.InstantiationDependent = true;
3794 if (E->containsUnexpandedParameterPack())
3795 ExprBits.ContainsUnexpandedParameterPack = true;
3796
3797 if (isa<OpaqueValueExpr>(E))
Craig Topper36250ad2014-05-12 05:36:57 +00003798 assert(cast<OpaqueValueExpr>(E)->getSourceExpr() != nullptr &&
John McCallfe96e0b2011-11-06 09:01:30 +00003799 "opaque-value semantic expressions for pseudo-object "
3800 "operations must have sources");
3801 }
3802}
3803
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003804//===----------------------------------------------------------------------===//
Ted Kremenek85e92ec2007-08-24 18:13:47 +00003805// Child Iterators for iterating over subexpressions/substatements
3806//===----------------------------------------------------------------------===//
3807
Peter Collingbournee190dee2011-03-11 19:24:49 +00003808// UnaryExprOrTypeTraitExpr
3809Stmt::child_range UnaryExprOrTypeTraitExpr::children() {
Sebastian Redl6f282892008-11-11 17:56:53 +00003810 // If this is of a type and the type is a VLA type (and not a typedef), the
3811 // size expression of the VLA needs to be treated as an executable expression.
3812 // Why isn't this weirdness documented better in StmtIterator?
3813 if (isArgumentType()) {
John McCall424cec92011-01-19 06:33:43 +00003814 if (const VariableArrayType* T = dyn_cast<VariableArrayType>(
Sebastian Redl6f282892008-11-11 17:56:53 +00003815 getArgumentType().getTypePtr()))
John McCallbd066782011-02-09 08:16:59 +00003816 return child_range(child_iterator(T), child_iterator());
Benjamin Kramer5733e352015-07-18 17:09:36 +00003817 return child_range(child_iterator(), child_iterator());
Sebastian Redl6f282892008-11-11 17:56:53 +00003818 }
John McCallbd066782011-02-09 08:16:59 +00003819 return child_range(&Argument.Ex, &Argument.Ex + 1);
Ted Kremenek04746ce2007-10-18 23:28:49 +00003820}
Fariborz Jahaniana32aaef2007-10-17 16:58:11 +00003821
Benjamin Kramerc215e762012-08-24 11:54:20 +00003822AtomicExpr::AtomicExpr(SourceLocation BLoc, ArrayRef<Expr*> args,
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003823 QualType t, AtomicOp op, SourceLocation RP)
3824 : Expr(AtomicExprClass, t, VK_RValue, OK_Ordinary,
3825 false, false, false, false),
Benjamin Kramerc215e762012-08-24 11:54:20 +00003826 NumSubExprs(args.size()), BuiltinLoc(BLoc), RParenLoc(RP), Op(op)
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003827{
Benjamin Kramerc215e762012-08-24 11:54:20 +00003828 assert(args.size() == getNumSubExprs(op) && "wrong number of subexpressions");
3829 for (unsigned i = 0; i != args.size(); i++) {
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003830 if (args[i]->isTypeDependent())
3831 ExprBits.TypeDependent = true;
3832 if (args[i]->isValueDependent())
3833 ExprBits.ValueDependent = true;
3834 if (args[i]->isInstantiationDependent())
3835 ExprBits.InstantiationDependent = true;
3836 if (args[i]->containsUnexpandedParameterPack())
3837 ExprBits.ContainsUnexpandedParameterPack = true;
3838
3839 SubExprs[i] = args[i];
3840 }
3841}
Richard Smithaa22a8c2012-04-10 22:49:28 +00003842
3843unsigned AtomicExpr::getNumSubExprs(AtomicOp Op) {
3844 switch (Op) {
Richard Smithfeea8832012-04-12 05:08:17 +00003845 case AO__c11_atomic_init:
3846 case AO__c11_atomic_load:
3847 case AO__atomic_load_n:
Richard Smithaa22a8c2012-04-10 22:49:28 +00003848 return 2;
Richard Smithfeea8832012-04-12 05:08:17 +00003849
3850 case AO__c11_atomic_store:
3851 case AO__c11_atomic_exchange:
3852 case AO__atomic_load:
3853 case AO__atomic_store:
3854 case AO__atomic_store_n:
3855 case AO__atomic_exchange_n:
3856 case AO__c11_atomic_fetch_add:
3857 case AO__c11_atomic_fetch_sub:
3858 case AO__c11_atomic_fetch_and:
3859 case AO__c11_atomic_fetch_or:
3860 case AO__c11_atomic_fetch_xor:
3861 case AO__atomic_fetch_add:
3862 case AO__atomic_fetch_sub:
3863 case AO__atomic_fetch_and:
3864 case AO__atomic_fetch_or:
3865 case AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00003866 case AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00003867 case AO__atomic_add_fetch:
3868 case AO__atomic_sub_fetch:
3869 case AO__atomic_and_fetch:
3870 case AO__atomic_or_fetch:
3871 case AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00003872 case AO__atomic_nand_fetch:
Richard Smithaa22a8c2012-04-10 22:49:28 +00003873 return 3;
Richard Smithfeea8832012-04-12 05:08:17 +00003874
3875 case AO__atomic_exchange:
3876 return 4;
3877
3878 case AO__c11_atomic_compare_exchange_strong:
3879 case AO__c11_atomic_compare_exchange_weak:
Richard Smithaa22a8c2012-04-10 22:49:28 +00003880 return 5;
Richard Smithfeea8832012-04-12 05:08:17 +00003881
3882 case AO__atomic_compare_exchange:
3883 case AO__atomic_compare_exchange_n:
3884 return 6;
Richard Smithaa22a8c2012-04-10 22:49:28 +00003885 }
3886 llvm_unreachable("unknown atomic op");
3887}
Alexey Bataeva1764212015-09-30 09:22:36 +00003888
Alexey Bataev31300ed2016-02-04 11:27:03 +00003889QualType OMPArraySectionExpr::getBaseOriginalType(const Expr *Base) {
Alexey Bataeva1764212015-09-30 09:22:36 +00003890 unsigned ArraySectionCount = 0;
3891 while (auto *OASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParens())) {
3892 Base = OASE->getBase();
3893 ++ArraySectionCount;
3894 }
Alexey Bataev31300ed2016-02-04 11:27:03 +00003895 while (auto *ASE =
3896 dyn_cast<ArraySubscriptExpr>(Base->IgnoreParenImpCasts())) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003897 Base = ASE->getBase();
3898 ++ArraySectionCount;
3899 }
Alexey Bataev31300ed2016-02-04 11:27:03 +00003900 Base = Base->IgnoreParenImpCasts();
Alexey Bataeva1764212015-09-30 09:22:36 +00003901 auto OriginalTy = Base->getType();
3902 if (auto *DRE = dyn_cast<DeclRefExpr>(Base))
3903 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
3904 OriginalTy = PVD->getOriginalType().getNonReferenceType();
3905
3906 for (unsigned Cnt = 0; Cnt < ArraySectionCount; ++Cnt) {
3907 if (OriginalTy->isAnyPointerType())
3908 OriginalTy = OriginalTy->getPointeeType();
3909 else {
3910 assert (OriginalTy->isArrayType());
3911 OriginalTy = OriginalTy->castAsArrayTypeUnsafe()->getElementType();
3912 }
3913 }
3914 return OriginalTy;
3915}