blob: 6f0b5fe6d512d87afdb7d82eeda342cda704b005 [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
Richard Smith018ac392016-11-03 18:55:18 +000038const Expr *Expr::getBestDynamicClassTypeExpr() const {
39 const Expr *E = this;
40 while (true) {
41 E = E->ignoreParenBaseCasts();
Rafael Espindola49e860b2012-06-26 17:45:31 +000042
Richard Smith018ac392016-11-03 18:55:18 +000043 // Follow the RHS of a comma operator.
44 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
45 if (BO->getOpcode() == BO_Comma) {
46 E = BO->getRHS();
47 continue;
48 }
49 }
50
51 // Step into initializer for materialized temporaries.
52 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
53 E = MTE->GetTemporaryExpr();
54 continue;
55 }
56
57 break;
58 }
59
60 return E;
61}
62
63const CXXRecordDecl *Expr::getBestDynamicClassType() const {
64 const Expr *E = getBestDynamicClassTypeExpr();
Rafael Espindola49e860b2012-06-26 17:45:31 +000065 QualType DerivedType = E->getType();
Rafael Espindola49e860b2012-06-26 17:45:31 +000066 if (const PointerType *PTy = DerivedType->getAs<PointerType>())
67 DerivedType = PTy->getPointeeType();
68
Rafael Espindola60a2bba2012-07-17 20:24:05 +000069 if (DerivedType->isDependentType())
Craig Topper36250ad2014-05-12 05:36:57 +000070 return nullptr;
Rafael Espindola60a2bba2012-07-17 20:24:05 +000071
Rafael Espindola49e860b2012-06-26 17:45:31 +000072 const RecordType *Ty = DerivedType->castAs<RecordType>();
Rafael Espindola49e860b2012-06-26 17:45:31 +000073 Decl *D = Ty->getDecl();
74 return cast<CXXRecordDecl>(D);
75}
76
Richard Smithf3fabd22013-06-03 00:17:11 +000077const Expr *Expr::skipRValueSubobjectAdjustments(
78 SmallVectorImpl<const Expr *> &CommaLHSs,
79 SmallVectorImpl<SubobjectAdjustment> &Adjustments) const {
Rafael Espindola9c006de2012-10-27 01:03:43 +000080 const Expr *E = this;
81 while (true) {
82 E = E->IgnoreParens();
83
84 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
85 if ((CE->getCastKind() == CK_DerivedToBase ||
86 CE->getCastKind() == CK_UncheckedDerivedToBase) &&
87 E->getType()->isRecordType()) {
88 E = CE->getSubExpr();
89 CXXRecordDecl *Derived
90 = cast<CXXRecordDecl>(E->getType()->getAs<RecordType>()->getDecl());
91 Adjustments.push_back(SubobjectAdjustment(CE, Derived));
92 continue;
93 }
94
95 if (CE->getCastKind() == CK_NoOp) {
96 E = CE->getSubExpr();
97 continue;
98 }
99 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
Richard Smith6b6f8aa2013-06-15 00:30:29 +0000100 if (!ME->isArrow()) {
Rafael Espindola9c006de2012-10-27 01:03:43 +0000101 assert(ME->getBase()->getType()->isRecordType());
102 if (FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
Richard Smith6b6f8aa2013-06-15 00:30:29 +0000103 if (!Field->isBitField() && !Field->getType()->isReferenceType()) {
Richard Smith2d187902013-06-03 07:13:35 +0000104 E = ME->getBase();
105 Adjustments.push_back(SubobjectAdjustment(Field));
106 continue;
107 }
Rafael Espindola9c006de2012-10-27 01:03:43 +0000108 }
109 }
110 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
111 if (BO->isPtrMemOp()) {
Rafael Espindola973aa202012-11-01 14:32:20 +0000112 assert(BO->getRHS()->isRValue());
Rafael Espindola9c006de2012-10-27 01:03:43 +0000113 E = BO->getLHS();
114 const MemberPointerType *MPT =
115 BO->getRHS()->getType()->getAs<MemberPointerType>();
116 Adjustments.push_back(SubobjectAdjustment(MPT, BO->getRHS()));
Richard Smithf3fabd22013-06-03 00:17:11 +0000117 continue;
118 } else if (BO->getOpcode() == BO_Comma) {
119 CommaLHSs.push_back(BO->getLHS());
120 E = BO->getRHS();
121 continue;
Rafael Espindola9c006de2012-10-27 01:03:43 +0000122 }
123 }
124
125 // Nothing changed.
126 break;
127 }
128 return E;
129}
130
Chris Lattner4ebae652010-04-16 23:34:13 +0000131/// isKnownToHaveBooleanValue - Return true if this is an integer expression
132/// that is known to return 0 or 1. This happens for _Bool/bool expressions
133/// but also int expressions which are produced by things like comparisons in
134/// C.
135bool Expr::isKnownToHaveBooleanValue() const {
Peter Collingbourne91147592011-04-15 00:35:48 +0000136 const Expr *E = IgnoreParens();
137
Chris Lattner4ebae652010-04-16 23:34:13 +0000138 // If this value has _Bool type, it is obvious 0/1.
Peter Collingbourne91147592011-04-15 00:35:48 +0000139 if (E->getType()->isBooleanType()) return true;
Alexis Hunta8136cc2010-05-05 15:23:54 +0000140 // If this is a non-scalar-integer type, we don't care enough to try.
Peter Collingbourne91147592011-04-15 00:35:48 +0000141 if (!E->getType()->isIntegralOrEnumerationType()) return false;
Alexis Hunta8136cc2010-05-05 15:23:54 +0000142
Peter Collingbourne91147592011-04-15 00:35:48 +0000143 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
Chris Lattner4ebae652010-04-16 23:34:13 +0000144 switch (UO->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +0000145 case UO_Plus:
Chris Lattner4ebae652010-04-16 23:34:13 +0000146 return UO->getSubExpr()->isKnownToHaveBooleanValue();
Richard Trieu0f097742014-04-04 04:13:47 +0000147 case UO_LNot:
148 return true;
Chris Lattner4ebae652010-04-16 23:34:13 +0000149 default:
150 return false;
151 }
152 }
Alexis Hunta8136cc2010-05-05 15:23:54 +0000153
John McCall45d30c32010-06-12 01:56:02 +0000154 // Only look through implicit casts. If the user writes
155 // '(int) (a && b)' treat it as an arbitrary int.
Peter Collingbourne91147592011-04-15 00:35:48 +0000156 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Chris Lattner4ebae652010-04-16 23:34:13 +0000157 return CE->getSubExpr()->isKnownToHaveBooleanValue();
Alexis Hunta8136cc2010-05-05 15:23:54 +0000158
Peter Collingbourne91147592011-04-15 00:35:48 +0000159 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
Chris Lattner4ebae652010-04-16 23:34:13 +0000160 switch (BO->getOpcode()) {
161 default: return false;
John McCalle3027922010-08-25 11:45:40 +0000162 case BO_LT: // Relational operators.
163 case BO_GT:
164 case BO_LE:
165 case BO_GE:
166 case BO_EQ: // Equality operators.
167 case BO_NE:
168 case BO_LAnd: // AND operator.
169 case BO_LOr: // Logical OR operator.
Chris Lattner4ebae652010-04-16 23:34:13 +0000170 return true;
Alexis Hunta8136cc2010-05-05 15:23:54 +0000171
John McCalle3027922010-08-25 11:45:40 +0000172 case BO_And: // Bitwise AND operator.
173 case BO_Xor: // Bitwise XOR operator.
174 case BO_Or: // Bitwise OR operator.
Chris Lattner4ebae652010-04-16 23:34:13 +0000175 // Handle things like (x==2)|(y==12).
176 return BO->getLHS()->isKnownToHaveBooleanValue() &&
177 BO->getRHS()->isKnownToHaveBooleanValue();
Alexis Hunta8136cc2010-05-05 15:23:54 +0000178
John McCalle3027922010-08-25 11:45:40 +0000179 case BO_Comma:
180 case BO_Assign:
Chris Lattner4ebae652010-04-16 23:34:13 +0000181 return BO->getRHS()->isKnownToHaveBooleanValue();
182 }
183 }
Alexis Hunta8136cc2010-05-05 15:23:54 +0000184
Peter Collingbourne91147592011-04-15 00:35:48 +0000185 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
Chris Lattner4ebae652010-04-16 23:34:13 +0000186 return CO->getTrueExpr()->isKnownToHaveBooleanValue() &&
187 CO->getFalseExpr()->isKnownToHaveBooleanValue();
Alexis Hunta8136cc2010-05-05 15:23:54 +0000188
Chris Lattner4ebae652010-04-16 23:34:13 +0000189 return false;
190}
191
John McCallbd066782011-02-09 08:16:59 +0000192// Amusing macro metaprogramming hack: check whether a class provides
193// a more specific implementation of getExprLoc().
Daniel Dunbarb0ab5e92012-03-09 15:39:19 +0000194//
195// See also Stmt.cpp:{getLocStart(),getLocEnd()}.
John McCallbd066782011-02-09 08:16:59 +0000196namespace {
197 /// This implementation is used when a class provides a custom
198 /// implementation of getExprLoc.
199 template <class E, class T>
200 SourceLocation getExprLocImpl(const Expr *expr,
201 SourceLocation (T::*v)() const) {
202 return static_cast<const E*>(expr)->getExprLoc();
203 }
204
205 /// This implementation is used when a class doesn't provide
206 /// a custom implementation of getExprLoc. Overload resolution
207 /// should pick it over the implementation above because it's
208 /// more specialized according to function template partial ordering.
209 template <class E>
210 SourceLocation getExprLocImpl(const Expr *expr,
211 SourceLocation (Expr::*v)() const) {
Daniel Dunbarb0ab5e92012-03-09 15:39:19 +0000212 return static_cast<const E*>(expr)->getLocStart();
John McCallbd066782011-02-09 08:16:59 +0000213 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000214}
John McCallbd066782011-02-09 08:16:59 +0000215
216SourceLocation Expr::getExprLoc() const {
217 switch (getStmtClass()) {
218 case Stmt::NoStmtClass: llvm_unreachable("statement without class");
219#define ABSTRACT_STMT(type)
220#define STMT(type, base) \
Richard Smitha0cbfc92014-07-26 00:47:13 +0000221 case Stmt::type##Class: break;
John McCallbd066782011-02-09 08:16:59 +0000222#define EXPR(type, base) \
223 case Stmt::type##Class: return getExprLocImpl<type>(this, &type::getExprLoc);
224#include "clang/AST/StmtNodes.inc"
225 }
Richard Smitha0cbfc92014-07-26 00:47:13 +0000226 llvm_unreachable("unknown expression kind");
John McCallbd066782011-02-09 08:16:59 +0000227}
228
Chris Lattner0eedafe2006-08-24 04:56:27 +0000229//===----------------------------------------------------------------------===//
230// Primary Expressions.
231//===----------------------------------------------------------------------===//
232
Douglas Gregor678d76c2011-07-01 01:22:09 +0000233/// \brief Compute the type-, value-, and instantiation-dependence of a
234/// declaration reference
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000235/// based on the declaration being referenced.
Craig Topperce7167c2013-08-22 04:58:56 +0000236static void computeDeclRefDependence(const ASTContext &Ctx, NamedDecl *D,
237 QualType T, bool &TypeDependent,
Douglas Gregor678d76c2011-07-01 01:22:09 +0000238 bool &ValueDependent,
239 bool &InstantiationDependent) {
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000240 TypeDependent = false;
241 ValueDependent = false;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000242 InstantiationDependent = false;
Douglas Gregored6c7442009-11-23 11:41:28 +0000243
244 // (TD) C++ [temp.dep.expr]p3:
245 // An id-expression is type-dependent if it contains:
246 //
Richard Smithcfaa5a32014-10-17 02:46:42 +0000247 // and
Douglas Gregored6c7442009-11-23 11:41:28 +0000248 //
249 // (VD) C++ [temp.dep.constexpr]p2:
250 // An identifier is value-dependent if it is:
Richard Smithcfaa5a32014-10-17 02:46:42 +0000251
Douglas Gregored6c7442009-11-23 11:41:28 +0000252 // (TD) - an identifier that was declared with dependent type
253 // (VD) - a name declared with a dependent type,
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000254 if (T->isDependentType()) {
255 TypeDependent = true;
256 ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000257 InstantiationDependent = true;
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000258 return;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000259 } else if (T->isInstantiationDependentType()) {
260 InstantiationDependent = true;
Douglas Gregored6c7442009-11-23 11:41:28 +0000261 }
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000262
Douglas Gregored6c7442009-11-23 11:41:28 +0000263 // (TD) - a conversion-function-id that specifies a dependent type
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000264 if (D->getDeclName().getNameKind()
Douglas Gregor678d76c2011-07-01 01:22:09 +0000265 == DeclarationName::CXXConversionFunctionName) {
266 QualType T = D->getDeclName().getCXXNameType();
267 if (T->isDependentType()) {
268 TypeDependent = true;
269 ValueDependent = true;
270 InstantiationDependent = true;
271 return;
272 }
273
274 if (T->isInstantiationDependentType())
275 InstantiationDependent = true;
Douglas Gregored6c7442009-11-23 11:41:28 +0000276 }
Douglas Gregor678d76c2011-07-01 01:22:09 +0000277
Douglas Gregored6c7442009-11-23 11:41:28 +0000278 // (VD) - the name of a non-type template parameter,
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000279 if (isa<NonTypeTemplateParmDecl>(D)) {
280 ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000281 InstantiationDependent = true;
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000282 return;
283 }
284
Douglas Gregored6c7442009-11-23 11:41:28 +0000285 // (VD) - a constant with integral or enumeration type and is
286 // initialized with an expression that is value-dependent.
Richard Smithec8dcd22011-11-08 01:31:09 +0000287 // (VD) - a constant with literal type and is initialized with an
288 // expression that is value-dependent [C++11].
289 // (VD) - FIXME: Missing from the standard:
290 // - an entity with reference type and is initialized with an
291 // expression that is value-dependent [C++11]
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000292 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000293 if ((Ctx.getLangOpts().CPlusPlus11 ?
Richard Smithd9f663b2013-04-22 15:31:51 +0000294 Var->getType()->isLiteralType(Ctx) :
Richard Smithec8dcd22011-11-08 01:31:09 +0000295 Var->getType()->isIntegralOrEnumerationType()) &&
David Blaikief5697e52012-08-10 00:55:35 +0000296 (Var->getType().isConstQualified() ||
Richard Smithec8dcd22011-11-08 01:31:09 +0000297 Var->getType()->isReferenceType())) {
Sebastian Redl5ca79842010-02-01 20:16:42 +0000298 if (const Expr *Init = Var->getAnyInitializer())
Douglas Gregor678d76c2011-07-01 01:22:09 +0000299 if (Init->isValueDependent()) {
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000300 ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000301 InstantiationDependent = true;
302 }
Richard Smithec8dcd22011-11-08 01:31:09 +0000303 }
304
Douglas Gregor0e4de762010-05-11 08:41:30 +0000305 // (VD) - FIXME: Missing from the standard:
306 // - a member function or a static data member of the current
307 // instantiation
Richard Smithec8dcd22011-11-08 01:31:09 +0000308 if (Var->isStaticDataMember() &&
309 Var->getDeclContext()->isDependentContext()) {
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000310 ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000311 InstantiationDependent = true;
Richard Smith00f5d892013-11-14 22:40:45 +0000312 TypeSourceInfo *TInfo = Var->getFirstDecl()->getTypeSourceInfo();
313 if (TInfo->getType()->isIncompleteArrayType())
314 TypeDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000315 }
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000316
317 return;
318 }
319
Douglas Gregor0e4de762010-05-11 08:41:30 +0000320 // (VD) - FIXME: Missing from the standard:
321 // - a member function or a static data member of the current
322 // instantiation
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000323 if (isa<CXXMethodDecl>(D) && D->getDeclContext()->isDependentContext()) {
324 ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000325 InstantiationDependent = true;
Richard Smithec8dcd22011-11-08 01:31:09 +0000326 }
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000327}
Douglas Gregora6e053e2010-12-15 01:34:56 +0000328
Craig Topperce7167c2013-08-22 04:58:56 +0000329void DeclRefExpr::computeDependence(const ASTContext &Ctx) {
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000330 bool TypeDependent = false;
331 bool ValueDependent = false;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000332 bool InstantiationDependent = false;
Daniel Dunbar9d355812012-03-09 01:51:51 +0000333 computeDeclRefDependence(Ctx, getDecl(), getType(), TypeDependent,
334 ValueDependent, InstantiationDependent);
Richard Smithcfaa5a32014-10-17 02:46:42 +0000335
336 ExprBits.TypeDependent |= TypeDependent;
337 ExprBits.ValueDependent |= ValueDependent;
338 ExprBits.InstantiationDependent |= InstantiationDependent;
339
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000340 // Is the declaration a parameter pack?
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000341 if (getDecl()->isParameterPack())
Douglas Gregor3c6bd2a2011-01-05 21:11:38 +0000342 ExprBits.ContainsUnexpandedParameterPack = true;
Douglas Gregored6c7442009-11-23 11:41:28 +0000343}
344
Craig Topperce7167c2013-08-22 04:58:56 +0000345DeclRefExpr::DeclRefExpr(const ASTContext &Ctx,
Daniel Dunbar9d355812012-03-09 01:51:51 +0000346 NestedNameSpecifierLoc QualifierLoc,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000347 SourceLocation TemplateKWLoc,
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000348 ValueDecl *D, bool RefersToEnclosingVariableOrCapture,
John McCall113bee02012-03-10 09:33:50 +0000349 const DeclarationNameInfo &NameInfo,
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000350 NamedDecl *FoundD,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000351 const TemplateArgumentListInfo *TemplateArgs,
John McCall7decc9e2010-11-18 06:31:45 +0000352 QualType T, ExprValueKind VK)
Douglas Gregor678d76c2011-07-01 01:22:09 +0000353 : Expr(DeclRefExprClass, T, VK, OK_Ordinary, false, false, false, false),
Chandler Carruth0e439962011-05-01 21:29:53 +0000354 D(D), Loc(NameInfo.getLoc()), DNLoc(NameInfo.getInfo()) {
355 DeclRefExprBits.HasQualifier = QualifierLoc ? 1 : 0;
Richard Smithcfaa5a32014-10-17 02:46:42 +0000356 if (QualifierLoc) {
James Y Knighte7d82282015-12-29 18:15:14 +0000357 new (getTrailingObjects<NestedNameSpecifierLoc>())
358 NestedNameSpecifierLoc(QualifierLoc);
Richard Smithcfaa5a32014-10-17 02:46:42 +0000359 auto *NNS = QualifierLoc.getNestedNameSpecifier();
360 if (NNS->isInstantiationDependent())
361 ExprBits.InstantiationDependent = true;
362 if (NNS->containsUnexpandedParameterPack())
363 ExprBits.ContainsUnexpandedParameterPack = true;
364 }
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000365 DeclRefExprBits.HasFoundDecl = FoundD ? 1 : 0;
366 if (FoundD)
James Y Knighte7d82282015-12-29 18:15:14 +0000367 *getTrailingObjects<NamedDecl *>() = FoundD;
Abramo Bagnara7945c982012-01-27 09:46:47 +0000368 DeclRefExprBits.HasTemplateKWAndArgsInfo
369 = (TemplateArgs || TemplateKWLoc.isValid()) ? 1 : 0;
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000370 DeclRefExprBits.RefersToEnclosingVariableOrCapture =
371 RefersToEnclosingVariableOrCapture;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000372 if (TemplateArgs) {
373 bool Dependent = false;
374 bool InstantiationDependent = false;
375 bool ContainsUnexpandedParameterPack = false;
James Y Knighte7d82282015-12-29 18:15:14 +0000376 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
377 TemplateKWLoc, *TemplateArgs, getTrailingObjects<TemplateArgumentLoc>(),
378 Dependent, InstantiationDependent, ContainsUnexpandedParameterPack);
Richard Smithcfaa5a32014-10-17 02:46:42 +0000379 assert(!Dependent && "built a DeclRefExpr with dependent template args");
380 ExprBits.InstantiationDependent |= InstantiationDependent;
381 ExprBits.ContainsUnexpandedParameterPack |= ContainsUnexpandedParameterPack;
Abramo Bagnara7945c982012-01-27 09:46:47 +0000382 } else if (TemplateKWLoc.isValid()) {
James Y Knighte7d82282015-12-29 18:15:14 +0000383 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
384 TemplateKWLoc);
Douglas Gregor678d76c2011-07-01 01:22:09 +0000385 }
Benjamin Kramer138ef9c2011-10-10 12:54:05 +0000386 DeclRefExprBits.HadMultipleCandidates = 0;
387
Daniel Dunbar9d355812012-03-09 01:51:51 +0000388 computeDependence(Ctx);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000389}
390
Craig Topperce7167c2013-08-22 04:58:56 +0000391DeclRefExpr *DeclRefExpr::Create(const ASTContext &Context,
Douglas Gregorea972d32011-02-28 21:54:11 +0000392 NestedNameSpecifierLoc QualifierLoc,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000393 SourceLocation TemplateKWLoc,
John McCallce546572009-12-08 09:08:17 +0000394 ValueDecl *D,
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000395 bool RefersToEnclosingVariableOrCapture,
Douglas Gregor4bd90e52009-10-23 18:54:35 +0000396 SourceLocation NameLoc,
Douglas Gregored6c7442009-11-23 11:41:28 +0000397 QualType T,
John McCall7decc9e2010-11-18 06:31:45 +0000398 ExprValueKind VK,
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000399 NamedDecl *FoundD,
Douglas Gregored6c7442009-11-23 11:41:28 +0000400 const TemplateArgumentListInfo *TemplateArgs) {
Abramo Bagnara7945c982012-01-27 09:46:47 +0000401 return Create(Context, QualifierLoc, TemplateKWLoc, D,
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000402 RefersToEnclosingVariableOrCapture,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000403 DeclarationNameInfo(D->getDeclName(), NameLoc),
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000404 T, VK, FoundD, TemplateArgs);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000405}
406
Craig Topperce7167c2013-08-22 04:58:56 +0000407DeclRefExpr *DeclRefExpr::Create(const ASTContext &Context,
Douglas Gregorea972d32011-02-28 21:54:11 +0000408 NestedNameSpecifierLoc QualifierLoc,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000409 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000410 ValueDecl *D,
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000411 bool RefersToEnclosingVariableOrCapture,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000412 const DeclarationNameInfo &NameInfo,
413 QualType T,
John McCall7decc9e2010-11-18 06:31:45 +0000414 ExprValueKind VK,
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000415 NamedDecl *FoundD,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000416 const TemplateArgumentListInfo *TemplateArgs) {
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000417 // Filter out cases where the found Decl is the same as the value refenenced.
418 if (D == FoundD)
Craig Topper36250ad2014-05-12 05:36:57 +0000419 FoundD = nullptr;
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000420
James Y Knighte7d82282015-12-29 18:15:14 +0000421 bool HasTemplateKWAndArgsInfo = TemplateArgs || TemplateKWLoc.isValid();
422 std::size_t Size =
423 totalSizeToAlloc<NestedNameSpecifierLoc, NamedDecl *,
424 ASTTemplateKWAndArgsInfo, TemplateArgumentLoc>(
425 QualifierLoc ? 1 : 0, FoundD ? 1 : 0,
426 HasTemplateKWAndArgsInfo ? 1 : 0,
427 TemplateArgs ? TemplateArgs->size() : 0);
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000428
Benjamin Kramerc3f89252016-10-20 14:27:22 +0000429 void *Mem = Context.Allocate(Size, alignof(DeclRefExpr));
Daniel Dunbar9d355812012-03-09 01:51:51 +0000430 return new (Mem) DeclRefExpr(Context, QualifierLoc, TemplateKWLoc, D,
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000431 RefersToEnclosingVariableOrCapture,
Daniel Dunbar9d355812012-03-09 01:51:51 +0000432 NameInfo, FoundD, TemplateArgs, T, VK);
Douglas Gregor4bd90e52009-10-23 18:54:35 +0000433}
434
Craig Topperce7167c2013-08-22 04:58:56 +0000435DeclRefExpr *DeclRefExpr::CreateEmpty(const ASTContext &Context,
Douglas Gregor87866ce2011-02-04 12:01:24 +0000436 bool HasQualifier,
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000437 bool HasFoundDecl,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000438 bool HasTemplateKWAndArgsInfo,
Argyrios Kyrtzidis1985bb32010-07-08 13:09:47 +0000439 unsigned NumTemplateArgs) {
James Y Knighte7d82282015-12-29 18:15:14 +0000440 assert(NumTemplateArgs == 0 || HasTemplateKWAndArgsInfo);
441 std::size_t Size =
442 totalSizeToAlloc<NestedNameSpecifierLoc, NamedDecl *,
443 ASTTemplateKWAndArgsInfo, TemplateArgumentLoc>(
444 HasQualifier ? 1 : 0, HasFoundDecl ? 1 : 0, HasTemplateKWAndArgsInfo,
445 NumTemplateArgs);
Benjamin Kramerc3f89252016-10-20 14:27:22 +0000446 void *Mem = Context.Allocate(Size, alignof(DeclRefExpr));
Argyrios Kyrtzidis1985bb32010-07-08 13:09:47 +0000447 return new (Mem) DeclRefExpr(EmptyShell());
448}
449
Daniel Dunbarb507f272012-03-09 15:39:15 +0000450SourceLocation DeclRefExpr::getLocStart() const {
451 if (hasQualifier())
452 return getQualifierLoc().getBeginLoc();
453 return getNameInfo().getLocStart();
454}
455SourceLocation DeclRefExpr::getLocEnd() const {
456 if (hasExplicitTemplateArgs())
457 return getRAngleLoc();
458 return getNameInfo().getLocEnd();
459}
Douglas Gregor4bd90e52009-10-23 18:54:35 +0000460
Alexey Bataevec474782014-10-09 08:45:04 +0000461PredefinedExpr::PredefinedExpr(SourceLocation L, QualType FNTy, IdentType IT,
462 StringLiteral *SL)
463 : Expr(PredefinedExprClass, FNTy, VK_LValue, OK_Ordinary,
464 FNTy->isDependentType(), FNTy->isDependentType(),
465 FNTy->isInstantiationDependentType(),
466 /*ContainsUnexpandedParameterPack=*/false),
467 Loc(L), Type(IT), FnName(SL) {}
468
469StringLiteral *PredefinedExpr::getFunctionName() {
Alexey Bataev769562a2014-10-10 18:58:13 +0000470 return cast_or_null<StringLiteral>(FnName);
Alexey Bataevec474782014-10-09 08:45:04 +0000471}
472
473StringRef PredefinedExpr::getIdentTypeName(PredefinedExpr::IdentType IT) {
474 switch (IT) {
475 case Func:
476 return "__func__";
477 case Function:
478 return "__FUNCTION__";
479 case FuncDName:
480 return "__FUNCDNAME__";
481 case LFunction:
482 return "L__FUNCTION__";
483 case PrettyFunction:
484 return "__PRETTY_FUNCTION__";
485 case FuncSig:
486 return "__FUNCSIG__";
487 case PrettyFunctionNoVirtual:
488 break;
489 }
490 llvm_unreachable("Unknown ident type for PredefinedExpr");
491}
492
Anders Carlsson2fb08242009-09-08 18:24:21 +0000493// FIXME: Maybe this should use DeclPrinter with a special "print predefined
494// expr" policy instead.
Anders Carlsson5bd8d192010-02-11 18:20:28 +0000495std::string PredefinedExpr::ComputeName(IdentType IT, const Decl *CurrentDecl) {
496 ASTContext &Context = CurrentDecl->getASTContext();
497
David Majnemerbed356a2013-11-06 23:31:56 +0000498 if (IT == PredefinedExpr::FuncDName) {
499 if (const NamedDecl *ND = dyn_cast<NamedDecl>(CurrentDecl)) {
Ahmed Charlesb8984322014-03-07 20:03:18 +0000500 std::unique_ptr<MangleContext> MC;
David Majnemerbed356a2013-11-06 23:31:56 +0000501 MC.reset(Context.createMangleContext());
502
503 if (MC->shouldMangleDeclName(ND)) {
504 SmallString<256> Buffer;
505 llvm::raw_svector_ostream Out(Buffer);
506 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(ND))
507 MC->mangleCXXCtor(CD, Ctor_Base, Out);
508 else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(ND))
509 MC->mangleCXXDtor(DD, Dtor_Base, Out);
510 else
511 MC->mangleName(ND, Out);
512
David Majnemerbed356a2013-11-06 23:31:56 +0000513 if (!Buffer.empty() && Buffer.front() == '\01')
514 return Buffer.substr(1);
515 return Buffer.str();
516 } else
517 return ND->getIdentifier()->getName();
518 }
519 return "";
520 }
Mehdi Aminidc9bf8f2016-11-16 07:07:28 +0000521 if (isa<BlockDecl>(CurrentDecl)) {
522 // For blocks we only emit something if it is enclosed in a function
523 // For top-level block we'd like to include the name of variable, but we
524 // don't have it at this point.
Mehdi Aminif5f37ee2016-11-15 22:19:50 +0000525 auto DC = CurrentDecl->getDeclContext();
526 if (DC->isFileContext())
Mehdi Aminidc9bf8f2016-11-16 07:07:28 +0000527 return "";
528
529 SmallString<256> Buffer;
530 llvm::raw_svector_ostream Out(Buffer);
531 if (auto *DCBlock = dyn_cast<BlockDecl>(DC))
532 // For nested blocks, propagate up to the parent.
533 Out << ComputeName(IT, DCBlock);
534 else if (auto *DCDecl = dyn_cast<Decl>(DC))
535 Out << ComputeName(IT, DCDecl) << "_block_invoke";
Alexey Bataevec474782014-10-09 08:45:04 +0000536 return Out.str();
537 }
Anders Carlsson2fb08242009-09-08 18:24:21 +0000538 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CurrentDecl)) {
Reid Kleckner52eddda2014-04-08 18:13:24 +0000539 if (IT != PrettyFunction && IT != PrettyFunctionNoVirtual && IT != FuncSig)
Anders Carlsson2fb08242009-09-08 18:24:21 +0000540 return FD->getNameAsString();
541
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000542 SmallString<256> Name;
Anders Carlsson2fb08242009-09-08 18:24:21 +0000543 llvm::raw_svector_ostream Out(Name);
544
545 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
Anders Carlsson5bd8d192010-02-11 18:20:28 +0000546 if (MD->isVirtual() && IT != PrettyFunctionNoVirtual)
Anders Carlsson2fb08242009-09-08 18:24:21 +0000547 Out << "virtual ";
Sam Weinig4e83bd22009-12-27 01:38:20 +0000548 if (MD->isStatic())
549 Out << "static ";
Anders Carlsson2fb08242009-09-08 18:24:21 +0000550 }
551
David Blaikiebbafb8a2012-03-11 07:00:24 +0000552 PrintingPolicy Policy(Context.getLangOpts());
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +0000553 std::string Proto;
Douglas Gregor11a434a2012-04-10 20:14:15 +0000554 llvm::raw_string_ostream POut(Proto);
Anders Carlsson2fb08242009-09-08 18:24:21 +0000555
Douglas Gregor11a434a2012-04-10 20:14:15 +0000556 const FunctionDecl *Decl = FD;
557 if (const FunctionDecl* Pattern = FD->getTemplateInstantiationPattern())
558 Decl = Pattern;
559 const FunctionType *AFT = Decl->getType()->getAs<FunctionType>();
Craig Topper36250ad2014-05-12 05:36:57 +0000560 const FunctionProtoType *FT = nullptr;
Anders Carlsson2fb08242009-09-08 18:24:21 +0000561 if (FD->hasWrittenPrototype())
562 FT = dyn_cast<FunctionProtoType>(AFT);
563
Reid Kleckner52eddda2014-04-08 18:13:24 +0000564 if (IT == FuncSig) {
Chandler Carruth59666772016-11-04 06:32:57 +0000565 assert(FT && "We must have a written prototype in this case.");
Reid Kleckner52eddda2014-04-08 18:13:24 +0000566 switch (FT->getCallConv()) {
567 case CC_C: POut << "__cdecl "; break;
568 case CC_X86StdCall: POut << "__stdcall "; break;
569 case CC_X86FastCall: POut << "__fastcall "; break;
570 case CC_X86ThisCall: POut << "__thiscall "; break;
Reid Klecknerd7857f02014-10-24 17:42:17 +0000571 case CC_X86VectorCall: POut << "__vectorcall "; break;
Erich Keane757d3172016-11-02 18:29:35 +0000572 case CC_X86RegCall: POut << "__regcall "; break;
Reid Kleckner52eddda2014-04-08 18:13:24 +0000573 // Only bother printing the conventions that MSVC knows about.
574 default: break;
575 }
576 }
577
578 FD->printQualifiedName(POut, Policy);
579
Douglas Gregor11a434a2012-04-10 20:14:15 +0000580 POut << "(";
Anders Carlsson2fb08242009-09-08 18:24:21 +0000581 if (FT) {
Douglas Gregor11a434a2012-04-10 20:14:15 +0000582 for (unsigned i = 0, e = Decl->getNumParams(); i != e; ++i) {
Anders Carlsson2fb08242009-09-08 18:24:21 +0000583 if (i) POut << ", ";
Argyrios Kyrtzidisa18347e2012-05-05 04:20:37 +0000584 POut << Decl->getParamDecl(i)->getType().stream(Policy);
Anders Carlsson2fb08242009-09-08 18:24:21 +0000585 }
586
587 if (FT->isVariadic()) {
588 if (FD->getNumParams()) POut << ", ";
589 POut << "...";
590 }
591 }
Douglas Gregor11a434a2012-04-10 20:14:15 +0000592 POut << ")";
Anders Carlsson2fb08242009-09-08 18:24:21 +0000593
Sam Weinig4e83bd22009-12-27 01:38:20 +0000594 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
Argyrios Kyrtzidis53e3d6d2012-12-14 19:44:11 +0000595 const FunctionType *FT = MD->getType()->castAs<FunctionType>();
David Blaikief5697e52012-08-10 00:55:35 +0000596 if (FT->isConst())
Douglas Gregor11a434a2012-04-10 20:14:15 +0000597 POut << " const";
David Blaikief5697e52012-08-10 00:55:35 +0000598 if (FT->isVolatile())
Douglas Gregor11a434a2012-04-10 20:14:15 +0000599 POut << " volatile";
600 RefQualifierKind Ref = MD->getRefQualifier();
601 if (Ref == RQ_LValue)
602 POut << " &";
603 else if (Ref == RQ_RValue)
604 POut << " &&";
Sam Weinig4e83bd22009-12-27 01:38:20 +0000605 }
606
Douglas Gregor11a434a2012-04-10 20:14:15 +0000607 typedef SmallVector<const ClassTemplateSpecializationDecl *, 8> SpecsTy;
608 SpecsTy Specs;
609 const DeclContext *Ctx = FD->getDeclContext();
610 while (Ctx && isa<NamedDecl>(Ctx)) {
611 const ClassTemplateSpecializationDecl *Spec
612 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx);
613 if (Spec && !Spec->isExplicitSpecialization())
614 Specs.push_back(Spec);
615 Ctx = Ctx->getParent();
616 }
617
618 std::string TemplateParams;
619 llvm::raw_string_ostream TOut(TemplateParams);
620 for (SpecsTy::reverse_iterator I = Specs.rbegin(), E = Specs.rend();
621 I != E; ++I) {
622 const TemplateParameterList *Params
623 = (*I)->getSpecializedTemplate()->getTemplateParameters();
624 const TemplateArgumentList &Args = (*I)->getTemplateArgs();
625 assert(Params->size() == Args.size());
626 for (unsigned i = 0, numParams = Params->size(); i != numParams; ++i) {
627 StringRef Param = Params->getParam(i)->getName();
628 if (Param.empty()) continue;
629 TOut << Param << " = ";
630 Args.get(i).print(Policy, TOut);
631 TOut << ", ";
632 }
633 }
634
635 FunctionTemplateSpecializationInfo *FSI
636 = FD->getTemplateSpecializationInfo();
637 if (FSI && !FSI->isExplicitSpecialization()) {
638 const TemplateParameterList* Params
639 = FSI->getTemplate()->getTemplateParameters();
640 const TemplateArgumentList* Args = FSI->TemplateArguments;
641 assert(Params->size() == Args->size());
642 for (unsigned i = 0, e = Params->size(); i != e; ++i) {
643 StringRef Param = Params->getParam(i)->getName();
644 if (Param.empty()) continue;
645 TOut << Param << " = ";
646 Args->get(i).print(Policy, TOut);
647 TOut << ", ";
648 }
649 }
650
651 TOut.flush();
652 if (!TemplateParams.empty()) {
653 // remove the trailing comma and space
654 TemplateParams.resize(TemplateParams.size() - 2);
655 POut << " [" << TemplateParams << "]";
656 }
657
658 POut.flush();
659
Benjamin Kramer90f54222013-08-21 11:45:27 +0000660 // Print "auto" for all deduced return types. This includes C++1y return
661 // type deduction and lambdas. For trailing return types resolve the
662 // decltype expression. Otherwise print the real type when this is
663 // not a constructor or destructor.
Alexey Bataevec474782014-10-09 08:45:04 +0000664 if (isa<CXXMethodDecl>(FD) &&
665 cast<CXXMethodDecl>(FD)->getParent()->isLambda())
Benjamin Kramer90f54222013-08-21 11:45:27 +0000666 Proto = "auto " + Proto;
Alp Toker314cc812014-01-25 16:55:45 +0000667 else if (FT && FT->getReturnType()->getAs<DecltypeType>())
668 FT->getReturnType()
669 ->getAs<DecltypeType>()
670 ->getUnderlyingType()
Benjamin Kramer90f54222013-08-21 11:45:27 +0000671 .getAsStringInternal(Proto, Policy);
672 else if (!isa<CXXConstructorDecl>(FD) && !isa<CXXDestructorDecl>(FD))
Alp Toker314cc812014-01-25 16:55:45 +0000673 AFT->getReturnType().getAsStringInternal(Proto, Policy);
Anders Carlsson2fb08242009-09-08 18:24:21 +0000674
675 Out << Proto;
676
Anders Carlsson2fb08242009-09-08 18:24:21 +0000677 return Name.str().str();
678 }
Wei Pan8d6b19a2013-08-26 14:27:34 +0000679 if (const CapturedDecl *CD = dyn_cast<CapturedDecl>(CurrentDecl)) {
680 for (const DeclContext *DC = CD->getParent(); DC; DC = DC->getParent())
681 // Skip to its enclosing function or method, but not its enclosing
682 // CapturedDecl.
683 if (DC->isFunctionOrMethod() && (DC->getDeclKind() != Decl::Captured)) {
684 const Decl *D = Decl::castFromDeclContext(DC);
685 return ComputeName(IT, D);
686 }
687 llvm_unreachable("CapturedDecl not inside a function or method");
688 }
Anders Carlsson2fb08242009-09-08 18:24:21 +0000689 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurrentDecl)) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000690 SmallString<256> Name;
Anders Carlsson2fb08242009-09-08 18:24:21 +0000691 llvm::raw_svector_ostream Out(Name);
692 Out << (MD->isInstanceMethod() ? '-' : '+');
693 Out << '[';
Ted Kremenek361ffd92010-03-18 21:23:08 +0000694
695 // For incorrect code, there might not be an ObjCInterfaceDecl. Do
696 // a null check to avoid a crash.
697 if (const ObjCInterfaceDecl *ID = MD->getClassInterface())
Benjamin Kramerb89514a2011-10-14 18:45:37 +0000698 Out << *ID;
Ted Kremenek361ffd92010-03-18 21:23:08 +0000699
Anders Carlsson2fb08242009-09-08 18:24:21 +0000700 if (const ObjCCategoryImplDecl *CID =
Benjamin Kramerb11416d2010-04-17 09:33:03 +0000701 dyn_cast<ObjCCategoryImplDecl>(MD->getDeclContext()))
Benjamin Kramer2f569922012-02-07 11:57:45 +0000702 Out << '(' << *CID << ')';
Benjamin Kramerb11416d2010-04-17 09:33:03 +0000703
Anders Carlsson2fb08242009-09-08 18:24:21 +0000704 Out << ' ';
Aaron Ballmanb190f972014-01-03 17:59:55 +0000705 MD->getSelector().print(Out);
Anders Carlsson2fb08242009-09-08 18:24:21 +0000706 Out << ']';
707
Anders Carlsson2fb08242009-09-08 18:24:21 +0000708 return Name.str().str();
709 }
710 if (isa<TranslationUnitDecl>(CurrentDecl) && IT == PrettyFunction) {
711 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
712 return "top level";
713 }
714 return "";
715}
716
Craig Topper37932912013-08-18 10:09:15 +0000717void APNumericStorage::setIntValue(const ASTContext &C,
718 const llvm::APInt &Val) {
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000719 if (hasAllocation())
720 C.Deallocate(pVal);
721
722 BitWidth = Val.getBitWidth();
723 unsigned NumWords = Val.getNumWords();
724 const uint64_t* Words = Val.getRawData();
725 if (NumWords > 1) {
726 pVal = new (C) uint64_t[NumWords];
727 std::copy(Words, Words + NumWords, pVal);
728 } else if (NumWords == 1)
729 VAL = Words[0];
730 else
731 VAL = 0;
732}
733
Craig Topper37932912013-08-18 10:09:15 +0000734IntegerLiteral::IntegerLiteral(const ASTContext &C, const llvm::APInt &V,
Benjamin Kramer1ea8e092012-07-04 17:04:04 +0000735 QualType type, SourceLocation l)
736 : Expr(IntegerLiteralClass, type, VK_RValue, OK_Ordinary, false, false,
737 false, false),
738 Loc(l) {
739 assert(type->isIntegerType() && "Illegal type in IntegerLiteral");
740 assert(V.getBitWidth() == C.getIntWidth(type) &&
741 "Integer type is not the correct size for constant.");
742 setValue(C, V);
743}
744
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000745IntegerLiteral *
Craig Topper37932912013-08-18 10:09:15 +0000746IntegerLiteral::Create(const ASTContext &C, const llvm::APInt &V,
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000747 QualType type, SourceLocation l) {
748 return new (C) IntegerLiteral(C, V, type, l);
749}
750
751IntegerLiteral *
Craig Topper37932912013-08-18 10:09:15 +0000752IntegerLiteral::Create(const ASTContext &C, EmptyShell Empty) {
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000753 return new (C) IntegerLiteral(Empty);
754}
755
Craig Topper37932912013-08-18 10:09:15 +0000756FloatingLiteral::FloatingLiteral(const ASTContext &C, const llvm::APFloat &V,
Benjamin Kramer1ea8e092012-07-04 17:04:04 +0000757 bool isexact, QualType Type, SourceLocation L)
758 : Expr(FloatingLiteralClass, Type, VK_RValue, OK_Ordinary, false, false,
759 false, false), Loc(L) {
Tim Northover178723a2013-01-22 09:46:51 +0000760 setSemantics(V.getSemantics());
Benjamin Kramer1ea8e092012-07-04 17:04:04 +0000761 FloatingLiteralBits.IsExact = isexact;
762 setValue(C, V);
763}
764
Craig Topper37932912013-08-18 10:09:15 +0000765FloatingLiteral::FloatingLiteral(const ASTContext &C, EmptyShell Empty)
Benjamin Kramer1ea8e092012-07-04 17:04:04 +0000766 : Expr(FloatingLiteralClass, Empty) {
Tim Northover178723a2013-01-22 09:46:51 +0000767 setRawSemantics(IEEEhalf);
Benjamin Kramer1ea8e092012-07-04 17:04:04 +0000768 FloatingLiteralBits.IsExact = false;
769}
770
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000771FloatingLiteral *
Craig Topper37932912013-08-18 10:09:15 +0000772FloatingLiteral::Create(const ASTContext &C, const llvm::APFloat &V,
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000773 bool isexact, QualType Type, SourceLocation L) {
774 return new (C) FloatingLiteral(C, V, isexact, Type, L);
775}
776
777FloatingLiteral *
Craig Topper37932912013-08-18 10:09:15 +0000778FloatingLiteral::Create(const ASTContext &C, EmptyShell Empty) {
Akira Hatanaka428f5b22012-01-10 22:40:09 +0000779 return new (C) FloatingLiteral(C, Empty);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000780}
781
Tim Northover178723a2013-01-22 09:46:51 +0000782const llvm::fltSemantics &FloatingLiteral::getSemantics() const {
783 switch(FloatingLiteralBits.Semantics) {
784 case IEEEhalf:
785 return llvm::APFloat::IEEEhalf;
786 case IEEEsingle:
787 return llvm::APFloat::IEEEsingle;
788 case IEEEdouble:
789 return llvm::APFloat::IEEEdouble;
790 case x87DoubleExtended:
791 return llvm::APFloat::x87DoubleExtended;
792 case IEEEquad:
793 return llvm::APFloat::IEEEquad;
794 case PPCDoubleDouble:
795 return llvm::APFloat::PPCDoubleDouble;
796 }
797 llvm_unreachable("Unrecognised floating semantics");
798}
799
800void FloatingLiteral::setSemantics(const llvm::fltSemantics &Sem) {
801 if (&Sem == &llvm::APFloat::IEEEhalf)
802 FloatingLiteralBits.Semantics = IEEEhalf;
803 else if (&Sem == &llvm::APFloat::IEEEsingle)
804 FloatingLiteralBits.Semantics = IEEEsingle;
805 else if (&Sem == &llvm::APFloat::IEEEdouble)
806 FloatingLiteralBits.Semantics = IEEEdouble;
807 else if (&Sem == &llvm::APFloat::x87DoubleExtended)
808 FloatingLiteralBits.Semantics = x87DoubleExtended;
809 else if (&Sem == &llvm::APFloat::IEEEquad)
810 FloatingLiteralBits.Semantics = IEEEquad;
811 else if (&Sem == &llvm::APFloat::PPCDoubleDouble)
812 FloatingLiteralBits.Semantics = PPCDoubleDouble;
813 else
814 llvm_unreachable("Unknown floating semantics");
815}
816
Chris Lattnera0173132008-06-07 22:13:43 +0000817/// getValueAsApproximateDouble - This returns the value as an inaccurate
818/// double. Note that this may cause loss of precision, but is useful for
819/// debugging dumps, etc.
820double FloatingLiteral::getValueAsApproximateDouble() const {
821 llvm::APFloat V = getValue();
Dale Johannesenc48814b2008-10-09 23:02:32 +0000822 bool ignored;
823 V.convert(llvm::APFloat::IEEEdouble, llvm::APFloat::rmNearestTiesToEven,
824 &ignored);
Chris Lattnera0173132008-06-07 22:13:43 +0000825 return V.convertToDouble();
826}
827
Nick Lewycky4ed84042012-02-24 09:07:53 +0000828int StringLiteral::mapCharByteWidth(TargetInfo const &target,StringKind k) {
Eli Friedman381f4312012-02-29 20:59:56 +0000829 int CharByteWidth = 0;
Nick Lewycky4ed84042012-02-24 09:07:53 +0000830 switch(k) {
Eli Friedmanfcec6302011-11-01 02:23:42 +0000831 case Ascii:
832 case UTF8:
Nick Lewycky4ed84042012-02-24 09:07:53 +0000833 CharByteWidth = target.getCharWidth();
Eli Friedmanfcec6302011-11-01 02:23:42 +0000834 break;
835 case Wide:
Nick Lewycky4ed84042012-02-24 09:07:53 +0000836 CharByteWidth = target.getWCharWidth();
Eli Friedmanfcec6302011-11-01 02:23:42 +0000837 break;
838 case UTF16:
Nick Lewycky4ed84042012-02-24 09:07:53 +0000839 CharByteWidth = target.getChar16Width();
Eli Friedmanfcec6302011-11-01 02:23:42 +0000840 break;
841 case UTF32:
Nick Lewycky4ed84042012-02-24 09:07:53 +0000842 CharByteWidth = target.getChar32Width();
Eli Friedman381f4312012-02-29 20:59:56 +0000843 break;
Eli Friedmanfcec6302011-11-01 02:23:42 +0000844 }
845 assert((CharByteWidth & 7) == 0 && "Assumes character size is byte multiple");
846 CharByteWidth /= 8;
Nick Lewycky4ed84042012-02-24 09:07:53 +0000847 assert((CharByteWidth==1 || CharByteWidth==2 || CharByteWidth==4)
Eli Friedmanfcec6302011-11-01 02:23:42 +0000848 && "character byte widths supported are 1, 2, and 4 only");
849 return CharByteWidth;
850}
851
Craig Topper37932912013-08-18 10:09:15 +0000852StringLiteral *StringLiteral::Create(const ASTContext &C, StringRef Str,
Douglas Gregorfb65e592011-07-27 05:40:30 +0000853 StringKind Kind, bool Pascal, QualType Ty,
Mike Stump11289f42009-09-09 15:08:12 +0000854 const SourceLocation *Loc,
Anders Carlssona3905812009-03-15 18:34:13 +0000855 unsigned NumStrs) {
Benjamin Kramercdac7612014-02-25 12:26:20 +0000856 assert(C.getAsConstantArrayType(Ty) &&
857 "StringLiteral must be of constant array type!");
858
Chris Lattnerf83b5af2009-02-18 06:40:38 +0000859 // Allocate enough space for the StringLiteral plus an array of locations for
860 // any concatenated string tokens.
Benjamin Kramerc3f89252016-10-20 14:27:22 +0000861 void *Mem =
862 C.Allocate(sizeof(StringLiteral) + sizeof(SourceLocation) * (NumStrs - 1),
863 alignof(StringLiteral));
Chris Lattnerf83b5af2009-02-18 06:40:38 +0000864 StringLiteral *SL = new (Mem) StringLiteral(Ty);
Mike Stump11289f42009-09-09 15:08:12 +0000865
Steve Naroffdf7855b2007-02-21 23:46:25 +0000866 // OPTIMIZE: could allocate this appended to the StringLiteral.
Eli Friedmanfcec6302011-11-01 02:23:42 +0000867 SL->setString(C,Str,Kind,Pascal);
868
Chris Lattnerf83b5af2009-02-18 06:40:38 +0000869 SL->TokLocs[0] = Loc[0];
870 SL->NumConcatenated = NumStrs;
Chris Lattnerd3e98952006-10-06 05:22:26 +0000871
Chris Lattner630970d2009-02-18 05:49:11 +0000872 if (NumStrs != 1)
Chris Lattnerf83b5af2009-02-18 06:40:38 +0000873 memcpy(&SL->TokLocs[1], Loc+1, sizeof(SourceLocation)*(NumStrs-1));
874 return SL;
Chris Lattner630970d2009-02-18 05:49:11 +0000875}
876
Craig Topper37932912013-08-18 10:09:15 +0000877StringLiteral *StringLiteral::CreateEmpty(const ASTContext &C,
878 unsigned NumStrs) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +0000879 void *Mem =
880 C.Allocate(sizeof(StringLiteral) + sizeof(SourceLocation) * (NumStrs - 1),
881 alignof(StringLiteral));
Douglas Gregor958dfc92009-04-15 16:35:07 +0000882 StringLiteral *SL = new (Mem) StringLiteral(QualType());
Eli Friedmanfcec6302011-11-01 02:23:42 +0000883 SL->CharByteWidth = 0;
884 SL->Length = 0;
Douglas Gregor958dfc92009-04-15 16:35:07 +0000885 SL->NumConcatenated = NumStrs;
886 return SL;
887}
888
Alexander Kornienko540bacb2013-02-01 12:35:51 +0000889void StringLiteral::outputString(raw_ostream &OS) const {
Richard Trieudc355912012-06-13 20:25:24 +0000890 switch (getKind()) {
891 case Ascii: break; // no prefix.
892 case Wide: OS << 'L'; break;
893 case UTF8: OS << "u8"; break;
894 case UTF16: OS << 'u'; break;
895 case UTF32: OS << 'U'; break;
896 }
897 OS << '"';
898 static const char Hex[] = "0123456789ABCDEF";
899
900 unsigned LastSlashX = getLength();
901 for (unsigned I = 0, N = getLength(); I != N; ++I) {
902 switch (uint32_t Char = getCodeUnit(I)) {
903 default:
904 // FIXME: Convert UTF-8 back to codepoints before rendering.
905
906 // Convert UTF-16 surrogate pairs back to codepoints before rendering.
907 // Leave invalid surrogates alone; we'll use \x for those.
908 if (getKind() == UTF16 && I != N - 1 && Char >= 0xd800 &&
909 Char <= 0xdbff) {
910 uint32_t Trail = getCodeUnit(I + 1);
911 if (Trail >= 0xdc00 && Trail <= 0xdfff) {
912 Char = 0x10000 + ((Char - 0xd800) << 10) + (Trail - 0xdc00);
913 ++I;
914 }
915 }
916
917 if (Char > 0xff) {
918 // If this is a wide string, output characters over 0xff using \x
919 // escapes. Otherwise, this is a UTF-16 or UTF-32 string, and Char is a
920 // codepoint: use \x escapes for invalid codepoints.
921 if (getKind() == Wide ||
922 (Char >= 0xd800 && Char <= 0xdfff) || Char >= 0x110000) {
923 // FIXME: Is this the best way to print wchar_t?
924 OS << "\\x";
925 int Shift = 28;
926 while ((Char >> Shift) == 0)
927 Shift -= 4;
928 for (/**/; Shift >= 0; Shift -= 4)
929 OS << Hex[(Char >> Shift) & 15];
930 LastSlashX = I;
931 break;
932 }
933
934 if (Char > 0xffff)
935 OS << "\\U00"
936 << Hex[(Char >> 20) & 15]
937 << Hex[(Char >> 16) & 15];
938 else
939 OS << "\\u";
940 OS << Hex[(Char >> 12) & 15]
941 << Hex[(Char >> 8) & 15]
942 << Hex[(Char >> 4) & 15]
943 << Hex[(Char >> 0) & 15];
944 break;
945 }
946
947 // If we used \x... for the previous character, and this character is a
948 // hexadecimal digit, prevent it being slurped as part of the \x.
949 if (LastSlashX + 1 == I) {
950 switch (Char) {
951 case '0': case '1': case '2': case '3': case '4':
952 case '5': case '6': case '7': case '8': case '9':
953 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
954 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
955 OS << "\"\"";
956 }
957 }
958
959 assert(Char <= 0xff &&
960 "Characters above 0xff should already have been handled.");
961
Jordan Rosea7d03842013-02-08 22:30:41 +0000962 if (isPrintable(Char))
Richard Trieudc355912012-06-13 20:25:24 +0000963 OS << (char)Char;
964 else // Output anything hard as an octal escape.
965 OS << '\\'
966 << (char)('0' + ((Char >> 6) & 7))
967 << (char)('0' + ((Char >> 3) & 7))
968 << (char)('0' + ((Char >> 0) & 7));
969 break;
970 // Handle some common non-printable cases to make dumps prettier.
971 case '\\': OS << "\\\\"; break;
972 case '"': OS << "\\\""; break;
973 case '\n': OS << "\\n"; break;
974 case '\t': OS << "\\t"; break;
975 case '\a': OS << "\\a"; break;
976 case '\b': OS << "\\b"; break;
977 }
978 }
979 OS << '"';
980}
981
Craig Topper37932912013-08-18 10:09:15 +0000982void StringLiteral::setString(const ASTContext &C, StringRef Str,
Eli Friedmanfcec6302011-11-01 02:23:42 +0000983 StringKind Kind, bool IsPascal) {
984 //FIXME: we assume that the string data comes from a target that uses the same
985 // code unit size and endianess for the type of string.
986 this->Kind = Kind;
987 this->IsPascal = IsPascal;
988
Nick Lewycky4ed84042012-02-24 09:07:53 +0000989 CharByteWidth = mapCharByteWidth(C.getTargetInfo(),Kind);
Eli Friedmanfcec6302011-11-01 02:23:42 +0000990 assert((Str.size()%CharByteWidth == 0)
991 && "size of data must be multiple of CharByteWidth");
992 Length = Str.size()/CharByteWidth;
993
994 switch(CharByteWidth) {
995 case 1: {
996 char *AStrData = new (C) char[Length];
Argyrios Kyrtzidis61710892012-09-14 21:17:41 +0000997 std::memcpy(AStrData,Str.data(),Length*sizeof(*AStrData));
Eli Friedmanfcec6302011-11-01 02:23:42 +0000998 StrData.asChar = AStrData;
999 break;
1000 }
1001 case 2: {
1002 uint16_t *AStrData = new (C) uint16_t[Length];
Argyrios Kyrtzidis61710892012-09-14 21:17:41 +00001003 std::memcpy(AStrData,Str.data(),Length*sizeof(*AStrData));
Eli Friedmanfcec6302011-11-01 02:23:42 +00001004 StrData.asUInt16 = AStrData;
1005 break;
1006 }
1007 case 4: {
1008 uint32_t *AStrData = new (C) uint32_t[Length];
Argyrios Kyrtzidis61710892012-09-14 21:17:41 +00001009 std::memcpy(AStrData,Str.data(),Length*sizeof(*AStrData));
Eli Friedmanfcec6302011-11-01 02:23:42 +00001010 StrData.asUInt32 = AStrData;
1011 break;
1012 }
1013 default:
Davide Italiano04839a52016-01-30 08:03:54 +00001014 llvm_unreachable("unsupported CharByteWidth");
Eli Friedmanfcec6302011-11-01 02:23:42 +00001015 }
Douglas Gregor958dfc92009-04-15 16:35:07 +00001016}
1017
Chris Lattnere925d612010-11-17 07:37:15 +00001018/// getLocationOfByte - Return a source location that points to the specified
1019/// byte of this string literal.
1020///
1021/// Strings are amazingly complex. They can be formed from multiple tokens and
1022/// can have escape sequences in them in addition to the usual trigraph and
1023/// escaped newline business. This routine handles this complexity.
1024///
Richard Smithefb116f2015-12-10 01:11:47 +00001025/// The *StartToken sets the first token to be searched in this function and
1026/// the *StartTokenByteOffset is the byte offset of the first token. Before
1027/// returning, it updates the *StartToken to the TokNo of the token being found
1028/// and sets *StartTokenByteOffset to the byte offset of the token in the
1029/// string.
1030/// Using these two parameters can reduce the time complexity from O(n^2) to
1031/// O(n) if one wants to get the location of byte for all the tokens in a
1032/// string.
1033///
1034SourceLocation
1035StringLiteral::getLocationOfByte(unsigned ByteNo, const SourceManager &SM,
1036 const LangOptions &Features,
1037 const TargetInfo &Target, unsigned *StartToken,
1038 unsigned *StartTokenByteOffset) const {
Richard Smith4060f772012-06-13 05:37:23 +00001039 assert((Kind == StringLiteral::Ascii || Kind == StringLiteral::UTF8) &&
1040 "Only narrow string literals are currently supported");
Douglas Gregorfb65e592011-07-27 05:40:30 +00001041
Chris Lattnere925d612010-11-17 07:37:15 +00001042 // Loop over all of the tokens in this string until we find the one that
1043 // contains the byte we're looking for.
1044 unsigned TokNo = 0;
Richard Smithefb116f2015-12-10 01:11:47 +00001045 unsigned StringOffset = 0;
1046 if (StartToken)
1047 TokNo = *StartToken;
1048 if (StartTokenByteOffset) {
1049 StringOffset = *StartTokenByteOffset;
1050 ByteNo -= StringOffset;
1051 }
Chris Lattnere925d612010-11-17 07:37:15 +00001052 while (1) {
1053 assert(TokNo < getNumConcatenated() && "Invalid byte number!");
1054 SourceLocation StrTokLoc = getStrTokenLoc(TokNo);
1055
1056 // Get the spelling of the string so that we can get the data that makes up
1057 // the string literal, not the identifier for the macro it is potentially
1058 // expanded through.
1059 SourceLocation StrTokSpellingLoc = SM.getSpellingLoc(StrTokLoc);
Richard Smithefb116f2015-12-10 01:11:47 +00001060
Chris Lattnere925d612010-11-17 07:37:15 +00001061 // Re-lex the token to get its length and original spelling.
Richard Smithefb116f2015-12-10 01:11:47 +00001062 std::pair<FileID, unsigned> LocInfo =
1063 SM.getDecomposedLoc(StrTokSpellingLoc);
Chris Lattnere925d612010-11-17 07:37:15 +00001064 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001065 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
Richard Smithefb116f2015-12-10 01:11:47 +00001066 if (Invalid) {
1067 if (StartTokenByteOffset != nullptr)
1068 *StartTokenByteOffset = StringOffset;
1069 if (StartToken != nullptr)
1070 *StartToken = TokNo;
Chris Lattnere925d612010-11-17 07:37:15 +00001071 return StrTokSpellingLoc;
Richard Smithefb116f2015-12-10 01:11:47 +00001072 }
1073
Chris Lattnere925d612010-11-17 07:37:15 +00001074 const char *StrData = Buffer.data()+LocInfo.second;
1075
Chris Lattnere925d612010-11-17 07:37:15 +00001076 // Create a lexer starting at the beginning of this token.
Argyrios Kyrtzidis45f51182012-05-11 21:39:18 +00001077 Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), Features,
1078 Buffer.begin(), StrData, Buffer.end());
Chris Lattnere925d612010-11-17 07:37:15 +00001079 Token TheTok;
1080 TheLexer.LexFromRawLexer(TheTok);
1081
1082 // Use the StringLiteralParser to compute the length of the string in bytes.
Craig Topper9d5583e2014-06-26 04:58:39 +00001083 StringLiteralParser SLP(TheTok, SM, Features, Target);
Chris Lattnere925d612010-11-17 07:37:15 +00001084 unsigned TokNumBytes = SLP.GetStringLength();
1085
1086 // If the byte is in this token, return the location of the byte.
1087 if (ByteNo < TokNumBytes ||
Hans Wennborg77d1abe2011-06-30 20:17:41 +00001088 (ByteNo == TokNumBytes && TokNo == getNumConcatenated() - 1)) {
Richard Smithefb116f2015-12-10 01:11:47 +00001089 unsigned Offset = SLP.getOffsetOfStringByte(TheTok, ByteNo);
1090
Chris Lattnere925d612010-11-17 07:37:15 +00001091 // Now that we know the offset of the token in the spelling, use the
1092 // preprocessor to get the offset in the original source.
Richard Smithefb116f2015-12-10 01:11:47 +00001093 if (StartTokenByteOffset != nullptr)
1094 *StartTokenByteOffset = StringOffset;
1095 if (StartToken != nullptr)
1096 *StartToken = TokNo;
Chris Lattnere925d612010-11-17 07:37:15 +00001097 return Lexer::AdvanceToTokenCharacter(StrTokLoc, Offset, SM, Features);
1098 }
Richard Smithefb116f2015-12-10 01:11:47 +00001099
Chris Lattnere925d612010-11-17 07:37:15 +00001100 // Move to the next string token.
Richard Smithefb116f2015-12-10 01:11:47 +00001101 StringOffset += TokNumBytes;
Chris Lattnere925d612010-11-17 07:37:15 +00001102 ++TokNo;
1103 ByteNo -= TokNumBytes;
1104 }
1105}
1106
1107
1108
Chris Lattner1b926492006-08-23 06:42:10 +00001109/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1110/// corresponds to, e.g. "sizeof" or "[pre]++".
David Blaikie1d202a62012-10-08 01:11:04 +00001111StringRef UnaryOperator::getOpcodeStr(Opcode Op) {
Chris Lattner1b926492006-08-23 06:42:10 +00001112 switch (Op) {
Etienne Bergeron5356d962016-05-12 20:58:56 +00001113#define UNARY_OPERATION(Name, Spelling) case UO_##Name: return Spelling;
1114#include "clang/AST/OperationKinds.def"
Chris Lattner1b926492006-08-23 06:42:10 +00001115 }
David Blaikief47fa302012-01-17 02:30:50 +00001116 llvm_unreachable("Unknown unary operator");
Chris Lattner1b926492006-08-23 06:42:10 +00001117}
1118
John McCalle3027922010-08-25 11:45:40 +00001119UnaryOperatorKind
Douglas Gregor084d8552009-03-13 23:49:33 +00001120UnaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix) {
1121 switch (OO) {
David Blaikie83d382b2011-09-23 05:06:16 +00001122 default: llvm_unreachable("No unary operator for overloaded function");
John McCalle3027922010-08-25 11:45:40 +00001123 case OO_PlusPlus: return Postfix ? UO_PostInc : UO_PreInc;
1124 case OO_MinusMinus: return Postfix ? UO_PostDec : UO_PreDec;
1125 case OO_Amp: return UO_AddrOf;
1126 case OO_Star: return UO_Deref;
1127 case OO_Plus: return UO_Plus;
1128 case OO_Minus: return UO_Minus;
1129 case OO_Tilde: return UO_Not;
1130 case OO_Exclaim: return UO_LNot;
Richard Smith9f690bd2015-10-27 06:02:45 +00001131 case OO_Coawait: return UO_Coawait;
Douglas Gregor084d8552009-03-13 23:49:33 +00001132 }
1133}
1134
1135OverloadedOperatorKind UnaryOperator::getOverloadedOperator(Opcode Opc) {
1136 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00001137 case UO_PostInc: case UO_PreInc: return OO_PlusPlus;
1138 case UO_PostDec: case UO_PreDec: return OO_MinusMinus;
1139 case UO_AddrOf: return OO_Amp;
1140 case UO_Deref: return OO_Star;
1141 case UO_Plus: return OO_Plus;
1142 case UO_Minus: return OO_Minus;
1143 case UO_Not: return OO_Tilde;
1144 case UO_LNot: return OO_Exclaim;
Richard Smith9f690bd2015-10-27 06:02:45 +00001145 case UO_Coawait: return OO_Coawait;
Douglas Gregor084d8552009-03-13 23:49:33 +00001146 default: return OO_None;
1147 }
1148}
1149
1150
Chris Lattner0eedafe2006-08-24 04:56:27 +00001151//===----------------------------------------------------------------------===//
1152// Postfix Operators.
1153//===----------------------------------------------------------------------===//
Chris Lattnere165d942006-08-24 04:40:38 +00001154
Justin Lebarf8bdacb2016-01-14 23:31:30 +00001155CallExpr::CallExpr(const ASTContext &C, StmtClass SC, Expr *fn,
1156 ArrayRef<Expr *> preargs, ArrayRef<Expr *> args, QualType t,
Craig Topper37932912013-08-18 10:09:15 +00001157 ExprValueKind VK, SourceLocation rparenloc)
Justin Lebarf8bdacb2016-01-14 23:31:30 +00001158 : Expr(SC, t, VK, OK_Ordinary, fn->isTypeDependent(),
1159 fn->isValueDependent(), fn->isInstantiationDependent(),
1160 fn->containsUnexpandedParameterPack()),
1161 NumArgs(args.size()) {
Mike Stump11289f42009-09-09 15:08:12 +00001162
Justin Lebarf8bdacb2016-01-14 23:31:30 +00001163 unsigned NumPreArgs = preargs.size();
1164 SubExprs = new (C) Stmt *[args.size()+PREARGS_START+NumPreArgs];
Douglas Gregor993603d2008-11-14 16:09:21 +00001165 SubExprs[FN] = fn;
Justin Lebarf8bdacb2016-01-14 23:31:30 +00001166 for (unsigned i = 0; i != NumPreArgs; ++i) {
1167 updateDependenciesFromArg(preargs[i]);
1168 SubExprs[i+PREARGS_START] = preargs[i];
1169 }
Benjamin Kramerc215e762012-08-24 11:54:20 +00001170 for (unsigned i = 0; i != args.size(); ++i) {
Justin Lebarf8bdacb2016-01-14 23:31:30 +00001171 updateDependenciesFromArg(args[i]);
Peter Collingbourne3a347252011-02-08 21:18:02 +00001172 SubExprs[i+PREARGS_START+NumPreArgs] = args[i];
Douglas Gregora6e053e2010-12-15 01:34:56 +00001173 }
Ted Kremenekd7b4f402009-02-09 20:51:47 +00001174
Peter Collingbourne3a347252011-02-08 21:18:02 +00001175 CallExprBits.NumPreArgs = NumPreArgs;
Douglas Gregor993603d2008-11-14 16:09:21 +00001176 RParenLoc = rparenloc;
1177}
Nate Begeman1e36a852008-01-17 17:46:27 +00001178
Justin Lebarf8bdacb2016-01-14 23:31:30 +00001179CallExpr::CallExpr(const ASTContext &C, StmtClass SC, Expr *fn,
1180 ArrayRef<Expr *> args, QualType t, ExprValueKind VK,
1181 SourceLocation rparenloc)
1182 : CallExpr(C, SC, fn, ArrayRef<Expr *>(), args, t, VK, rparenloc) {}
1183
Benjamin Kramerf04f98d2015-03-06 14:15:57 +00001184CallExpr::CallExpr(const ASTContext &C, Expr *fn, ArrayRef<Expr *> args,
John McCall7decc9e2010-11-18 06:31:45 +00001185 QualType t, ExprValueKind VK, SourceLocation rparenloc)
Justin Lebarf8bdacb2016-01-14 23:31:30 +00001186 : CallExpr(C, CallExprClass, fn, ArrayRef<Expr *>(), args, t, VK, rparenloc) {
Chris Lattnere165d942006-08-24 04:40:38 +00001187}
1188
Craig Topper37932912013-08-18 10:09:15 +00001189CallExpr::CallExpr(const ASTContext &C, StmtClass SC, EmptyShell Empty)
Benjamin Kramerf04f98d2015-03-06 14:15:57 +00001190 : CallExpr(C, SC, /*NumPreArgs=*/0, Empty) {}
Peter Collingbourne3a347252011-02-08 21:18:02 +00001191
Craig Topper37932912013-08-18 10:09:15 +00001192CallExpr::CallExpr(const ASTContext &C, StmtClass SC, unsigned NumPreArgs,
Peter Collingbourne3a347252011-02-08 21:18:02 +00001193 EmptyShell Empty)
Craig Topper36250ad2014-05-12 05:36:57 +00001194 : Expr(SC, Empty), SubExprs(nullptr), NumArgs(0) {
Peter Collingbourne3a347252011-02-08 21:18:02 +00001195 // FIXME: Why do we allocate this?
Justin Lebarf8bdacb2016-01-14 23:31:30 +00001196 SubExprs = new (C) Stmt*[PREARGS_START+NumPreArgs]();
Peter Collingbourne3a347252011-02-08 21:18:02 +00001197 CallExprBits.NumPreArgs = NumPreArgs;
Douglas Gregore20a2e52009-04-15 17:43:59 +00001198}
1199
Justin Lebarf8bdacb2016-01-14 23:31:30 +00001200void CallExpr::updateDependenciesFromArg(Expr *Arg) {
1201 if (Arg->isTypeDependent())
1202 ExprBits.TypeDependent = true;
1203 if (Arg->isValueDependent())
1204 ExprBits.ValueDependent = true;
1205 if (Arg->isInstantiationDependent())
1206 ExprBits.InstantiationDependent = true;
1207 if (Arg->containsUnexpandedParameterPack())
1208 ExprBits.ContainsUnexpandedParameterPack = true;
1209}
1210
John McCallb92ab1a2016-10-26 23:46:34 +00001211FunctionDecl *CallExpr::getDirectCallee() {
1212 return dyn_cast_or_null<FunctionDecl>(getCalleeDecl());
1213}
1214
Nuno Lopes518e3702009-12-20 23:11:08 +00001215Decl *CallExpr::getCalleeDecl() {
John McCallb92ab1a2016-10-26 23:46:34 +00001216 return getCallee()->getReferencedDeclOfCallee();
1217}
1218
1219Decl *Expr::getReferencedDeclOfCallee() {
1220 Expr *CEE = IgnoreParenImpCasts();
Douglas Gregore0e96302011-09-06 21:41:04 +00001221
1222 while (SubstNonTypeTemplateParmExpr *NTTP
1223 = dyn_cast<SubstNonTypeTemplateParmExpr>(CEE)) {
1224 CEE = NTTP->getReplacement()->IgnoreParenCasts();
1225 }
1226
Sebastian Redl2b1832e2010-09-10 20:55:30 +00001227 // If we're calling a dereference, look at the pointer instead.
1228 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CEE)) {
1229 if (BO->isPtrMemOp())
1230 CEE = BO->getRHS()->IgnoreParenCasts();
1231 } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(CEE)) {
1232 if (UO->getOpcode() == UO_Deref)
1233 CEE = UO->getSubExpr()->IgnoreParenCasts();
1234 }
Chris Lattner52301912009-07-17 15:46:27 +00001235 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CEE))
Nuno Lopes518e3702009-12-20 23:11:08 +00001236 return DRE->getDecl();
Nuno Lopesc095b532009-12-24 00:28:18 +00001237 if (MemberExpr *ME = dyn_cast<MemberExpr>(CEE))
1238 return ME->getMemberDecl();
Zhongxing Xu3c8fa972009-07-17 07:29:51 +00001239
Craig Topper36250ad2014-05-12 05:36:57 +00001240 return nullptr;
Zhongxing Xu3c8fa972009-07-17 07:29:51 +00001241}
1242
Chris Lattnere4407ed2007-12-28 05:25:02 +00001243/// setNumArgs - This changes the number of arguments present in this call.
1244/// Any orphaned expressions are deleted by this, and any new operands are set
1245/// to null.
Craig Topper37932912013-08-18 10:09:15 +00001246void CallExpr::setNumArgs(const ASTContext& C, unsigned NumArgs) {
Chris Lattnere4407ed2007-12-28 05:25:02 +00001247 // No change, just return.
1248 if (NumArgs == getNumArgs()) return;
Mike Stump11289f42009-09-09 15:08:12 +00001249
Chris Lattnere4407ed2007-12-28 05:25:02 +00001250 // If shrinking # arguments, just delete the extras and forgot them.
1251 if (NumArgs < getNumArgs()) {
Chris Lattnere4407ed2007-12-28 05:25:02 +00001252 this->NumArgs = NumArgs;
1253 return;
1254 }
1255
1256 // Otherwise, we are growing the # arguments. New an bigger argument array.
Peter Collingbourne3a347252011-02-08 21:18:02 +00001257 unsigned NumPreArgs = getNumPreArgs();
1258 Stmt **NewSubExprs = new (C) Stmt*[NumArgs+PREARGS_START+NumPreArgs];
Chris Lattnere4407ed2007-12-28 05:25:02 +00001259 // Copy over args.
Peter Collingbourne3a347252011-02-08 21:18:02 +00001260 for (unsigned i = 0; i != getNumArgs()+PREARGS_START+NumPreArgs; ++i)
Chris Lattnere4407ed2007-12-28 05:25:02 +00001261 NewSubExprs[i] = SubExprs[i];
1262 // Null out new args.
Peter Collingbourne3a347252011-02-08 21:18:02 +00001263 for (unsigned i = getNumArgs()+PREARGS_START+NumPreArgs;
1264 i != NumArgs+PREARGS_START+NumPreArgs; ++i)
Craig Topper36250ad2014-05-12 05:36:57 +00001265 NewSubExprs[i] = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001266
Douglas Gregorba6e5572009-04-17 21:46:47 +00001267 if (SubExprs) C.Deallocate(SubExprs);
Chris Lattnere4407ed2007-12-28 05:25:02 +00001268 SubExprs = NewSubExprs;
1269 this->NumArgs = NumArgs;
1270}
1271
Alp Tokera724cff2013-12-28 21:59:02 +00001272/// getBuiltinCallee - If this is a call to a builtin, return the builtin ID. If
Chris Lattner01ff98a2008-10-06 05:00:53 +00001273/// not, return 0.
Alp Tokera724cff2013-12-28 21:59:02 +00001274unsigned CallExpr::getBuiltinCallee() const {
Steve Narofff6e3b3292008-01-31 01:07:12 +00001275 // All simple function calls (e.g. func()) are implicitly cast to pointer to
Mike Stump11289f42009-09-09 15:08:12 +00001276 // function. As a result, we try and obtain the DeclRefExpr from the
Steve Narofff6e3b3292008-01-31 01:07:12 +00001277 // ImplicitCastExpr.
1278 const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(getCallee());
1279 if (!ICE) // FIXME: deal with more complex calls (e.g. (func)(), (*func)()).
Chris Lattner01ff98a2008-10-06 05:00:53 +00001280 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001281
Steve Narofff6e3b3292008-01-31 01:07:12 +00001282 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr());
1283 if (!DRE)
Chris Lattner01ff98a2008-10-06 05:00:53 +00001284 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001285
Anders Carlssonfbcf6762008-01-31 02:13:57 +00001286 const FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
1287 if (!FDecl)
Chris Lattner01ff98a2008-10-06 05:00:53 +00001288 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001289
Douglas Gregor9eb16ea2008-11-21 15:30:19 +00001290 if (!FDecl->getIdentifier())
1291 return 0;
1292
Douglas Gregor15fc9562009-09-12 00:22:50 +00001293 return FDecl->getBuiltinID();
Chris Lattner01ff98a2008-10-06 05:00:53 +00001294}
Anders Carlssonfbcf6762008-01-31 02:13:57 +00001295
Scott Douglass503fc392015-06-10 13:53:15 +00001296bool CallExpr::isUnevaluatedBuiltinCall(const ASTContext &Ctx) const {
Alp Tokera724cff2013-12-28 21:59:02 +00001297 if (unsigned BI = getBuiltinCallee())
Richard Smith5011a002013-01-17 23:46:04 +00001298 return Ctx.BuiltinInfo.isUnevaluated(BI);
1299 return false;
1300}
1301
David Majnemerced8bdf2015-02-25 17:36:15 +00001302QualType CallExpr::getCallReturnType(const ASTContext &Ctx) const {
1303 const Expr *Callee = getCallee();
1304 QualType CalleeType = Callee->getType();
1305 if (const auto *FnTypePtr = CalleeType->getAs<PointerType>()) {
Anders Carlsson00a27592009-05-26 04:57:27 +00001306 CalleeType = FnTypePtr->getPointeeType();
David Majnemerced8bdf2015-02-25 17:36:15 +00001307 } else if (const auto *BPT = CalleeType->getAs<BlockPointerType>()) {
Anders Carlsson00a27592009-05-26 04:57:27 +00001308 CalleeType = BPT->getPointeeType();
David Majnemerced8bdf2015-02-25 17:36:15 +00001309 } else if (CalleeType->isSpecificPlaceholderType(BuiltinType::BoundMember)) {
1310 if (isa<CXXPseudoDestructorExpr>(Callee->IgnoreParens()))
1311 return Ctx.VoidTy;
1312
John McCall0009fcc2011-04-26 20:42:42 +00001313 // This should never be overloaded and so should never return null.
David Majnemerced8bdf2015-02-25 17:36:15 +00001314 CalleeType = Expr::findBoundMemberType(Callee);
1315 }
1316
John McCall0009fcc2011-04-26 20:42:42 +00001317 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00001318 return FnType->getReturnType();
Anders Carlsson00a27592009-05-26 04:57:27 +00001319}
Chris Lattner01ff98a2008-10-06 05:00:53 +00001320
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001321SourceLocation CallExpr::getLocStart() const {
1322 if (isa<CXXOperatorCallExpr>(this))
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00001323 return cast<CXXOperatorCallExpr>(this)->getLocStart();
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001324
1325 SourceLocation begin = getCallee()->getLocStart();
Keno Fischer070db172014-08-15 01:39:12 +00001326 if (begin.isInvalid() && getNumArgs() > 0 && getArg(0))
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001327 begin = getArg(0)->getLocStart();
1328 return begin;
1329}
1330SourceLocation CallExpr::getLocEnd() const {
1331 if (isa<CXXOperatorCallExpr>(this))
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00001332 return cast<CXXOperatorCallExpr>(this)->getLocEnd();
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001333
1334 SourceLocation end = getRParenLoc();
Keno Fischer070db172014-08-15 01:39:12 +00001335 if (end.isInvalid() && getNumArgs() > 0 && getArg(getNumArgs() - 1))
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001336 end = getArg(getNumArgs() - 1)->getLocEnd();
1337 return end;
1338}
John McCall701417a2011-02-21 06:23:05 +00001339
Craig Topper37932912013-08-18 10:09:15 +00001340OffsetOfExpr *OffsetOfExpr::Create(const ASTContext &C, QualType type,
Douglas Gregor882211c2010-04-28 22:16:22 +00001341 SourceLocation OperatorLoc,
Alexis Hunta8136cc2010-05-05 15:23:54 +00001342 TypeSourceInfo *tsi,
Benjamin Kramerc215e762012-08-24 11:54:20 +00001343 ArrayRef<OffsetOfNode> comps,
1344 ArrayRef<Expr*> exprs,
Douglas Gregor882211c2010-04-28 22:16:22 +00001345 SourceLocation RParenLoc) {
James Y Knight7281c352015-12-29 22:31:18 +00001346 void *Mem = C.Allocate(
1347 totalSizeToAlloc<OffsetOfNode, Expr *>(comps.size(), exprs.size()));
Douglas Gregor882211c2010-04-28 22:16:22 +00001348
Benjamin Kramerc215e762012-08-24 11:54:20 +00001349 return new (Mem) OffsetOfExpr(C, type, OperatorLoc, tsi, comps, exprs,
1350 RParenLoc);
Douglas Gregor882211c2010-04-28 22:16:22 +00001351}
1352
Craig Topper37932912013-08-18 10:09:15 +00001353OffsetOfExpr *OffsetOfExpr::CreateEmpty(const ASTContext &C,
Douglas Gregor882211c2010-04-28 22:16:22 +00001354 unsigned numComps, unsigned numExprs) {
James Y Knight7281c352015-12-29 22:31:18 +00001355 void *Mem =
1356 C.Allocate(totalSizeToAlloc<OffsetOfNode, Expr *>(numComps, numExprs));
Douglas Gregor882211c2010-04-28 22:16:22 +00001357 return new (Mem) OffsetOfExpr(numComps, numExprs);
1358}
1359
Craig Topper37932912013-08-18 10:09:15 +00001360OffsetOfExpr::OffsetOfExpr(const ASTContext &C, QualType type,
Douglas Gregor882211c2010-04-28 22:16:22 +00001361 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
Benjamin Kramerc215e762012-08-24 11:54:20 +00001362 ArrayRef<OffsetOfNode> comps, ArrayRef<Expr*> exprs,
Douglas Gregor882211c2010-04-28 22:16:22 +00001363 SourceLocation RParenLoc)
John McCall7decc9e2010-11-18 06:31:45 +00001364 : Expr(OffsetOfExprClass, type, VK_RValue, OK_Ordinary,
1365 /*TypeDependent=*/false,
Douglas Gregora6e053e2010-12-15 01:34:56 +00001366 /*ValueDependent=*/tsi->getType()->isDependentType(),
Douglas Gregor678d76c2011-07-01 01:22:09 +00001367 tsi->getType()->isInstantiationDependentType(),
Douglas Gregora6e053e2010-12-15 01:34:56 +00001368 tsi->getType()->containsUnexpandedParameterPack()),
Alexis Hunta8136cc2010-05-05 15:23:54 +00001369 OperatorLoc(OperatorLoc), RParenLoc(RParenLoc), TSInfo(tsi),
Benjamin Kramerc215e762012-08-24 11:54:20 +00001370 NumComps(comps.size()), NumExprs(exprs.size())
Douglas Gregor882211c2010-04-28 22:16:22 +00001371{
Benjamin Kramerc215e762012-08-24 11:54:20 +00001372 for (unsigned i = 0; i != comps.size(); ++i) {
1373 setComponent(i, comps[i]);
Douglas Gregor882211c2010-04-28 22:16:22 +00001374 }
Alexis Hunta8136cc2010-05-05 15:23:54 +00001375
Benjamin Kramerc215e762012-08-24 11:54:20 +00001376 for (unsigned i = 0; i != exprs.size(); ++i) {
1377 if (exprs[i]->isTypeDependent() || exprs[i]->isValueDependent())
Douglas Gregora6e053e2010-12-15 01:34:56 +00001378 ExprBits.ValueDependent = true;
Benjamin Kramerc215e762012-08-24 11:54:20 +00001379 if (exprs[i]->containsUnexpandedParameterPack())
Douglas Gregora6e053e2010-12-15 01:34:56 +00001380 ExprBits.ContainsUnexpandedParameterPack = true;
1381
Benjamin Kramerc215e762012-08-24 11:54:20 +00001382 setIndexExpr(i, exprs[i]);
Douglas Gregor882211c2010-04-28 22:16:22 +00001383 }
1384}
1385
James Y Knight7281c352015-12-29 22:31:18 +00001386IdentifierInfo *OffsetOfNode::getFieldName() const {
Douglas Gregor882211c2010-04-28 22:16:22 +00001387 assert(getKind() == Field || getKind() == Identifier);
1388 if (getKind() == Field)
1389 return getField()->getIdentifier();
Alexis Hunta8136cc2010-05-05 15:23:54 +00001390
Douglas Gregor882211c2010-04-28 22:16:22 +00001391 return reinterpret_cast<IdentifierInfo *> (Data & ~(uintptr_t)Mask);
1392}
1393
David Majnemer10fd83d2015-01-15 10:04:14 +00001394UnaryExprOrTypeTraitExpr::UnaryExprOrTypeTraitExpr(
1395 UnaryExprOrTypeTrait ExprKind, Expr *E, QualType resultType,
1396 SourceLocation op, SourceLocation rp)
1397 : Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_RValue, OK_Ordinary,
1398 false, // Never type-dependent (C++ [temp.dep.expr]p3).
1399 // Value-dependent if the argument is type-dependent.
1400 E->isTypeDependent(), E->isInstantiationDependent(),
1401 E->containsUnexpandedParameterPack()),
1402 OpLoc(op), RParenLoc(rp) {
1403 UnaryExprOrTypeTraitExprBits.Kind = ExprKind;
1404 UnaryExprOrTypeTraitExprBits.IsType = false;
1405 Argument.Ex = E;
1406
1407 // Check to see if we are in the situation where alignof(decl) should be
1408 // dependent because decl's alignment is dependent.
1409 if (ExprKind == UETT_AlignOf) {
1410 if (!isValueDependent() || !isInstantiationDependent()) {
1411 E = E->IgnoreParens();
1412
1413 const ValueDecl *D = nullptr;
1414 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
1415 D = DRE->getDecl();
1416 else if (const auto *ME = dyn_cast<MemberExpr>(E))
1417 D = ME->getMemberDecl();
1418
1419 if (D) {
1420 for (const auto *I : D->specific_attrs<AlignedAttr>()) {
1421 if (I->isAlignmentDependent()) {
1422 setValueDependent(true);
1423 setInstantiationDependent(true);
1424 break;
1425 }
1426 }
1427 }
1428 }
1429 }
1430}
1431
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00001432MemberExpr *MemberExpr::Create(
1433 const ASTContext &C, Expr *base, bool isarrow, SourceLocation OperatorLoc,
1434 NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,
1435 ValueDecl *memberdecl, DeclAccessPair founddecl,
1436 DeclarationNameInfo nameinfo, const TemplateArgumentListInfo *targs,
1437 QualType ty, ExprValueKind vk, ExprObjectKind ok) {
John McCall16df1e52010-03-30 21:47:33 +00001438
Douglas Gregorea972d32011-02-28 21:54:11 +00001439 bool hasQualOrFound = (QualifierLoc ||
John McCalla8ae2222010-04-06 21:38:20 +00001440 founddecl.getDecl() != memberdecl ||
1441 founddecl.getAccess() != memberdecl->getAccess());
Mike Stump11289f42009-09-09 15:08:12 +00001442
James Y Knighte7d82282015-12-29 18:15:14 +00001443 bool HasTemplateKWAndArgsInfo = targs || TemplateKWLoc.isValid();
1444 std::size_t Size =
1445 totalSizeToAlloc<MemberExprNameQualifier, ASTTemplateKWAndArgsInfo,
1446 TemplateArgumentLoc>(hasQualOrFound ? 1 : 0,
1447 HasTemplateKWAndArgsInfo ? 1 : 0,
1448 targs ? targs->size() : 0);
Mike Stump11289f42009-09-09 15:08:12 +00001449
Benjamin Kramerc3f89252016-10-20 14:27:22 +00001450 void *Mem = C.Allocate(Size, alignof(MemberExpr));
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00001451 MemberExpr *E = new (Mem)
1452 MemberExpr(base, isarrow, OperatorLoc, memberdecl, nameinfo, ty, vk, ok);
John McCall16df1e52010-03-30 21:47:33 +00001453
1454 if (hasQualOrFound) {
Douglas Gregorea972d32011-02-28 21:54:11 +00001455 // FIXME: Wrong. We should be looking at the member declaration we found.
1456 if (QualifierLoc && QualifierLoc.getNestedNameSpecifier()->isDependent()) {
John McCall16df1e52010-03-30 21:47:33 +00001457 E->setValueDependent(true);
1458 E->setTypeDependent(true);
Douglas Gregor678d76c2011-07-01 01:22:09 +00001459 E->setInstantiationDependent(true);
1460 }
1461 else if (QualifierLoc &&
1462 QualifierLoc.getNestedNameSpecifier()->isInstantiationDependent())
1463 E->setInstantiationDependent(true);
1464
John McCall16df1e52010-03-30 21:47:33 +00001465 E->HasQualifierOrFoundDecl = true;
1466
James Y Knighte7d82282015-12-29 18:15:14 +00001467 MemberExprNameQualifier *NQ =
1468 E->getTrailingObjects<MemberExprNameQualifier>();
Douglas Gregorea972d32011-02-28 21:54:11 +00001469 NQ->QualifierLoc = QualifierLoc;
John McCall16df1e52010-03-30 21:47:33 +00001470 NQ->FoundDecl = founddecl;
1471 }
1472
Abramo Bagnara7945c982012-01-27 09:46:47 +00001473 E->HasTemplateKWAndArgsInfo = (targs || TemplateKWLoc.isValid());
1474
John McCall16df1e52010-03-30 21:47:33 +00001475 if (targs) {
Douglas Gregor678d76c2011-07-01 01:22:09 +00001476 bool Dependent = false;
1477 bool InstantiationDependent = false;
1478 bool ContainsUnexpandedParameterPack = false;
James Y Knighte7d82282015-12-29 18:15:14 +00001479 E->getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
1480 TemplateKWLoc, *targs, E->getTrailingObjects<TemplateArgumentLoc>(),
1481 Dependent, InstantiationDependent, ContainsUnexpandedParameterPack);
Douglas Gregor678d76c2011-07-01 01:22:09 +00001482 if (InstantiationDependent)
1483 E->setInstantiationDependent(true);
Abramo Bagnara7945c982012-01-27 09:46:47 +00001484 } else if (TemplateKWLoc.isValid()) {
James Y Knighte7d82282015-12-29 18:15:14 +00001485 E->getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
1486 TemplateKWLoc);
John McCall16df1e52010-03-30 21:47:33 +00001487 }
1488
1489 return E;
Douglas Gregorf405d7e2009-08-31 23:41:50 +00001490}
1491
Daniel Dunbarb507f272012-03-09 15:39:15 +00001492SourceLocation MemberExpr::getLocStart() const {
Douglas Gregor25b7e052011-03-02 21:06:53 +00001493 if (isImplicitAccess()) {
1494 if (hasQualifier())
Daniel Dunbarb507f272012-03-09 15:39:15 +00001495 return getQualifierLoc().getBeginLoc();
1496 return MemberLoc;
Douglas Gregor25b7e052011-03-02 21:06:53 +00001497 }
Abramo Bagnara7945c982012-01-27 09:46:47 +00001498
Daniel Dunbarb507f272012-03-09 15:39:15 +00001499 // FIXME: We don't want this to happen. Rather, we should be able to
1500 // detect all kinds of implicit accesses more cleanly.
1501 SourceLocation BaseStartLoc = getBase()->getLocStart();
1502 if (BaseStartLoc.isValid())
1503 return BaseStartLoc;
1504 return MemberLoc;
1505}
1506SourceLocation MemberExpr::getLocEnd() const {
Abramo Bagnara9b836fb2012-11-08 13:52:58 +00001507 SourceLocation EndLoc = getMemberNameInfo().getEndLoc();
Daniel Dunbarb507f272012-03-09 15:39:15 +00001508 if (hasExplicitTemplateArgs())
Abramo Bagnara9b836fb2012-11-08 13:52:58 +00001509 EndLoc = getRAngleLoc();
1510 else if (EndLoc.isInvalid())
1511 EndLoc = getBase()->getLocEnd();
1512 return EndLoc;
Douglas Gregor25b7e052011-03-02 21:06:53 +00001513}
1514
Alp Tokerc1086762013-12-07 13:51:35 +00001515bool CastExpr::CastConsistency() const {
John McCall9320b872011-09-09 05:25:32 +00001516 switch (getCastKind()) {
1517 case CK_DerivedToBase:
1518 case CK_UncheckedDerivedToBase:
1519 case CK_DerivedToBaseMemberPointer:
1520 case CK_BaseToDerived:
1521 case CK_BaseToDerivedMemberPointer:
1522 assert(!path_empty() && "Cast kind should have a base path!");
1523 break;
1524
1525 case CK_CPointerToObjCPointerCast:
1526 assert(getType()->isObjCObjectPointerType());
1527 assert(getSubExpr()->getType()->isPointerType());
1528 goto CheckNoBasePath;
1529
1530 case CK_BlockPointerToObjCPointerCast:
1531 assert(getType()->isObjCObjectPointerType());
1532 assert(getSubExpr()->getType()->isBlockPointerType());
1533 goto CheckNoBasePath;
1534
John McCallc62bb392012-02-15 01:22:51 +00001535 case CK_ReinterpretMemberPointer:
1536 assert(getType()->isMemberPointerType());
1537 assert(getSubExpr()->getType()->isMemberPointerType());
1538 goto CheckNoBasePath;
1539
John McCall9320b872011-09-09 05:25:32 +00001540 case CK_BitCast:
1541 // Arbitrary casts to C pointer types count as bitcasts.
1542 // Otherwise, we should only have block and ObjC pointer casts
1543 // here if they stay within the type kind.
1544 if (!getType()->isPointerType()) {
1545 assert(getType()->isObjCObjectPointerType() ==
1546 getSubExpr()->getType()->isObjCObjectPointerType());
1547 assert(getType()->isBlockPointerType() ==
1548 getSubExpr()->getType()->isBlockPointerType());
1549 }
1550 goto CheckNoBasePath;
1551
1552 case CK_AnyPointerToBlockPointerCast:
1553 assert(getType()->isBlockPointerType());
1554 assert(getSubExpr()->getType()->isAnyPointerType() &&
1555 !getSubExpr()->getType()->isBlockPointerType());
1556 goto CheckNoBasePath;
1557
Douglas Gregored90df32012-02-22 05:02:47 +00001558 case CK_CopyAndAutoreleaseBlockObject:
1559 assert(getType()->isBlockPointerType());
1560 assert(getSubExpr()->getType()->isBlockPointerType());
1561 goto CheckNoBasePath;
Eli Friedman34866c72012-08-31 00:14:07 +00001562
1563 case CK_FunctionToPointerDecay:
1564 assert(getType()->isPointerType());
1565 assert(getSubExpr()->getType()->isFunctionType());
1566 goto CheckNoBasePath;
1567
David Tweede1468322013-12-11 13:39:46 +00001568 case CK_AddressSpaceConversion:
1569 assert(getType()->isPointerType());
1570 assert(getSubExpr()->getType()->isPointerType());
1571 assert(getType()->getPointeeType().getAddressSpace() !=
1572 getSubExpr()->getType()->getPointeeType().getAddressSpace());
John McCall9320b872011-09-09 05:25:32 +00001573 // These should not have an inheritance path.
1574 case CK_Dynamic:
1575 case CK_ToUnion:
1576 case CK_ArrayToPointerDecay:
John McCall9320b872011-09-09 05:25:32 +00001577 case CK_NullToMemberPointer:
1578 case CK_NullToPointer:
1579 case CK_ConstructorConversion:
1580 case CK_IntegralToPointer:
1581 case CK_PointerToIntegral:
1582 case CK_ToVoid:
1583 case CK_VectorSplat:
1584 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +00001585 case CK_BooleanToSignedIntegral:
John McCall9320b872011-09-09 05:25:32 +00001586 case CK_IntegralToFloating:
1587 case CK_FloatingToIntegral:
1588 case CK_FloatingCast:
1589 case CK_ObjCObjectLValueCast:
1590 case CK_FloatingRealToComplex:
1591 case CK_FloatingComplexToReal:
1592 case CK_FloatingComplexCast:
1593 case CK_FloatingComplexToIntegralComplex:
1594 case CK_IntegralRealToComplex:
1595 case CK_IntegralComplexToReal:
1596 case CK_IntegralComplexCast:
1597 case CK_IntegralComplexToFloatingComplex:
John McCall2d637d22011-09-10 06:18:15 +00001598 case CK_ARCProduceObject:
1599 case CK_ARCConsumeObject:
1600 case CK_ARCReclaimReturnedObject:
1601 case CK_ARCExtendBlockObject:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001602 case CK_ZeroToOCLEvent:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00001603 case CK_IntToOCLSampler:
John McCall9320b872011-09-09 05:25:32 +00001604 assert(!getType()->isBooleanType() && "unheralded conversion to bool");
1605 goto CheckNoBasePath;
1606
1607 case CK_Dependent:
1608 case CK_LValueToRValue:
John McCall9320b872011-09-09 05:25:32 +00001609 case CK_NoOp:
David Chisnallfa35df62012-01-16 17:27:18 +00001610 case CK_AtomicToNonAtomic:
1611 case CK_NonAtomicToAtomic:
John McCall9320b872011-09-09 05:25:32 +00001612 case CK_PointerToBoolean:
1613 case CK_IntegralToBoolean:
1614 case CK_FloatingToBoolean:
1615 case CK_MemberPointerToBoolean:
1616 case CK_FloatingComplexToBoolean:
1617 case CK_IntegralComplexToBoolean:
1618 case CK_LValueBitCast: // -> bool&
1619 case CK_UserDefinedConversion: // operator bool()
Eli Friedman34866c72012-08-31 00:14:07 +00001620 case CK_BuiltinFnToFnPtr:
John McCall9320b872011-09-09 05:25:32 +00001621 CheckNoBasePath:
1622 assert(path_empty() && "Cast kind should not have a base path!");
1623 break;
1624 }
Alp Tokerc1086762013-12-07 13:51:35 +00001625 return true;
John McCall9320b872011-09-09 05:25:32 +00001626}
1627
Anders Carlsson496335e2009-09-03 00:59:21 +00001628const char *CastExpr::getCastKindName() const {
1629 switch (getCastKind()) {
Etienne Bergeron5356d962016-05-12 20:58:56 +00001630#define CAST_OPERATION(Name) case CK_##Name: return #Name;
1631#include "clang/AST/OperationKinds.def"
Anders Carlsson496335e2009-09-03 00:59:21 +00001632 }
John McCallc5e62b42010-11-13 09:02:35 +00001633 llvm_unreachable("Unhandled cast kind!");
Anders Carlsson496335e2009-09-03 00:59:21 +00001634}
1635
Douglas Gregord196a582009-12-14 19:27:10 +00001636Expr *CastExpr::getSubExprAsWritten() {
Craig Topper36250ad2014-05-12 05:36:57 +00001637 Expr *SubExpr = nullptr;
Douglas Gregord196a582009-12-14 19:27:10 +00001638 CastExpr *E = this;
1639 do {
1640 SubExpr = E->getSubExpr();
Douglas Gregorfe314812011-06-21 17:03:29 +00001641
1642 // Skip through reference binding to temporary.
1643 if (MaterializeTemporaryExpr *Materialize
1644 = dyn_cast<MaterializeTemporaryExpr>(SubExpr))
1645 SubExpr = Materialize->GetTemporaryExpr();
1646
Douglas Gregord196a582009-12-14 19:27:10 +00001647 // Skip any temporary bindings; they're implicit.
1648 if (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(SubExpr))
1649 SubExpr = Binder->getSubExpr();
Alexis Hunta8136cc2010-05-05 15:23:54 +00001650
Douglas Gregord196a582009-12-14 19:27:10 +00001651 // Conversions by constructor and conversion functions have a
1652 // subexpression describing the call; strip it off.
John McCalle3027922010-08-25 11:45:40 +00001653 if (E->getCastKind() == CK_ConstructorConversion)
Douglas Gregord196a582009-12-14 19:27:10 +00001654 SubExpr = cast<CXXConstructExpr>(SubExpr)->getArg(0);
Manman Ren8abc2e52016-02-02 22:23:03 +00001655 else if (E->getCastKind() == CK_UserDefinedConversion) {
1656 assert((isa<CXXMemberCallExpr>(SubExpr) ||
1657 isa<BlockExpr>(SubExpr)) &&
1658 "Unexpected SubExpr for CK_UserDefinedConversion.");
1659 if (isa<CXXMemberCallExpr>(SubExpr))
1660 SubExpr = cast<CXXMemberCallExpr>(SubExpr)->getImplicitObjectArgument();
1661 }
Alexis Hunta8136cc2010-05-05 15:23:54 +00001662
Douglas Gregord196a582009-12-14 19:27:10 +00001663 // If the subexpression we're left with is an implicit cast, look
1664 // through that, too.
Alexis Hunta8136cc2010-05-05 15:23:54 +00001665 } while ((E = dyn_cast<ImplicitCastExpr>(SubExpr)));
1666
Douglas Gregord196a582009-12-14 19:27:10 +00001667 return SubExpr;
1668}
1669
John McCallcf142162010-08-07 06:22:56 +00001670CXXBaseSpecifier **CastExpr::path_buffer() {
1671 switch (getStmtClass()) {
1672#define ABSTRACT_STMT(x)
James Y Knight1d75c5e2015-12-30 02:27:28 +00001673#define CASTEXPR(Type, Base) \
1674 case Stmt::Type##Class: \
1675 return static_cast<Type *>(this)->getTrailingObjects<CXXBaseSpecifier *>();
John McCallcf142162010-08-07 06:22:56 +00001676#define STMT(Type, Base)
1677#include "clang/AST/StmtNodes.inc"
1678 default:
1679 llvm_unreachable("non-cast expressions not possible here");
John McCallcf142162010-08-07 06:22:56 +00001680 }
1681}
1682
Craig Topper37932912013-08-18 10:09:15 +00001683ImplicitCastExpr *ImplicitCastExpr::Create(const ASTContext &C, QualType T,
John McCallcf142162010-08-07 06:22:56 +00001684 CastKind Kind, Expr *Operand,
1685 const CXXCastPath *BasePath,
John McCall2536c6d2010-08-25 10:28:54 +00001686 ExprValueKind VK) {
John McCallcf142162010-08-07 06:22:56 +00001687 unsigned PathSize = (BasePath ? BasePath->size() : 0);
James Y Knight1d75c5e2015-12-30 02:27:28 +00001688 void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
John McCallcf142162010-08-07 06:22:56 +00001689 ImplicitCastExpr *E =
John McCall2536c6d2010-08-25 10:28:54 +00001690 new (Buffer) ImplicitCastExpr(T, Kind, Operand, PathSize, VK);
James Y Knight1d75c5e2015-12-30 02:27:28 +00001691 if (PathSize)
1692 std::uninitialized_copy_n(BasePath->data(), BasePath->size(),
1693 E->getTrailingObjects<CXXBaseSpecifier *>());
John McCallcf142162010-08-07 06:22:56 +00001694 return E;
1695}
1696
Craig Topper37932912013-08-18 10:09:15 +00001697ImplicitCastExpr *ImplicitCastExpr::CreateEmpty(const ASTContext &C,
John McCallcf142162010-08-07 06:22:56 +00001698 unsigned PathSize) {
James Y Knight1d75c5e2015-12-30 02:27:28 +00001699 void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
John McCallcf142162010-08-07 06:22:56 +00001700 return new (Buffer) ImplicitCastExpr(EmptyShell(), PathSize);
1701}
1702
1703
Craig Topper37932912013-08-18 10:09:15 +00001704CStyleCastExpr *CStyleCastExpr::Create(const ASTContext &C, QualType T,
John McCall7decc9e2010-11-18 06:31:45 +00001705 ExprValueKind VK, CastKind K, Expr *Op,
John McCallcf142162010-08-07 06:22:56 +00001706 const CXXCastPath *BasePath,
1707 TypeSourceInfo *WrittenTy,
1708 SourceLocation L, SourceLocation R) {
1709 unsigned PathSize = (BasePath ? BasePath->size() : 0);
James Y Knight1d75c5e2015-12-30 02:27:28 +00001710 void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
John McCallcf142162010-08-07 06:22:56 +00001711 CStyleCastExpr *E =
John McCall7decc9e2010-11-18 06:31:45 +00001712 new (Buffer) CStyleCastExpr(T, VK, K, Op, PathSize, WrittenTy, L, R);
James Y Knight1d75c5e2015-12-30 02:27:28 +00001713 if (PathSize)
1714 std::uninitialized_copy_n(BasePath->data(), BasePath->size(),
1715 E->getTrailingObjects<CXXBaseSpecifier *>());
John McCallcf142162010-08-07 06:22:56 +00001716 return E;
1717}
1718
Craig Topper37932912013-08-18 10:09:15 +00001719CStyleCastExpr *CStyleCastExpr::CreateEmpty(const ASTContext &C,
1720 unsigned PathSize) {
James Y Knight1d75c5e2015-12-30 02:27:28 +00001721 void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
John McCallcf142162010-08-07 06:22:56 +00001722 return new (Buffer) CStyleCastExpr(EmptyShell(), PathSize);
1723}
1724
Chris Lattner1b926492006-08-23 06:42:10 +00001725/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1726/// corresponds to, e.g. "<<=".
David Blaikie1d202a62012-10-08 01:11:04 +00001727StringRef BinaryOperator::getOpcodeStr(Opcode Op) {
Chris Lattner1b926492006-08-23 06:42:10 +00001728 switch (Op) {
Etienne Bergeron5356d962016-05-12 20:58:56 +00001729#define BINARY_OPERATION(Name, Spelling) case BO_##Name: return Spelling;
1730#include "clang/AST/OperationKinds.def"
Chris Lattner1b926492006-08-23 06:42:10 +00001731 }
David Blaikiee4d798f2012-01-20 21:50:17 +00001732 llvm_unreachable("Invalid OpCode!");
Chris Lattner1b926492006-08-23 06:42:10 +00001733}
Steve Naroff47500512007-04-19 23:00:49 +00001734
John McCalle3027922010-08-25 11:45:40 +00001735BinaryOperatorKind
Douglas Gregor1baf54e2009-03-13 18:40:31 +00001736BinaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO) {
1737 switch (OO) {
David Blaikie83d382b2011-09-23 05:06:16 +00001738 default: llvm_unreachable("Not an overloadable binary operator");
John McCalle3027922010-08-25 11:45:40 +00001739 case OO_Plus: return BO_Add;
1740 case OO_Minus: return BO_Sub;
1741 case OO_Star: return BO_Mul;
1742 case OO_Slash: return BO_Div;
1743 case OO_Percent: return BO_Rem;
1744 case OO_Caret: return BO_Xor;
1745 case OO_Amp: return BO_And;
1746 case OO_Pipe: return BO_Or;
1747 case OO_Equal: return BO_Assign;
1748 case OO_Less: return BO_LT;
1749 case OO_Greater: return BO_GT;
1750 case OO_PlusEqual: return BO_AddAssign;
1751 case OO_MinusEqual: return BO_SubAssign;
1752 case OO_StarEqual: return BO_MulAssign;
1753 case OO_SlashEqual: return BO_DivAssign;
1754 case OO_PercentEqual: return BO_RemAssign;
1755 case OO_CaretEqual: return BO_XorAssign;
1756 case OO_AmpEqual: return BO_AndAssign;
1757 case OO_PipeEqual: return BO_OrAssign;
1758 case OO_LessLess: return BO_Shl;
1759 case OO_GreaterGreater: return BO_Shr;
1760 case OO_LessLessEqual: return BO_ShlAssign;
1761 case OO_GreaterGreaterEqual: return BO_ShrAssign;
1762 case OO_EqualEqual: return BO_EQ;
1763 case OO_ExclaimEqual: return BO_NE;
1764 case OO_LessEqual: return BO_LE;
1765 case OO_GreaterEqual: return BO_GE;
1766 case OO_AmpAmp: return BO_LAnd;
1767 case OO_PipePipe: return BO_LOr;
1768 case OO_Comma: return BO_Comma;
1769 case OO_ArrowStar: return BO_PtrMemI;
Douglas Gregor1baf54e2009-03-13 18:40:31 +00001770 }
1771}
1772
1773OverloadedOperatorKind BinaryOperator::getOverloadedOperator(Opcode Opc) {
1774 static const OverloadedOperatorKind OverOps[] = {
1775 /* .* Cannot be overloaded */OO_None, OO_ArrowStar,
1776 OO_Star, OO_Slash, OO_Percent,
1777 OO_Plus, OO_Minus,
1778 OO_LessLess, OO_GreaterGreater,
1779 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
1780 OO_EqualEqual, OO_ExclaimEqual,
1781 OO_Amp,
1782 OO_Caret,
1783 OO_Pipe,
1784 OO_AmpAmp,
1785 OO_PipePipe,
1786 OO_Equal, OO_StarEqual,
1787 OO_SlashEqual, OO_PercentEqual,
1788 OO_PlusEqual, OO_MinusEqual,
1789 OO_LessLessEqual, OO_GreaterGreaterEqual,
1790 OO_AmpEqual, OO_CaretEqual,
1791 OO_PipeEqual,
1792 OO_Comma
1793 };
1794 return OverOps[Opc];
1795}
1796
Craig Topper37932912013-08-18 10:09:15 +00001797InitListExpr::InitListExpr(const ASTContext &C, SourceLocation lbraceloc,
Benjamin Kramerc215e762012-08-24 11:54:20 +00001798 ArrayRef<Expr*> initExprs, SourceLocation rbraceloc)
Douglas Gregora6e053e2010-12-15 01:34:56 +00001799 : Expr(InitListExprClass, QualType(), VK_RValue, OK_Ordinary, false, false,
Douglas Gregor678d76c2011-07-01 01:22:09 +00001800 false, false),
Benjamin Kramerc215e762012-08-24 11:54:20 +00001801 InitExprs(C, initExprs.size()),
Craig Topper36250ad2014-05-12 05:36:57 +00001802 LBraceLoc(lbraceloc), RBraceLoc(rbraceloc), AltForm(nullptr, true)
Sebastian Redlc83ed822012-02-17 08:42:25 +00001803{
1804 sawArrayRangeDesignator(false);
Benjamin Kramerc215e762012-08-24 11:54:20 +00001805 for (unsigned I = 0; I != initExprs.size(); ++I) {
Ted Kremenek013041e2010-02-19 01:50:18 +00001806 if (initExprs[I]->isTypeDependent())
John McCall925b16622010-10-26 08:39:16 +00001807 ExprBits.TypeDependent = true;
Ted Kremenek013041e2010-02-19 01:50:18 +00001808 if (initExprs[I]->isValueDependent())
John McCall925b16622010-10-26 08:39:16 +00001809 ExprBits.ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +00001810 if (initExprs[I]->isInstantiationDependent())
1811 ExprBits.InstantiationDependent = true;
Douglas Gregora6e053e2010-12-15 01:34:56 +00001812 if (initExprs[I]->containsUnexpandedParameterPack())
1813 ExprBits.ContainsUnexpandedParameterPack = true;
Douglas Gregordeebf6e2009-11-19 23:25:22 +00001814 }
Alexis Hunta8136cc2010-05-05 15:23:54 +00001815
Benjamin Kramerc215e762012-08-24 11:54:20 +00001816 InitExprs.insert(C, InitExprs.end(), initExprs.begin(), initExprs.end());
Anders Carlsson4692db02007-08-31 04:56:16 +00001817}
Chris Lattner1ec5f562007-06-27 05:38:08 +00001818
Craig Topper37932912013-08-18 10:09:15 +00001819void InitListExpr::reserveInits(const ASTContext &C, unsigned NumInits) {
Ted Kremenek013041e2010-02-19 01:50:18 +00001820 if (NumInits > InitExprs.size())
Ted Kremenekac034612010-04-13 23:39:13 +00001821 InitExprs.reserve(C, NumInits);
Douglas Gregor6d00c992009-03-20 23:58:33 +00001822}
1823
Craig Topper37932912013-08-18 10:09:15 +00001824void InitListExpr::resizeInits(const ASTContext &C, unsigned NumInits) {
Craig Topper36250ad2014-05-12 05:36:57 +00001825 InitExprs.resize(C, NumInits, nullptr);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001826}
1827
Craig Topper37932912013-08-18 10:09:15 +00001828Expr *InitListExpr::updateInit(const ASTContext &C, unsigned Init, Expr *expr) {
Ted Kremenek013041e2010-02-19 01:50:18 +00001829 if (Init >= InitExprs.size()) {
Craig Topper36250ad2014-05-12 05:36:57 +00001830 InitExprs.insert(C, InitExprs.end(), Init - InitExprs.size() + 1, nullptr);
Richard Smithc275da62013-12-06 01:27:24 +00001831 setInit(Init, expr);
Craig Topper36250ad2014-05-12 05:36:57 +00001832 return nullptr;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001833 }
Mike Stump11289f42009-09-09 15:08:12 +00001834
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001835 Expr *Result = cast_or_null<Expr>(InitExprs[Init]);
Richard Smithc275da62013-12-06 01:27:24 +00001836 setInit(Init, expr);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001837 return Result;
1838}
1839
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +00001840void InitListExpr::setArrayFiller(Expr *filler) {
Argyrios Kyrtzidisd4590a5d2011-10-21 23:02:22 +00001841 assert(!hasArrayFiller() && "Filler already set!");
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +00001842 ArrayFillerOrUnionFieldInit = filler;
1843 // Fill out any "holes" in the array due to designated initializers.
1844 Expr **inits = getInits();
1845 for (unsigned i = 0, e = getNumInits(); i != e; ++i)
Craig Topper36250ad2014-05-12 05:36:57 +00001846 if (inits[i] == nullptr)
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +00001847 inits[i] = filler;
1848}
1849
Richard Smith9ec1e482012-04-15 02:50:59 +00001850bool InitListExpr::isStringLiteralInit() const {
1851 if (getNumInits() != 1)
1852 return false;
Eli Friedmancf4ab082012-08-20 20:55:45 +00001853 const ArrayType *AT = getType()->getAsArrayTypeUnsafe();
1854 if (!AT || !AT->getElementType()->isIntegerType())
Richard Smith9ec1e482012-04-15 02:50:59 +00001855 return false;
Ted Kremenek256bd962014-01-19 06:31:34 +00001856 // It is possible for getInit() to return null.
1857 const Expr *Init = getInit(0);
1858 if (!Init)
1859 return false;
1860 Init = Init->IgnoreParens();
Richard Smith9ec1e482012-04-15 02:50:59 +00001861 return isa<StringLiteral>(Init) || isa<ObjCEncodeExpr>(Init);
1862}
1863
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00001864SourceLocation InitListExpr::getLocStart() const {
Abramo Bagnara8d16bd42012-11-08 18:41:43 +00001865 if (InitListExpr *SyntacticForm = getSyntacticForm())
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00001866 return SyntacticForm->getLocStart();
1867 SourceLocation Beg = LBraceLoc;
Ted Kremenek16e6026f2010-11-09 02:11:40 +00001868 if (Beg.isInvalid()) {
1869 // Find the first non-null initializer.
1870 for (InitExprsTy::const_iterator I = InitExprs.begin(),
1871 E = InitExprs.end();
1872 I != E; ++I) {
1873 if (Stmt *S = *I) {
1874 Beg = S->getLocStart();
1875 break;
1876 }
1877 }
1878 }
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00001879 return Beg;
1880}
1881
1882SourceLocation InitListExpr::getLocEnd() const {
1883 if (InitListExpr *SyntacticForm = getSyntacticForm())
1884 return SyntacticForm->getLocEnd();
1885 SourceLocation End = RBraceLoc;
Ted Kremenek16e6026f2010-11-09 02:11:40 +00001886 if (End.isInvalid()) {
1887 // Find the first non-null initializer from the end.
1888 for (InitExprsTy::const_reverse_iterator I = InitExprs.rbegin(),
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00001889 E = InitExprs.rend();
1890 I != E; ++I) {
Ted Kremenek16e6026f2010-11-09 02:11:40 +00001891 if (Stmt *S = *I) {
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00001892 End = S->getLocEnd();
Ted Kremenek16e6026f2010-11-09 02:11:40 +00001893 break;
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00001894 }
Ted Kremenek16e6026f2010-11-09 02:11:40 +00001895 }
1896 }
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00001897 return End;
Ted Kremenek16e6026f2010-11-09 02:11:40 +00001898}
1899
Steve Naroff991e99d2008-09-04 15:31:07 +00001900/// getFunctionType - Return the underlying function type for this block.
Steve Naroffc540d662008-09-03 18:15:37 +00001901///
John McCallc833dea2012-02-17 03:32:35 +00001902const FunctionProtoType *BlockExpr::getFunctionType() const {
1903 // The block pointer is never sugared, but the function type might be.
1904 return cast<BlockPointerType>(getType())
1905 ->getPointeeType()->castAs<FunctionProtoType>();
Steve Naroffc540d662008-09-03 18:15:37 +00001906}
1907
Mike Stump11289f42009-09-09 15:08:12 +00001908SourceLocation BlockExpr::getCaretLocation() const {
1909 return TheBlock->getCaretLocation();
Steve Naroff415d3d52008-10-08 17:01:13 +00001910}
Mike Stump11289f42009-09-09 15:08:12 +00001911const Stmt *BlockExpr::getBody() const {
Douglas Gregore3dcb2d2009-04-18 00:02:19 +00001912 return TheBlock->getBody();
1913}
Mike Stump11289f42009-09-09 15:08:12 +00001914Stmt *BlockExpr::getBody() {
1915 return TheBlock->getBody();
Douglas Gregore3dcb2d2009-04-18 00:02:19 +00001916}
Steve Naroff415d3d52008-10-08 17:01:13 +00001917
1918
Chris Lattner1ec5f562007-06-27 05:38:08 +00001919//===----------------------------------------------------------------------===//
1920// Generic Expression Routines
1921//===----------------------------------------------------------------------===//
1922
Chris Lattner237f2752009-02-14 07:37:35 +00001923/// isUnusedResultAWarning - Return true if this immediate expression should
1924/// be warned about if the result is unused. If so, fill in Loc and Ranges
1925/// with location to warn on and the source range[s] to report with the
1926/// warning.
Eli Friedmanc11535c2012-05-24 00:47:05 +00001927bool Expr::isUnusedResultAWarning(const Expr *&WarnE, SourceLocation &Loc,
1928 SourceRange &R1, SourceRange &R2,
1929 ASTContext &Ctx) const {
Anders Carlsson789e2cc2009-05-15 23:10:19 +00001930 // Don't warn if the expr is type dependent. The type could end up
1931 // instantiating to void.
1932 if (isTypeDependent())
1933 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001934
Chris Lattner1ec5f562007-06-27 05:38:08 +00001935 switch (getStmtClass()) {
1936 default:
John McCallc493a732010-03-12 07:11:26 +00001937 if (getType()->isVoidType())
1938 return false;
Eli Friedmanc11535c2012-05-24 00:47:05 +00001939 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00001940 Loc = getExprLoc();
1941 R1 = getSourceRange();
1942 return true;
Chris Lattner1ec5f562007-06-27 05:38:08 +00001943 case ParenExprClass:
Chris Lattner237f2752009-02-14 07:37:35 +00001944 return cast<ParenExpr>(this)->getSubExpr()->
Eli Friedmanc11535c2012-05-24 00:47:05 +00001945 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00001946 case GenericSelectionExprClass:
1947 return cast<GenericSelectionExpr>(this)->getResultExpr()->
Eli Friedmanc11535c2012-05-24 00:47:05 +00001948 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Eli Friedman75807f22013-07-20 00:40:58 +00001949 case ChooseExprClass:
1950 return cast<ChooseExpr>(this)->getChosenSubExpr()->
1951 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Chris Lattner1ec5f562007-06-27 05:38:08 +00001952 case UnaryOperatorClass: {
1953 const UnaryOperator *UO = cast<UnaryOperator>(this);
Mike Stump11289f42009-09-09 15:08:12 +00001954
Chris Lattner1ec5f562007-06-27 05:38:08 +00001955 switch (UO->getOpcode()) {
Eli Friedmanc11535c2012-05-24 00:47:05 +00001956 case UO_Plus:
1957 case UO_Minus:
1958 case UO_AddrOf:
1959 case UO_Not:
1960 case UO_LNot:
1961 case UO_Deref:
1962 break;
Richard Smith9f690bd2015-10-27 06:02:45 +00001963 case UO_Coawait:
1964 // This is just the 'operator co_await' call inside the guts of a
1965 // dependent co_await call.
John McCalle3027922010-08-25 11:45:40 +00001966 case UO_PostInc:
1967 case UO_PostDec:
1968 case UO_PreInc:
1969 case UO_PreDec: // ++/--
Chris Lattner237f2752009-02-14 07:37:35 +00001970 return false; // Not a warning.
John McCalle3027922010-08-25 11:45:40 +00001971 case UO_Real:
1972 case UO_Imag:
Chris Lattnera44d1162007-06-27 05:58:59 +00001973 // accessing a piece of a volatile complex is a side-effect.
Mike Stump53f9ded2009-11-03 23:25:48 +00001974 if (Ctx.getCanonicalType(UO->getSubExpr()->getType())
1975 .isVolatileQualified())
Chris Lattner237f2752009-02-14 07:37:35 +00001976 return false;
1977 break;
John McCalle3027922010-08-25 11:45:40 +00001978 case UO_Extension:
Eli Friedmanc11535c2012-05-24 00:47:05 +00001979 return UO->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Chris Lattner1ec5f562007-06-27 05:38:08 +00001980 }
Eli Friedmanc11535c2012-05-24 00:47:05 +00001981 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00001982 Loc = UO->getOperatorLoc();
1983 R1 = UO->getSubExpr()->getSourceRange();
1984 return true;
Chris Lattner1ec5f562007-06-27 05:38:08 +00001985 }
Chris Lattnerae7a8342007-12-01 06:07:34 +00001986 case BinaryOperatorClass: {
Chris Lattner237f2752009-02-14 07:37:35 +00001987 const BinaryOperator *BO = cast<BinaryOperator>(this);
Ted Kremenek43a9c962010-04-07 18:49:21 +00001988 switch (BO->getOpcode()) {
1989 default:
1990 break;
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00001991 // Consider the RHS of comma for side effects. LHS was checked by
1992 // Sema::CheckCommaOperands.
John McCalle3027922010-08-25 11:45:40 +00001993 case BO_Comma:
Ted Kremenek43a9c962010-04-07 18:49:21 +00001994 // ((foo = <blah>), 0) is an idiom for hiding the result (and
1995 // lvalue-ness) of an assignment written in a macro.
1996 if (IntegerLiteral *IE =
1997 dyn_cast<IntegerLiteral>(BO->getRHS()->IgnoreParens()))
1998 if (IE->getValue() == 0)
1999 return false;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002000 return BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00002001 // Consider '||', '&&' to have side effects if the LHS or RHS does.
John McCalle3027922010-08-25 11:45:40 +00002002 case BO_LAnd:
2003 case BO_LOr:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002004 if (!BO->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx) ||
2005 !BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx))
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00002006 return false;
2007 break;
John McCall1e3715a2010-02-16 04:10:53 +00002008 }
Chris Lattner237f2752009-02-14 07:37:35 +00002009 if (BO->isAssignmentOp())
2010 return false;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002011 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002012 Loc = BO->getOperatorLoc();
2013 R1 = BO->getLHS()->getSourceRange();
2014 R2 = BO->getRHS()->getSourceRange();
2015 return true;
Chris Lattnerae7a8342007-12-01 06:07:34 +00002016 }
Chris Lattner86928112007-08-25 02:00:02 +00002017 case CompoundAssignOperatorClass:
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00002018 case VAArgExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002019 case AtomicExprClass:
Chris Lattner237f2752009-02-14 07:37:35 +00002020 return false;
Chris Lattner1ec5f562007-06-27 05:38:08 +00002021
Fariborz Jahanian9fac54d2007-12-01 19:58:28 +00002022 case ConditionalOperatorClass: {
Ted Kremeneke96dad92011-03-01 20:34:48 +00002023 // If only one of the LHS or RHS is a warning, the operator might
2024 // be being used for control flow. Only warn if both the LHS and
2025 // RHS are warnings.
Fariborz Jahanian9fac54d2007-12-01 19:58:28 +00002026 const ConditionalOperator *Exp = cast<ConditionalOperator>(this);
Eli Friedmanc11535c2012-05-24 00:47:05 +00002027 if (!Exp->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx))
Ted Kremeneke96dad92011-03-01 20:34:48 +00002028 return false;
2029 if (!Exp->getLHS())
Chris Lattner237f2752009-02-14 07:37:35 +00002030 return true;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002031 return Exp->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Fariborz Jahanian9fac54d2007-12-01 19:58:28 +00002032 }
2033
Chris Lattnera44d1162007-06-27 05:58:59 +00002034 case MemberExprClass:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002035 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002036 Loc = cast<MemberExpr>(this)->getMemberLoc();
2037 R1 = SourceRange(Loc, Loc);
2038 R2 = cast<MemberExpr>(this)->getBase()->getSourceRange();
2039 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002040
Chris Lattner1ec5f562007-06-27 05:38:08 +00002041 case ArraySubscriptExprClass:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002042 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002043 Loc = cast<ArraySubscriptExpr>(this)->getRBracketLoc();
2044 R1 = cast<ArraySubscriptExpr>(this)->getLHS()->getSourceRange();
2045 R2 = cast<ArraySubscriptExpr>(this)->getRHS()->getSourceRange();
2046 return true;
Eli Friedman824f8c12008-05-27 15:24:04 +00002047
Chandler Carruth46339472011-08-17 09:49:44 +00002048 case CXXOperatorCallExprClass: {
Richard Trieu99e1c952014-03-11 03:11:08 +00002049 // Warn about operator ==,!=,<,>,<=, and >= even when user-defined operator
Chandler Carruth46339472011-08-17 09:49:44 +00002050 // overloads as there is no reasonable way to define these such that they
2051 // have non-trivial, desirable side-effects. See the -Wunused-comparison
Richard Trieu99e1c952014-03-11 03:11:08 +00002052 // warning: operators == and != are commonly typo'ed, and so warning on them
Chandler Carruth46339472011-08-17 09:49:44 +00002053 // provides additional value as well. If this list is updated,
2054 // DiagnoseUnusedComparison should be as well.
2055 const CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(this);
Richard Trieu99e1c952014-03-11 03:11:08 +00002056 switch (Op->getOperator()) {
2057 default:
2058 break;
2059 case OO_EqualEqual:
2060 case OO_ExclaimEqual:
2061 case OO_Less:
2062 case OO_Greater:
2063 case OO_GreaterEqual:
2064 case OO_LessEqual:
David Majnemerced8bdf2015-02-25 17:36:15 +00002065 if (Op->getCallReturnType(Ctx)->isReferenceType() ||
2066 Op->getCallReturnType(Ctx)->isVoidType())
Richard Trieu161132b2014-05-14 23:22:10 +00002067 break;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002068 WarnE = this;
Matt Beaumont-Gaydcaacaa2011-09-19 18:51:20 +00002069 Loc = Op->getOperatorLoc();
2070 R1 = Op->getSourceRange();
Chandler Carruth46339472011-08-17 09:49:44 +00002071 return true;
Matt Beaumont-Gaydcaacaa2011-09-19 18:51:20 +00002072 }
Chandler Carruth46339472011-08-17 09:49:44 +00002073
2074 // Fallthrough for generic call handling.
2075 }
Chris Lattner1ec5f562007-06-27 05:38:08 +00002076 case CallExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00002077 case CXXMemberCallExprClass:
2078 case UserDefinedLiteralClass: {
Chris Lattner237f2752009-02-14 07:37:35 +00002079 // If this is a direct call, get the callee.
2080 const CallExpr *CE = cast<CallExpr>(this);
Nuno Lopes518e3702009-12-20 23:11:08 +00002081 if (const Decl *FD = CE->getCalleeDecl()) {
Kaelyn Takata0a2e84c2015-04-09 19:43:04 +00002082 const FunctionDecl *Func = dyn_cast<FunctionDecl>(FD);
2083 bool HasWarnUnusedResultAttr = Func ? Func->hasUnusedResultAttr()
2084 : FD->hasAttr<WarnUnusedResultAttr>();
2085
Chris Lattner237f2752009-02-14 07:37:35 +00002086 // If the callee has attribute pure, const, or warn_unused_result, warn
2087 // about it. void foo() { strlen("bar"); } should warn.
Chris Lattner1a6babf2009-10-13 04:53:48 +00002088 //
2089 // Note: If new cases are added here, DiagnoseUnusedExprResult should be
2090 // updated to match for QoI.
Kaelyn Takata0a2e84c2015-04-09 19:43:04 +00002091 if (HasWarnUnusedResultAttr ||
Aaron Ballman9ead1242013-12-19 02:39:40 +00002092 FD->hasAttr<PureAttr>() || FD->hasAttr<ConstAttr>()) {
Eli Friedmanc11535c2012-05-24 00:47:05 +00002093 WarnE = this;
Chris Lattner1a6babf2009-10-13 04:53:48 +00002094 Loc = CE->getCallee()->getLocStart();
2095 R1 = CE->getCallee()->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002096
Chris Lattner1a6babf2009-10-13 04:53:48 +00002097 if (unsigned NumArgs = CE->getNumArgs())
2098 R2 = SourceRange(CE->getArg(0)->getLocStart(),
2099 CE->getArg(NumArgs-1)->getLocEnd());
2100 return true;
2101 }
Chris Lattner237f2752009-02-14 07:37:35 +00002102 }
2103 return false;
2104 }
Anders Carlsson6aa50392009-11-17 17:11:23 +00002105
Matt Beaumont-Gayabf836c2012-10-23 06:15:26 +00002106 // If we don't know precisely what we're looking at, let's not warn.
2107 case UnresolvedLookupExprClass:
2108 case CXXUnresolvedConstructExprClass:
2109 return false;
2110
Anders Carlsson6aa50392009-11-17 17:11:23 +00002111 case CXXTemporaryObjectExprClass:
Lubos Lunak1f490f32013-07-21 13:15:58 +00002112 case CXXConstructExprClass: {
2113 if (const CXXRecordDecl *Type = getType()->getAsCXXRecordDecl()) {
2114 if (Type->hasAttr<WarnUnusedAttr>()) {
2115 WarnE = this;
2116 Loc = getLocStart();
2117 R1 = getSourceRange();
2118 return true;
2119 }
2120 }
Anders Carlsson6aa50392009-11-17 17:11:23 +00002121 return false;
Lubos Lunak1f490f32013-07-21 13:15:58 +00002122 }
Anders Carlsson6aa50392009-11-17 17:11:23 +00002123
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +00002124 case ObjCMessageExprClass: {
2125 const ObjCMessageExpr *ME = cast<ObjCMessageExpr>(this);
David Blaikiebbafb8a2012-03-11 07:00:24 +00002126 if (Ctx.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00002127 ME->isInstanceMessage() &&
2128 !ME->getType()->isVoidType() &&
Jean-Daniel Dupas06028a52013-07-19 20:25:56 +00002129 ME->getMethodFamily() == OMF_init) {
Eli Friedmanc11535c2012-05-24 00:47:05 +00002130 WarnE = this;
John McCall31168b02011-06-15 23:02:42 +00002131 Loc = getExprLoc();
2132 R1 = ME->getSourceRange();
2133 return true;
2134 }
2135
Fariborz Jahanianac6b4ef2014-07-18 22:59:10 +00002136 if (const ObjCMethodDecl *MD = ME->getMethodDecl())
Fariborz Jahanianb0553e22015-02-16 23:49:44 +00002137 if (MD->hasAttr<WarnUnusedResultAttr>()) {
Fariborz Jahanianac6b4ef2014-07-18 22:59:10 +00002138 WarnE = this;
2139 Loc = getExprLoc();
2140 return true;
2141 }
2142
Chris Lattner237f2752009-02-14 07:37:35 +00002143 return false;
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +00002144 }
Mike Stump11289f42009-09-09 15:08:12 +00002145
John McCallb7bd14f2010-12-02 01:19:52 +00002146 case ObjCPropertyRefExprClass:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002147 WarnE = this;
Chris Lattnerd37f61c2009-08-16 16:51:50 +00002148 Loc = getExprLoc();
2149 R1 = getSourceRange();
Chris Lattnerd8b800a2009-08-16 16:45:18 +00002150 return true;
John McCallb7bd14f2010-12-02 01:19:52 +00002151
John McCallfe96e0b2011-11-06 09:01:30 +00002152 case PseudoObjectExprClass: {
2153 const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this);
2154
2155 // Only complain about things that have the form of a getter.
2156 if (isa<UnaryOperator>(PO->getSyntacticForm()) ||
2157 isa<BinaryOperator>(PO->getSyntacticForm()))
2158 return false;
2159
Eli Friedmanc11535c2012-05-24 00:47:05 +00002160 WarnE = this;
John McCallfe96e0b2011-11-06 09:01:30 +00002161 Loc = getExprLoc();
2162 R1 = getSourceRange();
2163 return true;
2164 }
2165
Chris Lattner944d3062008-07-26 19:51:01 +00002166 case StmtExprClass: {
2167 // Statement exprs don't logically have side effects themselves, but are
2168 // sometimes used in macros in ways that give them a type that is unused.
2169 // For example ({ blah; foo(); }) will end up with a type if foo has a type.
2170 // however, if the result of the stmt expr is dead, we don't want to emit a
2171 // warning.
2172 const CompoundStmt *CS = cast<StmtExpr>(this)->getSubStmt();
Argyrios Kyrtzidis90963412010-09-19 21:21:10 +00002173 if (!CS->body_empty()) {
Chris Lattner944d3062008-07-26 19:51:01 +00002174 if (const Expr *E = dyn_cast<Expr>(CS->body_back()))
Eli Friedmanc11535c2012-05-24 00:47:05 +00002175 return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Argyrios Kyrtzidis90963412010-09-19 21:21:10 +00002176 if (const LabelStmt *Label = dyn_cast<LabelStmt>(CS->body_back()))
2177 if (const Expr *E = dyn_cast<Expr>(Label->getSubStmt()))
Eli Friedmanc11535c2012-05-24 00:47:05 +00002178 return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Argyrios Kyrtzidis90963412010-09-19 21:21:10 +00002179 }
Mike Stump11289f42009-09-09 15:08:12 +00002180
John McCallc493a732010-03-12 07:11:26 +00002181 if (getType()->isVoidType())
2182 return false;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002183 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002184 Loc = cast<StmtExpr>(this)->getLParenLoc();
2185 R1 = getSourceRange();
2186 return true;
Chris Lattner944d3062008-07-26 19:51:01 +00002187 }
Eli Friedmanbdd57532012-09-24 23:02:26 +00002188 case CXXFunctionalCastExprClass:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002189 case CStyleCastExprClass: {
Eli Friedmanf92f6452012-05-24 21:05:41 +00002190 // Ignore an explicit cast to void unless the operand is a non-trivial
Eli Friedmanc11535c2012-05-24 00:47:05 +00002191 // volatile lvalue.
Eli Friedmanf92f6452012-05-24 21:05:41 +00002192 const CastExpr *CE = cast<CastExpr>(this);
Eli Friedmanc11535c2012-05-24 00:47:05 +00002193 if (CE->getCastKind() == CK_ToVoid) {
2194 if (CE->getSubExpr()->isGLValue() &&
Eli Friedmanf92f6452012-05-24 21:05:41 +00002195 CE->getSubExpr()->getType().isVolatileQualified()) {
2196 const DeclRefExpr *DRE =
2197 dyn_cast<DeclRefExpr>(CE->getSubExpr()->IgnoreParens());
2198 if (!(DRE && isa<VarDecl>(DRE->getDecl()) &&
2199 cast<VarDecl>(DRE->getDecl())->hasLocalStorage())) {
2200 return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc,
2201 R1, R2, Ctx);
2202 }
2203 }
Chris Lattner2706a552009-07-28 18:25:28 +00002204 return false;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002205 }
Eli Friedmanf92f6452012-05-24 21:05:41 +00002206
Eli Friedmanc11535c2012-05-24 00:47:05 +00002207 // If this is a cast to a constructor conversion, check the operand.
Anders Carlsson6aa50392009-11-17 17:11:23 +00002208 // Otherwise, the result of the cast is unused.
Eli Friedmanc11535c2012-05-24 00:47:05 +00002209 if (CE->getCastKind() == CK_ConstructorConversion)
2210 return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Eli Friedmanf92f6452012-05-24 21:05:41 +00002211
Eli Friedmanc11535c2012-05-24 00:47:05 +00002212 WarnE = this;
Eli Friedmanf92f6452012-05-24 21:05:41 +00002213 if (const CXXFunctionalCastExpr *CXXCE =
2214 dyn_cast<CXXFunctionalCastExpr>(this)) {
Eli Friedman89fe0d52013-08-15 22:02:56 +00002215 Loc = CXXCE->getLocStart();
Eli Friedmanf92f6452012-05-24 21:05:41 +00002216 R1 = CXXCE->getSubExpr()->getSourceRange();
2217 } else {
2218 const CStyleCastExpr *CStyleCE = cast<CStyleCastExpr>(this);
2219 Loc = CStyleCE->getLParenLoc();
2220 R1 = CStyleCE->getSubExpr()->getSourceRange();
2221 }
Chris Lattner237f2752009-02-14 07:37:35 +00002222 return true;
Anders Carlsson6aa50392009-11-17 17:11:23 +00002223 }
Eli Friedmanc11535c2012-05-24 00:47:05 +00002224 case ImplicitCastExprClass: {
2225 const CastExpr *ICE = cast<ImplicitCastExpr>(this);
Eli Friedmanca8da1d2008-05-19 21:24:43 +00002226
Eli Friedmanc11535c2012-05-24 00:47:05 +00002227 // lvalue-to-rvalue conversion on a volatile lvalue is a side-effect.
2228 if (ICE->getCastKind() == CK_LValueToRValue &&
2229 ICE->getSubExpr()->getType().isVolatileQualified())
2230 return false;
2231
2232 return ICE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2233 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002234 case CXXDefaultArgExprClass:
Mike Stump53f9ded2009-11-03 23:25:48 +00002235 return (cast<CXXDefaultArgExpr>(this)
Eli Friedmanc11535c2012-05-24 00:47:05 +00002236 ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
Richard Smith852c9db2013-04-20 22:23:05 +00002237 case CXXDefaultInitExprClass:
2238 return (cast<CXXDefaultInitExpr>(this)
2239 ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
Sebastian Redlbd150f42008-11-21 19:14:01 +00002240
2241 case CXXNewExprClass:
2242 // FIXME: In theory, there might be new expressions that don't have side
2243 // effects (e.g. a placement new with an uninitialized POD).
2244 case CXXDeleteExprClass:
Chris Lattner237f2752009-02-14 07:37:35 +00002245 return false;
Anders Carlssone80ccac2009-08-16 04:11:06 +00002246 case CXXBindTemporaryExprClass:
Mike Stump53f9ded2009-11-03 23:25:48 +00002247 return (cast<CXXBindTemporaryExpr>(this)
Eli Friedmanc11535c2012-05-24 00:47:05 +00002248 ->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
John McCall5d413782010-12-06 08:20:24 +00002249 case ExprWithCleanupsClass:
2250 return (cast<ExprWithCleanups>(this)
Eli Friedmanc11535c2012-05-24 00:47:05 +00002251 ->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
Sebastian Redlbd150f42008-11-21 19:14:01 +00002252 }
Chris Lattner1ec5f562007-06-27 05:38:08 +00002253}
2254
Fariborz Jahanian07735332009-02-22 18:40:18 +00002255/// isOBJCGCCandidate - Check if an expression is objc gc'able.
Fariborz Jahanian063c7722009-09-08 23:38:54 +00002256/// returns true, if it is; false otherwise.
Fariborz Jahanianc6d98002009-06-01 21:29:32 +00002257bool Expr::isOBJCGCCandidate(ASTContext &Ctx) const {
Peter Collingbourne91147592011-04-15 00:35:48 +00002258 const Expr *E = IgnoreParens();
2259 switch (E->getStmtClass()) {
Fariborz Jahanian07735332009-02-22 18:40:18 +00002260 default:
2261 return false;
2262 case ObjCIvarRefExprClass:
2263 return true;
Fariborz Jahanian392124c2009-02-23 18:59:50 +00002264 case Expr::UnaryOperatorClass:
Peter Collingbourne91147592011-04-15 00:35:48 +00002265 return cast<UnaryOperator>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
Fariborz Jahanian07735332009-02-22 18:40:18 +00002266 case ImplicitCastExprClass:
Peter Collingbourne91147592011-04-15 00:35:48 +00002267 return cast<ImplicitCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
Douglas Gregorfe314812011-06-21 17:03:29 +00002268 case MaterializeTemporaryExprClass:
2269 return cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr()
2270 ->isOBJCGCCandidate(Ctx);
Fariborz Jahaniana16904b2009-05-05 23:28:21 +00002271 case CStyleCastExprClass:
Peter Collingbourne91147592011-04-15 00:35:48 +00002272 return cast<CStyleCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002273 case DeclRefExprClass: {
John McCall113bee02012-03-10 09:33:50 +00002274 const Decl *D = cast<DeclRefExpr>(E)->getDecl();
Fariborz Jahanianc367b8f2011-09-23 18:57:30 +00002275
Fariborz Jahanianc6d98002009-06-01 21:29:32 +00002276 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2277 if (VD->hasGlobalStorage())
2278 return true;
2279 QualType T = VD->getType();
Fariborz Jahaniancceedbf2009-09-16 18:09:18 +00002280 // dereferencing to a pointer is always a gc'able candidate,
2281 // unless it is __weak.
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00002282 return T->isPointerType() &&
John McCall8ccfcb52009-09-24 19:53:00 +00002283 (Ctx.getObjCGCAttrKind(T) != Qualifiers::Weak);
Fariborz Jahanianc6d98002009-06-01 21:29:32 +00002284 }
Fariborz Jahanian07735332009-02-22 18:40:18 +00002285 return false;
2286 }
Douglas Gregorf405d7e2009-08-31 23:41:50 +00002287 case MemberExprClass: {
Peter Collingbourne91147592011-04-15 00:35:48 +00002288 const MemberExpr *M = cast<MemberExpr>(E);
Fariborz Jahanianc6d98002009-06-01 21:29:32 +00002289 return M->getBase()->isOBJCGCCandidate(Ctx);
Fariborz Jahanian07735332009-02-22 18:40:18 +00002290 }
2291 case ArraySubscriptExprClass:
Peter Collingbourne91147592011-04-15 00:35:48 +00002292 return cast<ArraySubscriptExpr>(E)->getBase()->isOBJCGCCandidate(Ctx);
Fariborz Jahanian07735332009-02-22 18:40:18 +00002293 }
2294}
Sebastian Redlce354af2010-09-10 20:55:33 +00002295
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +00002296bool Expr::isBoundMemberFunction(ASTContext &Ctx) const {
2297 if (isTypeDependent())
2298 return false;
John McCall086a4642010-11-24 05:12:34 +00002299 return ClassifyLValue(Ctx) == Expr::LV_MemberFunction;
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +00002300}
2301
John McCall0009fcc2011-04-26 20:42:42 +00002302QualType Expr::findBoundMemberType(const Expr *expr) {
John McCalle314e272011-10-18 21:02:43 +00002303 assert(expr->hasPlaceholderType(BuiltinType::BoundMember));
John McCall0009fcc2011-04-26 20:42:42 +00002304
2305 // Bound member expressions are always one of these possibilities:
2306 // x->m x.m x->*y x.*y
2307 // (possibly parenthesized)
2308
2309 expr = expr->IgnoreParens();
2310 if (const MemberExpr *mem = dyn_cast<MemberExpr>(expr)) {
2311 assert(isa<CXXMethodDecl>(mem->getMemberDecl()));
2312 return mem->getMemberDecl()->getType();
2313 }
2314
2315 if (const BinaryOperator *op = dyn_cast<BinaryOperator>(expr)) {
2316 QualType type = op->getRHS()->getType()->castAs<MemberPointerType>()
2317 ->getPointeeType();
2318 assert(type->isFunctionType());
2319 return type;
2320 }
2321
David Majnemerced8bdf2015-02-25 17:36:15 +00002322 assert(isa<UnresolvedMemberExpr>(expr) || isa<CXXPseudoDestructorExpr>(expr));
John McCall0009fcc2011-04-26 20:42:42 +00002323 return QualType();
2324}
2325
Ted Kremenekfff70962008-01-17 16:57:34 +00002326Expr* Expr::IgnoreParens() {
2327 Expr* E = this;
Abramo Bagnara932e3932010-10-15 07:51:18 +00002328 while (true) {
2329 if (ParenExpr* P = dyn_cast<ParenExpr>(E)) {
2330 E = P->getSubExpr();
2331 continue;
2332 }
2333 if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) {
2334 if (P->getOpcode() == UO_Extension) {
2335 E = P->getSubExpr();
2336 continue;
2337 }
2338 }
Peter Collingbourne91147592011-04-15 00:35:48 +00002339 if (GenericSelectionExpr* P = dyn_cast<GenericSelectionExpr>(E)) {
2340 if (!P->isResultDependent()) {
2341 E = P->getResultExpr();
2342 continue;
2343 }
2344 }
Eli Friedman75807f22013-07-20 00:40:58 +00002345 if (ChooseExpr* P = dyn_cast<ChooseExpr>(E)) {
2346 if (!P->isConditionDependent()) {
2347 E = P->getChosenSubExpr();
2348 continue;
2349 }
2350 }
Abramo Bagnara932e3932010-10-15 07:51:18 +00002351 return E;
2352 }
Ted Kremenekfff70962008-01-17 16:57:34 +00002353}
2354
Chris Lattnerf2660962008-02-13 01:02:39 +00002355/// IgnoreParenCasts - Ignore parentheses and casts. Strip off any ParenExpr
2356/// or CastExprs or ImplicitCastExprs, returning their operand.
2357Expr *Expr::IgnoreParenCasts() {
2358 Expr *E = this;
2359 while (true) {
Eli Friedman75807f22013-07-20 00:40:58 +00002360 E = E->IgnoreParens();
Abramo Bagnara932e3932010-10-15 07:51:18 +00002361 if (CastExpr *P = dyn_cast<CastExpr>(E)) {
Chris Lattnerf2660962008-02-13 01:02:39 +00002362 E = P->getSubExpr();
Abramo Bagnara932e3932010-10-15 07:51:18 +00002363 continue;
2364 }
Douglas Gregorfe314812011-06-21 17:03:29 +00002365 if (MaterializeTemporaryExpr *Materialize
2366 = dyn_cast<MaterializeTemporaryExpr>(E)) {
2367 E = Materialize->GetTemporaryExpr();
2368 continue;
2369 }
Douglas Gregor6a40b082011-09-08 17:56:33 +00002370 if (SubstNonTypeTemplateParmExpr *NTTP
2371 = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2372 E = NTTP->getReplacement();
2373 continue;
2374 }
Abramo Bagnara932e3932010-10-15 07:51:18 +00002375 return E;
Chris Lattnerf2660962008-02-13 01:02:39 +00002376 }
2377}
2378
Ted Kremenek6f375e52014-04-16 07:26:09 +00002379Expr *Expr::IgnoreCasts() {
2380 Expr *E = this;
2381 while (true) {
2382 if (CastExpr *P = dyn_cast<CastExpr>(E)) {
2383 E = P->getSubExpr();
2384 continue;
2385 }
2386 if (MaterializeTemporaryExpr *Materialize
2387 = dyn_cast<MaterializeTemporaryExpr>(E)) {
2388 E = Materialize->GetTemporaryExpr();
2389 continue;
2390 }
2391 if (SubstNonTypeTemplateParmExpr *NTTP
2392 = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2393 E = NTTP->getReplacement();
2394 continue;
2395 }
2396 return E;
2397 }
2398}
2399
John McCall5a4ce8b2010-12-04 08:24:19 +00002400/// IgnoreParenLValueCasts - Ignore parentheses and lvalue-to-rvalue
2401/// casts. This is intended purely as a temporary workaround for code
2402/// that hasn't yet been rewritten to do the right thing about those
2403/// casts, and may disappear along with the last internal use.
John McCall34376a62010-12-04 03:47:34 +00002404Expr *Expr::IgnoreParenLValueCasts() {
2405 Expr *E = this;
John McCall5a4ce8b2010-12-04 08:24:19 +00002406 while (true) {
Eli Friedman75807f22013-07-20 00:40:58 +00002407 E = E->IgnoreParens();
2408 if (CastExpr *P = dyn_cast<CastExpr>(E)) {
John McCall34376a62010-12-04 03:47:34 +00002409 if (P->getCastKind() == CK_LValueToRValue) {
2410 E = P->getSubExpr();
2411 continue;
2412 }
Douglas Gregorfe314812011-06-21 17:03:29 +00002413 } else if (MaterializeTemporaryExpr *Materialize
2414 = dyn_cast<MaterializeTemporaryExpr>(E)) {
2415 E = Materialize->GetTemporaryExpr();
2416 continue;
Douglas Gregor6a40b082011-09-08 17:56:33 +00002417 } else if (SubstNonTypeTemplateParmExpr *NTTP
2418 = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2419 E = NTTP->getReplacement();
2420 continue;
John McCall34376a62010-12-04 03:47:34 +00002421 }
2422 break;
2423 }
2424 return E;
2425}
Rafael Espindolaecbe2e92012-06-28 01:56:38 +00002426
2427Expr *Expr::ignoreParenBaseCasts() {
2428 Expr *E = this;
2429 while (true) {
Eli Friedman75807f22013-07-20 00:40:58 +00002430 E = E->IgnoreParens();
Rafael Espindolaecbe2e92012-06-28 01:56:38 +00002431 if (CastExpr *CE = dyn_cast<CastExpr>(E)) {
2432 if (CE->getCastKind() == CK_DerivedToBase ||
2433 CE->getCastKind() == CK_UncheckedDerivedToBase ||
2434 CE->getCastKind() == CK_NoOp) {
2435 E = CE->getSubExpr();
2436 continue;
2437 }
2438 }
2439
2440 return E;
2441 }
2442}
2443
John McCalleebc8322010-05-05 22:59:52 +00002444Expr *Expr::IgnoreParenImpCasts() {
2445 Expr *E = this;
2446 while (true) {
Eli Friedman75807f22013-07-20 00:40:58 +00002447 E = E->IgnoreParens();
Abramo Bagnara932e3932010-10-15 07:51:18 +00002448 if (ImplicitCastExpr *P = dyn_cast<ImplicitCastExpr>(E)) {
John McCalleebc8322010-05-05 22:59:52 +00002449 E = P->getSubExpr();
Abramo Bagnara932e3932010-10-15 07:51:18 +00002450 continue;
2451 }
Douglas Gregorfe314812011-06-21 17:03:29 +00002452 if (MaterializeTemporaryExpr *Materialize
2453 = dyn_cast<MaterializeTemporaryExpr>(E)) {
2454 E = Materialize->GetTemporaryExpr();
2455 continue;
2456 }
Douglas Gregor6a40b082011-09-08 17:56:33 +00002457 if (SubstNonTypeTemplateParmExpr *NTTP
2458 = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2459 E = NTTP->getReplacement();
2460 continue;
2461 }
Abramo Bagnara932e3932010-10-15 07:51:18 +00002462 return E;
John McCalleebc8322010-05-05 22:59:52 +00002463 }
2464}
2465
Hans Wennborgde2e67e2011-06-09 17:06:51 +00002466Expr *Expr::IgnoreConversionOperator() {
2467 if (CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(this)) {
Chandler Carruth4352b0b2011-06-21 17:22:09 +00002468 if (MCE->getMethodDecl() && isa<CXXConversionDecl>(MCE->getMethodDecl()))
Hans Wennborgde2e67e2011-06-09 17:06:51 +00002469 return MCE->getImplicitObjectArgument();
2470 }
2471 return this;
2472}
2473
Chris Lattneref26c772009-03-13 17:28:01 +00002474/// IgnoreParenNoopCasts - Ignore parentheses and casts that do not change the
2475/// value (including ptr->int casts of the same size). Strip off any
2476/// ParenExpr or CastExprs, returning their operand.
2477Expr *Expr::IgnoreParenNoopCasts(ASTContext &Ctx) {
2478 Expr *E = this;
2479 while (true) {
Eli Friedman75807f22013-07-20 00:40:58 +00002480 E = E->IgnoreParens();
Mike Stump11289f42009-09-09 15:08:12 +00002481
Chris Lattneref26c772009-03-13 17:28:01 +00002482 if (CastExpr *P = dyn_cast<CastExpr>(E)) {
2483 // We ignore integer <-> casts that are of the same width, ptr<->ptr and
Douglas Gregorb90df602010-06-16 00:17:44 +00002484 // ptr<->int casts of the same width. We also ignore all identity casts.
Chris Lattneref26c772009-03-13 17:28:01 +00002485 Expr *SE = P->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002486
Chris Lattneref26c772009-03-13 17:28:01 +00002487 if (Ctx.hasSameUnqualifiedType(E->getType(), SE->getType())) {
2488 E = SE;
2489 continue;
2490 }
Mike Stump11289f42009-09-09 15:08:12 +00002491
Abramo Bagnara932e3932010-10-15 07:51:18 +00002492 if ((E->getType()->isPointerType() ||
Douglas Gregor6972a622010-06-16 00:35:25 +00002493 E->getType()->isIntegralType(Ctx)) &&
Abramo Bagnara932e3932010-10-15 07:51:18 +00002494 (SE->getType()->isPointerType() ||
Douglas Gregor6972a622010-06-16 00:35:25 +00002495 SE->getType()->isIntegralType(Ctx)) &&
Chris Lattneref26c772009-03-13 17:28:01 +00002496 Ctx.getTypeSize(E->getType()) == Ctx.getTypeSize(SE->getType())) {
2497 E = SE;
2498 continue;
2499 }
2500 }
Mike Stump11289f42009-09-09 15:08:12 +00002501
Douglas Gregor6a40b082011-09-08 17:56:33 +00002502 if (SubstNonTypeTemplateParmExpr *NTTP
2503 = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2504 E = NTTP->getReplacement();
2505 continue;
2506 }
2507
Chris Lattneref26c772009-03-13 17:28:01 +00002508 return E;
2509 }
2510}
2511
Douglas Gregord196a582009-12-14 19:27:10 +00002512bool Expr::isDefaultArgument() const {
2513 const Expr *E = this;
Douglas Gregorfe314812011-06-21 17:03:29 +00002514 if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
2515 E = M->GetTemporaryExpr();
2516
Douglas Gregord196a582009-12-14 19:27:10 +00002517 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
2518 E = ICE->getSubExprAsWritten();
Alexis Hunta8136cc2010-05-05 15:23:54 +00002519
Douglas Gregord196a582009-12-14 19:27:10 +00002520 return isa<CXXDefaultArgExpr>(E);
2521}
Chris Lattneref26c772009-03-13 17:28:01 +00002522
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002523/// \brief Skip over any no-op casts and any temporary-binding
2524/// expressions.
Anders Carlsson66bbf502010-11-28 16:40:49 +00002525static const Expr *skipTemporaryBindingsNoOpCastsAndParens(const Expr *E) {
Douglas Gregorfe314812011-06-21 17:03:29 +00002526 if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
2527 E = M->GetTemporaryExpr();
2528
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002529 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCalle3027922010-08-25 11:45:40 +00002530 if (ICE->getCastKind() == CK_NoOp)
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002531 E = ICE->getSubExpr();
2532 else
2533 break;
2534 }
2535
2536 while (const CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
2537 E = BE->getSubExpr();
2538
2539 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCalle3027922010-08-25 11:45:40 +00002540 if (ICE->getCastKind() == CK_NoOp)
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002541 E = ICE->getSubExpr();
2542 else
2543 break;
2544 }
Anders Carlsson66bbf502010-11-28 16:40:49 +00002545
2546 return E->IgnoreParens();
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002547}
2548
John McCall7a626f62010-09-15 10:14:12 +00002549/// isTemporaryObject - Determines if this expression produces a
2550/// temporary of the given class type.
2551bool Expr::isTemporaryObject(ASTContext &C, const CXXRecordDecl *TempTy) const {
2552 if (!C.hasSameUnqualifiedType(getType(), C.getTypeDeclType(TempTy)))
2553 return false;
2554
Anders Carlsson66bbf502010-11-28 16:40:49 +00002555 const Expr *E = skipTemporaryBindingsNoOpCastsAndParens(this);
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002556
John McCall02dc8c72010-09-15 20:59:13 +00002557 // Temporaries are by definition pr-values of class type.
Fariborz Jahanian30e8d582010-09-27 17:30:38 +00002558 if (!E->Classify(C).isPRValue()) {
2559 // In this context, property reference is a message call and is pr-value.
John McCallb7bd14f2010-12-02 01:19:52 +00002560 if (!isa<ObjCPropertyRefExpr>(E))
Fariborz Jahanian30e8d582010-09-27 17:30:38 +00002561 return false;
2562 }
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002563
John McCallf4ee1dd2010-09-16 06:57:56 +00002564 // Black-list a few cases which yield pr-values of class type that don't
2565 // refer to temporaries of that type:
2566
2567 // - implicit derived-to-base conversions
John McCall7a626f62010-09-15 10:14:12 +00002568 if (isa<ImplicitCastExpr>(E)) {
2569 switch (cast<ImplicitCastExpr>(E)->getCastKind()) {
2570 case CK_DerivedToBase:
2571 case CK_UncheckedDerivedToBase:
2572 return false;
2573 default:
2574 break;
2575 }
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002576 }
2577
John McCallf4ee1dd2010-09-16 06:57:56 +00002578 // - member expressions (all)
2579 if (isa<MemberExpr>(E))
2580 return false;
2581
Eli Friedman13ffdd82012-06-15 23:51:06 +00002582 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E))
2583 if (BO->isPtrMemOp())
2584 return false;
2585
John McCallc07a0c72011-02-17 10:25:35 +00002586 // - opaque values (all)
2587 if (isa<OpaqueValueExpr>(E))
2588 return false;
2589
John McCall7a626f62010-09-15 10:14:12 +00002590 return true;
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002591}
2592
Douglas Gregor25b7e052011-03-02 21:06:53 +00002593bool Expr::isImplicitCXXThis() const {
2594 const Expr *E = this;
2595
2596 // Strip away parentheses and casts we don't care about.
2597 while (true) {
2598 if (const ParenExpr *Paren = dyn_cast<ParenExpr>(E)) {
2599 E = Paren->getSubExpr();
2600 continue;
2601 }
2602
2603 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2604 if (ICE->getCastKind() == CK_NoOp ||
2605 ICE->getCastKind() == CK_LValueToRValue ||
2606 ICE->getCastKind() == CK_DerivedToBase ||
2607 ICE->getCastKind() == CK_UncheckedDerivedToBase) {
2608 E = ICE->getSubExpr();
2609 continue;
2610 }
2611 }
2612
2613 if (const UnaryOperator* UnOp = dyn_cast<UnaryOperator>(E)) {
2614 if (UnOp->getOpcode() == UO_Extension) {
2615 E = UnOp->getSubExpr();
2616 continue;
2617 }
2618 }
2619
Douglas Gregorfe314812011-06-21 17:03:29 +00002620 if (const MaterializeTemporaryExpr *M
2621 = dyn_cast<MaterializeTemporaryExpr>(E)) {
2622 E = M->GetTemporaryExpr();
2623 continue;
2624 }
2625
Douglas Gregor25b7e052011-03-02 21:06:53 +00002626 break;
2627 }
2628
2629 if (const CXXThisExpr *This = dyn_cast<CXXThisExpr>(E))
2630 return This->isImplicit();
2631
2632 return false;
2633}
2634
Douglas Gregor4619e432008-12-05 23:32:09 +00002635/// hasAnyTypeDependentArguments - Determines if any of the expressions
2636/// in Exprs is type-dependent.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002637bool Expr::hasAnyTypeDependentArguments(ArrayRef<Expr *> Exprs) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002638 for (unsigned I = 0; I < Exprs.size(); ++I)
Douglas Gregor4619e432008-12-05 23:32:09 +00002639 if (Exprs[I]->isTypeDependent())
2640 return true;
2641
2642 return false;
2643}
2644
Abramo Bagnara847c6602014-05-22 19:20:46 +00002645bool Expr::isConstantInitializer(ASTContext &Ctx, bool IsForRef,
2646 const Expr **Culprit) const {
Eli Friedman384da272009-01-25 03:12:18 +00002647 // This function is attempting whether an expression is an initializer
Eli Friedman4c27ac22013-07-16 22:40:53 +00002648 // which can be evaluated at compile-time. It very closely parallels
2649 // ConstExprEmitter in CGExprConstant.cpp; if they don't match, it
2650 // will lead to unexpected results. Like ConstExprEmitter, it falls back
2651 // to isEvaluatable most of the time.
2652 //
John McCall8b0f4ff2010-08-02 21:13:48 +00002653 // If we ever capture reference-binding directly in the AST, we can
2654 // kill the second parameter.
2655
2656 if (IsForRef) {
2657 EvalResult Result;
Abramo Bagnara847c6602014-05-22 19:20:46 +00002658 if (EvaluateAsLValue(Result, Ctx) && !Result.HasSideEffects)
2659 return true;
2660 if (Culprit)
2661 *Culprit = this;
2662 return false;
John McCall8b0f4ff2010-08-02 21:13:48 +00002663 }
Eli Friedmancf7cbe72009-02-20 02:36:22 +00002664
Anders Carlssona7c5eb72008-11-24 05:23:59 +00002665 switch (getStmtClass()) {
Eli Friedman384da272009-01-25 03:12:18 +00002666 default: break;
Anders Carlssona7c5eb72008-11-24 05:23:59 +00002667 case StringLiteralClass:
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00002668 case ObjCEncodeExprClass:
Anders Carlssona7c5eb72008-11-24 05:23:59 +00002669 return true;
John McCall81c9cea2010-08-01 21:51:45 +00002670 case CXXTemporaryObjectExprClass:
2671 case CXXConstructExprClass: {
2672 const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
John McCall8b0f4ff2010-08-02 21:13:48 +00002673
Eli Friedman4c27ac22013-07-16 22:40:53 +00002674 if (CE->getConstructor()->isTrivial() &&
2675 CE->getConstructor()->getParent()->hasTrivialDestructor()) {
2676 // Trivial default constructor
Richard Smithd62306a2011-11-10 06:34:14 +00002677 if (!CE->getNumArgs()) return true;
John McCall8b0f4ff2010-08-02 21:13:48 +00002678
Eli Friedman4c27ac22013-07-16 22:40:53 +00002679 // Trivial copy constructor
2680 assert(CE->getNumArgs() == 1 && "trivial ctor with > 1 argument");
Abramo Bagnara847c6602014-05-22 19:20:46 +00002681 return CE->getArg(0)->isConstantInitializer(Ctx, false, Culprit);
Richard Smithd62306a2011-11-10 06:34:14 +00002682 }
2683
Richard Smithd62306a2011-11-10 06:34:14 +00002684 break;
John McCall81c9cea2010-08-01 21:51:45 +00002685 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002686 case CompoundLiteralExprClass: {
Eli Friedmancf7cbe72009-02-20 02:36:22 +00002687 // This handles gcc's extension that allows global initializers like
2688 // "struct x {int x;} x = (struct x) {};".
2689 // FIXME: This accepts other cases it shouldn't!
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002690 const Expr *Exp = cast<CompoundLiteralExpr>(this)->getInitializer();
Abramo Bagnara847c6602014-05-22 19:20:46 +00002691 return Exp->isConstantInitializer(Ctx, false, Culprit);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002692 }
Yunzhong Gaocb779302015-06-10 00:27:52 +00002693 case DesignatedInitUpdateExprClass: {
2694 const DesignatedInitUpdateExpr *DIUE = cast<DesignatedInitUpdateExpr>(this);
2695 return DIUE->getBase()->isConstantInitializer(Ctx, false, Culprit) &&
2696 DIUE->getUpdater()->isConstantInitializer(Ctx, false, Culprit);
2697 }
Anders Carlssona7c5eb72008-11-24 05:23:59 +00002698 case InitListExprClass: {
Eli Friedman4c27ac22013-07-16 22:40:53 +00002699 const InitListExpr *ILE = cast<InitListExpr>(this);
2700 if (ILE->getType()->isArrayType()) {
2701 unsigned numInits = ILE->getNumInits();
2702 for (unsigned i = 0; i < numInits; i++) {
Abramo Bagnara847c6602014-05-22 19:20:46 +00002703 if (!ILE->getInit(i)->isConstantInitializer(Ctx, false, Culprit))
Eli Friedman4c27ac22013-07-16 22:40:53 +00002704 return false;
2705 }
2706 return true;
Anders Carlssona7c5eb72008-11-24 05:23:59 +00002707 }
Eli Friedman4c27ac22013-07-16 22:40:53 +00002708
2709 if (ILE->getType()->isRecordType()) {
2710 unsigned ElementNo = 0;
2711 RecordDecl *RD = ILE->getType()->getAs<RecordType>()->getDecl();
Hans Wennborga302cd92014-08-21 16:06:57 +00002712 for (const auto *Field : RD->fields()) {
Eli Friedman4c27ac22013-07-16 22:40:53 +00002713 // If this is a union, skip all the fields that aren't being initialized.
Hans Wennborga302cd92014-08-21 16:06:57 +00002714 if (RD->isUnion() && ILE->getInitializedFieldInUnion() != Field)
Eli Friedman4c27ac22013-07-16 22:40:53 +00002715 continue;
2716
2717 // Don't emit anonymous bitfields, they just affect layout.
2718 if (Field->isUnnamedBitfield())
2719 continue;
2720
2721 if (ElementNo < ILE->getNumInits()) {
2722 const Expr *Elt = ILE->getInit(ElementNo++);
2723 if (Field->isBitField()) {
2724 // Bitfields have to evaluate to an integer.
2725 llvm::APSInt ResultTmp;
Abramo Bagnara847c6602014-05-22 19:20:46 +00002726 if (!Elt->EvaluateAsInt(ResultTmp, Ctx)) {
2727 if (Culprit)
2728 *Culprit = Elt;
Eli Friedman4c27ac22013-07-16 22:40:53 +00002729 return false;
Abramo Bagnara847c6602014-05-22 19:20:46 +00002730 }
Eli Friedman4c27ac22013-07-16 22:40:53 +00002731 } else {
2732 bool RefType = Field->getType()->isReferenceType();
Abramo Bagnara847c6602014-05-22 19:20:46 +00002733 if (!Elt->isConstantInitializer(Ctx, RefType, Culprit))
Eli Friedman4c27ac22013-07-16 22:40:53 +00002734 return false;
2735 }
2736 }
2737 }
2738 return true;
2739 }
2740
2741 break;
Anders Carlssona7c5eb72008-11-24 05:23:59 +00002742 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00002743 case ImplicitValueInitExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00002744 case NoInitExprClass:
Douglas Gregor0202cb42009-01-29 17:44:32 +00002745 return true;
Chris Lattner3eb172a2009-10-13 07:14:16 +00002746 case ParenExprClass:
John McCall8b0f4ff2010-08-02 21:13:48 +00002747 return cast<ParenExpr>(this)->getSubExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00002748 ->isConstantInitializer(Ctx, IsForRef, Culprit);
Peter Collingbourne91147592011-04-15 00:35:48 +00002749 case GenericSelectionExprClass:
Peter Collingbourne91147592011-04-15 00:35:48 +00002750 return cast<GenericSelectionExpr>(this)->getResultExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00002751 ->isConstantInitializer(Ctx, IsForRef, Culprit);
Abramo Bagnarab59a5b62010-09-27 07:13:32 +00002752 case ChooseExprClass:
Abramo Bagnara847c6602014-05-22 19:20:46 +00002753 if (cast<ChooseExpr>(this)->isConditionDependent()) {
2754 if (Culprit)
2755 *Culprit = this;
Eli Friedman75807f22013-07-20 00:40:58 +00002756 return false;
Abramo Bagnara847c6602014-05-22 19:20:46 +00002757 }
Eli Friedman75807f22013-07-20 00:40:58 +00002758 return cast<ChooseExpr>(this)->getChosenSubExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00002759 ->isConstantInitializer(Ctx, IsForRef, Culprit);
Eli Friedman384da272009-01-25 03:12:18 +00002760 case UnaryOperatorClass: {
2761 const UnaryOperator* Exp = cast<UnaryOperator>(this);
John McCalle3027922010-08-25 11:45:40 +00002762 if (Exp->getOpcode() == UO_Extension)
Abramo Bagnara847c6602014-05-22 19:20:46 +00002763 return Exp->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
Eli Friedman384da272009-01-25 03:12:18 +00002764 break;
2765 }
John McCall8b0f4ff2010-08-02 21:13:48 +00002766 case CXXFunctionalCastExprClass:
John McCall81c9cea2010-08-01 21:51:45 +00002767 case CXXStaticCastExprClass:
Chris Lattner1f02e052009-04-21 05:19:11 +00002768 case ImplicitCastExprClass:
Eli Friedman4c27ac22013-07-16 22:40:53 +00002769 case CStyleCastExprClass:
2770 case ObjCBridgedCastExprClass:
2771 case CXXDynamicCastExprClass:
2772 case CXXReinterpretCastExprClass:
2773 case CXXConstCastExprClass: {
Richard Smith161f09a2011-12-06 22:44:34 +00002774 const CastExpr *CE = cast<CastExpr>(this);
2775
Eli Friedman13ec75b2011-12-21 00:43:02 +00002776 // Handle misc casts we want to ignore.
Eli Friedman13ec75b2011-12-21 00:43:02 +00002777 if (CE->getCastKind() == CK_NoOp ||
2778 CE->getCastKind() == CK_LValueToRValue ||
2779 CE->getCastKind() == CK_ToUnion ||
Eli Friedman4c27ac22013-07-16 22:40:53 +00002780 CE->getCastKind() == CK_ConstructorConversion ||
2781 CE->getCastKind() == CK_NonAtomicToAtomic ||
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00002782 CE->getCastKind() == CK_AtomicToNonAtomic ||
2783 CE->getCastKind() == CK_IntToOCLSampler)
Abramo Bagnara847c6602014-05-22 19:20:46 +00002784 return CE->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
Richard Smith161f09a2011-12-06 22:44:34 +00002785
Eli Friedman384da272009-01-25 03:12:18 +00002786 break;
Richard Smith161f09a2011-12-06 22:44:34 +00002787 }
Douglas Gregorfe314812011-06-21 17:03:29 +00002788 case MaterializeTemporaryExprClass:
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002789 return cast<MaterializeTemporaryExpr>(this)->GetTemporaryExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00002790 ->isConstantInitializer(Ctx, false, Culprit);
Eli Friedman4c27ac22013-07-16 22:40:53 +00002791
2792 case SubstNonTypeTemplateParmExprClass:
2793 return cast<SubstNonTypeTemplateParmExpr>(this)->getReplacement()
Abramo Bagnara847c6602014-05-22 19:20:46 +00002794 ->isConstantInitializer(Ctx, false, Culprit);
Eli Friedman4c27ac22013-07-16 22:40:53 +00002795 case CXXDefaultArgExprClass:
2796 return cast<CXXDefaultArgExpr>(this)->getExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00002797 ->isConstantInitializer(Ctx, false, Culprit);
Eli Friedman4c27ac22013-07-16 22:40:53 +00002798 case CXXDefaultInitExprClass:
2799 return cast<CXXDefaultInitExpr>(this)->getExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00002800 ->isConstantInitializer(Ctx, false, Culprit);
Anders Carlssona7c5eb72008-11-24 05:23:59 +00002801 }
Richard Smithce8eca52015-12-08 03:21:47 +00002802 // Allow certain forms of UB in constant initializers: signed integer
2803 // overflow and floating-point division by zero. We'll give a warning on
2804 // these, but they're common enough that we have to accept them.
2805 if (isEvaluatable(Ctx, SE_AllowUndefinedBehavior))
Abramo Bagnara847c6602014-05-22 19:20:46 +00002806 return true;
2807 if (Culprit)
2808 *Culprit = this;
2809 return false;
Steve Naroffb03f5942007-09-02 20:30:18 +00002810}
2811
Scott Douglasscc013592015-06-10 15:18:23 +00002812namespace {
2813 /// \brief Look for any side effects within a Stmt.
2814 class SideEffectFinder : public ConstEvaluatedExprVisitor<SideEffectFinder> {
2815 typedef ConstEvaluatedExprVisitor<SideEffectFinder> Inherited;
2816 const bool IncludePossibleEffects;
2817 bool HasSideEffects;
2818
2819 public:
2820 explicit SideEffectFinder(const ASTContext &Context, bool IncludePossible)
2821 : Inherited(Context),
2822 IncludePossibleEffects(IncludePossible), HasSideEffects(false) { }
2823
2824 bool hasSideEffects() const { return HasSideEffects; }
2825
2826 void VisitExpr(const Expr *E) {
2827 if (!HasSideEffects &&
2828 E->HasSideEffects(Context, IncludePossibleEffects))
2829 HasSideEffects = true;
2830 }
2831 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002832}
Scott Douglasscc013592015-06-10 15:18:23 +00002833
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00002834bool Expr::HasSideEffects(const ASTContext &Ctx,
2835 bool IncludePossibleEffects) const {
2836 // In circumstances where we care about definite side effects instead of
2837 // potential side effects, we want to ignore expressions that are part of a
2838 // macro expansion as a potential side effect.
2839 if (!IncludePossibleEffects && getExprLoc().isMacroID())
2840 return false;
2841
Richard Smith0421ce72012-08-07 04:16:51 +00002842 if (isInstantiationDependent())
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00002843 return IncludePossibleEffects;
Richard Smith0421ce72012-08-07 04:16:51 +00002844
2845 switch (getStmtClass()) {
2846 case NoStmtClass:
2847 #define ABSTRACT_STMT(Type)
2848 #define STMT(Type, Base) case Type##Class:
2849 #define EXPR(Type, Base)
2850 #include "clang/AST/StmtNodes.inc"
2851 llvm_unreachable("unexpected Expr kind");
2852
2853 case DependentScopeDeclRefExprClass:
2854 case CXXUnresolvedConstructExprClass:
2855 case CXXDependentScopeMemberExprClass:
2856 case UnresolvedLookupExprClass:
2857 case UnresolvedMemberExprClass:
2858 case PackExpansionExprClass:
2859 case SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +00002860 case FunctionParmPackExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +00002861 case TypoExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +00002862 case CXXFoldExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00002863 llvm_unreachable("shouldn't see dependent / unresolved nodes here");
2864
Richard Smitha33e4fe2012-08-07 05:18:29 +00002865 case DeclRefExprClass:
2866 case ObjCIvarRefExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00002867 case PredefinedExprClass:
2868 case IntegerLiteralClass:
2869 case FloatingLiteralClass:
2870 case ImaginaryLiteralClass:
2871 case StringLiteralClass:
2872 case CharacterLiteralClass:
2873 case OffsetOfExprClass:
2874 case ImplicitValueInitExprClass:
2875 case UnaryExprOrTypeTraitExprClass:
2876 case AddrLabelExprClass:
2877 case GNUNullExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00002878 case NoInitExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00002879 case CXXBoolLiteralExprClass:
2880 case CXXNullPtrLiteralExprClass:
2881 case CXXThisExprClass:
2882 case CXXScalarValueInitExprClass:
2883 case TypeTraitExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00002884 case ArrayTypeTraitExprClass:
2885 case ExpressionTraitExprClass:
2886 case CXXNoexceptExprClass:
2887 case SizeOfPackExprClass:
2888 case ObjCStringLiteralClass:
2889 case ObjCEncodeExprClass:
2890 case ObjCBoolLiteralExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +00002891 case ObjCAvailabilityCheckExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00002892 case CXXUuidofExprClass:
2893 case OpaqueValueExprClass:
2894 // These never have a side-effect.
2895 return false;
2896
2897 case CallExprClass:
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00002898 case CXXOperatorCallExprClass:
2899 case CXXMemberCallExprClass:
2900 case CUDAKernelCallExprClass:
Michael Kupersteinaed5ccd2015-04-06 13:22:01 +00002901 case UserDefinedLiteralClass: {
2902 // We don't know a call definitely has side effects, except for calls
2903 // to pure/const functions that definitely don't.
2904 // If the call itself is considered side-effect free, check the operands.
2905 const Decl *FD = cast<CallExpr>(this)->getCalleeDecl();
2906 bool IsPure = FD && (FD->hasAttr<ConstAttr>() || FD->hasAttr<PureAttr>());
2907 if (IsPure || !IncludePossibleEffects)
2908 break;
2909 return true;
2910 }
2911
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00002912 case BlockExprClass:
2913 case CXXBindTemporaryExprClass:
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00002914 if (!IncludePossibleEffects)
2915 break;
2916 return true;
2917
John McCall5e77d762013-04-16 07:28:30 +00002918 case MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +00002919 case MSPropertySubscriptExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00002920 case CompoundAssignOperatorClass:
2921 case VAArgExprClass:
2922 case AtomicExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00002923 case CXXThrowExprClass:
2924 case CXXNewExprClass:
2925 case CXXDeleteExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +00002926 case CoawaitExprClass:
2927 case CoyieldExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00002928 // These always have a side-effect.
2929 return true;
2930
Scott Douglasscc013592015-06-10 15:18:23 +00002931 case StmtExprClass: {
2932 // StmtExprs have a side-effect if any substatement does.
2933 SideEffectFinder Finder(Ctx, IncludePossibleEffects);
2934 Finder.Visit(cast<StmtExpr>(this)->getSubStmt());
2935 return Finder.hasSideEffects();
2936 }
2937
Tim Shen4a05bb82016-06-21 20:29:17 +00002938 case ExprWithCleanupsClass:
2939 if (IncludePossibleEffects)
2940 if (cast<ExprWithCleanups>(this)->cleanupsHaveSideEffects())
2941 return true;
2942 break;
2943
Richard Smith0421ce72012-08-07 04:16:51 +00002944 case ParenExprClass:
2945 case ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +00002946 case OMPArraySectionExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00002947 case MemberExprClass:
2948 case ConditionalOperatorClass:
2949 case BinaryConditionalOperatorClass:
Richard Smith0421ce72012-08-07 04:16:51 +00002950 case CompoundLiteralExprClass:
2951 case ExtVectorElementExprClass:
2952 case DesignatedInitExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00002953 case DesignatedInitUpdateExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00002954 case ParenListExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00002955 case CXXPseudoDestructorExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +00002956 case CXXStdInitializerListExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00002957 case SubstNonTypeTemplateParmExprClass:
2958 case MaterializeTemporaryExprClass:
2959 case ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +00002960 case ConvertVectorExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00002961 case AsTypeExprClass:
2962 // These have a side-effect if any subexpression does.
2963 break;
2964
Richard Smitha33e4fe2012-08-07 05:18:29 +00002965 case UnaryOperatorClass:
2966 if (cast<UnaryOperator>(this)->isIncrementDecrementOp())
Richard Smith0421ce72012-08-07 04:16:51 +00002967 return true;
2968 break;
Richard Smith0421ce72012-08-07 04:16:51 +00002969
2970 case BinaryOperatorClass:
2971 if (cast<BinaryOperator>(this)->isAssignmentOp())
2972 return true;
2973 break;
2974
Richard Smith0421ce72012-08-07 04:16:51 +00002975 case InitListExprClass:
2976 // FIXME: The children for an InitListExpr doesn't include the array filler.
2977 if (const Expr *E = cast<InitListExpr>(this)->getArrayFiller())
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00002978 if (E->HasSideEffects(Ctx, IncludePossibleEffects))
Richard Smith0421ce72012-08-07 04:16:51 +00002979 return true;
2980 break;
2981
2982 case GenericSelectionExprClass:
2983 return cast<GenericSelectionExpr>(this)->getResultExpr()->
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00002984 HasSideEffects(Ctx, IncludePossibleEffects);
Richard Smith0421ce72012-08-07 04:16:51 +00002985
2986 case ChooseExprClass:
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00002987 return cast<ChooseExpr>(this)->getChosenSubExpr()->HasSideEffects(
2988 Ctx, IncludePossibleEffects);
Richard Smith0421ce72012-08-07 04:16:51 +00002989
2990 case CXXDefaultArgExprClass:
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00002991 return cast<CXXDefaultArgExpr>(this)->getExpr()->HasSideEffects(
2992 Ctx, IncludePossibleEffects);
Richard Smith0421ce72012-08-07 04:16:51 +00002993
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002994 case CXXDefaultInitExprClass: {
2995 const FieldDecl *FD = cast<CXXDefaultInitExpr>(this)->getField();
2996 if (const Expr *E = FD->getInClassInitializer())
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00002997 return E->HasSideEffects(Ctx, IncludePossibleEffects);
Richard Smith852c9db2013-04-20 22:23:05 +00002998 // If we've not yet parsed the initializer, assume it has side-effects.
2999 return true;
Reid Klecknerd60b82f2014-11-17 23:36:45 +00003000 }
Richard Smith852c9db2013-04-20 22:23:05 +00003001
Richard Smith0421ce72012-08-07 04:16:51 +00003002 case CXXDynamicCastExprClass: {
3003 // A dynamic_cast expression has side-effects if it can throw.
3004 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(this);
3005 if (DCE->getTypeAsWritten()->isReferenceType() &&
3006 DCE->getCastKind() == CK_Dynamic)
3007 return true;
Richard Smitha33e4fe2012-08-07 05:18:29 +00003008 } // Fall through.
3009 case ImplicitCastExprClass:
3010 case CStyleCastExprClass:
3011 case CXXStaticCastExprClass:
3012 case CXXReinterpretCastExprClass:
3013 case CXXConstCastExprClass:
3014 case CXXFunctionalCastExprClass: {
Aaron Ballman409af502015-01-03 17:00:12 +00003015 // While volatile reads are side-effecting in both C and C++, we treat them
3016 // as having possible (not definite) side-effects. This allows idiomatic
3017 // code to behave without warning, such as sizeof(*v) for a volatile-
3018 // qualified pointer.
3019 if (!IncludePossibleEffects)
3020 break;
3021
Richard Smitha33e4fe2012-08-07 05:18:29 +00003022 const CastExpr *CE = cast<CastExpr>(this);
3023 if (CE->getCastKind() == CK_LValueToRValue &&
3024 CE->getSubExpr()->getType().isVolatileQualified())
3025 return true;
Richard Smith0421ce72012-08-07 04:16:51 +00003026 break;
3027 }
3028
Richard Smithef8bf432012-08-13 20:08:14 +00003029 case CXXTypeidExprClass:
3030 // typeid might throw if its subexpression is potentially-evaluated, so has
3031 // side-effects in that case whether or not its subexpression does.
3032 return cast<CXXTypeidExpr>(this)->isPotentiallyEvaluated();
Richard Smith0421ce72012-08-07 04:16:51 +00003033
3034 case CXXConstructExprClass:
3035 case CXXTemporaryObjectExprClass: {
3036 const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003037 if (!CE->getConstructor()->isTrivial() && IncludePossibleEffects)
Richard Smith0421ce72012-08-07 04:16:51 +00003038 return true;
Richard Smitha33e4fe2012-08-07 05:18:29 +00003039 // A trivial constructor does not add any side-effects of its own. Just look
3040 // at its arguments.
Richard Smith0421ce72012-08-07 04:16:51 +00003041 break;
3042 }
3043
Richard Smith5179eb72016-06-28 19:03:57 +00003044 case CXXInheritedCtorInitExprClass: {
3045 const auto *ICIE = cast<CXXInheritedCtorInitExpr>(this);
3046 if (!ICIE->getConstructor()->isTrivial() && IncludePossibleEffects)
3047 return true;
3048 break;
3049 }
3050
Richard Smith0421ce72012-08-07 04:16:51 +00003051 case LambdaExprClass: {
3052 const LambdaExpr *LE = cast<LambdaExpr>(this);
3053 for (LambdaExpr::capture_iterator I = LE->capture_begin(),
3054 E = LE->capture_end(); I != E; ++I)
3055 if (I->getCaptureKind() == LCK_ByCopy)
3056 // FIXME: Only has a side-effect if the variable is volatile or if
3057 // the copy would invoke a non-trivial copy constructor.
3058 return true;
3059 return false;
3060 }
3061
3062 case PseudoObjectExprClass: {
3063 // Only look for side-effects in the semantic form, and look past
3064 // OpaqueValueExpr bindings in that form.
3065 const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this);
3066 for (PseudoObjectExpr::const_semantics_iterator I = PO->semantics_begin(),
3067 E = PO->semantics_end();
3068 I != E; ++I) {
3069 const Expr *Subexpr = *I;
3070 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Subexpr))
3071 Subexpr = OVE->getSourceExpr();
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003072 if (Subexpr->HasSideEffects(Ctx, IncludePossibleEffects))
Richard Smith0421ce72012-08-07 04:16:51 +00003073 return true;
3074 }
3075 return false;
3076 }
3077
3078 case ObjCBoxedExprClass:
3079 case ObjCArrayLiteralClass:
3080 case ObjCDictionaryLiteralClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003081 case ObjCSelectorExprClass:
3082 case ObjCProtocolExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003083 case ObjCIsaExprClass:
3084 case ObjCIndirectCopyRestoreExprClass:
3085 case ObjCSubscriptRefExprClass:
3086 case ObjCBridgedCastExprClass:
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003087 case ObjCMessageExprClass:
3088 case ObjCPropertyRefExprClass:
3089 // FIXME: Classify these cases better.
3090 if (IncludePossibleEffects)
3091 return true;
3092 break;
Richard Smith0421ce72012-08-07 04:16:51 +00003093 }
3094
3095 // Recurse to children.
Benjamin Kramer642f1732015-07-02 21:03:14 +00003096 for (const Stmt *SubStmt : children())
3097 if (SubStmt &&
3098 cast<Expr>(SubStmt)->HasSideEffects(Ctx, IncludePossibleEffects))
3099 return true;
Richard Smith0421ce72012-08-07 04:16:51 +00003100
3101 return false;
3102}
3103
Douglas Gregor1be329d2012-02-23 07:33:15 +00003104namespace {
3105 /// \brief Look for a call to a non-trivial function within an expression.
Scott Douglass503fc392015-06-10 13:53:15 +00003106 class NonTrivialCallFinder : public ConstEvaluatedExprVisitor<NonTrivialCallFinder>
Douglas Gregor1be329d2012-02-23 07:33:15 +00003107 {
Scott Douglass503fc392015-06-10 13:53:15 +00003108 typedef ConstEvaluatedExprVisitor<NonTrivialCallFinder> Inherited;
3109
Douglas Gregor1be329d2012-02-23 07:33:15 +00003110 bool NonTrivial;
3111
3112 public:
Scott Douglass503fc392015-06-10 13:53:15 +00003113 explicit NonTrivialCallFinder(const ASTContext &Context)
Douglas Gregor6427a5e2012-02-23 07:44:18 +00003114 : Inherited(Context), NonTrivial(false) { }
Douglas Gregor1be329d2012-02-23 07:33:15 +00003115
3116 bool hasNonTrivialCall() const { return NonTrivial; }
Scott Douglass503fc392015-06-10 13:53:15 +00003117
3118 void VisitCallExpr(const CallExpr *E) {
3119 if (const CXXMethodDecl *Method
3120 = dyn_cast_or_null<const CXXMethodDecl>(E->getCalleeDecl())) {
Douglas Gregor1be329d2012-02-23 07:33:15 +00003121 if (Method->isTrivial()) {
3122 // Recurse to children of the call.
3123 Inherited::VisitStmt(E);
3124 return;
3125 }
3126 }
3127
3128 NonTrivial = true;
3129 }
Scott Douglass503fc392015-06-10 13:53:15 +00003130
3131 void VisitCXXConstructExpr(const CXXConstructExpr *E) {
Douglas Gregor1be329d2012-02-23 07:33:15 +00003132 if (E->getConstructor()->isTrivial()) {
3133 // Recurse to children of the call.
3134 Inherited::VisitStmt(E);
3135 return;
3136 }
3137
3138 NonTrivial = true;
3139 }
Scott Douglass503fc392015-06-10 13:53:15 +00003140
3141 void VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
Douglas Gregor1be329d2012-02-23 07:33:15 +00003142 if (E->getTemporary()->getDestructor()->isTrivial()) {
3143 Inherited::VisitStmt(E);
3144 return;
3145 }
3146
3147 NonTrivial = true;
3148 }
3149 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003150}
Douglas Gregor1be329d2012-02-23 07:33:15 +00003151
Scott Douglass503fc392015-06-10 13:53:15 +00003152bool Expr::hasNonTrivialCall(const ASTContext &Ctx) const {
Douglas Gregor1be329d2012-02-23 07:33:15 +00003153 NonTrivialCallFinder Finder(Ctx);
3154 Finder.Visit(this);
3155 return Finder.hasNonTrivialCall();
3156}
3157
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003158/// isNullPointerConstant - C99 6.3.2.3p3 - Return whether this is a null
3159/// pointer constant or not, as well as the specific kind of constant detected.
3160/// Null pointer constants can be integer constant expressions with the
3161/// value zero, casts of zero to void*, nullptr (C++0X), or __null
3162/// (a GNU extension).
3163Expr::NullPointerConstantKind
3164Expr::isNullPointerConstant(ASTContext &Ctx,
3165 NullPointerConstantValueDependence NPC) const {
Reid Klecknera5eef142013-11-12 02:22:34 +00003166 if (isValueDependent() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00003167 (!Ctx.getLangOpts().CPlusPlus11 || Ctx.getLangOpts().MSVCCompat)) {
Douglas Gregor56751b52009-09-25 04:25:58 +00003168 switch (NPC) {
3169 case NPC_NeverValueDependent:
David Blaikie83d382b2011-09-23 05:06:16 +00003170 llvm_unreachable("Unexpected value dependent expression!");
Douglas Gregor56751b52009-09-25 04:25:58 +00003171 case NPC_ValueDependentIsNull:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003172 if (isTypeDependent() || getType()->isIntegralType(Ctx))
David Blaikie1c7c8f72012-08-08 17:33:31 +00003173 return NPCK_ZeroExpression;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003174 else
3175 return NPCK_NotNull;
Alexis Hunta8136cc2010-05-05 15:23:54 +00003176
Douglas Gregor56751b52009-09-25 04:25:58 +00003177 case NPC_ValueDependentIsNotNull:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003178 return NPCK_NotNull;
Douglas Gregor56751b52009-09-25 04:25:58 +00003179 }
3180 }
Daniel Dunbarebc51402009-09-18 08:46:16 +00003181
Sebastian Redl72b8aef2008-10-31 14:43:28 +00003182 // Strip off a cast to void*, if it exists. Except in C++.
Argyrios Kyrtzidis3bab3d22008-08-18 23:01:59 +00003183 if (const ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(this)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003184 if (!Ctx.getLangOpts().CPlusPlus) {
Sebastian Redl72b8aef2008-10-31 14:43:28 +00003185 // Check that it is a cast to void*.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003186 if (const PointerType *PT = CE->getType()->getAs<PointerType>()) {
Sebastian Redl72b8aef2008-10-31 14:43:28 +00003187 QualType Pointee = PT->getPointeeType();
Anastasia Stulova2446b8b2015-12-11 17:41:19 +00003188 Qualifiers Q = Pointee.getQualifiers();
3189 // In OpenCL v2.0 generic address space acts as a placeholder
3190 // and should be ignored.
3191 bool IsASValid = true;
3192 if (Ctx.getLangOpts().OpenCLVersion >= 200) {
3193 if (Pointee.getAddressSpace() == LangAS::opencl_generic)
3194 Q.removeAddressSpace();
3195 else
3196 IsASValid = false;
3197 }
3198
3199 if (IsASValid && !Q.hasQualifiers() &&
3200 Pointee->isVoidType() && // to void*
3201 CE->getSubExpr()->getType()->isIntegerType()) // from int.
Douglas Gregor56751b52009-09-25 04:25:58 +00003202 return CE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
Sebastian Redl72b8aef2008-10-31 14:43:28 +00003203 }
Steve Naroffada7d422007-05-20 17:54:12 +00003204 }
Steve Naroff4871fe02008-01-14 16:10:57 +00003205 } else if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(this)) {
3206 // Ignore the ImplicitCastExpr type entirely.
Douglas Gregor56751b52009-09-25 04:25:58 +00003207 return ICE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
Steve Naroff4871fe02008-01-14 16:10:57 +00003208 } else if (const ParenExpr *PE = dyn_cast<ParenExpr>(this)) {
3209 // Accept ((void*)0) as a null pointer constant, as many other
3210 // implementations do.
Douglas Gregor56751b52009-09-25 04:25:58 +00003211 return PE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
Peter Collingbourne91147592011-04-15 00:35:48 +00003212 } else if (const GenericSelectionExpr *GE =
3213 dyn_cast<GenericSelectionExpr>(this)) {
Eli Friedman75807f22013-07-20 00:40:58 +00003214 if (GE->isResultDependent())
3215 return NPCK_NotNull;
Peter Collingbourne91147592011-04-15 00:35:48 +00003216 return GE->getResultExpr()->isNullPointerConstant(Ctx, NPC);
Eli Friedman75807f22013-07-20 00:40:58 +00003217 } else if (const ChooseExpr *CE = dyn_cast<ChooseExpr>(this)) {
3218 if (CE->isConditionDependent())
3219 return NPCK_NotNull;
3220 return CE->getChosenSubExpr()->isNullPointerConstant(Ctx, NPC);
Mike Stump11289f42009-09-09 15:08:12 +00003221 } else if (const CXXDefaultArgExpr *DefaultArg
Chris Lattner58258242008-04-10 02:22:51 +00003222 = dyn_cast<CXXDefaultArgExpr>(this)) {
Richard Smith852c9db2013-04-20 22:23:05 +00003223 // See through default argument expressions.
Douglas Gregor56751b52009-09-25 04:25:58 +00003224 return DefaultArg->getExpr()->isNullPointerConstant(Ctx, NPC);
Richard Smith852c9db2013-04-20 22:23:05 +00003225 } else if (const CXXDefaultInitExpr *DefaultInit
3226 = dyn_cast<CXXDefaultInitExpr>(this)) {
3227 // See through default initializer expressions.
3228 return DefaultInit->getExpr()->isNullPointerConstant(Ctx, NPC);
Douglas Gregor3be4b122008-11-29 04:51:27 +00003229 } else if (isa<GNUNullExpr>(this)) {
3230 // The GNU __null extension is always a null pointer constant.
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003231 return NPCK_GNUNull;
Douglas Gregorfe314812011-06-21 17:03:29 +00003232 } else if (const MaterializeTemporaryExpr *M
3233 = dyn_cast<MaterializeTemporaryExpr>(this)) {
3234 return M->GetTemporaryExpr()->isNullPointerConstant(Ctx, NPC);
John McCallfe96e0b2011-11-06 09:01:30 +00003235 } else if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(this)) {
3236 if (const Expr *Source = OVE->getSourceExpr())
3237 return Source->isNullPointerConstant(Ctx, NPC);
Steve Naroff09035312008-01-14 02:53:34 +00003238 }
Douglas Gregor3be4b122008-11-29 04:51:27 +00003239
Richard Smith89645bc2013-01-02 12:01:23 +00003240 // C++11 nullptr_t is always a null pointer constant.
Sebastian Redl576fd422009-05-10 18:38:11 +00003241 if (getType()->isNullPtrType())
Richard Smith89645bc2013-01-02 12:01:23 +00003242 return NPCK_CXX11_nullptr;
Sebastian Redl576fd422009-05-10 18:38:11 +00003243
Fariborz Jahanian3567c422010-09-27 22:42:37 +00003244 if (const RecordType *UT = getType()->getAsUnionType())
Richard Smith4055de42013-06-13 02:46:14 +00003245 if (!Ctx.getLangOpts().CPlusPlus11 &&
3246 UT && UT->getDecl()->hasAttr<TransparentUnionAttr>())
Fariborz Jahanian3567c422010-09-27 22:42:37 +00003247 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(this)){
3248 const Expr *InitExpr = CLE->getInitializer();
3249 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(InitExpr))
3250 return ILE->getInit(0)->isNullPointerConstant(Ctx, NPC);
3251 }
Steve Naroff4871fe02008-01-14 16:10:57 +00003252 // This expression must be an integer type.
Alexis Hunta8136cc2010-05-05 15:23:54 +00003253 if (!getType()->isIntegerType() ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00003254 (Ctx.getLangOpts().CPlusPlus && getType()->isEnumeralType()))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003255 return NPCK_NotNull;
Mike Stump11289f42009-09-09 15:08:12 +00003256
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003257 if (Ctx.getLangOpts().CPlusPlus11) {
Richard Smith4055de42013-06-13 02:46:14 +00003258 // C++11 [conv.ptr]p1: A null pointer constant is an integer literal with
3259 // value zero or a prvalue of type std::nullptr_t.
Reid Klecknera5eef142013-11-12 02:22:34 +00003260 // Microsoft mode permits C++98 rules reflecting MSVC behavior.
Richard Smith4055de42013-06-13 02:46:14 +00003261 const IntegerLiteral *Lit = dyn_cast<IntegerLiteral>(this);
Reid Klecknera5eef142013-11-12 02:22:34 +00003262 if (Lit && !Lit->getValue())
3263 return NPCK_ZeroLiteral;
Alp Tokerbfa39342014-01-14 12:51:41 +00003264 else if (!Ctx.getLangOpts().MSVCCompat || !isCXX98IntegralConstantExpr(Ctx))
Reid Klecknera5eef142013-11-12 02:22:34 +00003265 return NPCK_NotNull;
Richard Smith98a0a492012-02-14 21:38:30 +00003266 } else {
Richard Smith4055de42013-06-13 02:46:14 +00003267 // If we have an integer constant expression, we need to *evaluate* it and
3268 // test for the value 0.
Richard Smith98a0a492012-02-14 21:38:30 +00003269 if (!isIntegerConstantExpr(Ctx))
3270 return NPCK_NotNull;
3271 }
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003272
David Blaikie1c7c8f72012-08-08 17:33:31 +00003273 if (EvaluateKnownConstInt(Ctx) != 0)
3274 return NPCK_NotNull;
3275
3276 if (isa<IntegerLiteral>(this))
3277 return NPCK_ZeroLiteral;
3278 return NPCK_ZeroExpression;
Steve Naroff218bc2b2007-05-04 21:54:46 +00003279}
Steve Narofff7a5da12007-07-28 23:10:27 +00003280
John McCall34376a62010-12-04 03:47:34 +00003281/// \brief If this expression is an l-value for an Objective C
3282/// property, find the underlying property reference expression.
3283const ObjCPropertyRefExpr *Expr::getObjCProperty() const {
3284 const Expr *E = this;
3285 while (true) {
3286 assert((E->getValueKind() == VK_LValue &&
3287 E->getObjectKind() == OK_ObjCProperty) &&
3288 "expression is not a property reference");
3289 E = E->IgnoreParenCasts();
3290 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3291 if (BO->getOpcode() == BO_Comma) {
3292 E = BO->getRHS();
3293 continue;
3294 }
3295 }
3296
3297 break;
3298 }
3299
3300 return cast<ObjCPropertyRefExpr>(E);
3301}
3302
Anna Zaks97c7ce32012-10-01 20:34:04 +00003303bool Expr::isObjCSelfExpr() const {
3304 const Expr *E = IgnoreParenImpCasts();
3305
3306 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
3307 if (!DRE)
3308 return false;
3309
3310 const ImplicitParamDecl *Param = dyn_cast<ImplicitParamDecl>(DRE->getDecl());
3311 if (!Param)
3312 return false;
3313
3314 const ObjCMethodDecl *M = dyn_cast<ObjCMethodDecl>(Param->getDeclContext());
3315 if (!M)
3316 return false;
3317
3318 return M->getSelfDecl() == Param;
3319}
3320
John McCalld25db7e2013-05-06 21:39:12 +00003321FieldDecl *Expr::getSourceBitField() {
Douglas Gregor19623dc2009-07-06 15:38:40 +00003322 Expr *E = this->IgnoreParens();
Douglas Gregor71235ec2009-05-02 02:18:30 +00003323
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003324 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall34376a62010-12-04 03:47:34 +00003325 if (ICE->getCastKind() == CK_LValueToRValue ||
3326 (ICE->getValueKind() != VK_RValue && ICE->getCastKind() == CK_NoOp))
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003327 E = ICE->getSubExpr()->IgnoreParens();
3328 else
3329 break;
3330 }
3331
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003332 if (MemberExpr *MemRef = dyn_cast<MemberExpr>(E))
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00003333 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemRef->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00003334 if (Field->isBitField())
3335 return Field;
3336
John McCalld25db7e2013-05-06 21:39:12 +00003337 if (ObjCIvarRefExpr *IvarRef = dyn_cast<ObjCIvarRefExpr>(E))
3338 if (FieldDecl *Ivar = dyn_cast<FieldDecl>(IvarRef->getDecl()))
3339 if (Ivar->isBitField())
3340 return Ivar;
3341
Richard Smith7873de02016-08-11 22:25:46 +00003342 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E)) {
Argyrios Kyrtzidisd3f00542010-10-30 19:52:22 +00003343 if (FieldDecl *Field = dyn_cast<FieldDecl>(DeclRef->getDecl()))
3344 if (Field->isBitField())
3345 return Field;
3346
Richard Smith7873de02016-08-11 22:25:46 +00003347 if (BindingDecl *BD = dyn_cast<BindingDecl>(DeclRef->getDecl()))
3348 if (Expr *E = BD->getBinding())
3349 return E->getSourceBitField();
3350 }
3351
Eli Friedman609ada22011-07-13 02:05:57 +00003352 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(E)) {
Douglas Gregor71235ec2009-05-02 02:18:30 +00003353 if (BinOp->isAssignmentOp() && BinOp->getLHS())
John McCalld25db7e2013-05-06 21:39:12 +00003354 return BinOp->getLHS()->getSourceBitField();
Douglas Gregor71235ec2009-05-02 02:18:30 +00003355
Eli Friedman609ada22011-07-13 02:05:57 +00003356 if (BinOp->getOpcode() == BO_Comma && BinOp->getRHS())
John McCalld25db7e2013-05-06 21:39:12 +00003357 return BinOp->getRHS()->getSourceBitField();
Eli Friedman609ada22011-07-13 02:05:57 +00003358 }
3359
Richard Smith5b571672014-09-24 23:55:00 +00003360 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E))
3361 if (UnOp->isPrefix() && UnOp->isIncrementDecrementOp())
3362 return UnOp->getSubExpr()->getSourceBitField();
3363
Craig Topper36250ad2014-05-12 05:36:57 +00003364 return nullptr;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003365}
3366
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003367bool Expr::refersToVectorElement() const {
Richard Smith7873de02016-08-11 22:25:46 +00003368 // FIXME: Why do we not just look at the ObjectKind here?
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003369 const Expr *E = this->IgnoreParens();
Alexis Hunta8136cc2010-05-05 15:23:54 +00003370
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003371 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall2536c6d2010-08-25 10:28:54 +00003372 if (ICE->getValueKind() != VK_RValue &&
John McCalle3027922010-08-25 11:45:40 +00003373 ICE->getCastKind() == CK_NoOp)
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003374 E = ICE->getSubExpr()->IgnoreParens();
3375 else
3376 break;
3377 }
Alexis Hunta8136cc2010-05-05 15:23:54 +00003378
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003379 if (const ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(E))
3380 return ASE->getBase()->getType()->isVectorType();
3381
3382 if (isa<ExtVectorElementExpr>(E))
3383 return true;
3384
Richard Smith7873de02016-08-11 22:25:46 +00003385 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3386 if (auto *BD = dyn_cast<BindingDecl>(DRE->getDecl()))
3387 if (auto *E = BD->getBinding())
3388 return E->refersToVectorElement();
3389
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003390 return false;
3391}
3392
Andrey Bokhankod9eab9c2015-08-03 10:38:10 +00003393bool Expr::refersToGlobalRegisterVar() const {
3394 const Expr *E = this->IgnoreParenImpCasts();
3395
3396 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
3397 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
3398 if (VD->getStorageClass() == SC_Register &&
3399 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
3400 return true;
3401
3402 return false;
3403}
3404
Chris Lattnerb8211f62009-02-16 22:14:05 +00003405/// isArrow - Return true if the base expression is a pointer to vector,
3406/// return false if the base expression is a vector.
3407bool ExtVectorElementExpr::isArrow() const {
3408 return getBase()->getType()->isPointerType();
3409}
3410
Nate Begemance4d7fc2008-04-18 23:10:10 +00003411unsigned ExtVectorElementExpr::getNumElements() const {
John McCall9dd450b2009-09-21 23:43:11 +00003412 if (const VectorType *VT = getType()->getAs<VectorType>())
Nate Begemanf322eab2008-05-09 06:41:27 +00003413 return VT->getNumElements();
3414 return 1;
Chris Lattner177bd452007-08-03 16:00:20 +00003415}
3416
Nate Begemanf322eab2008-05-09 06:41:27 +00003417/// containsDuplicateElements - Return true if any element access is repeated.
Nate Begemance4d7fc2008-04-18 23:10:10 +00003418bool ExtVectorElementExpr::containsDuplicateElements() const {
Daniel Dunbarcb2a0562009-10-18 02:09:09 +00003419 // FIXME: Refactor this code to an accessor on the AST node which returns the
3420 // "type" of component access, and share with code below and in Sema.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003421 StringRef Comp = Accessor->getName();
Nate Begeman7e5185b2009-01-18 02:01:21 +00003422
3423 // Halving swizzles do not contain duplicate elements.
Daniel Dunbar125c9c92009-10-17 23:53:04 +00003424 if (Comp == "hi" || Comp == "lo" || Comp == "even" || Comp == "odd")
Nate Begeman7e5185b2009-01-18 02:01:21 +00003425 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003426
Nate Begeman7e5185b2009-01-18 02:01:21 +00003427 // Advance past s-char prefix on hex swizzles.
Daniel Dunbar125c9c92009-10-17 23:53:04 +00003428 if (Comp[0] == 's' || Comp[0] == 'S')
3429 Comp = Comp.substr(1);
Mike Stump11289f42009-09-09 15:08:12 +00003430
Daniel Dunbar125c9c92009-10-17 23:53:04 +00003431 for (unsigned i = 0, e = Comp.size(); i != e; ++i)
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003432 if (Comp.substr(i + 1).find(Comp[i]) != StringRef::npos)
Steve Naroff0d595ca2007-07-30 03:29:09 +00003433 return true;
Daniel Dunbar125c9c92009-10-17 23:53:04 +00003434
Steve Naroff0d595ca2007-07-30 03:29:09 +00003435 return false;
3436}
Chris Lattner885b4952007-08-02 23:36:59 +00003437
Nate Begemanf322eab2008-05-09 06:41:27 +00003438/// getEncodedElementAccess - We encode the fields as a llvm ConstantArray.
Nate Begemand3862152008-05-13 21:03:02 +00003439void ExtVectorElementExpr::getEncodedElementAccess(
Benjamin Kramer99383102015-07-28 16:25:32 +00003440 SmallVectorImpl<uint32_t> &Elts) const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003441 StringRef Comp = Accessor->getName();
Pirama Arumuga Nainar98eaa622016-07-22 18:49:43 +00003442 bool isNumericAccessor = false;
3443 if (Comp[0] == 's' || Comp[0] == 'S') {
Daniel Dunbarce5a0b32009-10-18 02:09:31 +00003444 Comp = Comp.substr(1);
Pirama Arumuga Nainar98eaa622016-07-22 18:49:43 +00003445 isNumericAccessor = true;
3446 }
Mike Stump11289f42009-09-09 15:08:12 +00003447
Daniel Dunbarce5a0b32009-10-18 02:09:31 +00003448 bool isHi = Comp == "hi";
3449 bool isLo = Comp == "lo";
3450 bool isEven = Comp == "even";
3451 bool isOdd = Comp == "odd";
Mike Stump11289f42009-09-09 15:08:12 +00003452
Nate Begemanf322eab2008-05-09 06:41:27 +00003453 for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
3454 uint64_t Index;
Mike Stump11289f42009-09-09 15:08:12 +00003455
Nate Begemanf322eab2008-05-09 06:41:27 +00003456 if (isHi)
3457 Index = e + i;
3458 else if (isLo)
3459 Index = i;
3460 else if (isEven)
3461 Index = 2 * i;
3462 else if (isOdd)
3463 Index = 2 * i + 1;
3464 else
Pirama Arumuga Nainar98eaa622016-07-22 18:49:43 +00003465 Index = ExtVectorType::getAccessorIdx(Comp[i], isNumericAccessor);
Chris Lattner885b4952007-08-02 23:36:59 +00003466
Nate Begemand3862152008-05-13 21:03:02 +00003467 Elts.push_back(Index);
Chris Lattner885b4952007-08-02 23:36:59 +00003468 }
Nate Begemanf322eab2008-05-09 06:41:27 +00003469}
3470
Craig Topper37932912013-08-18 10:09:15 +00003471ShuffleVectorExpr::ShuffleVectorExpr(const ASTContext &C, ArrayRef<Expr*> args,
Douglas Gregora6e053e2010-12-15 01:34:56 +00003472 QualType Type, SourceLocation BLoc,
3473 SourceLocation RP)
3474 : Expr(ShuffleVectorExprClass, Type, VK_RValue, OK_Ordinary,
3475 Type->isDependentType(), Type->isDependentType(),
Douglas Gregor678d76c2011-07-01 01:22:09 +00003476 Type->isInstantiationDependentType(),
Douglas Gregora6e053e2010-12-15 01:34:56 +00003477 Type->containsUnexpandedParameterPack()),
Benjamin Kramerc215e762012-08-24 11:54:20 +00003478 BuiltinLoc(BLoc), RParenLoc(RP), NumExprs(args.size())
Douglas Gregora6e053e2010-12-15 01:34:56 +00003479{
Benjamin Kramerc215e762012-08-24 11:54:20 +00003480 SubExprs = new (C) Stmt*[args.size()];
3481 for (unsigned i = 0; i != args.size(); i++) {
Douglas Gregora6e053e2010-12-15 01:34:56 +00003482 if (args[i]->isTypeDependent())
3483 ExprBits.TypeDependent = true;
3484 if (args[i]->isValueDependent())
3485 ExprBits.ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003486 if (args[i]->isInstantiationDependent())
3487 ExprBits.InstantiationDependent = true;
Douglas Gregora6e053e2010-12-15 01:34:56 +00003488 if (args[i]->containsUnexpandedParameterPack())
3489 ExprBits.ContainsUnexpandedParameterPack = true;
3490
3491 SubExprs[i] = args[i];
3492 }
3493}
3494
Craig Topper37932912013-08-18 10:09:15 +00003495void ShuffleVectorExpr::setExprs(const ASTContext &C, ArrayRef<Expr *> Exprs) {
Nate Begeman48745922009-08-12 02:28:50 +00003496 if (SubExprs) C.Deallocate(SubExprs);
3497
Dmitri Gribenko674eaa22013-05-10 00:43:44 +00003498 this->NumExprs = Exprs.size();
Dmitri Gribenko48d6daf2013-05-10 17:30:13 +00003499 SubExprs = new (C) Stmt*[NumExprs];
Dmitri Gribenko674eaa22013-05-10 00:43:44 +00003500 memcpy(SubExprs, Exprs.data(), sizeof(Expr *) * Exprs.size());
Mike Stump11289f42009-09-09 15:08:12 +00003501}
Nate Begeman48745922009-08-12 02:28:50 +00003502
Craig Topper37932912013-08-18 10:09:15 +00003503GenericSelectionExpr::GenericSelectionExpr(const ASTContext &Context,
Peter Collingbourne91147592011-04-15 00:35:48 +00003504 SourceLocation GenericLoc, Expr *ControllingExpr,
Benjamin Kramerc215e762012-08-24 11:54:20 +00003505 ArrayRef<TypeSourceInfo*> AssocTypes,
3506 ArrayRef<Expr*> AssocExprs,
3507 SourceLocation DefaultLoc,
Peter Collingbourne91147592011-04-15 00:35:48 +00003508 SourceLocation RParenLoc,
3509 bool ContainsUnexpandedParameterPack,
3510 unsigned ResultIndex)
3511 : Expr(GenericSelectionExprClass,
3512 AssocExprs[ResultIndex]->getType(),
3513 AssocExprs[ResultIndex]->getValueKind(),
3514 AssocExprs[ResultIndex]->getObjectKind(),
3515 AssocExprs[ResultIndex]->isTypeDependent(),
3516 AssocExprs[ResultIndex]->isValueDependent(),
Douglas Gregor678d76c2011-07-01 01:22:09 +00003517 AssocExprs[ResultIndex]->isInstantiationDependent(),
Peter Collingbourne91147592011-04-15 00:35:48 +00003518 ContainsUnexpandedParameterPack),
Benjamin Kramerc215e762012-08-24 11:54:20 +00003519 AssocTypes(new (Context) TypeSourceInfo*[AssocTypes.size()]),
3520 SubExprs(new (Context) Stmt*[END_EXPR+AssocExprs.size()]),
3521 NumAssocs(AssocExprs.size()), ResultIndex(ResultIndex),
3522 GenericLoc(GenericLoc), DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
Peter Collingbourne91147592011-04-15 00:35:48 +00003523 SubExprs[CONTROLLING] = ControllingExpr;
Benjamin Kramerc215e762012-08-24 11:54:20 +00003524 assert(AssocTypes.size() == AssocExprs.size());
3525 std::copy(AssocTypes.begin(), AssocTypes.end(), this->AssocTypes);
3526 std::copy(AssocExprs.begin(), AssocExprs.end(), SubExprs+END_EXPR);
Peter Collingbourne91147592011-04-15 00:35:48 +00003527}
3528
Craig Topper37932912013-08-18 10:09:15 +00003529GenericSelectionExpr::GenericSelectionExpr(const ASTContext &Context,
Peter Collingbourne91147592011-04-15 00:35:48 +00003530 SourceLocation GenericLoc, Expr *ControllingExpr,
Benjamin Kramerc215e762012-08-24 11:54:20 +00003531 ArrayRef<TypeSourceInfo*> AssocTypes,
3532 ArrayRef<Expr*> AssocExprs,
3533 SourceLocation DefaultLoc,
Peter Collingbourne91147592011-04-15 00:35:48 +00003534 SourceLocation RParenLoc,
3535 bool ContainsUnexpandedParameterPack)
3536 : Expr(GenericSelectionExprClass,
3537 Context.DependentTy,
3538 VK_RValue,
3539 OK_Ordinary,
Douglas Gregor678d76c2011-07-01 01:22:09 +00003540 /*isTypeDependent=*/true,
3541 /*isValueDependent=*/true,
3542 /*isInstantiationDependent=*/true,
Peter Collingbourne91147592011-04-15 00:35:48 +00003543 ContainsUnexpandedParameterPack),
Benjamin Kramerc215e762012-08-24 11:54:20 +00003544 AssocTypes(new (Context) TypeSourceInfo*[AssocTypes.size()]),
3545 SubExprs(new (Context) Stmt*[END_EXPR+AssocExprs.size()]),
3546 NumAssocs(AssocExprs.size()), ResultIndex(-1U), GenericLoc(GenericLoc),
3547 DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
Peter Collingbourne91147592011-04-15 00:35:48 +00003548 SubExprs[CONTROLLING] = ControllingExpr;
Benjamin Kramerc215e762012-08-24 11:54:20 +00003549 assert(AssocTypes.size() == AssocExprs.size());
3550 std::copy(AssocTypes.begin(), AssocTypes.end(), this->AssocTypes);
3551 std::copy(AssocExprs.begin(), AssocExprs.end(), SubExprs+END_EXPR);
Peter Collingbourne91147592011-04-15 00:35:48 +00003552}
3553
Ted Kremenek85e92ec2007-08-24 18:13:47 +00003554//===----------------------------------------------------------------------===//
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003555// DesignatedInitExpr
3556//===----------------------------------------------------------------------===//
3557
Chandler Carruth631abd92011-06-16 06:47:06 +00003558IdentifierInfo *DesignatedInitExpr::Designator::getFieldName() const {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003559 assert(Kind == FieldDesignator && "Only valid on a field designator");
3560 if (Field.NameOrField & 0x01)
3561 return reinterpret_cast<IdentifierInfo *>(Field.NameOrField&~0x01);
3562 else
3563 return getField()->getIdentifier();
3564}
3565
Craig Topper37932912013-08-18 10:09:15 +00003566DesignatedInitExpr::DesignatedInitExpr(const ASTContext &C, QualType Ty,
David Majnemerf7e36092016-06-23 00:15:04 +00003567 llvm::ArrayRef<Designator> Designators,
Mike Stump11289f42009-09-09 15:08:12 +00003568 SourceLocation EqualOrColonLoc,
Douglas Gregord5846a12009-04-15 06:41:24 +00003569 bool GNUSyntax,
Benjamin Kramerc215e762012-08-24 11:54:20 +00003570 ArrayRef<Expr*> IndexExprs,
Douglas Gregorca1aeec2009-05-21 23:17:49 +00003571 Expr *Init)
Mike Stump11289f42009-09-09 15:08:12 +00003572 : Expr(DesignatedInitExprClass, Ty,
John McCall7decc9e2010-11-18 06:31:45 +00003573 Init->getValueKind(), Init->getObjectKind(),
Douglas Gregora6e053e2010-12-15 01:34:56 +00003574 Init->isTypeDependent(), Init->isValueDependent(),
Douglas Gregor678d76c2011-07-01 01:22:09 +00003575 Init->isInstantiationDependent(),
Douglas Gregora6e053e2010-12-15 01:34:56 +00003576 Init->containsUnexpandedParameterPack()),
Mike Stump11289f42009-09-09 15:08:12 +00003577 EqualOrColonLoc(EqualOrColonLoc), GNUSyntax(GNUSyntax),
David Majnemerf7e36092016-06-23 00:15:04 +00003578 NumDesignators(Designators.size()), NumSubExprs(IndexExprs.size() + 1) {
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00003579 this->Designators = new (C) Designator[NumDesignators];
Douglas Gregorca1aeec2009-05-21 23:17:49 +00003580
3581 // Record the initializer itself.
Benjamin Kramer5733e352015-07-18 17:09:36 +00003582 child_iterator Child = child_begin();
Douglas Gregorca1aeec2009-05-21 23:17:49 +00003583 *Child++ = Init;
3584
3585 // Copy the designators and their subexpressions, computing
3586 // value-dependence along the way.
3587 unsigned IndexIdx = 0;
3588 for (unsigned I = 0; I != NumDesignators; ++I) {
Douglas Gregord5846a12009-04-15 06:41:24 +00003589 this->Designators[I] = Designators[I];
Douglas Gregorca1aeec2009-05-21 23:17:49 +00003590
3591 if (this->Designators[I].isArrayDesignator()) {
3592 // Compute type- and value-dependence.
3593 Expr *Index = IndexExprs[IndexIdx];
Douglas Gregora6e053e2010-12-15 01:34:56 +00003594 if (Index->isTypeDependent() || Index->isValueDependent())
David Majnemer4f217682015-01-09 01:39:09 +00003595 ExprBits.TypeDependent = ExprBits.ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003596 if (Index->isInstantiationDependent())
3597 ExprBits.InstantiationDependent = true;
Douglas Gregora6e053e2010-12-15 01:34:56 +00003598 // Propagate unexpanded parameter packs.
3599 if (Index->containsUnexpandedParameterPack())
3600 ExprBits.ContainsUnexpandedParameterPack = true;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00003601
3602 // Copy the index expressions into permanent storage.
3603 *Child++ = IndexExprs[IndexIdx++];
3604 } else if (this->Designators[I].isArrayRangeDesignator()) {
3605 // Compute type- and value-dependence.
3606 Expr *Start = IndexExprs[IndexIdx];
3607 Expr *End = IndexExprs[IndexIdx + 1];
Douglas Gregora6e053e2010-12-15 01:34:56 +00003608 if (Start->isTypeDependent() || Start->isValueDependent() ||
Douglas Gregor678d76c2011-07-01 01:22:09 +00003609 End->isTypeDependent() || End->isValueDependent()) {
David Majnemer4f217682015-01-09 01:39:09 +00003610 ExprBits.TypeDependent = ExprBits.ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003611 ExprBits.InstantiationDependent = true;
3612 } else if (Start->isInstantiationDependent() ||
3613 End->isInstantiationDependent()) {
3614 ExprBits.InstantiationDependent = true;
3615 }
3616
Douglas Gregora6e053e2010-12-15 01:34:56 +00003617 // Propagate unexpanded parameter packs.
3618 if (Start->containsUnexpandedParameterPack() ||
3619 End->containsUnexpandedParameterPack())
3620 ExprBits.ContainsUnexpandedParameterPack = true;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00003621
3622 // Copy the start/end expressions into permanent storage.
3623 *Child++ = IndexExprs[IndexIdx++];
3624 *Child++ = IndexExprs[IndexIdx++];
3625 }
3626 }
3627
Benjamin Kramerc215e762012-08-24 11:54:20 +00003628 assert(IndexIdx == IndexExprs.size() && "Wrong number of index expressions");
Douglas Gregord5846a12009-04-15 06:41:24 +00003629}
3630
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003631DesignatedInitExpr *
David Majnemerf7e36092016-06-23 00:15:04 +00003632DesignatedInitExpr::Create(const ASTContext &C,
3633 llvm::ArrayRef<Designator> Designators,
Benjamin Kramerc215e762012-08-24 11:54:20 +00003634 ArrayRef<Expr*> IndexExprs,
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003635 SourceLocation ColonOrEqualLoc,
3636 bool UsesColonSyntax, Expr *Init) {
James Y Knighte00a67e2015-12-31 04:18:25 +00003637 void *Mem = C.Allocate(totalSizeToAlloc<Stmt *>(IndexExprs.size() + 1),
Benjamin Kramerc3f89252016-10-20 14:27:22 +00003638 alignof(DesignatedInitExpr));
David Majnemerf7e36092016-06-23 00:15:04 +00003639 return new (Mem) DesignatedInitExpr(C, C.VoidTy, Designators,
Douglas Gregorca1aeec2009-05-21 23:17:49 +00003640 ColonOrEqualLoc, UsesColonSyntax,
Benjamin Kramerc215e762012-08-24 11:54:20 +00003641 IndexExprs, Init);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003642}
3643
Craig Topper37932912013-08-18 10:09:15 +00003644DesignatedInitExpr *DesignatedInitExpr::CreateEmpty(const ASTContext &C,
Douglas Gregor38676d52009-04-16 00:55:48 +00003645 unsigned NumIndexExprs) {
James Y Knighte00a67e2015-12-31 04:18:25 +00003646 void *Mem = C.Allocate(totalSizeToAlloc<Stmt *>(NumIndexExprs + 1),
Benjamin Kramerc3f89252016-10-20 14:27:22 +00003647 alignof(DesignatedInitExpr));
Douglas Gregor38676d52009-04-16 00:55:48 +00003648 return new (Mem) DesignatedInitExpr(NumIndexExprs + 1);
3649}
3650
Craig Topper37932912013-08-18 10:09:15 +00003651void DesignatedInitExpr::setDesignators(const ASTContext &C,
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00003652 const Designator *Desigs,
Douglas Gregor38676d52009-04-16 00:55:48 +00003653 unsigned NumDesigs) {
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00003654 Designators = new (C) Designator[NumDesigs];
Douglas Gregor38676d52009-04-16 00:55:48 +00003655 NumDesignators = NumDesigs;
3656 for (unsigned I = 0; I != NumDesigs; ++I)
3657 Designators[I] = Desigs[I];
3658}
3659
Abramo Bagnara22f8cd72011-03-16 15:08:46 +00003660SourceRange DesignatedInitExpr::getDesignatorsSourceRange() const {
3661 DesignatedInitExpr *DIE = const_cast<DesignatedInitExpr*>(this);
3662 if (size() == 1)
3663 return DIE->getDesignator(0)->getSourceRange();
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00003664 return SourceRange(DIE->getDesignator(0)->getLocStart(),
3665 DIE->getDesignator(size()-1)->getLocEnd());
Abramo Bagnara22f8cd72011-03-16 15:08:46 +00003666}
3667
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00003668SourceLocation DesignatedInitExpr::getLocStart() const {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003669 SourceLocation StartLoc;
David Majnemerf7e36092016-06-23 00:15:04 +00003670 auto *DIE = const_cast<DesignatedInitExpr *>(this);
3671 Designator &First = *DIE->getDesignator(0);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003672 if (First.isFieldDesignator()) {
Douglas Gregor5c7c9cb2009-03-28 00:41:23 +00003673 if (GNUSyntax)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003674 StartLoc = SourceLocation::getFromRawEncoding(First.Field.FieldLoc);
3675 else
3676 StartLoc = SourceLocation::getFromRawEncoding(First.Field.DotLoc);
3677 } else
Chris Lattner8ba22472009-02-16 22:33:34 +00003678 StartLoc =
3679 SourceLocation::getFromRawEncoding(First.ArrayOrRange.LBracketLoc);
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00003680 return StartLoc;
3681}
3682
3683SourceLocation DesignatedInitExpr::getLocEnd() const {
3684 return getInit()->getLocEnd();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003685}
3686
Dmitri Gribenkod06f7ff2013-01-26 15:15:52 +00003687Expr *DesignatedInitExpr::getArrayIndex(const Designator& D) const {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003688 assert(D.Kind == Designator::ArrayDesignator && "Requires array designator");
James Y Knighte00a67e2015-12-31 04:18:25 +00003689 return getSubExpr(D.ArrayOrRange.Index + 1);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003690}
3691
Dmitri Gribenkod06f7ff2013-01-26 15:15:52 +00003692Expr *DesignatedInitExpr::getArrayRangeStart(const Designator &D) const {
Mike Stump11289f42009-09-09 15:08:12 +00003693 assert(D.Kind == Designator::ArrayRangeDesignator &&
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003694 "Requires array range designator");
James Y Knighte00a67e2015-12-31 04:18:25 +00003695 return getSubExpr(D.ArrayOrRange.Index + 1);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003696}
3697
Dmitri Gribenkod06f7ff2013-01-26 15:15:52 +00003698Expr *DesignatedInitExpr::getArrayRangeEnd(const Designator &D) const {
Mike Stump11289f42009-09-09 15:08:12 +00003699 assert(D.Kind == Designator::ArrayRangeDesignator &&
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003700 "Requires array range designator");
James Y Knighte00a67e2015-12-31 04:18:25 +00003701 return getSubExpr(D.ArrayOrRange.Index + 2);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003702}
3703
Douglas Gregord5846a12009-04-15 06:41:24 +00003704/// \brief Replaces the designator at index @p Idx with the series
3705/// of designators in [First, Last).
Craig Topper37932912013-08-18 10:09:15 +00003706void DesignatedInitExpr::ExpandDesignator(const ASTContext &C, unsigned Idx,
Mike Stump11289f42009-09-09 15:08:12 +00003707 const Designator *First,
Douglas Gregord5846a12009-04-15 06:41:24 +00003708 const Designator *Last) {
3709 unsigned NumNewDesignators = Last - First;
3710 if (NumNewDesignators == 0) {
3711 std::copy_backward(Designators + Idx + 1,
3712 Designators + NumDesignators,
3713 Designators + Idx);
3714 --NumNewDesignators;
3715 return;
3716 } else if (NumNewDesignators == 1) {
3717 Designators[Idx] = *First;
3718 return;
3719 }
3720
Mike Stump11289f42009-09-09 15:08:12 +00003721 Designator *NewDesignators
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00003722 = new (C) Designator[NumDesignators - 1 + NumNewDesignators];
Douglas Gregord5846a12009-04-15 06:41:24 +00003723 std::copy(Designators, Designators + Idx, NewDesignators);
3724 std::copy(First, Last, NewDesignators + Idx);
3725 std::copy(Designators + Idx + 1, Designators + NumDesignators,
3726 NewDesignators + Idx + NumNewDesignators);
Douglas Gregord5846a12009-04-15 06:41:24 +00003727 Designators = NewDesignators;
3728 NumDesignators = NumDesignators - 1 + NumNewDesignators;
3729}
3730
Yunzhong Gaocb779302015-06-10 00:27:52 +00003731DesignatedInitUpdateExpr::DesignatedInitUpdateExpr(const ASTContext &C,
3732 SourceLocation lBraceLoc, Expr *baseExpr, SourceLocation rBraceLoc)
3733 : Expr(DesignatedInitUpdateExprClass, baseExpr->getType(), VK_RValue,
3734 OK_Ordinary, false, false, false, false) {
3735 BaseAndUpdaterExprs[0] = baseExpr;
3736
3737 InitListExpr *ILE = new (C) InitListExpr(C, lBraceLoc, None, rBraceLoc);
3738 ILE->setType(baseExpr->getType());
3739 BaseAndUpdaterExprs[1] = ILE;
3740}
3741
3742SourceLocation DesignatedInitUpdateExpr::getLocStart() const {
3743 return getBase()->getLocStart();
3744}
3745
3746SourceLocation DesignatedInitUpdateExpr::getLocEnd() const {
3747 return getBase()->getLocEnd();
3748}
3749
Craig Topper37932912013-08-18 10:09:15 +00003750ParenListExpr::ParenListExpr(const ASTContext& C, SourceLocation lparenloc,
Benjamin Kramerc215e762012-08-24 11:54:20 +00003751 ArrayRef<Expr*> exprs,
Sebastian Redla9351792012-02-11 23:51:47 +00003752 SourceLocation rparenloc)
3753 : Expr(ParenListExprClass, QualType(), VK_RValue, OK_Ordinary,
Douglas Gregor678d76c2011-07-01 01:22:09 +00003754 false, false, false, false),
Benjamin Kramerc215e762012-08-24 11:54:20 +00003755 NumExprs(exprs.size()), LParenLoc(lparenloc), RParenLoc(rparenloc) {
3756 Exprs = new (C) Stmt*[exprs.size()];
3757 for (unsigned i = 0; i != exprs.size(); ++i) {
Douglas Gregora6e053e2010-12-15 01:34:56 +00003758 if (exprs[i]->isTypeDependent())
3759 ExprBits.TypeDependent = true;
3760 if (exprs[i]->isValueDependent())
3761 ExprBits.ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003762 if (exprs[i]->isInstantiationDependent())
3763 ExprBits.InstantiationDependent = true;
Douglas Gregora6e053e2010-12-15 01:34:56 +00003764 if (exprs[i]->containsUnexpandedParameterPack())
3765 ExprBits.ContainsUnexpandedParameterPack = true;
3766
Nate Begeman5ec4b312009-08-10 23:49:36 +00003767 Exprs[i] = exprs[i];
Douglas Gregora6e053e2010-12-15 01:34:56 +00003768 }
Nate Begeman5ec4b312009-08-10 23:49:36 +00003769}
3770
John McCall1bf58462011-02-16 08:02:54 +00003771const OpaqueValueExpr *OpaqueValueExpr::findInCopyConstruct(const Expr *e) {
3772 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(e))
3773 e = ewc->getSubExpr();
Douglas Gregorfe314812011-06-21 17:03:29 +00003774 if (const MaterializeTemporaryExpr *m = dyn_cast<MaterializeTemporaryExpr>(e))
3775 e = m->GetTemporaryExpr();
John McCall1bf58462011-02-16 08:02:54 +00003776 e = cast<CXXConstructExpr>(e)->getArg(0);
3777 while (const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
3778 e = ice->getSubExpr();
3779 return cast<OpaqueValueExpr>(e);
3780}
3781
Craig Topper37932912013-08-18 10:09:15 +00003782PseudoObjectExpr *PseudoObjectExpr::Create(const ASTContext &Context,
3783 EmptyShell sh,
John McCallfe96e0b2011-11-06 09:01:30 +00003784 unsigned numSemanticExprs) {
James Y Knighte00a67e2015-12-31 04:18:25 +00003785 void *buffer =
3786 Context.Allocate(totalSizeToAlloc<Expr *>(1 + numSemanticExprs),
Benjamin Kramerc3f89252016-10-20 14:27:22 +00003787 alignof(PseudoObjectExpr));
John McCallfe96e0b2011-11-06 09:01:30 +00003788 return new(buffer) PseudoObjectExpr(sh, numSemanticExprs);
3789}
3790
3791PseudoObjectExpr::PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs)
3792 : Expr(PseudoObjectExprClass, shell) {
3793 PseudoObjectExprBits.NumSubExprs = numSemanticExprs + 1;
3794}
3795
Craig Topper37932912013-08-18 10:09:15 +00003796PseudoObjectExpr *PseudoObjectExpr::Create(const ASTContext &C, Expr *syntax,
John McCallfe96e0b2011-11-06 09:01:30 +00003797 ArrayRef<Expr*> semantics,
3798 unsigned resultIndex) {
3799 assert(syntax && "no syntactic expression!");
3800 assert(semantics.size() && "no semantic expressions!");
3801
3802 QualType type;
3803 ExprValueKind VK;
3804 if (resultIndex == NoResult) {
3805 type = C.VoidTy;
3806 VK = VK_RValue;
3807 } else {
3808 assert(resultIndex < semantics.size());
3809 type = semantics[resultIndex]->getType();
3810 VK = semantics[resultIndex]->getValueKind();
3811 assert(semantics[resultIndex]->getObjectKind() == OK_Ordinary);
3812 }
3813
James Y Knighte00a67e2015-12-31 04:18:25 +00003814 void *buffer = C.Allocate(totalSizeToAlloc<Expr *>(semantics.size() + 1),
Benjamin Kramerc3f89252016-10-20 14:27:22 +00003815 alignof(PseudoObjectExpr));
John McCallfe96e0b2011-11-06 09:01:30 +00003816 return new(buffer) PseudoObjectExpr(type, VK, syntax, semantics,
3817 resultIndex);
3818}
3819
3820PseudoObjectExpr::PseudoObjectExpr(QualType type, ExprValueKind VK,
3821 Expr *syntax, ArrayRef<Expr*> semantics,
3822 unsigned resultIndex)
3823 : Expr(PseudoObjectExprClass, type, VK, OK_Ordinary,
3824 /*filled in at end of ctor*/ false, false, false, false) {
3825 PseudoObjectExprBits.NumSubExprs = semantics.size() + 1;
3826 PseudoObjectExprBits.ResultIndex = resultIndex + 1;
3827
3828 for (unsigned i = 0, e = semantics.size() + 1; i != e; ++i) {
3829 Expr *E = (i == 0 ? syntax : semantics[i-1]);
3830 getSubExprsBuffer()[i] = E;
3831
3832 if (E->isTypeDependent())
3833 ExprBits.TypeDependent = true;
3834 if (E->isValueDependent())
3835 ExprBits.ValueDependent = true;
3836 if (E->isInstantiationDependent())
3837 ExprBits.InstantiationDependent = true;
3838 if (E->containsUnexpandedParameterPack())
3839 ExprBits.ContainsUnexpandedParameterPack = true;
3840
3841 if (isa<OpaqueValueExpr>(E))
Craig Topper36250ad2014-05-12 05:36:57 +00003842 assert(cast<OpaqueValueExpr>(E)->getSourceExpr() != nullptr &&
John McCallfe96e0b2011-11-06 09:01:30 +00003843 "opaque-value semantic expressions for pseudo-object "
3844 "operations must have sources");
3845 }
3846}
3847
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003848//===----------------------------------------------------------------------===//
Ted Kremenek85e92ec2007-08-24 18:13:47 +00003849// Child Iterators for iterating over subexpressions/substatements
3850//===----------------------------------------------------------------------===//
3851
Peter Collingbournee190dee2011-03-11 19:24:49 +00003852// UnaryExprOrTypeTraitExpr
3853Stmt::child_range UnaryExprOrTypeTraitExpr::children() {
Sebastian Redl6f282892008-11-11 17:56:53 +00003854 // If this is of a type and the type is a VLA type (and not a typedef), the
3855 // size expression of the VLA needs to be treated as an executable expression.
3856 // Why isn't this weirdness documented better in StmtIterator?
3857 if (isArgumentType()) {
John McCall424cec92011-01-19 06:33:43 +00003858 if (const VariableArrayType* T = dyn_cast<VariableArrayType>(
Sebastian Redl6f282892008-11-11 17:56:53 +00003859 getArgumentType().getTypePtr()))
John McCallbd066782011-02-09 08:16:59 +00003860 return child_range(child_iterator(T), child_iterator());
Benjamin Kramer5733e352015-07-18 17:09:36 +00003861 return child_range(child_iterator(), child_iterator());
Sebastian Redl6f282892008-11-11 17:56:53 +00003862 }
John McCallbd066782011-02-09 08:16:59 +00003863 return child_range(&Argument.Ex, &Argument.Ex + 1);
Ted Kremenek04746ce2007-10-18 23:28:49 +00003864}
Fariborz Jahaniana32aaef2007-10-17 16:58:11 +00003865
Benjamin Kramerc215e762012-08-24 11:54:20 +00003866AtomicExpr::AtomicExpr(SourceLocation BLoc, ArrayRef<Expr*> args,
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003867 QualType t, AtomicOp op, SourceLocation RP)
3868 : Expr(AtomicExprClass, t, VK_RValue, OK_Ordinary,
3869 false, false, false, false),
Benjamin Kramerc215e762012-08-24 11:54:20 +00003870 NumSubExprs(args.size()), BuiltinLoc(BLoc), RParenLoc(RP), Op(op)
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003871{
Benjamin Kramerc215e762012-08-24 11:54:20 +00003872 assert(args.size() == getNumSubExprs(op) && "wrong number of subexpressions");
3873 for (unsigned i = 0; i != args.size(); i++) {
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003874 if (args[i]->isTypeDependent())
3875 ExprBits.TypeDependent = true;
3876 if (args[i]->isValueDependent())
3877 ExprBits.ValueDependent = true;
3878 if (args[i]->isInstantiationDependent())
3879 ExprBits.InstantiationDependent = true;
3880 if (args[i]->containsUnexpandedParameterPack())
3881 ExprBits.ContainsUnexpandedParameterPack = true;
3882
3883 SubExprs[i] = args[i];
3884 }
3885}
Richard Smithaa22a8c2012-04-10 22:49:28 +00003886
3887unsigned AtomicExpr::getNumSubExprs(AtomicOp Op) {
3888 switch (Op) {
Richard Smithfeea8832012-04-12 05:08:17 +00003889 case AO__c11_atomic_init:
3890 case AO__c11_atomic_load:
3891 case AO__atomic_load_n:
Richard Smithaa22a8c2012-04-10 22:49:28 +00003892 return 2;
Richard Smithfeea8832012-04-12 05:08:17 +00003893
3894 case AO__c11_atomic_store:
3895 case AO__c11_atomic_exchange:
3896 case AO__atomic_load:
3897 case AO__atomic_store:
3898 case AO__atomic_store_n:
3899 case AO__atomic_exchange_n:
3900 case AO__c11_atomic_fetch_add:
3901 case AO__c11_atomic_fetch_sub:
3902 case AO__c11_atomic_fetch_and:
3903 case AO__c11_atomic_fetch_or:
3904 case AO__c11_atomic_fetch_xor:
3905 case AO__atomic_fetch_add:
3906 case AO__atomic_fetch_sub:
3907 case AO__atomic_fetch_and:
3908 case AO__atomic_fetch_or:
3909 case AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00003910 case AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00003911 case AO__atomic_add_fetch:
3912 case AO__atomic_sub_fetch:
3913 case AO__atomic_and_fetch:
3914 case AO__atomic_or_fetch:
3915 case AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00003916 case AO__atomic_nand_fetch:
Richard Smithaa22a8c2012-04-10 22:49:28 +00003917 return 3;
Richard Smithfeea8832012-04-12 05:08:17 +00003918
3919 case AO__atomic_exchange:
3920 return 4;
3921
3922 case AO__c11_atomic_compare_exchange_strong:
3923 case AO__c11_atomic_compare_exchange_weak:
Richard Smithaa22a8c2012-04-10 22:49:28 +00003924 return 5;
Richard Smithfeea8832012-04-12 05:08:17 +00003925
3926 case AO__atomic_compare_exchange:
3927 case AO__atomic_compare_exchange_n:
3928 return 6;
Richard Smithaa22a8c2012-04-10 22:49:28 +00003929 }
3930 llvm_unreachable("unknown atomic op");
3931}
Alexey Bataeva1764212015-09-30 09:22:36 +00003932
Alexey Bataev31300ed2016-02-04 11:27:03 +00003933QualType OMPArraySectionExpr::getBaseOriginalType(const Expr *Base) {
Alexey Bataeva1764212015-09-30 09:22:36 +00003934 unsigned ArraySectionCount = 0;
3935 while (auto *OASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParens())) {
3936 Base = OASE->getBase();
3937 ++ArraySectionCount;
3938 }
Alexey Bataev31300ed2016-02-04 11:27:03 +00003939 while (auto *ASE =
3940 dyn_cast<ArraySubscriptExpr>(Base->IgnoreParenImpCasts())) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003941 Base = ASE->getBase();
3942 ++ArraySectionCount;
3943 }
Alexey Bataev31300ed2016-02-04 11:27:03 +00003944 Base = Base->IgnoreParenImpCasts();
Alexey Bataeva1764212015-09-30 09:22:36 +00003945 auto OriginalTy = Base->getType();
3946 if (auto *DRE = dyn_cast<DeclRefExpr>(Base))
3947 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
3948 OriginalTy = PVD->getOriginalType().getNonReferenceType();
3949
3950 for (unsigned Cnt = 0; Cnt < ArraySectionCount; ++Cnt) {
3951 if (OriginalTy->isAnyPointerType())
3952 OriginalTy = OriginalTy->getPointeeType();
3953 else {
3954 assert (OriginalTy->isArrayType());
3955 OriginalTy = OriginalTy->castAsArrayTypeUnsafe()->getElementType();
3956 }
3957 }
3958 return OriginalTy;
3959}