blob: b7ebf318518dd57ac3b1a2a8e2d47bba63717471 [file] [log] [blame]
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001//===--- Expr.cpp - Expression AST Node Implementation --------------------===//
Chris Lattner1b926492006-08-23 06:42:10 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chris Lattner1b926492006-08-23 06:42:10 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the Expr class and subclasses.
10//
11//===----------------------------------------------------------------------===//
12
Eric Fiselier708afb52019-05-16 21:04:15 +000013#include "clang/AST/Expr.h"
14#include "clang/AST/APValue.h"
Chris Lattner5c4664e2007-07-15 23:32:58 +000015#include "clang/AST/ASTContext.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000016#include "clang/AST/Attr.h"
Douglas Gregor9a657932008-10-21 23:43:52 +000017#include "clang/AST/DeclCXX.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000018#include "clang/AST/DeclObjC.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000019#include "clang/AST/DeclTemplate.h"
Douglas Gregor1be329d2012-02-23 07:33:15 +000020#include "clang/AST/EvaluatedExprVisitor.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000021#include "clang/AST/ExprCXX.h"
David Majnemerbed356a2013-11-06 23:31:56 +000022#include "clang/AST/Mangle.h"
Eugene Zelenkoae304b02017-11-17 18:09:48 +000023#include "clang/AST/RecordLayout.h"
24#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"
Douglas Gregor0840cc02009-11-01 20:32:48 +000031#include "llvm/Support/ErrorHandling.h"
Anders Carlsson2fb08242009-09-08 18:24:21 +000032#include "llvm/Support/raw_ostream.h"
Douglas Gregord5846a12009-04-15 06:41:24 +000033#include <algorithm>
Eli Friedmanfcec6302011-11-01 02:23:42 +000034#include <cstring>
Chris Lattner1b926492006-08-23 06:42:10 +000035using namespace clang;
36
Richard Smith018ac392016-11-03 18:55:18 +000037const Expr *Expr::getBestDynamicClassTypeExpr() const {
38 const Expr *E = this;
39 while (true) {
40 E = E->ignoreParenBaseCasts();
Rafael Espindola49e860b2012-06-26 17:45:31 +000041
Richard Smith018ac392016-11-03 18:55:18 +000042 // Follow the RHS of a comma operator.
43 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
44 if (BO->getOpcode() == BO_Comma) {
45 E = BO->getRHS();
46 continue;
47 }
48 }
49
50 // Step into initializer for materialized temporaries.
51 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
52 E = MTE->GetTemporaryExpr();
53 continue;
54 }
55
56 break;
57 }
58
59 return E;
60}
61
62const CXXRecordDecl *Expr::getBestDynamicClassType() const {
63 const Expr *E = getBestDynamicClassTypeExpr();
Rafael Espindola49e860b2012-06-26 17:45:31 +000064 QualType DerivedType = E->getType();
Rafael Espindola49e860b2012-06-26 17:45:31 +000065 if (const PointerType *PTy = DerivedType->getAs<PointerType>())
66 DerivedType = PTy->getPointeeType();
67
Rafael Espindola60a2bba2012-07-17 20:24:05 +000068 if (DerivedType->isDependentType())
Craig Topper36250ad2014-05-12 05:36:57 +000069 return nullptr;
Rafael Espindola60a2bba2012-07-17 20:24:05 +000070
Rafael Espindola49e860b2012-06-26 17:45:31 +000071 const RecordType *Ty = DerivedType->castAs<RecordType>();
Rafael Espindola49e860b2012-06-26 17:45:31 +000072 Decl *D = Ty->getDecl();
73 return cast<CXXRecordDecl>(D);
74}
75
Richard Smithf3fabd22013-06-03 00:17:11 +000076const Expr *Expr::skipRValueSubobjectAdjustments(
77 SmallVectorImpl<const Expr *> &CommaLHSs,
78 SmallVectorImpl<SubobjectAdjustment> &Adjustments) const {
Rafael Espindola9c006de2012-10-27 01:03:43 +000079 const Expr *E = this;
80 while (true) {
81 E = E->IgnoreParens();
82
83 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
84 if ((CE->getCastKind() == CK_DerivedToBase ||
85 CE->getCastKind() == CK_UncheckedDerivedToBase) &&
86 E->getType()->isRecordType()) {
87 E = CE->getSubExpr();
88 CXXRecordDecl *Derived
89 = cast<CXXRecordDecl>(E->getType()->getAs<RecordType>()->getDecl());
90 Adjustments.push_back(SubobjectAdjustment(CE, Derived));
91 continue;
92 }
93
94 if (CE->getCastKind() == CK_NoOp) {
95 E = CE->getSubExpr();
96 continue;
97 }
98 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
Richard Smith6b6f8aa2013-06-15 00:30:29 +000099 if (!ME->isArrow()) {
Rafael Espindola9c006de2012-10-27 01:03:43 +0000100 assert(ME->getBase()->getType()->isRecordType());
101 if (FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
Richard Smith6b6f8aa2013-06-15 00:30:29 +0000102 if (!Field->isBitField() && !Field->getType()->isReferenceType()) {
Richard Smith2d187902013-06-03 07:13:35 +0000103 E = ME->getBase();
104 Adjustments.push_back(SubobjectAdjustment(Field));
105 continue;
106 }
Rafael Espindola9c006de2012-10-27 01:03:43 +0000107 }
108 }
109 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
Richard Smitha3fd1162018-07-24 21:18:30 +0000110 if (BO->getOpcode() == BO_PtrMemD) {
Rafael Espindola973aa202012-11-01 14:32:20 +0000111 assert(BO->getRHS()->isRValue());
Rafael Espindola9c006de2012-10-27 01:03:43 +0000112 E = BO->getLHS();
113 const MemberPointerType *MPT =
114 BO->getRHS()->getType()->getAs<MemberPointerType>();
115 Adjustments.push_back(SubobjectAdjustment(MPT, BO->getRHS()));
Richard Smithf3fabd22013-06-03 00:17:11 +0000116 continue;
117 } else if (BO->getOpcode() == BO_Comma) {
118 CommaLHSs.push_back(BO->getLHS());
119 E = BO->getRHS();
120 continue;
Rafael Espindola9c006de2012-10-27 01:03:43 +0000121 }
122 }
123
124 // Nothing changed.
125 break;
126 }
127 return E;
128}
129
Chris Lattner4ebae652010-04-16 23:34:13 +0000130/// isKnownToHaveBooleanValue - Return true if this is an integer expression
131/// that is known to return 0 or 1. This happens for _Bool/bool expressions
132/// but also int expressions which are produced by things like comparisons in
133/// C.
134bool Expr::isKnownToHaveBooleanValue() const {
Peter Collingbourne91147592011-04-15 00:35:48 +0000135 const Expr *E = IgnoreParens();
136
Chris Lattner4ebae652010-04-16 23:34:13 +0000137 // If this value has _Bool type, it is obvious 0/1.
Peter Collingbourne91147592011-04-15 00:35:48 +0000138 if (E->getType()->isBooleanType()) return true;
Fangrui Song6907ce22018-07-30 19:24:48 +0000139 // If this is a non-scalar-integer type, we don't care enough to try.
Peter Collingbourne91147592011-04-15 00:35:48 +0000140 if (!E->getType()->isIntegralOrEnumerationType()) return false;
Fangrui Song6907ce22018-07-30 19:24:48 +0000141
Peter Collingbourne91147592011-04-15 00:35:48 +0000142 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
Chris Lattner4ebae652010-04-16 23:34:13 +0000143 switch (UO->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +0000144 case UO_Plus:
Chris Lattner4ebae652010-04-16 23:34:13 +0000145 return UO->getSubExpr()->isKnownToHaveBooleanValue();
Richard Trieu0f097742014-04-04 04:13:47 +0000146 case UO_LNot:
147 return true;
Chris Lattner4ebae652010-04-16 23:34:13 +0000148 default:
149 return false;
150 }
151 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000152
John McCall45d30c32010-06-12 01:56:02 +0000153 // Only look through implicit casts. If the user writes
154 // '(int) (a && b)' treat it as an arbitrary int.
Peter Collingbourne91147592011-04-15 00:35:48 +0000155 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Chris Lattner4ebae652010-04-16 23:34:13 +0000156 return CE->getSubExpr()->isKnownToHaveBooleanValue();
Fangrui Song6907ce22018-07-30 19:24:48 +0000157
Peter Collingbourne91147592011-04-15 00:35:48 +0000158 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
Chris Lattner4ebae652010-04-16 23:34:13 +0000159 switch (BO->getOpcode()) {
160 default: return false;
John McCalle3027922010-08-25 11:45:40 +0000161 case BO_LT: // Relational operators.
162 case BO_GT:
163 case BO_LE:
164 case BO_GE:
165 case BO_EQ: // Equality operators.
166 case BO_NE:
167 case BO_LAnd: // AND operator.
168 case BO_LOr: // Logical OR operator.
Chris Lattner4ebae652010-04-16 23:34:13 +0000169 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +0000170
John McCalle3027922010-08-25 11:45:40 +0000171 case BO_And: // Bitwise AND operator.
172 case BO_Xor: // Bitwise XOR operator.
173 case BO_Or: // Bitwise OR operator.
Chris Lattner4ebae652010-04-16 23:34:13 +0000174 // Handle things like (x==2)|(y==12).
175 return BO->getLHS()->isKnownToHaveBooleanValue() &&
176 BO->getRHS()->isKnownToHaveBooleanValue();
Fangrui Song6907ce22018-07-30 19:24:48 +0000177
John McCalle3027922010-08-25 11:45:40 +0000178 case BO_Comma:
179 case BO_Assign:
Chris Lattner4ebae652010-04-16 23:34:13 +0000180 return BO->getRHS()->isKnownToHaveBooleanValue();
181 }
182 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000183
Peter Collingbourne91147592011-04-15 00:35:48 +0000184 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
Chris Lattner4ebae652010-04-16 23:34:13 +0000185 return CO->getTrueExpr()->isKnownToHaveBooleanValue() &&
186 CO->getFalseExpr()->isKnownToHaveBooleanValue();
Fangrui Song6907ce22018-07-30 19:24:48 +0000187
Chris Lattner4ebae652010-04-16 23:34:13 +0000188 return false;
189}
190
John McCallbd066782011-02-09 08:16:59 +0000191// Amusing macro metaprogramming hack: check whether a class provides
192// a more specific implementation of getExprLoc().
Daniel Dunbarb0ab5e92012-03-09 15:39:19 +0000193//
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000194// See also Stmt.cpp:{getBeginLoc(),getEndLoc()}.
Eugene Zelenkoae304b02017-11-17 18:09:48 +0000195namespace {
196 /// This implementation is used when a class provides a custom
197 /// implementation of getExprLoc.
198 template <class E, class T>
199 SourceLocation getExprLocImpl(const Expr *expr,
200 SourceLocation (T::*v)() const) {
201 return static_cast<const E*>(expr)->getExprLoc();
202 }
John McCallbd066782011-02-09 08:16:59 +0000203
Eugene Zelenkoae304b02017-11-17 18:09:48 +0000204 /// This implementation is used when a class doesn't provide
205 /// a custom implementation of getExprLoc. Overload resolution
206 /// should pick it over the implementation above because it's
207 /// more specialized according to function template partial ordering.
208 template <class E>
209 SourceLocation getExprLocImpl(const Expr *expr,
210 SourceLocation (Expr::*v)() const) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000211 return static_cast<const E *>(expr)->getBeginLoc();
Eugene Zelenkoae304b02017-11-17 18:09:48 +0000212 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000213}
John McCallbd066782011-02-09 08:16:59 +0000214
215SourceLocation Expr::getExprLoc() const {
216 switch (getStmtClass()) {
217 case Stmt::NoStmtClass: llvm_unreachable("statement without class");
218#define ABSTRACT_STMT(type)
219#define STMT(type, base) \
Richard Smitha0cbfc92014-07-26 00:47:13 +0000220 case Stmt::type##Class: break;
John McCallbd066782011-02-09 08:16:59 +0000221#define EXPR(type, base) \
222 case Stmt::type##Class: return getExprLocImpl<type>(this, &type::getExprLoc);
223#include "clang/AST/StmtNodes.inc"
224 }
Richard Smitha0cbfc92014-07-26 00:47:13 +0000225 llvm_unreachable("unknown expression kind");
John McCallbd066782011-02-09 08:16:59 +0000226}
227
Chris Lattner0eedafe2006-08-24 04:56:27 +0000228//===----------------------------------------------------------------------===//
229// Primary Expressions.
230//===----------------------------------------------------------------------===//
231
Fangrui Song6907ce22018-07-30 19:24:48 +0000232/// Compute the type-, value-, and instantiation-dependence of a
Douglas Gregor678d76c2011-07-01 01:22:09 +0000233/// declaration reference
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000234/// based on the declaration being referenced.
Craig Topperce7167c2013-08-22 04:58:56 +0000235static void computeDeclRefDependence(const ASTContext &Ctx, NamedDecl *D,
236 QualType T, bool &TypeDependent,
Douglas Gregor678d76c2011-07-01 01:22:09 +0000237 bool &ValueDependent,
238 bool &InstantiationDependent) {
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000239 TypeDependent = false;
240 ValueDependent = false;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000241 InstantiationDependent = false;
Douglas Gregored6c7442009-11-23 11:41:28 +0000242
243 // (TD) C++ [temp.dep.expr]p3:
244 // An id-expression is type-dependent if it contains:
245 //
Richard Smithcfaa5a32014-10-17 02:46:42 +0000246 // and
Douglas Gregored6c7442009-11-23 11:41:28 +0000247 //
248 // (VD) C++ [temp.dep.constexpr]p2:
249 // An identifier is value-dependent if it is:
Richard Smithcfaa5a32014-10-17 02:46:42 +0000250
Douglas Gregored6c7442009-11-23 11:41:28 +0000251 // (TD) - an identifier that was declared with dependent type
252 // (VD) - a name declared with a dependent type,
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000253 if (T->isDependentType()) {
254 TypeDependent = true;
255 ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000256 InstantiationDependent = true;
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000257 return;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000258 } else if (T->isInstantiationDependentType()) {
259 InstantiationDependent = true;
Douglas Gregored6c7442009-11-23 11:41:28 +0000260 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000261
Douglas Gregored6c7442009-11-23 11:41:28 +0000262 // (TD) - a conversion-function-id that specifies a dependent type
Fangrui Song6907ce22018-07-30 19:24:48 +0000263 if (D->getDeclName().getNameKind()
Douglas Gregor678d76c2011-07-01 01:22:09 +0000264 == DeclarationName::CXXConversionFunctionName) {
265 QualType T = D->getDeclName().getCXXNameType();
266 if (T->isDependentType()) {
267 TypeDependent = true;
268 ValueDependent = true;
269 InstantiationDependent = true;
270 return;
271 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000272
Douglas Gregor678d76c2011-07-01 01:22:09 +0000273 if (T->isInstantiationDependentType())
274 InstantiationDependent = true;
Douglas Gregored6c7442009-11-23 11:41:28 +0000275 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000276
Douglas Gregored6c7442009-11-23 11:41:28 +0000277 // (VD) - the name of a non-type template parameter,
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000278 if (isa<NonTypeTemplateParmDecl>(D)) {
279 ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000280 InstantiationDependent = true;
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000281 return;
282 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000283
Douglas Gregored6c7442009-11-23 11:41:28 +0000284 // (VD) - a constant with integral or enumeration type and is
285 // initialized with an expression that is value-dependent.
Richard Smithec8dcd22011-11-08 01:31:09 +0000286 // (VD) - a constant with literal type and is initialized with an
287 // expression that is value-dependent [C++11].
288 // (VD) - FIXME: Missing from the standard:
289 // - an entity with reference type and is initialized with an
290 // expression that is value-dependent [C++11]
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000291 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000292 if ((Ctx.getLangOpts().CPlusPlus11 ?
Richard Smithd9f663b2013-04-22 15:31:51 +0000293 Var->getType()->isLiteralType(Ctx) :
Richard Smithec8dcd22011-11-08 01:31:09 +0000294 Var->getType()->isIntegralOrEnumerationType()) &&
David Blaikief5697e52012-08-10 00:55:35 +0000295 (Var->getType().isConstQualified() ||
Richard Smithec8dcd22011-11-08 01:31:09 +0000296 Var->getType()->isReferenceType())) {
Sebastian Redl5ca79842010-02-01 20:16:42 +0000297 if (const Expr *Init = Var->getAnyInitializer())
Douglas Gregor678d76c2011-07-01 01:22:09 +0000298 if (Init->isValueDependent()) {
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000299 ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000300 InstantiationDependent = true;
301 }
Richard Smithec8dcd22011-11-08 01:31:09 +0000302 }
303
Fangrui Song6907ce22018-07-30 19:24:48 +0000304 // (VD) - FIXME: Missing from the standard:
305 // - a member function or a static data member of the current
Douglas Gregor0e4de762010-05-11 08:41:30 +0000306 // instantiation
Fangrui Song6907ce22018-07-30 19:24:48 +0000307 if (Var->isStaticDataMember() &&
Richard Smithec8dcd22011-11-08 01:31:09 +0000308 Var->getDeclContext()->isDependentContext()) {
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000309 ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000310 InstantiationDependent = true;
Richard Smith00f5d892013-11-14 22:40:45 +0000311 TypeSourceInfo *TInfo = Var->getFirstDecl()->getTypeSourceInfo();
312 if (TInfo->getType()->isIncompleteArrayType())
313 TypeDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000314 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000315
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000316 return;
317 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000318
319 // (VD) - FIXME: Missing from the standard:
320 // - a member function or a static data member of the current
Douglas Gregor0e4de762010-05-11 08:41:30 +0000321 // instantiation
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000322 if (isa<CXXMethodDecl>(D) && D->getDeclContext()->isDependentContext()) {
323 ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000324 InstantiationDependent = true;
Richard Smithec8dcd22011-11-08 01:31:09 +0000325 }
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000326}
Douglas Gregora6e053e2010-12-15 01:34:56 +0000327
Craig Topperce7167c2013-08-22 04:58:56 +0000328void DeclRefExpr::computeDependence(const ASTContext &Ctx) {
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000329 bool TypeDependent = false;
330 bool ValueDependent = false;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000331 bool InstantiationDependent = false;
Daniel Dunbar9d355812012-03-09 01:51:51 +0000332 computeDeclRefDependence(Ctx, getDecl(), getType(), TypeDependent,
333 ValueDependent, InstantiationDependent);
Richard Smithcfaa5a32014-10-17 02:46:42 +0000334
335 ExprBits.TypeDependent |= TypeDependent;
336 ExprBits.ValueDependent |= ValueDependent;
337 ExprBits.InstantiationDependent |= InstantiationDependent;
338
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000339 // Is the declaration a parameter pack?
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000340 if (getDecl()->isParameterPack())
Douglas Gregor3c6bd2a2011-01-05 21:11:38 +0000341 ExprBits.ContainsUnexpandedParameterPack = true;
Douglas Gregored6c7442009-11-23 11:41:28 +0000342}
343
Bruno Ricci5fc4db72018-12-21 14:10:18 +0000344DeclRefExpr::DeclRefExpr(const ASTContext &Ctx, ValueDecl *D,
345 bool RefersToEnclosingVariableOrCapture, QualType T,
346 ExprValueKind VK, SourceLocation L,
347 const DeclarationNameLoc &LocInfo)
348 : Expr(DeclRefExprClass, T, VK, OK_Ordinary, false, false, false, false),
349 D(D), DNLoc(LocInfo) {
350 DeclRefExprBits.HasQualifier = false;
351 DeclRefExprBits.HasTemplateKWAndArgsInfo = false;
352 DeclRefExprBits.HasFoundDecl = false;
353 DeclRefExprBits.HadMultipleCandidates = false;
354 DeclRefExprBits.RefersToEnclosingVariableOrCapture =
355 RefersToEnclosingVariableOrCapture;
356 DeclRefExprBits.Loc = L;
357 computeDependence(Ctx);
358}
359
Craig Topperce7167c2013-08-22 04:58:56 +0000360DeclRefExpr::DeclRefExpr(const ASTContext &Ctx,
Daniel Dunbar9d355812012-03-09 01:51:51 +0000361 NestedNameSpecifierLoc QualifierLoc,
Bruno Ricci5fc4db72018-12-21 14:10:18 +0000362 SourceLocation TemplateKWLoc, ValueDecl *D,
363 bool RefersToEnclosingVariableOrCapture,
364 const DeclarationNameInfo &NameInfo, NamedDecl *FoundD,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000365 const TemplateArgumentListInfo *TemplateArgs,
John McCall7decc9e2010-11-18 06:31:45 +0000366 QualType T, ExprValueKind VK)
Bruno Ricci5fc4db72018-12-21 14:10:18 +0000367 : Expr(DeclRefExprClass, T, VK, OK_Ordinary, false, false, false, false),
368 D(D), DNLoc(NameInfo.getInfo()) {
Bruno Riccia795e802018-11-13 17:56:44 +0000369 DeclRefExprBits.Loc = NameInfo.getLoc();
Chandler Carruth0e439962011-05-01 21:29:53 +0000370 DeclRefExprBits.HasQualifier = QualifierLoc ? 1 : 0;
Richard Smithcfaa5a32014-10-17 02:46:42 +0000371 if (QualifierLoc) {
James Y Knighte7d82282015-12-29 18:15:14 +0000372 new (getTrailingObjects<NestedNameSpecifierLoc>())
373 NestedNameSpecifierLoc(QualifierLoc);
Richard Smithcfaa5a32014-10-17 02:46:42 +0000374 auto *NNS = QualifierLoc.getNestedNameSpecifier();
375 if (NNS->isInstantiationDependent())
376 ExprBits.InstantiationDependent = true;
377 if (NNS->containsUnexpandedParameterPack())
378 ExprBits.ContainsUnexpandedParameterPack = true;
379 }
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000380 DeclRefExprBits.HasFoundDecl = FoundD ? 1 : 0;
381 if (FoundD)
James Y Knighte7d82282015-12-29 18:15:14 +0000382 *getTrailingObjects<NamedDecl *>() = FoundD;
Abramo Bagnara7945c982012-01-27 09:46:47 +0000383 DeclRefExprBits.HasTemplateKWAndArgsInfo
384 = (TemplateArgs || TemplateKWLoc.isValid()) ? 1 : 0;
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000385 DeclRefExprBits.RefersToEnclosingVariableOrCapture =
386 RefersToEnclosingVariableOrCapture;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000387 if (TemplateArgs) {
388 bool Dependent = false;
389 bool InstantiationDependent = false;
390 bool ContainsUnexpandedParameterPack = false;
James Y Knighte7d82282015-12-29 18:15:14 +0000391 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
392 TemplateKWLoc, *TemplateArgs, getTrailingObjects<TemplateArgumentLoc>(),
393 Dependent, InstantiationDependent, ContainsUnexpandedParameterPack);
Richard Smithcfaa5a32014-10-17 02:46:42 +0000394 assert(!Dependent && "built a DeclRefExpr with dependent template args");
395 ExprBits.InstantiationDependent |= InstantiationDependent;
396 ExprBits.ContainsUnexpandedParameterPack |= ContainsUnexpandedParameterPack;
Abramo Bagnara7945c982012-01-27 09:46:47 +0000397 } else if (TemplateKWLoc.isValid()) {
James Y Knighte7d82282015-12-29 18:15:14 +0000398 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
399 TemplateKWLoc);
Douglas Gregor678d76c2011-07-01 01:22:09 +0000400 }
Benjamin Kramer138ef9c2011-10-10 12:54:05 +0000401 DeclRefExprBits.HadMultipleCandidates = 0;
402
Daniel Dunbar9d355812012-03-09 01:51:51 +0000403 computeDependence(Ctx);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000404}
405
Craig Topperce7167c2013-08-22 04:58:56 +0000406DeclRefExpr *DeclRefExpr::Create(const ASTContext &Context,
Douglas Gregorea972d32011-02-28 21:54:11 +0000407 NestedNameSpecifierLoc QualifierLoc,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000408 SourceLocation TemplateKWLoc,
John McCallce546572009-12-08 09:08:17 +0000409 ValueDecl *D,
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000410 bool RefersToEnclosingVariableOrCapture,
Douglas Gregor4bd90e52009-10-23 18:54:35 +0000411 SourceLocation NameLoc,
Douglas Gregored6c7442009-11-23 11:41:28 +0000412 QualType T,
John McCall7decc9e2010-11-18 06:31:45 +0000413 ExprValueKind VK,
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000414 NamedDecl *FoundD,
Douglas Gregored6c7442009-11-23 11:41:28 +0000415 const TemplateArgumentListInfo *TemplateArgs) {
Abramo Bagnara7945c982012-01-27 09:46:47 +0000416 return Create(Context, QualifierLoc, TemplateKWLoc, D,
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000417 RefersToEnclosingVariableOrCapture,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000418 DeclarationNameInfo(D->getDeclName(), NameLoc),
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000419 T, VK, FoundD, TemplateArgs);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000420}
421
Craig Topperce7167c2013-08-22 04:58:56 +0000422DeclRefExpr *DeclRefExpr::Create(const ASTContext &Context,
Douglas Gregorea972d32011-02-28 21:54:11 +0000423 NestedNameSpecifierLoc QualifierLoc,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000424 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000425 ValueDecl *D,
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000426 bool RefersToEnclosingVariableOrCapture,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000427 const DeclarationNameInfo &NameInfo,
428 QualType T,
John McCall7decc9e2010-11-18 06:31:45 +0000429 ExprValueKind VK,
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000430 NamedDecl *FoundD,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000431 const TemplateArgumentListInfo *TemplateArgs) {
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000432 // Filter out cases where the found Decl is the same as the value refenenced.
433 if (D == FoundD)
Craig Topper36250ad2014-05-12 05:36:57 +0000434 FoundD = nullptr;
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000435
James Y Knighte7d82282015-12-29 18:15:14 +0000436 bool HasTemplateKWAndArgsInfo = TemplateArgs || TemplateKWLoc.isValid();
437 std::size_t Size =
438 totalSizeToAlloc<NestedNameSpecifierLoc, NamedDecl *,
439 ASTTemplateKWAndArgsInfo, TemplateArgumentLoc>(
440 QualifierLoc ? 1 : 0, FoundD ? 1 : 0,
441 HasTemplateKWAndArgsInfo ? 1 : 0,
442 TemplateArgs ? TemplateArgs->size() : 0);
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000443
Benjamin Kramerc3f89252016-10-20 14:27:22 +0000444 void *Mem = Context.Allocate(Size, alignof(DeclRefExpr));
Daniel Dunbar9d355812012-03-09 01:51:51 +0000445 return new (Mem) DeclRefExpr(Context, QualifierLoc, TemplateKWLoc, D,
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000446 RefersToEnclosingVariableOrCapture,
Daniel Dunbar9d355812012-03-09 01:51:51 +0000447 NameInfo, FoundD, TemplateArgs, T, VK);
Douglas Gregor4bd90e52009-10-23 18:54:35 +0000448}
449
Craig Topperce7167c2013-08-22 04:58:56 +0000450DeclRefExpr *DeclRefExpr::CreateEmpty(const ASTContext &Context,
Douglas Gregor87866ce2011-02-04 12:01:24 +0000451 bool HasQualifier,
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000452 bool HasFoundDecl,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000453 bool HasTemplateKWAndArgsInfo,
Argyrios Kyrtzidis1985bb32010-07-08 13:09:47 +0000454 unsigned NumTemplateArgs) {
James Y Knighte7d82282015-12-29 18:15:14 +0000455 assert(NumTemplateArgs == 0 || HasTemplateKWAndArgsInfo);
456 std::size_t Size =
457 totalSizeToAlloc<NestedNameSpecifierLoc, NamedDecl *,
458 ASTTemplateKWAndArgsInfo, TemplateArgumentLoc>(
459 HasQualifier ? 1 : 0, HasFoundDecl ? 1 : 0, HasTemplateKWAndArgsInfo,
460 NumTemplateArgs);
Benjamin Kramerc3f89252016-10-20 14:27:22 +0000461 void *Mem = Context.Allocate(Size, alignof(DeclRefExpr));
Argyrios Kyrtzidis1985bb32010-07-08 13:09:47 +0000462 return new (Mem) DeclRefExpr(EmptyShell());
463}
464
Stephen Kelly724e9e52018-08-09 20:05:03 +0000465SourceLocation DeclRefExpr::getBeginLoc() const {
Daniel Dunbarb507f272012-03-09 15:39:15 +0000466 if (hasQualifier())
467 return getQualifierLoc().getBeginLoc();
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000468 return getNameInfo().getBeginLoc();
Daniel Dunbarb507f272012-03-09 15:39:15 +0000469}
Stephen Kelly02a67ba2018-08-09 20:05:47 +0000470SourceLocation DeclRefExpr::getEndLoc() const {
Daniel Dunbarb507f272012-03-09 15:39:15 +0000471 if (hasExplicitTemplateArgs())
472 return getRAngleLoc();
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000473 return getNameInfo().getEndLoc();
Daniel Dunbarb507f272012-03-09 15:39:15 +0000474}
Douglas Gregor4bd90e52009-10-23 18:54:35 +0000475
Bruno Ricci17ff0262018-10-27 19:21:19 +0000476PredefinedExpr::PredefinedExpr(SourceLocation L, QualType FNTy, IdentKind IK,
Alexey Bataevec474782014-10-09 08:45:04 +0000477 StringLiteral *SL)
478 : Expr(PredefinedExprClass, FNTy, VK_LValue, OK_Ordinary,
479 FNTy->isDependentType(), FNTy->isDependentType(),
480 FNTy->isInstantiationDependentType(),
Bruno Ricci17ff0262018-10-27 19:21:19 +0000481 /*ContainsUnexpandedParameterPack=*/false) {
482 PredefinedExprBits.Kind = IK;
483 assert((getIdentKind() == IK) &&
484 "IdentKind do not fit in PredefinedExprBitfields!");
485 bool HasFunctionName = SL != nullptr;
486 PredefinedExprBits.HasFunctionName = HasFunctionName;
487 PredefinedExprBits.Loc = L;
488 if (HasFunctionName)
489 setFunctionName(SL);
Alexey Bataevec474782014-10-09 08:45:04 +0000490}
491
Bruno Ricci17ff0262018-10-27 19:21:19 +0000492PredefinedExpr::PredefinedExpr(EmptyShell Empty, bool HasFunctionName)
493 : Expr(PredefinedExprClass, Empty) {
494 PredefinedExprBits.HasFunctionName = HasFunctionName;
495}
496
497PredefinedExpr *PredefinedExpr::Create(const ASTContext &Ctx, SourceLocation L,
498 QualType FNTy, IdentKind IK,
499 StringLiteral *SL) {
500 bool HasFunctionName = SL != nullptr;
501 void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *>(HasFunctionName),
502 alignof(PredefinedExpr));
503 return new (Mem) PredefinedExpr(L, FNTy, IK, SL);
504}
505
506PredefinedExpr *PredefinedExpr::CreateEmpty(const ASTContext &Ctx,
507 bool HasFunctionName) {
508 void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *>(HasFunctionName),
509 alignof(PredefinedExpr));
510 return new (Mem) PredefinedExpr(EmptyShell(), HasFunctionName);
511}
512
513StringRef PredefinedExpr::getIdentKindName(PredefinedExpr::IdentKind IK) {
514 switch (IK) {
Alexey Bataevec474782014-10-09 08:45:04 +0000515 case Func:
516 return "__func__";
517 case Function:
518 return "__FUNCTION__";
519 case FuncDName:
520 return "__FUNCDNAME__";
521 case LFunction:
522 return "L__FUNCTION__";
523 case PrettyFunction:
524 return "__PRETTY_FUNCTION__";
525 case FuncSig:
526 return "__FUNCSIG__";
Reid Kleckner4a83f0a2018-07-26 23:18:44 +0000527 case LFuncSig:
528 return "L__FUNCSIG__";
Alexey Bataevec474782014-10-09 08:45:04 +0000529 case PrettyFunctionNoVirtual:
530 break;
531 }
Bruno Ricci17ff0262018-10-27 19:21:19 +0000532 llvm_unreachable("Unknown ident kind for PredefinedExpr");
Alexey Bataevec474782014-10-09 08:45:04 +0000533}
534
Anders Carlsson2fb08242009-09-08 18:24:21 +0000535// FIXME: Maybe this should use DeclPrinter with a special "print predefined
536// expr" policy instead.
Bruno Ricci17ff0262018-10-27 19:21:19 +0000537std::string PredefinedExpr::ComputeName(IdentKind IK, const Decl *CurrentDecl) {
Anders Carlsson5bd8d192010-02-11 18:20:28 +0000538 ASTContext &Context = CurrentDecl->getASTContext();
539
Bruno Ricci17ff0262018-10-27 19:21:19 +0000540 if (IK == PredefinedExpr::FuncDName) {
David Majnemerbed356a2013-11-06 23:31:56 +0000541 if (const NamedDecl *ND = dyn_cast<NamedDecl>(CurrentDecl)) {
Ahmed Charlesb8984322014-03-07 20:03:18 +0000542 std::unique_ptr<MangleContext> MC;
David Majnemerbed356a2013-11-06 23:31:56 +0000543 MC.reset(Context.createMangleContext());
544
545 if (MC->shouldMangleDeclName(ND)) {
546 SmallString<256> Buffer;
547 llvm::raw_svector_ostream Out(Buffer);
548 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(ND))
549 MC->mangleCXXCtor(CD, Ctor_Base, Out);
550 else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(ND))
551 MC->mangleCXXDtor(DD, Dtor_Base, Out);
552 else
553 MC->mangleName(ND, Out);
554
David Majnemerbed356a2013-11-06 23:31:56 +0000555 if (!Buffer.empty() && Buffer.front() == '\01')
556 return Buffer.substr(1);
557 return Buffer.str();
558 } else
559 return ND->getIdentifier()->getName();
560 }
561 return "";
562 }
Mehdi Aminidc9bf8f2016-11-16 07:07:28 +0000563 if (isa<BlockDecl>(CurrentDecl)) {
564 // For blocks we only emit something if it is enclosed in a function
565 // For top-level block we'd like to include the name of variable, but we
566 // don't have it at this point.
Mehdi Aminif5f37ee2016-11-15 22:19:50 +0000567 auto DC = CurrentDecl->getDeclContext();
568 if (DC->isFileContext())
Mehdi Aminidc9bf8f2016-11-16 07:07:28 +0000569 return "";
570
571 SmallString<256> Buffer;
572 llvm::raw_svector_ostream Out(Buffer);
573 if (auto *DCBlock = dyn_cast<BlockDecl>(DC))
574 // For nested blocks, propagate up to the parent.
Bruno Ricci17ff0262018-10-27 19:21:19 +0000575 Out << ComputeName(IK, DCBlock);
Mehdi Aminidc9bf8f2016-11-16 07:07:28 +0000576 else if (auto *DCDecl = dyn_cast<Decl>(DC))
Bruno Ricci17ff0262018-10-27 19:21:19 +0000577 Out << ComputeName(IK, DCDecl) << "_block_invoke";
Alexey Bataevec474782014-10-09 08:45:04 +0000578 return Out.str();
579 }
Anders Carlsson2fb08242009-09-08 18:24:21 +0000580 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CurrentDecl)) {
Bruno Ricci17ff0262018-10-27 19:21:19 +0000581 if (IK != PrettyFunction && IK != PrettyFunctionNoVirtual &&
582 IK != FuncSig && IK != LFuncSig)
Anders Carlsson2fb08242009-09-08 18:24:21 +0000583 return FD->getNameAsString();
584
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000585 SmallString<256> Name;
Anders Carlsson2fb08242009-09-08 18:24:21 +0000586 llvm::raw_svector_ostream Out(Name);
587
588 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
Bruno Ricci17ff0262018-10-27 19:21:19 +0000589 if (MD->isVirtual() && IK != PrettyFunctionNoVirtual)
Anders Carlsson2fb08242009-09-08 18:24:21 +0000590 Out << "virtual ";
Sam Weinig4e83bd22009-12-27 01:38:20 +0000591 if (MD->isStatic())
592 Out << "static ";
Anders Carlsson2fb08242009-09-08 18:24:21 +0000593 }
594
David Blaikiebbafb8a2012-03-11 07:00:24 +0000595 PrintingPolicy Policy(Context.getLangOpts());
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +0000596 std::string Proto;
Douglas Gregor11a434a2012-04-10 20:14:15 +0000597 llvm::raw_string_ostream POut(Proto);
Anders Carlsson2fb08242009-09-08 18:24:21 +0000598
Douglas Gregor11a434a2012-04-10 20:14:15 +0000599 const FunctionDecl *Decl = FD;
600 if (const FunctionDecl* Pattern = FD->getTemplateInstantiationPattern())
601 Decl = Pattern;
602 const FunctionType *AFT = Decl->getType()->getAs<FunctionType>();
Craig Topper36250ad2014-05-12 05:36:57 +0000603 const FunctionProtoType *FT = nullptr;
Anders Carlsson2fb08242009-09-08 18:24:21 +0000604 if (FD->hasWrittenPrototype())
605 FT = dyn_cast<FunctionProtoType>(AFT);
606
Bruno Ricci17ff0262018-10-27 19:21:19 +0000607 if (IK == FuncSig || IK == LFuncSig) {
Richard Smith2f63d462017-01-09 21:40:40 +0000608 switch (AFT->getCallConv()) {
Reid Kleckner52eddda2014-04-08 18:13:24 +0000609 case CC_C: POut << "__cdecl "; break;
610 case CC_X86StdCall: POut << "__stdcall "; break;
611 case CC_X86FastCall: POut << "__fastcall "; break;
612 case CC_X86ThisCall: POut << "__thiscall "; break;
Reid Klecknerd7857f02014-10-24 17:42:17 +0000613 case CC_X86VectorCall: POut << "__vectorcall "; break;
Erich Keane757d3172016-11-02 18:29:35 +0000614 case CC_X86RegCall: POut << "__regcall "; break;
Reid Kleckner52eddda2014-04-08 18:13:24 +0000615 // Only bother printing the conventions that MSVC knows about.
616 default: break;
617 }
618 }
619
620 FD->printQualifiedName(POut, Policy);
621
Douglas Gregor11a434a2012-04-10 20:14:15 +0000622 POut << "(";
Anders Carlsson2fb08242009-09-08 18:24:21 +0000623 if (FT) {
Douglas Gregor11a434a2012-04-10 20:14:15 +0000624 for (unsigned i = 0, e = Decl->getNumParams(); i != e; ++i) {
Anders Carlsson2fb08242009-09-08 18:24:21 +0000625 if (i) POut << ", ";
Argyrios Kyrtzidisa18347e2012-05-05 04:20:37 +0000626 POut << Decl->getParamDecl(i)->getType().stream(Policy);
Anders Carlsson2fb08242009-09-08 18:24:21 +0000627 }
628
629 if (FT->isVariadic()) {
630 if (FD->getNumParams()) POut << ", ";
631 POut << "...";
Bruno Ricci17ff0262018-10-27 19:21:19 +0000632 } else if ((IK == FuncSig || IK == LFuncSig ||
Reid Kleckner4a83f0a2018-07-26 23:18:44 +0000633 !Context.getLangOpts().CPlusPlus) &&
Richard Smithcf63b842017-01-09 22:16:16 +0000634 !Decl->getNumParams()) {
635 POut << "void";
Anders Carlsson2fb08242009-09-08 18:24:21 +0000636 }
637 }
Douglas Gregor11a434a2012-04-10 20:14:15 +0000638 POut << ")";
Anders Carlsson2fb08242009-09-08 18:24:21 +0000639
Sam Weinig4e83bd22009-12-27 01:38:20 +0000640 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
Richard Smith2f63d462017-01-09 21:40:40 +0000641 assert(FT && "We must have a written prototype in this case.");
David Blaikief5697e52012-08-10 00:55:35 +0000642 if (FT->isConst())
Douglas Gregor11a434a2012-04-10 20:14:15 +0000643 POut << " const";
David Blaikief5697e52012-08-10 00:55:35 +0000644 if (FT->isVolatile())
Douglas Gregor11a434a2012-04-10 20:14:15 +0000645 POut << " volatile";
646 RefQualifierKind Ref = MD->getRefQualifier();
647 if (Ref == RQ_LValue)
648 POut << " &";
649 else if (Ref == RQ_RValue)
650 POut << " &&";
Sam Weinig4e83bd22009-12-27 01:38:20 +0000651 }
652
Eugene Zelenkoae304b02017-11-17 18:09:48 +0000653 typedef SmallVector<const ClassTemplateSpecializationDecl *, 8> SpecsTy;
Douglas Gregor11a434a2012-04-10 20:14:15 +0000654 SpecsTy Specs;
655 const DeclContext *Ctx = FD->getDeclContext();
656 while (Ctx && isa<NamedDecl>(Ctx)) {
657 const ClassTemplateSpecializationDecl *Spec
658 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx);
659 if (Spec && !Spec->isExplicitSpecialization())
660 Specs.push_back(Spec);
661 Ctx = Ctx->getParent();
662 }
663
664 std::string TemplateParams;
665 llvm::raw_string_ostream TOut(TemplateParams);
666 for (SpecsTy::reverse_iterator I = Specs.rbegin(), E = Specs.rend();
667 I != E; ++I) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000668 const TemplateParameterList *Params
Douglas Gregor11a434a2012-04-10 20:14:15 +0000669 = (*I)->getSpecializedTemplate()->getTemplateParameters();
670 const TemplateArgumentList &Args = (*I)->getTemplateArgs();
671 assert(Params->size() == Args.size());
672 for (unsigned i = 0, numParams = Params->size(); i != numParams; ++i) {
673 StringRef Param = Params->getParam(i)->getName();
674 if (Param.empty()) continue;
675 TOut << Param << " = ";
676 Args.get(i).print(Policy, TOut);
677 TOut << ", ";
678 }
679 }
680
Fangrui Song6907ce22018-07-30 19:24:48 +0000681 FunctionTemplateSpecializationInfo *FSI
Douglas Gregor11a434a2012-04-10 20:14:15 +0000682 = FD->getTemplateSpecializationInfo();
683 if (FSI && !FSI->isExplicitSpecialization()) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000684 const TemplateParameterList* Params
Douglas Gregor11a434a2012-04-10 20:14:15 +0000685 = FSI->getTemplate()->getTemplateParameters();
686 const TemplateArgumentList* Args = FSI->TemplateArguments;
687 assert(Params->size() == Args->size());
688 for (unsigned i = 0, e = Params->size(); i != e; ++i) {
689 StringRef Param = Params->getParam(i)->getName();
690 if (Param.empty()) continue;
691 TOut << Param << " = ";
692 Args->get(i).print(Policy, TOut);
693 TOut << ", ";
694 }
695 }
696
697 TOut.flush();
698 if (!TemplateParams.empty()) {
699 // remove the trailing comma and space
700 TemplateParams.resize(TemplateParams.size() - 2);
701 POut << " [" << TemplateParams << "]";
702 }
703
704 POut.flush();
705
Benjamin Kramer90f54222013-08-21 11:45:27 +0000706 // Print "auto" for all deduced return types. This includes C++1y return
707 // type deduction and lambdas. For trailing return types resolve the
708 // decltype expression. Otherwise print the real type when this is
709 // not a constructor or destructor.
Alexey Bataevec474782014-10-09 08:45:04 +0000710 if (isa<CXXMethodDecl>(FD) &&
711 cast<CXXMethodDecl>(FD)->getParent()->isLambda())
Benjamin Kramer90f54222013-08-21 11:45:27 +0000712 Proto = "auto " + Proto;
Alp Toker314cc812014-01-25 16:55:45 +0000713 else if (FT && FT->getReturnType()->getAs<DecltypeType>())
714 FT->getReturnType()
715 ->getAs<DecltypeType>()
716 ->getUnderlyingType()
Benjamin Kramer90f54222013-08-21 11:45:27 +0000717 .getAsStringInternal(Proto, Policy);
718 else if (!isa<CXXConstructorDecl>(FD) && !isa<CXXDestructorDecl>(FD))
Alp Toker314cc812014-01-25 16:55:45 +0000719 AFT->getReturnType().getAsStringInternal(Proto, Policy);
Anders Carlsson2fb08242009-09-08 18:24:21 +0000720
721 Out << Proto;
722
Anders Carlsson2fb08242009-09-08 18:24:21 +0000723 return Name.str().str();
724 }
Wei Pan8d6b19a2013-08-26 14:27:34 +0000725 if (const CapturedDecl *CD = dyn_cast<CapturedDecl>(CurrentDecl)) {
726 for (const DeclContext *DC = CD->getParent(); DC; DC = DC->getParent())
727 // Skip to its enclosing function or method, but not its enclosing
728 // CapturedDecl.
729 if (DC->isFunctionOrMethod() && (DC->getDeclKind() != Decl::Captured)) {
730 const Decl *D = Decl::castFromDeclContext(DC);
Bruno Ricci17ff0262018-10-27 19:21:19 +0000731 return ComputeName(IK, D);
Wei Pan8d6b19a2013-08-26 14:27:34 +0000732 }
733 llvm_unreachable("CapturedDecl not inside a function or method");
734 }
Anders Carlsson2fb08242009-09-08 18:24:21 +0000735 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurrentDecl)) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000736 SmallString<256> Name;
Anders Carlsson2fb08242009-09-08 18:24:21 +0000737 llvm::raw_svector_ostream Out(Name);
738 Out << (MD->isInstanceMethod() ? '-' : '+');
739 Out << '[';
Ted Kremenek361ffd92010-03-18 21:23:08 +0000740
741 // For incorrect code, there might not be an ObjCInterfaceDecl. Do
742 // a null check to avoid a crash.
743 if (const ObjCInterfaceDecl *ID = MD->getClassInterface())
Benjamin Kramerb89514a2011-10-14 18:45:37 +0000744 Out << *ID;
Ted Kremenek361ffd92010-03-18 21:23:08 +0000745
Anders Carlsson2fb08242009-09-08 18:24:21 +0000746 if (const ObjCCategoryImplDecl *CID =
Benjamin Kramerb11416d2010-04-17 09:33:03 +0000747 dyn_cast<ObjCCategoryImplDecl>(MD->getDeclContext()))
Benjamin Kramer2f569922012-02-07 11:57:45 +0000748 Out << '(' << *CID << ')';
Benjamin Kramerb11416d2010-04-17 09:33:03 +0000749
Anders Carlsson2fb08242009-09-08 18:24:21 +0000750 Out << ' ';
Aaron Ballmanb190f972014-01-03 17:59:55 +0000751 MD->getSelector().print(Out);
Anders Carlsson2fb08242009-09-08 18:24:21 +0000752 Out << ']';
753
Anders Carlsson2fb08242009-09-08 18:24:21 +0000754 return Name.str().str();
755 }
Bruno Ricci17ff0262018-10-27 19:21:19 +0000756 if (isa<TranslationUnitDecl>(CurrentDecl) && IK == PrettyFunction) {
Anders Carlsson2fb08242009-09-08 18:24:21 +0000757 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
758 return "top level";
759 }
760 return "";
761}
762
Craig Topper37932912013-08-18 10:09:15 +0000763void APNumericStorage::setIntValue(const ASTContext &C,
764 const llvm::APInt &Val) {
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000765 if (hasAllocation())
766 C.Deallocate(pVal);
767
768 BitWidth = Val.getBitWidth();
769 unsigned NumWords = Val.getNumWords();
770 const uint64_t* Words = Val.getRawData();
771 if (NumWords > 1) {
772 pVal = new (C) uint64_t[NumWords];
773 std::copy(Words, Words + NumWords, pVal);
774 } else if (NumWords == 1)
775 VAL = Words[0];
776 else
777 VAL = 0;
778}
779
Craig Topper37932912013-08-18 10:09:15 +0000780IntegerLiteral::IntegerLiteral(const ASTContext &C, const llvm::APInt &V,
Benjamin Kramer1ea8e092012-07-04 17:04:04 +0000781 QualType type, SourceLocation l)
782 : Expr(IntegerLiteralClass, type, VK_RValue, OK_Ordinary, false, false,
783 false, false),
784 Loc(l) {
785 assert(type->isIntegerType() && "Illegal type in IntegerLiteral");
786 assert(V.getBitWidth() == C.getIntWidth(type) &&
787 "Integer type is not the correct size for constant.");
788 setValue(C, V);
789}
790
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000791IntegerLiteral *
Craig Topper37932912013-08-18 10:09:15 +0000792IntegerLiteral::Create(const ASTContext &C, const llvm::APInt &V,
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000793 QualType type, SourceLocation l) {
794 return new (C) IntegerLiteral(C, V, type, l);
795}
796
797IntegerLiteral *
Craig Topper37932912013-08-18 10:09:15 +0000798IntegerLiteral::Create(const ASTContext &C, EmptyShell Empty) {
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000799 return new (C) IntegerLiteral(Empty);
800}
801
Leonard Chandb01c3a2018-06-20 17:19:40 +0000802FixedPointLiteral::FixedPointLiteral(const ASTContext &C, const llvm::APInt &V,
803 QualType type, SourceLocation l,
804 unsigned Scale)
805 : Expr(FixedPointLiteralClass, type, VK_RValue, OK_Ordinary, false, false,
806 false, false),
807 Loc(l), Scale(Scale) {
808 assert(type->isFixedPointType() && "Illegal type in FixedPointLiteral");
809 assert(V.getBitWidth() == C.getTypeInfo(type).Width &&
810 "Fixed point type is not the correct size for constant.");
811 setValue(C, V);
812}
813
814FixedPointLiteral *FixedPointLiteral::CreateFromRawInt(const ASTContext &C,
815 const llvm::APInt &V,
816 QualType type,
817 SourceLocation l,
818 unsigned Scale) {
819 return new (C) FixedPointLiteral(C, V, type, l, Scale);
820}
821
822std::string FixedPointLiteral::getValueAsString(unsigned Radix) const {
823 // Currently the longest decimal number that can be printed is the max for an
824 // unsigned long _Accum: 4294967295.99999999976716935634613037109375
825 // which is 43 characters.
826 SmallString<64> S;
827 FixedPointValueToString(
Leonard Chanc03642e2018-08-06 16:05:08 +0000828 S, llvm::APSInt::getUnsigned(getValue().getZExtValue()), Scale);
Leonard Chandb01c3a2018-06-20 17:19:40 +0000829 return S.str();
830}
831
Craig Topper37932912013-08-18 10:09:15 +0000832FloatingLiteral::FloatingLiteral(const ASTContext &C, const llvm::APFloat &V,
Benjamin Kramer1ea8e092012-07-04 17:04:04 +0000833 bool isexact, QualType Type, SourceLocation L)
834 : Expr(FloatingLiteralClass, Type, VK_RValue, OK_Ordinary, false, false,
835 false, false), Loc(L) {
Tim Northover178723a2013-01-22 09:46:51 +0000836 setSemantics(V.getSemantics());
Benjamin Kramer1ea8e092012-07-04 17:04:04 +0000837 FloatingLiteralBits.IsExact = isexact;
838 setValue(C, V);
839}
840
Craig Topper37932912013-08-18 10:09:15 +0000841FloatingLiteral::FloatingLiteral(const ASTContext &C, EmptyShell Empty)
Eugene Zelenkoae304b02017-11-17 18:09:48 +0000842 : Expr(FloatingLiteralClass, Empty) {
Tim Northover178723a2013-01-22 09:46:51 +0000843 setRawSemantics(IEEEhalf);
Benjamin Kramer1ea8e092012-07-04 17:04:04 +0000844 FloatingLiteralBits.IsExact = false;
845}
846
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000847FloatingLiteral *
Craig Topper37932912013-08-18 10:09:15 +0000848FloatingLiteral::Create(const ASTContext &C, const llvm::APFloat &V,
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000849 bool isexact, QualType Type, SourceLocation L) {
850 return new (C) FloatingLiteral(C, V, isexact, Type, L);
851}
852
853FloatingLiteral *
Craig Topper37932912013-08-18 10:09:15 +0000854FloatingLiteral::Create(const ASTContext &C, EmptyShell Empty) {
Akira Hatanaka428f5b22012-01-10 22:40:09 +0000855 return new (C) FloatingLiteral(C, Empty);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000856}
857
Tim Northover178723a2013-01-22 09:46:51 +0000858const llvm::fltSemantics &FloatingLiteral::getSemantics() const {
859 switch(FloatingLiteralBits.Semantics) {
860 case IEEEhalf:
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000861 return llvm::APFloat::IEEEhalf();
Tim Northover178723a2013-01-22 09:46:51 +0000862 case IEEEsingle:
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000863 return llvm::APFloat::IEEEsingle();
Tim Northover178723a2013-01-22 09:46:51 +0000864 case IEEEdouble:
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000865 return llvm::APFloat::IEEEdouble();
Tim Northover178723a2013-01-22 09:46:51 +0000866 case x87DoubleExtended:
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000867 return llvm::APFloat::x87DoubleExtended();
Tim Northover178723a2013-01-22 09:46:51 +0000868 case IEEEquad:
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000869 return llvm::APFloat::IEEEquad();
Tim Northover178723a2013-01-22 09:46:51 +0000870 case PPCDoubleDouble:
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000871 return llvm::APFloat::PPCDoubleDouble();
Tim Northover178723a2013-01-22 09:46:51 +0000872 }
873 llvm_unreachable("Unrecognised floating semantics");
874}
875
876void FloatingLiteral::setSemantics(const llvm::fltSemantics &Sem) {
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000877 if (&Sem == &llvm::APFloat::IEEEhalf())
Tim Northover178723a2013-01-22 09:46:51 +0000878 FloatingLiteralBits.Semantics = IEEEhalf;
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000879 else if (&Sem == &llvm::APFloat::IEEEsingle())
Tim Northover178723a2013-01-22 09:46:51 +0000880 FloatingLiteralBits.Semantics = IEEEsingle;
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000881 else if (&Sem == &llvm::APFloat::IEEEdouble())
Tim Northover178723a2013-01-22 09:46:51 +0000882 FloatingLiteralBits.Semantics = IEEEdouble;
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000883 else if (&Sem == &llvm::APFloat::x87DoubleExtended())
Tim Northover178723a2013-01-22 09:46:51 +0000884 FloatingLiteralBits.Semantics = x87DoubleExtended;
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000885 else if (&Sem == &llvm::APFloat::IEEEquad())
Tim Northover178723a2013-01-22 09:46:51 +0000886 FloatingLiteralBits.Semantics = IEEEquad;
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000887 else if (&Sem == &llvm::APFloat::PPCDoubleDouble())
Tim Northover178723a2013-01-22 09:46:51 +0000888 FloatingLiteralBits.Semantics = PPCDoubleDouble;
889 else
890 llvm_unreachable("Unknown floating semantics");
891}
892
Chris Lattnera0173132008-06-07 22:13:43 +0000893/// getValueAsApproximateDouble - This returns the value as an inaccurate
894/// double. Note that this may cause loss of precision, but is useful for
895/// debugging dumps, etc.
896double FloatingLiteral::getValueAsApproximateDouble() const {
897 llvm::APFloat V = getValue();
Dale Johannesenc48814b2008-10-09 23:02:32 +0000898 bool ignored;
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000899 V.convert(llvm::APFloat::IEEEdouble(), llvm::APFloat::rmNearestTiesToEven,
Dale Johannesenc48814b2008-10-09 23:02:32 +0000900 &ignored);
Chris Lattnera0173132008-06-07 22:13:43 +0000901 return V.convertToDouble();
902}
903
Bruno Ricciaf214882018-11-15 16:42:14 +0000904unsigned StringLiteral::mapCharByteWidth(TargetInfo const &Target,
905 StringKind SK) {
906 unsigned CharByteWidth = 0;
907 switch (SK) {
908 case Ascii:
909 case UTF8:
910 CharByteWidth = Target.getCharWidth();
911 break;
912 case Wide:
913 CharByteWidth = Target.getWCharWidth();
914 break;
915 case UTF16:
916 CharByteWidth = Target.getChar16Width();
917 break;
918 case UTF32:
919 CharByteWidth = Target.getChar32Width();
920 break;
Eli Friedmanfcec6302011-11-01 02:23:42 +0000921 }
922 assert((CharByteWidth & 7) == 0 && "Assumes character size is byte multiple");
923 CharByteWidth /= 8;
Bruno Ricciaf214882018-11-15 16:42:14 +0000924 assert((CharByteWidth == 1 || CharByteWidth == 2 || CharByteWidth == 4) &&
925 "The only supported character byte widths are 1,2 and 4!");
Eli Friedmanfcec6302011-11-01 02:23:42 +0000926 return CharByteWidth;
927}
928
Bruno Riccib94ad1e2018-11-15 17:31:16 +0000929StringLiteral::StringLiteral(const ASTContext &Ctx, StringRef Str,
930 StringKind Kind, bool Pascal, QualType Ty,
931 const SourceLocation *Loc,
932 unsigned NumConcatenated)
933 : Expr(StringLiteralClass, Ty, VK_LValue, OK_Ordinary, false, false, false,
934 false) {
935 assert(Ctx.getAsConstantArrayType(Ty) &&
Benjamin Kramercdac7612014-02-25 12:26:20 +0000936 "StringLiteral must be of constant array type!");
Bruno Riccib94ad1e2018-11-15 17:31:16 +0000937 unsigned CharByteWidth = mapCharByteWidth(Ctx.getTargetInfo(), Kind);
938 unsigned ByteLength = Str.size();
939 assert((ByteLength % CharByteWidth == 0) &&
940 "The size of the data must be a multiple of CharByteWidth!");
Benjamin Kramercdac7612014-02-25 12:26:20 +0000941
Bruno Riccib94ad1e2018-11-15 17:31:16 +0000942 // Avoid the expensive division. The compiler should be able to figure it
943 // out by itself. However as of clang 7, even with the appropriate
944 // llvm_unreachable added just here, it is not able to do so.
945 unsigned Length;
946 switch (CharByteWidth) {
947 case 1:
948 Length = ByteLength;
949 break;
950 case 2:
951 Length = ByteLength / 2;
952 break;
953 case 4:
954 Length = ByteLength / 4;
955 break;
956 default:
957 llvm_unreachable("Unsupported character width!");
958 }
Mike Stump11289f42009-09-09 15:08:12 +0000959
Bruno Riccib94ad1e2018-11-15 17:31:16 +0000960 StringLiteralBits.Kind = Kind;
961 StringLiteralBits.CharByteWidth = CharByteWidth;
962 StringLiteralBits.IsPascal = Pascal;
963 StringLiteralBits.NumConcatenated = NumConcatenated;
964 *getTrailingObjects<unsigned>() = Length;
Eli Friedmanfcec6302011-11-01 02:23:42 +0000965
Bruno Riccib94ad1e2018-11-15 17:31:16 +0000966 // Initialize the trailing array of SourceLocation.
967 // This is safe since SourceLocation is POD-like.
968 std::memcpy(getTrailingObjects<SourceLocation>(), Loc,
969 NumConcatenated * sizeof(SourceLocation));
Chris Lattnerd3e98952006-10-06 05:22:26 +0000970
Bruno Riccib94ad1e2018-11-15 17:31:16 +0000971 // Initialize the trailing array of char holding the string data.
972 std::memcpy(getTrailingObjects<char>(), Str.data(), ByteLength);
Chris Lattner630970d2009-02-18 05:49:11 +0000973}
974
Bruno Riccib94ad1e2018-11-15 17:31:16 +0000975StringLiteral::StringLiteral(EmptyShell Empty, unsigned NumConcatenated,
976 unsigned Length, unsigned CharByteWidth)
977 : Expr(StringLiteralClass, Empty) {
978 StringLiteralBits.CharByteWidth = CharByteWidth;
979 StringLiteralBits.NumConcatenated = NumConcatenated;
980 *getTrailingObjects<unsigned>() = Length;
981}
982
983StringLiteral *StringLiteral::Create(const ASTContext &Ctx, StringRef Str,
984 StringKind Kind, bool Pascal, QualType Ty,
985 const SourceLocation *Loc,
986 unsigned NumConcatenated) {
987 void *Mem = Ctx.Allocate(totalSizeToAlloc<unsigned, SourceLocation, char>(
988 1, NumConcatenated, Str.size()),
989 alignof(StringLiteral));
990 return new (Mem)
991 StringLiteral(Ctx, Str, Kind, Pascal, Ty, Loc, NumConcatenated);
992}
993
994StringLiteral *StringLiteral::CreateEmpty(const ASTContext &Ctx,
995 unsigned NumConcatenated,
996 unsigned Length,
997 unsigned CharByteWidth) {
998 void *Mem = Ctx.Allocate(totalSizeToAlloc<unsigned, SourceLocation, char>(
999 1, NumConcatenated, Length * CharByteWidth),
1000 alignof(StringLiteral));
1001 return new (Mem)
1002 StringLiteral(EmptyShell(), NumConcatenated, Length, CharByteWidth);
Douglas Gregor958dfc92009-04-15 16:35:07 +00001003}
1004
Alexander Kornienko540bacb2013-02-01 12:35:51 +00001005void StringLiteral::outputString(raw_ostream &OS) const {
Richard Trieudc355912012-06-13 20:25:24 +00001006 switch (getKind()) {
1007 case Ascii: break; // no prefix.
1008 case Wide: OS << 'L'; break;
1009 case UTF8: OS << "u8"; break;
1010 case UTF16: OS << 'u'; break;
1011 case UTF32: OS << 'U'; break;
1012 }
1013 OS << '"';
1014 static const char Hex[] = "0123456789ABCDEF";
1015
1016 unsigned LastSlashX = getLength();
1017 for (unsigned I = 0, N = getLength(); I != N; ++I) {
1018 switch (uint32_t Char = getCodeUnit(I)) {
1019 default:
1020 // FIXME: Convert UTF-8 back to codepoints before rendering.
1021
1022 // Convert UTF-16 surrogate pairs back to codepoints before rendering.
1023 // Leave invalid surrogates alone; we'll use \x for those.
Fangrui Song6907ce22018-07-30 19:24:48 +00001024 if (getKind() == UTF16 && I != N - 1 && Char >= 0xd800 &&
Richard Trieudc355912012-06-13 20:25:24 +00001025 Char <= 0xdbff) {
1026 uint32_t Trail = getCodeUnit(I + 1);
1027 if (Trail >= 0xdc00 && Trail <= 0xdfff) {
1028 Char = 0x10000 + ((Char - 0xd800) << 10) + (Trail - 0xdc00);
1029 ++I;
1030 }
1031 }
1032
1033 if (Char > 0xff) {
1034 // If this is a wide string, output characters over 0xff using \x
1035 // escapes. Otherwise, this is a UTF-16 or UTF-32 string, and Char is a
1036 // codepoint: use \x escapes for invalid codepoints.
1037 if (getKind() == Wide ||
1038 (Char >= 0xd800 && Char <= 0xdfff) || Char >= 0x110000) {
1039 // FIXME: Is this the best way to print wchar_t?
1040 OS << "\\x";
1041 int Shift = 28;
1042 while ((Char >> Shift) == 0)
1043 Shift -= 4;
1044 for (/**/; Shift >= 0; Shift -= 4)
1045 OS << Hex[(Char >> Shift) & 15];
1046 LastSlashX = I;
1047 break;
1048 }
1049
1050 if (Char > 0xffff)
1051 OS << "\\U00"
1052 << Hex[(Char >> 20) & 15]
1053 << Hex[(Char >> 16) & 15];
1054 else
1055 OS << "\\u";
1056 OS << Hex[(Char >> 12) & 15]
1057 << Hex[(Char >> 8) & 15]
1058 << Hex[(Char >> 4) & 15]
1059 << Hex[(Char >> 0) & 15];
1060 break;
1061 }
1062
1063 // If we used \x... for the previous character, and this character is a
1064 // hexadecimal digit, prevent it being slurped as part of the \x.
1065 if (LastSlashX + 1 == I) {
1066 switch (Char) {
1067 case '0': case '1': case '2': case '3': case '4':
1068 case '5': case '6': case '7': case '8': case '9':
1069 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
1070 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
1071 OS << "\"\"";
1072 }
1073 }
1074
1075 assert(Char <= 0xff &&
1076 "Characters above 0xff should already have been handled.");
1077
Jordan Rosea7d03842013-02-08 22:30:41 +00001078 if (isPrintable(Char))
Richard Trieudc355912012-06-13 20:25:24 +00001079 OS << (char)Char;
1080 else // Output anything hard as an octal escape.
1081 OS << '\\'
1082 << (char)('0' + ((Char >> 6) & 7))
1083 << (char)('0' + ((Char >> 3) & 7))
1084 << (char)('0' + ((Char >> 0) & 7));
1085 break;
1086 // Handle some common non-printable cases to make dumps prettier.
1087 case '\\': OS << "\\\\"; break;
1088 case '"': OS << "\\\""; break;
Richard Trieudc355912012-06-13 20:25:24 +00001089 case '\a': OS << "\\a"; break;
1090 case '\b': OS << "\\b"; break;
Benjamin Kramer60a53d52016-11-24 09:41:33 +00001091 case '\f': OS << "\\f"; break;
1092 case '\n': OS << "\\n"; break;
1093 case '\r': OS << "\\r"; break;
1094 case '\t': OS << "\\t"; break;
1095 case '\v': OS << "\\v"; break;
Richard Trieudc355912012-06-13 20:25:24 +00001096 }
1097 }
1098 OS << '"';
1099}
1100
Chris Lattnere925d612010-11-17 07:37:15 +00001101/// getLocationOfByte - Return a source location that points to the specified
1102/// byte of this string literal.
1103///
1104/// Strings are amazingly complex. They can be formed from multiple tokens and
1105/// can have escape sequences in them in addition to the usual trigraph and
1106/// escaped newline business. This routine handles this complexity.
1107///
Richard Smithefb116f2015-12-10 01:11:47 +00001108/// The *StartToken sets the first token to be searched in this function and
1109/// the *StartTokenByteOffset is the byte offset of the first token. Before
1110/// returning, it updates the *StartToken to the TokNo of the token being found
1111/// and sets *StartTokenByteOffset to the byte offset of the token in the
1112/// string.
1113/// Using these two parameters can reduce the time complexity from O(n^2) to
1114/// O(n) if one wants to get the location of byte for all the tokens in a
1115/// string.
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001116///
Richard Smithefb116f2015-12-10 01:11:47 +00001117SourceLocation
1118StringLiteral::getLocationOfByte(unsigned ByteNo, const SourceManager &SM,
1119 const LangOptions &Features,
1120 const TargetInfo &Target, unsigned *StartToken,
1121 unsigned *StartTokenByteOffset) const {
Bruno Ricciaf214882018-11-15 16:42:14 +00001122 assert((getKind() == StringLiteral::Ascii ||
1123 getKind() == StringLiteral::UTF8) &&
Richard Smith4060f772012-06-13 05:37:23 +00001124 "Only narrow string literals are currently supported");
Douglas Gregorfb65e592011-07-27 05:40:30 +00001125
Chris Lattnere925d612010-11-17 07:37:15 +00001126 // Loop over all of the tokens in this string until we find the one that
1127 // contains the byte we're looking for.
1128 unsigned TokNo = 0;
Richard Smithefb116f2015-12-10 01:11:47 +00001129 unsigned StringOffset = 0;
1130 if (StartToken)
1131 TokNo = *StartToken;
1132 if (StartTokenByteOffset) {
1133 StringOffset = *StartTokenByteOffset;
1134 ByteNo -= StringOffset;
1135 }
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001136 while (1) {
Chris Lattnere925d612010-11-17 07:37:15 +00001137 assert(TokNo < getNumConcatenated() && "Invalid byte number!");
1138 SourceLocation StrTokLoc = getStrTokenLoc(TokNo);
Fangrui Song6907ce22018-07-30 19:24:48 +00001139
Chris Lattnere925d612010-11-17 07:37:15 +00001140 // Get the spelling of the string so that we can get the data that makes up
1141 // the string literal, not the identifier for the macro it is potentially
1142 // expanded through.
1143 SourceLocation StrTokSpellingLoc = SM.getSpellingLoc(StrTokLoc);
Richard Smithefb116f2015-12-10 01:11:47 +00001144
Chris Lattnere925d612010-11-17 07:37:15 +00001145 // Re-lex the token to get its length and original spelling.
Richard Smithefb116f2015-12-10 01:11:47 +00001146 std::pair<FileID, unsigned> LocInfo =
1147 SM.getDecomposedLoc(StrTokSpellingLoc);
Chris Lattnere925d612010-11-17 07:37:15 +00001148 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001149 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
Richard Smithefb116f2015-12-10 01:11:47 +00001150 if (Invalid) {
1151 if (StartTokenByteOffset != nullptr)
1152 *StartTokenByteOffset = StringOffset;
1153 if (StartToken != nullptr)
1154 *StartToken = TokNo;
Chris Lattnere925d612010-11-17 07:37:15 +00001155 return StrTokSpellingLoc;
Richard Smithefb116f2015-12-10 01:11:47 +00001156 }
1157
Chris Lattnere925d612010-11-17 07:37:15 +00001158 const char *StrData = Buffer.data()+LocInfo.second;
Fangrui Song6907ce22018-07-30 19:24:48 +00001159
Chris Lattnere925d612010-11-17 07:37:15 +00001160 // Create a lexer starting at the beginning of this token.
Argyrios Kyrtzidis45f51182012-05-11 21:39:18 +00001161 Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), Features,
1162 Buffer.begin(), StrData, Buffer.end());
Chris Lattnere925d612010-11-17 07:37:15 +00001163 Token TheTok;
1164 TheLexer.LexFromRawLexer(TheTok);
Fangrui Song6907ce22018-07-30 19:24:48 +00001165
Chris Lattnere925d612010-11-17 07:37:15 +00001166 // Use the StringLiteralParser to compute the length of the string in bytes.
Craig Topper9d5583e2014-06-26 04:58:39 +00001167 StringLiteralParser SLP(TheTok, SM, Features, Target);
Chris Lattnere925d612010-11-17 07:37:15 +00001168 unsigned TokNumBytes = SLP.GetStringLength();
Fangrui Song6907ce22018-07-30 19:24:48 +00001169
Chris Lattnere925d612010-11-17 07:37:15 +00001170 // If the byte is in this token, return the location of the byte.
1171 if (ByteNo < TokNumBytes ||
Hans Wennborg77d1abe2011-06-30 20:17:41 +00001172 (ByteNo == TokNumBytes && TokNo == getNumConcatenated() - 1)) {
Richard Smithefb116f2015-12-10 01:11:47 +00001173 unsigned Offset = SLP.getOffsetOfStringByte(TheTok, ByteNo);
1174
Chris Lattnere925d612010-11-17 07:37:15 +00001175 // Now that we know the offset of the token in the spelling, use the
1176 // preprocessor to get the offset in the original source.
Richard Smithefb116f2015-12-10 01:11:47 +00001177 if (StartTokenByteOffset != nullptr)
1178 *StartTokenByteOffset = StringOffset;
1179 if (StartToken != nullptr)
1180 *StartToken = TokNo;
Chris Lattnere925d612010-11-17 07:37:15 +00001181 return Lexer::AdvanceToTokenCharacter(StrTokLoc, Offset, SM, Features);
1182 }
Richard Smithefb116f2015-12-10 01:11:47 +00001183
Chris Lattnere925d612010-11-17 07:37:15 +00001184 // Move to the next string token.
Richard Smithefb116f2015-12-10 01:11:47 +00001185 StringOffset += TokNumBytes;
Chris Lattnere925d612010-11-17 07:37:15 +00001186 ++TokNo;
1187 ByteNo -= TokNumBytes;
1188 }
1189}
1190
Chris Lattner1b926492006-08-23 06:42:10 +00001191/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1192/// corresponds to, e.g. "sizeof" or "[pre]++".
Bruno Ricci3dfcb842018-11-13 21:33:22 +00001193StringRef UnaryOperator::getOpcodeStr(Opcode Op) {
1194 switch (Op) {
Etienne Bergeron5356d962016-05-12 20:58:56 +00001195#define UNARY_OPERATION(Name, Spelling) case UO_##Name: return Spelling;
1196#include "clang/AST/OperationKinds.def"
Chris Lattner1b926492006-08-23 06:42:10 +00001197 }
David Blaikief47fa302012-01-17 02:30:50 +00001198 llvm_unreachable("Unknown unary operator");
Chris Lattner1b926492006-08-23 06:42:10 +00001199}
1200
John McCalle3027922010-08-25 11:45:40 +00001201UnaryOperatorKind
Douglas Gregor084d8552009-03-13 23:49:33 +00001202UnaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix) {
1203 switch (OO) {
David Blaikie83d382b2011-09-23 05:06:16 +00001204 default: llvm_unreachable("No unary operator for overloaded function");
John McCalle3027922010-08-25 11:45:40 +00001205 case OO_PlusPlus: return Postfix ? UO_PostInc : UO_PreInc;
1206 case OO_MinusMinus: return Postfix ? UO_PostDec : UO_PreDec;
1207 case OO_Amp: return UO_AddrOf;
1208 case OO_Star: return UO_Deref;
1209 case OO_Plus: return UO_Plus;
1210 case OO_Minus: return UO_Minus;
1211 case OO_Tilde: return UO_Not;
1212 case OO_Exclaim: return UO_LNot;
Richard Smith9f690bd2015-10-27 06:02:45 +00001213 case OO_Coawait: return UO_Coawait;
Douglas Gregor084d8552009-03-13 23:49:33 +00001214 }
1215}
1216
1217OverloadedOperatorKind UnaryOperator::getOverloadedOperator(Opcode Opc) {
1218 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00001219 case UO_PostInc: case UO_PreInc: return OO_PlusPlus;
1220 case UO_PostDec: case UO_PreDec: return OO_MinusMinus;
1221 case UO_AddrOf: return OO_Amp;
1222 case UO_Deref: return OO_Star;
1223 case UO_Plus: return OO_Plus;
1224 case UO_Minus: return OO_Minus;
1225 case UO_Not: return OO_Tilde;
1226 case UO_LNot: return OO_Exclaim;
Richard Smith9f690bd2015-10-27 06:02:45 +00001227 case UO_Coawait: return OO_Coawait;
Douglas Gregor084d8552009-03-13 23:49:33 +00001228 default: return OO_None;
1229 }
1230}
1231
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001232
Chris Lattner0eedafe2006-08-24 04:56:27 +00001233//===----------------------------------------------------------------------===//
1234// Postfix Operators.
1235//===----------------------------------------------------------------------===//
Chris Lattnere165d942006-08-24 04:40:38 +00001236
Bruno Riccic5885cf2018-12-21 15:20:32 +00001237CallExpr::CallExpr(StmtClass SC, Expr *Fn, ArrayRef<Expr *> PreArgs,
1238 ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,
1239 SourceLocation RParenLoc, unsigned MinNumArgs,
1240 ADLCallKind UsesADL)
1241 : Expr(SC, Ty, VK, OK_Ordinary, Fn->isTypeDependent(),
1242 Fn->isValueDependent(), Fn->isInstantiationDependent(),
1243 Fn->containsUnexpandedParameterPack()),
1244 RParenLoc(RParenLoc) {
1245 NumArgs = std::max<unsigned>(Args.size(), MinNumArgs);
1246 unsigned NumPreArgs = PreArgs.size();
1247 CallExprBits.NumPreArgs = NumPreArgs;
1248 assert((NumPreArgs == getNumPreArgs()) && "NumPreArgs overflow!");
1249
1250 unsigned OffsetToTrailingObjects = offsetToTrailingObjects(SC);
1251 CallExprBits.OffsetToTrailingObjects = OffsetToTrailingObjects;
1252 assert((CallExprBits.OffsetToTrailingObjects == OffsetToTrailingObjects) &&
1253 "OffsetToTrailingObjects overflow!");
1254
Eric Fiselier5cdc2cd2018-12-12 21:50:55 +00001255 CallExprBits.UsesADL = static_cast<bool>(UsesADL);
1256
Bruno Riccic5885cf2018-12-21 15:20:32 +00001257 setCallee(Fn);
1258 for (unsigned I = 0; I != NumPreArgs; ++I) {
1259 updateDependenciesFromArg(PreArgs[I]);
1260 setPreArg(I, PreArgs[I]);
Justin Lebarf8bdacb2016-01-14 23:31:30 +00001261 }
Bruno Riccic5885cf2018-12-21 15:20:32 +00001262 for (unsigned I = 0; I != Args.size(); ++I) {
1263 updateDependenciesFromArg(Args[I]);
1264 setArg(I, Args[I]);
Douglas Gregora6e053e2010-12-15 01:34:56 +00001265 }
Bruno Riccic5885cf2018-12-21 15:20:32 +00001266 for (unsigned I = Args.size(); I != NumArgs; ++I) {
1267 setArg(I, nullptr);
Bruno Ricci4c9a0192018-12-03 14:54:03 +00001268 }
Douglas Gregor993603d2008-11-14 16:09:21 +00001269}
Nate Begeman1e36a852008-01-17 17:46:27 +00001270
Bruno Riccic5885cf2018-12-21 15:20:32 +00001271CallExpr::CallExpr(StmtClass SC, unsigned NumPreArgs, unsigned NumArgs,
1272 EmptyShell Empty)
Bruno Ricci4c9a0192018-12-03 14:54:03 +00001273 : Expr(SC, Empty), NumArgs(NumArgs) {
Peter Collingbourne3a347252011-02-08 21:18:02 +00001274 CallExprBits.NumPreArgs = NumPreArgs;
Bruno Riccic5885cf2018-12-21 15:20:32 +00001275 assert((NumPreArgs == getNumPreArgs()) && "NumPreArgs overflow!");
1276
1277 unsigned OffsetToTrailingObjects = offsetToTrailingObjects(SC);
1278 CallExprBits.OffsetToTrailingObjects = OffsetToTrailingObjects;
1279 assert((CallExprBits.OffsetToTrailingObjects == OffsetToTrailingObjects) &&
1280 "OffsetToTrailingObjects overflow!");
Douglas Gregore20a2e52009-04-15 17:43:59 +00001281}
1282
Bruno Riccic5885cf2018-12-21 15:20:32 +00001283CallExpr *CallExpr::Create(const ASTContext &Ctx, Expr *Fn,
1284 ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,
1285 SourceLocation RParenLoc, unsigned MinNumArgs,
1286 ADLCallKind UsesADL) {
1287 unsigned NumArgs = std::max<unsigned>(Args.size(), MinNumArgs);
1288 unsigned SizeOfTrailingObjects =
1289 CallExpr::sizeOfTrailingObjects(/*NumPreArgs=*/0, NumArgs);
1290 void *Mem =
1291 Ctx.Allocate(sizeof(CallExpr) + SizeOfTrailingObjects, alignof(CallExpr));
1292 return new (Mem) CallExpr(CallExprClass, Fn, /*PreArgs=*/{}, Args, Ty, VK,
1293 RParenLoc, MinNumArgs, UsesADL);
1294}
1295
1296CallExpr *CallExpr::CreateTemporary(void *Mem, Expr *Fn, QualType Ty,
1297 ExprValueKind VK, SourceLocation RParenLoc,
1298 ADLCallKind UsesADL) {
1299 assert(!(reinterpret_cast<uintptr_t>(Mem) % alignof(CallExpr)) &&
1300 "Misaligned memory in CallExpr::CreateTemporary!");
1301 return new (Mem) CallExpr(CallExprClass, Fn, /*PreArgs=*/{}, /*Args=*/{}, Ty,
1302 VK, RParenLoc, /*MinNumArgs=*/0, UsesADL);
1303}
1304
1305CallExpr *CallExpr::CreateEmpty(const ASTContext &Ctx, unsigned NumArgs,
1306 EmptyShell Empty) {
1307 unsigned SizeOfTrailingObjects =
1308 CallExpr::sizeOfTrailingObjects(/*NumPreArgs=*/0, NumArgs);
1309 void *Mem =
1310 Ctx.Allocate(sizeof(CallExpr) + SizeOfTrailingObjects, alignof(CallExpr));
1311 return new (Mem) CallExpr(CallExprClass, /*NumPreArgs=*/0, NumArgs, Empty);
1312}
1313
1314unsigned CallExpr::offsetToTrailingObjects(StmtClass SC) {
1315 switch (SC) {
1316 case CallExprClass:
1317 return sizeof(CallExpr);
1318 case CXXOperatorCallExprClass:
1319 return sizeof(CXXOperatorCallExpr);
1320 case CXXMemberCallExprClass:
1321 return sizeof(CXXMemberCallExpr);
1322 case UserDefinedLiteralClass:
1323 return sizeof(UserDefinedLiteral);
1324 case CUDAKernelCallExprClass:
1325 return sizeof(CUDAKernelCallExpr);
1326 default:
1327 llvm_unreachable("unexpected class deriving from CallExpr!");
1328 }
1329}
Bruno Ricci4c9a0192018-12-03 14:54:03 +00001330
Justin Lebarf8bdacb2016-01-14 23:31:30 +00001331void CallExpr::updateDependenciesFromArg(Expr *Arg) {
1332 if (Arg->isTypeDependent())
1333 ExprBits.TypeDependent = true;
1334 if (Arg->isValueDependent())
1335 ExprBits.ValueDependent = true;
1336 if (Arg->isInstantiationDependent())
1337 ExprBits.InstantiationDependent = true;
1338 if (Arg->containsUnexpandedParameterPack())
1339 ExprBits.ContainsUnexpandedParameterPack = true;
1340}
1341
John McCallb92ab1a2016-10-26 23:46:34 +00001342Decl *Expr::getReferencedDeclOfCallee() {
1343 Expr *CEE = IgnoreParenImpCasts();
Fangrui Song6907ce22018-07-30 19:24:48 +00001344
Douglas Gregore0e96302011-09-06 21:41:04 +00001345 while (SubstNonTypeTemplateParmExpr *NTTP
1346 = dyn_cast<SubstNonTypeTemplateParmExpr>(CEE)) {
1347 CEE = NTTP->getReplacement()->IgnoreParenCasts();
1348 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001349
Sebastian Redl2b1832e2010-09-10 20:55:30 +00001350 // If we're calling a dereference, look at the pointer instead.
1351 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CEE)) {
1352 if (BO->isPtrMemOp())
1353 CEE = BO->getRHS()->IgnoreParenCasts();
1354 } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(CEE)) {
1355 if (UO->getOpcode() == UO_Deref)
1356 CEE = UO->getSubExpr()->IgnoreParenCasts();
1357 }
Chris Lattner52301912009-07-17 15:46:27 +00001358 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CEE))
Nuno Lopes518e3702009-12-20 23:11:08 +00001359 return DRE->getDecl();
Nuno Lopesc095b532009-12-24 00:28:18 +00001360 if (MemberExpr *ME = dyn_cast<MemberExpr>(CEE))
1361 return ME->getMemberDecl();
Yaxun Liud83c7402019-02-26 16:20:41 +00001362 if (auto *BE = dyn_cast<BlockExpr>(CEE))
1363 return BE->getBlockDecl();
Zhongxing Xu3c8fa972009-07-17 07:29:51 +00001364
Craig Topper36250ad2014-05-12 05:36:57 +00001365 return nullptr;
Zhongxing Xu3c8fa972009-07-17 07:29:51 +00001366}
1367
Alp Tokera724cff2013-12-28 21:59:02 +00001368/// getBuiltinCallee - If this is a call to a builtin, return the builtin ID. If
Chris Lattner01ff98a2008-10-06 05:00:53 +00001369/// not, return 0.
Alp Tokera724cff2013-12-28 21:59:02 +00001370unsigned CallExpr::getBuiltinCallee() const {
Steve Narofff6e3b3292008-01-31 01:07:12 +00001371 // All simple function calls (e.g. func()) are implicitly cast to pointer to
Mike Stump11289f42009-09-09 15:08:12 +00001372 // function. As a result, we try and obtain the DeclRefExpr from the
Steve Narofff6e3b3292008-01-31 01:07:12 +00001373 // ImplicitCastExpr.
1374 const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(getCallee());
1375 if (!ICE) // FIXME: deal with more complex calls (e.g. (func)(), (*func)()).
Chris Lattner01ff98a2008-10-06 05:00:53 +00001376 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001377
Steve Narofff6e3b3292008-01-31 01:07:12 +00001378 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr());
1379 if (!DRE)
Chris Lattner01ff98a2008-10-06 05:00:53 +00001380 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001381
Anders Carlssonfbcf6762008-01-31 02:13:57 +00001382 const FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
1383 if (!FDecl)
Chris Lattner01ff98a2008-10-06 05:00:53 +00001384 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001385
Douglas Gregor9eb16ea2008-11-21 15:30:19 +00001386 if (!FDecl->getIdentifier())
1387 return 0;
1388
Douglas Gregor15fc9562009-09-12 00:22:50 +00001389 return FDecl->getBuiltinID();
Chris Lattner01ff98a2008-10-06 05:00:53 +00001390}
Anders Carlssonfbcf6762008-01-31 02:13:57 +00001391
Scott Douglass503fc392015-06-10 13:53:15 +00001392bool CallExpr::isUnevaluatedBuiltinCall(const ASTContext &Ctx) const {
Alp Tokera724cff2013-12-28 21:59:02 +00001393 if (unsigned BI = getBuiltinCallee())
Richard Smith5011a002013-01-17 23:46:04 +00001394 return Ctx.BuiltinInfo.isUnevaluated(BI);
1395 return false;
1396}
1397
David Majnemerced8bdf2015-02-25 17:36:15 +00001398QualType CallExpr::getCallReturnType(const ASTContext &Ctx) const {
1399 const Expr *Callee = getCallee();
1400 QualType CalleeType = Callee->getType();
1401 if (const auto *FnTypePtr = CalleeType->getAs<PointerType>()) {
Anders Carlsson00a27592009-05-26 04:57:27 +00001402 CalleeType = FnTypePtr->getPointeeType();
David Majnemerced8bdf2015-02-25 17:36:15 +00001403 } else if (const auto *BPT = CalleeType->getAs<BlockPointerType>()) {
Anders Carlsson00a27592009-05-26 04:57:27 +00001404 CalleeType = BPT->getPointeeType();
David Majnemerced8bdf2015-02-25 17:36:15 +00001405 } else if (CalleeType->isSpecificPlaceholderType(BuiltinType::BoundMember)) {
1406 if (isa<CXXPseudoDestructorExpr>(Callee->IgnoreParens()))
1407 return Ctx.VoidTy;
1408
John McCall0009fcc2011-04-26 20:42:42 +00001409 // This should never be overloaded and so should never return null.
David Majnemerced8bdf2015-02-25 17:36:15 +00001410 CalleeType = Expr::findBoundMemberType(Callee);
1411 }
1412
John McCall0009fcc2011-04-26 20:42:42 +00001413 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00001414 return FnType->getReturnType();
Anders Carlsson00a27592009-05-26 04:57:27 +00001415}
Chris Lattner01ff98a2008-10-06 05:00:53 +00001416
Aaron Ballmand23e9bc2019-01-03 14:24:31 +00001417const Attr *CallExpr::getUnusedResultAttr(const ASTContext &Ctx) const {
1418 // If the return type is a struct, union, or enum that is marked nodiscard,
1419 // then return the return type attribute.
1420 if (const TagDecl *TD = getCallReturnType(Ctx)->getAsTagDecl())
1421 if (const auto *A = TD->getAttr<WarnUnusedResultAttr>())
1422 return A;
1423
1424 // Otherwise, see if the callee is marked nodiscard and return that attribute
1425 // instead.
1426 const Decl *D = getCalleeDecl();
1427 return D ? D->getAttr<WarnUnusedResultAttr>() : nullptr;
1428}
1429
Stephen Kelly724e9e52018-08-09 20:05:03 +00001430SourceLocation CallExpr::getBeginLoc() const {
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001431 if (isa<CXXOperatorCallExpr>(this))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001432 return cast<CXXOperatorCallExpr>(this)->getBeginLoc();
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001433
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001434 SourceLocation begin = getCallee()->getBeginLoc();
Keno Fischer070db172014-08-15 01:39:12 +00001435 if (begin.isInvalid() && getNumArgs() > 0 && getArg(0))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001436 begin = getArg(0)->getBeginLoc();
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001437 return begin;
1438}
Stephen Kelly02a67ba2018-08-09 20:05:47 +00001439SourceLocation CallExpr::getEndLoc() const {
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001440 if (isa<CXXOperatorCallExpr>(this))
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001441 return cast<CXXOperatorCallExpr>(this)->getEndLoc();
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001442
1443 SourceLocation end = getRParenLoc();
Keno Fischer070db172014-08-15 01:39:12 +00001444 if (end.isInvalid() && getNumArgs() > 0 && getArg(getNumArgs() - 1))
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001445 end = getArg(getNumArgs() - 1)->getEndLoc();
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001446 return end;
1447}
John McCall701417a2011-02-21 06:23:05 +00001448
Craig Topper37932912013-08-18 10:09:15 +00001449OffsetOfExpr *OffsetOfExpr::Create(const ASTContext &C, QualType type,
Douglas Gregor882211c2010-04-28 22:16:22 +00001450 SourceLocation OperatorLoc,
Fangrui Song6907ce22018-07-30 19:24:48 +00001451 TypeSourceInfo *tsi,
Benjamin Kramerc215e762012-08-24 11:54:20 +00001452 ArrayRef<OffsetOfNode> comps,
1453 ArrayRef<Expr*> exprs,
Douglas Gregor882211c2010-04-28 22:16:22 +00001454 SourceLocation RParenLoc) {
James Y Knight7281c352015-12-29 22:31:18 +00001455 void *Mem = C.Allocate(
1456 totalSizeToAlloc<OffsetOfNode, Expr *>(comps.size(), exprs.size()));
Douglas Gregor882211c2010-04-28 22:16:22 +00001457
Benjamin Kramerc215e762012-08-24 11:54:20 +00001458 return new (Mem) OffsetOfExpr(C, type, OperatorLoc, tsi, comps, exprs,
1459 RParenLoc);
Douglas Gregor882211c2010-04-28 22:16:22 +00001460}
1461
Craig Topper37932912013-08-18 10:09:15 +00001462OffsetOfExpr *OffsetOfExpr::CreateEmpty(const ASTContext &C,
Douglas Gregor882211c2010-04-28 22:16:22 +00001463 unsigned numComps, unsigned numExprs) {
James Y Knight7281c352015-12-29 22:31:18 +00001464 void *Mem =
1465 C.Allocate(totalSizeToAlloc<OffsetOfNode, Expr *>(numComps, numExprs));
Douglas Gregor882211c2010-04-28 22:16:22 +00001466 return new (Mem) OffsetOfExpr(numComps, numExprs);
1467}
1468
Craig Topper37932912013-08-18 10:09:15 +00001469OffsetOfExpr::OffsetOfExpr(const ASTContext &C, QualType type,
Douglas Gregor882211c2010-04-28 22:16:22 +00001470 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
Benjamin Kramerc215e762012-08-24 11:54:20 +00001471 ArrayRef<OffsetOfNode> comps, ArrayRef<Expr*> exprs,
Douglas Gregor882211c2010-04-28 22:16:22 +00001472 SourceLocation RParenLoc)
John McCall7decc9e2010-11-18 06:31:45 +00001473 : Expr(OffsetOfExprClass, type, VK_RValue, OK_Ordinary,
Fangrui Song6907ce22018-07-30 19:24:48 +00001474 /*TypeDependent=*/false,
Douglas Gregora6e053e2010-12-15 01:34:56 +00001475 /*ValueDependent=*/tsi->getType()->isDependentType(),
Douglas Gregor678d76c2011-07-01 01:22:09 +00001476 tsi->getType()->isInstantiationDependentType(),
Douglas Gregora6e053e2010-12-15 01:34:56 +00001477 tsi->getType()->containsUnexpandedParameterPack()),
Fangrui Song6907ce22018-07-30 19:24:48 +00001478 OperatorLoc(OperatorLoc), RParenLoc(RParenLoc), TSInfo(tsi),
Benjamin Kramerc215e762012-08-24 11:54:20 +00001479 NumComps(comps.size()), NumExprs(exprs.size())
Douglas Gregor882211c2010-04-28 22:16:22 +00001480{
Benjamin Kramerc215e762012-08-24 11:54:20 +00001481 for (unsigned i = 0; i != comps.size(); ++i) {
1482 setComponent(i, comps[i]);
Douglas Gregor882211c2010-04-28 22:16:22 +00001483 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001484
Benjamin Kramerc215e762012-08-24 11:54:20 +00001485 for (unsigned i = 0; i != exprs.size(); ++i) {
1486 if (exprs[i]->isTypeDependent() || exprs[i]->isValueDependent())
Douglas Gregora6e053e2010-12-15 01:34:56 +00001487 ExprBits.ValueDependent = true;
Benjamin Kramerc215e762012-08-24 11:54:20 +00001488 if (exprs[i]->containsUnexpandedParameterPack())
Douglas Gregora6e053e2010-12-15 01:34:56 +00001489 ExprBits.ContainsUnexpandedParameterPack = true;
1490
Benjamin Kramerc215e762012-08-24 11:54:20 +00001491 setIndexExpr(i, exprs[i]);
Douglas Gregor882211c2010-04-28 22:16:22 +00001492 }
1493}
1494
James Y Knight7281c352015-12-29 22:31:18 +00001495IdentifierInfo *OffsetOfNode::getFieldName() const {
Douglas Gregor882211c2010-04-28 22:16:22 +00001496 assert(getKind() == Field || getKind() == Identifier);
1497 if (getKind() == Field)
1498 return getField()->getIdentifier();
Fangrui Song6907ce22018-07-30 19:24:48 +00001499
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001500 return reinterpret_cast<IdentifierInfo *> (Data & ~(uintptr_t)Mask);
Douglas Gregor882211c2010-04-28 22:16:22 +00001501}
1502
David Majnemer10fd83d2015-01-15 10:04:14 +00001503UnaryExprOrTypeTraitExpr::UnaryExprOrTypeTraitExpr(
1504 UnaryExprOrTypeTrait ExprKind, Expr *E, QualType resultType,
1505 SourceLocation op, SourceLocation rp)
1506 : Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_RValue, OK_Ordinary,
1507 false, // Never type-dependent (C++ [temp.dep.expr]p3).
1508 // Value-dependent if the argument is type-dependent.
1509 E->isTypeDependent(), E->isInstantiationDependent(),
1510 E->containsUnexpandedParameterPack()),
1511 OpLoc(op), RParenLoc(rp) {
1512 UnaryExprOrTypeTraitExprBits.Kind = ExprKind;
1513 UnaryExprOrTypeTraitExprBits.IsType = false;
1514 Argument.Ex = E;
1515
1516 // Check to see if we are in the situation where alignof(decl) should be
1517 // dependent because decl's alignment is dependent.
Richard Smith6822bd72018-10-26 19:26:45 +00001518 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
David Majnemer10fd83d2015-01-15 10:04:14 +00001519 if (!isValueDependent() || !isInstantiationDependent()) {
1520 E = E->IgnoreParens();
1521
1522 const ValueDecl *D = nullptr;
1523 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
1524 D = DRE->getDecl();
1525 else if (const auto *ME = dyn_cast<MemberExpr>(E))
1526 D = ME->getMemberDecl();
1527
1528 if (D) {
1529 for (const auto *I : D->specific_attrs<AlignedAttr>()) {
1530 if (I->isAlignmentDependent()) {
1531 setValueDependent(true);
1532 setInstantiationDependent(true);
1533 break;
1534 }
1535 }
1536 }
1537 }
1538 }
1539}
1540
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00001541MemberExpr *MemberExpr::Create(
1542 const ASTContext &C, Expr *base, bool isarrow, SourceLocation OperatorLoc,
1543 NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,
1544 ValueDecl *memberdecl, DeclAccessPair founddecl,
1545 DeclarationNameInfo nameinfo, const TemplateArgumentListInfo *targs,
1546 QualType ty, ExprValueKind vk, ExprObjectKind ok) {
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001547
Douglas Gregorea972d32011-02-28 21:54:11 +00001548 bool hasQualOrFound = (QualifierLoc ||
John McCalla8ae2222010-04-06 21:38:20 +00001549 founddecl.getDecl() != memberdecl ||
1550 founddecl.getAccess() != memberdecl->getAccess());
Mike Stump11289f42009-09-09 15:08:12 +00001551
James Y Knighte7d82282015-12-29 18:15:14 +00001552 bool HasTemplateKWAndArgsInfo = targs || TemplateKWLoc.isValid();
1553 std::size_t Size =
1554 totalSizeToAlloc<MemberExprNameQualifier, ASTTemplateKWAndArgsInfo,
1555 TemplateArgumentLoc>(hasQualOrFound ? 1 : 0,
1556 HasTemplateKWAndArgsInfo ? 1 : 0,
1557 targs ? targs->size() : 0);
Mike Stump11289f42009-09-09 15:08:12 +00001558
Benjamin Kramerc3f89252016-10-20 14:27:22 +00001559 void *Mem = C.Allocate(Size, alignof(MemberExpr));
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00001560 MemberExpr *E = new (Mem)
1561 MemberExpr(base, isarrow, OperatorLoc, memberdecl, nameinfo, ty, vk, ok);
John McCall16df1e52010-03-30 21:47:33 +00001562
1563 if (hasQualOrFound) {
Douglas Gregorea972d32011-02-28 21:54:11 +00001564 // FIXME: Wrong. We should be looking at the member declaration we found.
1565 if (QualifierLoc && QualifierLoc.getNestedNameSpecifier()->isDependent()) {
John McCall16df1e52010-03-30 21:47:33 +00001566 E->setValueDependent(true);
1567 E->setTypeDependent(true);
Douglas Gregor678d76c2011-07-01 01:22:09 +00001568 E->setInstantiationDependent(true);
Fangrui Song6907ce22018-07-30 19:24:48 +00001569 }
1570 else if (QualifierLoc &&
1571 QualifierLoc.getNestedNameSpecifier()->isInstantiationDependent())
Douglas Gregor678d76c2011-07-01 01:22:09 +00001572 E->setInstantiationDependent(true);
Fangrui Song6907ce22018-07-30 19:24:48 +00001573
Bruno Ricci4c742532018-11-15 13:56:22 +00001574 E->MemberExprBits.HasQualifierOrFoundDecl = true;
John McCall16df1e52010-03-30 21:47:33 +00001575
James Y Knighte7d82282015-12-29 18:15:14 +00001576 MemberExprNameQualifier *NQ =
1577 E->getTrailingObjects<MemberExprNameQualifier>();
Douglas Gregorea972d32011-02-28 21:54:11 +00001578 NQ->QualifierLoc = QualifierLoc;
John McCall16df1e52010-03-30 21:47:33 +00001579 NQ->FoundDecl = founddecl;
1580 }
1581
Bruno Ricci4c742532018-11-15 13:56:22 +00001582 E->MemberExprBits.HasTemplateKWAndArgsInfo =
1583 (targs || TemplateKWLoc.isValid());
Abramo Bagnara7945c982012-01-27 09:46:47 +00001584
John McCall16df1e52010-03-30 21:47:33 +00001585 if (targs) {
Douglas Gregor678d76c2011-07-01 01:22:09 +00001586 bool Dependent = false;
1587 bool InstantiationDependent = false;
1588 bool ContainsUnexpandedParameterPack = false;
James Y Knighte7d82282015-12-29 18:15:14 +00001589 E->getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
1590 TemplateKWLoc, *targs, E->getTrailingObjects<TemplateArgumentLoc>(),
1591 Dependent, InstantiationDependent, ContainsUnexpandedParameterPack);
Douglas Gregor678d76c2011-07-01 01:22:09 +00001592 if (InstantiationDependent)
1593 E->setInstantiationDependent(true);
Abramo Bagnara7945c982012-01-27 09:46:47 +00001594 } else if (TemplateKWLoc.isValid()) {
James Y Knighte7d82282015-12-29 18:15:14 +00001595 E->getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
1596 TemplateKWLoc);
John McCall16df1e52010-03-30 21:47:33 +00001597 }
1598
1599 return E;
Douglas Gregorf405d7e2009-08-31 23:41:50 +00001600}
1601
Stephen Kelly724e9e52018-08-09 20:05:03 +00001602SourceLocation MemberExpr::getBeginLoc() const {
Douglas Gregor25b7e052011-03-02 21:06:53 +00001603 if (isImplicitAccess()) {
1604 if (hasQualifier())
Daniel Dunbarb507f272012-03-09 15:39:15 +00001605 return getQualifierLoc().getBeginLoc();
1606 return MemberLoc;
Douglas Gregor25b7e052011-03-02 21:06:53 +00001607 }
Abramo Bagnara7945c982012-01-27 09:46:47 +00001608
Daniel Dunbarb507f272012-03-09 15:39:15 +00001609 // FIXME: We don't want this to happen. Rather, we should be able to
1610 // detect all kinds of implicit accesses more cleanly.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001611 SourceLocation BaseStartLoc = getBase()->getBeginLoc();
Daniel Dunbarb507f272012-03-09 15:39:15 +00001612 if (BaseStartLoc.isValid())
1613 return BaseStartLoc;
1614 return MemberLoc;
1615}
Stephen Kelly02a67ba2018-08-09 20:05:47 +00001616SourceLocation MemberExpr::getEndLoc() const {
Abramo Bagnara9b836fb2012-11-08 13:52:58 +00001617 SourceLocation EndLoc = getMemberNameInfo().getEndLoc();
Daniel Dunbarb507f272012-03-09 15:39:15 +00001618 if (hasExplicitTemplateArgs())
Abramo Bagnara9b836fb2012-11-08 13:52:58 +00001619 EndLoc = getRAngleLoc();
1620 else if (EndLoc.isInvalid())
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001621 EndLoc = getBase()->getEndLoc();
Abramo Bagnara9b836fb2012-11-08 13:52:58 +00001622 return EndLoc;
Douglas Gregor25b7e052011-03-02 21:06:53 +00001623}
1624
Alp Tokerc1086762013-12-07 13:51:35 +00001625bool CastExpr::CastConsistency() const {
John McCall9320b872011-09-09 05:25:32 +00001626 switch (getCastKind()) {
1627 case CK_DerivedToBase:
1628 case CK_UncheckedDerivedToBase:
1629 case CK_DerivedToBaseMemberPointer:
1630 case CK_BaseToDerived:
1631 case CK_BaseToDerivedMemberPointer:
1632 assert(!path_empty() && "Cast kind should have a base path!");
1633 break;
1634
1635 case CK_CPointerToObjCPointerCast:
1636 assert(getType()->isObjCObjectPointerType());
1637 assert(getSubExpr()->getType()->isPointerType());
1638 goto CheckNoBasePath;
1639
1640 case CK_BlockPointerToObjCPointerCast:
1641 assert(getType()->isObjCObjectPointerType());
1642 assert(getSubExpr()->getType()->isBlockPointerType());
1643 goto CheckNoBasePath;
1644
John McCallc62bb392012-02-15 01:22:51 +00001645 case CK_ReinterpretMemberPointer:
1646 assert(getType()->isMemberPointerType());
1647 assert(getSubExpr()->getType()->isMemberPointerType());
1648 goto CheckNoBasePath;
1649
John McCall9320b872011-09-09 05:25:32 +00001650 case CK_BitCast:
1651 // Arbitrary casts to C pointer types count as bitcasts.
1652 // Otherwise, we should only have block and ObjC pointer casts
1653 // here if they stay within the type kind.
1654 if (!getType()->isPointerType()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001655 assert(getType()->isObjCObjectPointerType() ==
John McCall9320b872011-09-09 05:25:32 +00001656 getSubExpr()->getType()->isObjCObjectPointerType());
Fangrui Song6907ce22018-07-30 19:24:48 +00001657 assert(getType()->isBlockPointerType() ==
John McCall9320b872011-09-09 05:25:32 +00001658 getSubExpr()->getType()->isBlockPointerType());
1659 }
1660 goto CheckNoBasePath;
1661
1662 case CK_AnyPointerToBlockPointerCast:
1663 assert(getType()->isBlockPointerType());
1664 assert(getSubExpr()->getType()->isAnyPointerType() &&
1665 !getSubExpr()->getType()->isBlockPointerType());
1666 goto CheckNoBasePath;
1667
Douglas Gregored90df32012-02-22 05:02:47 +00001668 case CK_CopyAndAutoreleaseBlockObject:
1669 assert(getType()->isBlockPointerType());
1670 assert(getSubExpr()->getType()->isBlockPointerType());
1671 goto CheckNoBasePath;
Eli Friedman34866c72012-08-31 00:14:07 +00001672
1673 case CK_FunctionToPointerDecay:
1674 assert(getType()->isPointerType());
1675 assert(getSubExpr()->getType()->isFunctionType());
1676 goto CheckNoBasePath;
1677
Anastasia Stulova04307942018-11-16 16:22:56 +00001678 case CK_AddressSpaceConversion: {
1679 auto Ty = getType();
1680 auto SETy = getSubExpr()->getType();
1681 assert(getValueKindForType(Ty) == Expr::getValueKindForType(SETy));
Anastasia Stulova094c7262019-04-04 10:48:36 +00001682 if (/*isRValue()*/ !Ty->getPointeeType().isNull()) {
Anastasia Stulova04307942018-11-16 16:22:56 +00001683 Ty = Ty->getPointeeType();
Anastasia Stulova04307942018-11-16 16:22:56 +00001684 SETy = SETy->getPointeeType();
Anastasia Stulovad1986d12019-01-14 11:44:22 +00001685 }
Anastasia Stulova04307942018-11-16 16:22:56 +00001686 assert(!Ty.isNull() && !SETy.isNull() &&
1687 Ty.getAddressSpace() != SETy.getAddressSpace());
1688 goto CheckNoBasePath;
1689 }
John McCall9320b872011-09-09 05:25:32 +00001690 // These should not have an inheritance path.
1691 case CK_Dynamic:
1692 case CK_ToUnion:
1693 case CK_ArrayToPointerDecay:
John McCall9320b872011-09-09 05:25:32 +00001694 case CK_NullToMemberPointer:
1695 case CK_NullToPointer:
1696 case CK_ConstructorConversion:
1697 case CK_IntegralToPointer:
1698 case CK_PointerToIntegral:
1699 case CK_ToVoid:
1700 case CK_VectorSplat:
1701 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +00001702 case CK_BooleanToSignedIntegral:
John McCall9320b872011-09-09 05:25:32 +00001703 case CK_IntegralToFloating:
1704 case CK_FloatingToIntegral:
1705 case CK_FloatingCast:
1706 case CK_ObjCObjectLValueCast:
1707 case CK_FloatingRealToComplex:
1708 case CK_FloatingComplexToReal:
1709 case CK_FloatingComplexCast:
1710 case CK_FloatingComplexToIntegralComplex:
1711 case CK_IntegralRealToComplex:
1712 case CK_IntegralComplexToReal:
1713 case CK_IntegralComplexCast:
1714 case CK_IntegralComplexToFloatingComplex:
John McCall2d637d22011-09-10 06:18:15 +00001715 case CK_ARCProduceObject:
1716 case CK_ARCConsumeObject:
1717 case CK_ARCReclaimReturnedObject:
1718 case CK_ARCExtendBlockObject:
Andrew Savonichevb555b762018-10-23 15:19:20 +00001719 case CK_ZeroToOCLOpaqueType:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00001720 case CK_IntToOCLSampler:
Leonard Chan99bda372018-10-15 16:07:02 +00001721 case CK_FixedPointCast:
Leonard Chan8f7caae2019-03-06 00:28:43 +00001722 case CK_FixedPointToIntegral:
1723 case CK_IntegralToFixedPoint:
John McCall9320b872011-09-09 05:25:32 +00001724 assert(!getType()->isBooleanType() && "unheralded conversion to bool");
1725 goto CheckNoBasePath;
1726
1727 case CK_Dependent:
1728 case CK_LValueToRValue:
John McCall9320b872011-09-09 05:25:32 +00001729 case CK_NoOp:
David Chisnallfa35df62012-01-16 17:27:18 +00001730 case CK_AtomicToNonAtomic:
1731 case CK_NonAtomicToAtomic:
John McCall9320b872011-09-09 05:25:32 +00001732 case CK_PointerToBoolean:
1733 case CK_IntegralToBoolean:
1734 case CK_FloatingToBoolean:
1735 case CK_MemberPointerToBoolean:
1736 case CK_FloatingComplexToBoolean:
1737 case CK_IntegralComplexToBoolean:
1738 case CK_LValueBitCast: // -> bool&
1739 case CK_UserDefinedConversion: // operator bool()
Eli Friedman34866c72012-08-31 00:14:07 +00001740 case CK_BuiltinFnToFnPtr:
Leonard Chanb4ba4672018-10-23 17:55:35 +00001741 case CK_FixedPointToBoolean:
John McCall9320b872011-09-09 05:25:32 +00001742 CheckNoBasePath:
1743 assert(path_empty() && "Cast kind should not have a base path!");
1744 break;
1745 }
Alp Tokerc1086762013-12-07 13:51:35 +00001746 return true;
John McCall9320b872011-09-09 05:25:32 +00001747}
1748
Eric Fiselier0683c0e2018-05-07 21:07:10 +00001749const char *CastExpr::getCastKindName(CastKind CK) {
1750 switch (CK) {
Etienne Bergeron5356d962016-05-12 20:58:56 +00001751#define CAST_OPERATION(Name) case CK_##Name: return #Name;
1752#include "clang/AST/OperationKinds.def"
Anders Carlsson496335e2009-09-03 00:59:21 +00001753 }
John McCallc5e62b42010-11-13 09:02:35 +00001754 llvm_unreachable("Unhandled cast kind!");
Anders Carlsson496335e2009-09-03 00:59:21 +00001755}
1756
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001757namespace {
Richard Smith1ef75542018-06-27 20:30:34 +00001758 const Expr *skipImplicitTemporary(const Expr *E) {
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001759 // Skip through reference binding to temporary.
Richard Smith1ef75542018-06-27 20:30:34 +00001760 if (auto *Materialize = dyn_cast<MaterializeTemporaryExpr>(E))
1761 E = Materialize->GetTemporaryExpr();
Stephan Bergmannf31b0dc2017-06-27 08:19:09 +00001762
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001763 // Skip any temporary bindings; they're implicit.
Richard Smith1ef75542018-06-27 20:30:34 +00001764 if (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
1765 E = Binder->getSubExpr();
Stephan Bergmannf31b0dc2017-06-27 08:19:09 +00001766
Richard Smith1ef75542018-06-27 20:30:34 +00001767 return E;
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001768 }
Stephan Bergmannf31b0dc2017-06-27 08:19:09 +00001769}
1770
Douglas Gregord196a582009-12-14 19:27:10 +00001771Expr *CastExpr::getSubExprAsWritten() {
Richard Smith1ef75542018-06-27 20:30:34 +00001772 const Expr *SubExpr = nullptr;
1773 const CastExpr *E = this;
Douglas Gregord196a582009-12-14 19:27:10 +00001774 do {
Stephan Bergmannf31b0dc2017-06-27 08:19:09 +00001775 SubExpr = skipImplicitTemporary(E->getSubExpr());
Douglas Gregorfe314812011-06-21 17:03:29 +00001776
Douglas Gregord196a582009-12-14 19:27:10 +00001777 // Conversions by constructor and conversion functions have a
1778 // subexpression describing the call; strip it off.
John McCalle3027922010-08-25 11:45:40 +00001779 if (E->getCastKind() == CK_ConstructorConversion)
Stephan Bergmannf31b0dc2017-06-27 08:19:09 +00001780 SubExpr =
1781 skipImplicitTemporary(cast<CXXConstructExpr>(SubExpr)->getArg(0));
Manman Ren8abc2e52016-02-02 22:23:03 +00001782 else if (E->getCastKind() == CK_UserDefinedConversion) {
1783 assert((isa<CXXMemberCallExpr>(SubExpr) ||
1784 isa<BlockExpr>(SubExpr)) &&
1785 "Unexpected SubExpr for CK_UserDefinedConversion.");
Richard Smith1ef75542018-06-27 20:30:34 +00001786 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SubExpr))
1787 SubExpr = MCE->getImplicitObjectArgument();
Manman Ren8abc2e52016-02-02 22:23:03 +00001788 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001789
Douglas Gregord196a582009-12-14 19:27:10 +00001790 // If the subexpression we're left with is an implicit cast, look
1791 // through that, too.
Fangrui Song6907ce22018-07-30 19:24:48 +00001792 } while ((E = dyn_cast<ImplicitCastExpr>(SubExpr)));
1793
Richard Smith1ef75542018-06-27 20:30:34 +00001794 return const_cast<Expr*>(SubExpr);
1795}
1796
1797NamedDecl *CastExpr::getConversionFunction() const {
1798 const Expr *SubExpr = nullptr;
1799
1800 for (const CastExpr *E = this; E; E = dyn_cast<ImplicitCastExpr>(SubExpr)) {
1801 SubExpr = skipImplicitTemporary(E->getSubExpr());
1802
1803 if (E->getCastKind() == CK_ConstructorConversion)
1804 return cast<CXXConstructExpr>(SubExpr)->getConstructor();
1805
1806 if (E->getCastKind() == CK_UserDefinedConversion) {
1807 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SubExpr))
1808 return MCE->getMethodDecl();
1809 }
1810 }
1811
1812 return nullptr;
Douglas Gregord196a582009-12-14 19:27:10 +00001813}
1814
John McCallcf142162010-08-07 06:22:56 +00001815CXXBaseSpecifier **CastExpr::path_buffer() {
1816 switch (getStmtClass()) {
1817#define ABSTRACT_STMT(x)
James Y Knight1d75c5e2015-12-30 02:27:28 +00001818#define CASTEXPR(Type, Base) \
1819 case Stmt::Type##Class: \
1820 return static_cast<Type *>(this)->getTrailingObjects<CXXBaseSpecifier *>();
John McCallcf142162010-08-07 06:22:56 +00001821#define STMT(Type, Base)
1822#include "clang/AST/StmtNodes.inc"
1823 default:
1824 llvm_unreachable("non-cast expressions not possible here");
John McCallcf142162010-08-07 06:22:56 +00001825 }
1826}
1827
John McCallf1ef7962017-08-15 21:42:47 +00001828const FieldDecl *CastExpr::getTargetFieldForToUnionCast(QualType unionType,
1829 QualType opType) {
1830 auto RD = unionType->castAs<RecordType>()->getDecl();
1831 return getTargetFieldForToUnionCast(RD, opType);
1832}
1833
1834const FieldDecl *CastExpr::getTargetFieldForToUnionCast(const RecordDecl *RD,
1835 QualType OpType) {
1836 auto &Ctx = RD->getASTContext();
1837 RecordDecl::field_iterator Field, FieldEnd;
1838 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
1839 Field != FieldEnd; ++Field) {
1840 if (Ctx.hasSameUnqualifiedType(Field->getType(), OpType) &&
1841 !Field->isUnnamedBitfield()) {
1842 return *Field;
1843 }
1844 }
1845 return nullptr;
1846}
1847
Craig Topper37932912013-08-18 10:09:15 +00001848ImplicitCastExpr *ImplicitCastExpr::Create(const ASTContext &C, QualType T,
John McCallcf142162010-08-07 06:22:56 +00001849 CastKind Kind, Expr *Operand,
1850 const CXXCastPath *BasePath,
John McCall2536c6d2010-08-25 10:28:54 +00001851 ExprValueKind VK) {
John McCallcf142162010-08-07 06:22:56 +00001852 unsigned PathSize = (BasePath ? BasePath->size() : 0);
Bruno Ricci49391652019-01-09 16:41:33 +00001853 void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
John McCallcf142162010-08-07 06:22:56 +00001854 ImplicitCastExpr *E =
John McCall2536c6d2010-08-25 10:28:54 +00001855 new (Buffer) ImplicitCastExpr(T, Kind, Operand, PathSize, VK);
James Y Knight1d75c5e2015-12-30 02:27:28 +00001856 if (PathSize)
1857 std::uninitialized_copy_n(BasePath->data(), BasePath->size(),
1858 E->getTrailingObjects<CXXBaseSpecifier *>());
John McCallcf142162010-08-07 06:22:56 +00001859 return E;
1860}
1861
Craig Topper37932912013-08-18 10:09:15 +00001862ImplicitCastExpr *ImplicitCastExpr::CreateEmpty(const ASTContext &C,
John McCallcf142162010-08-07 06:22:56 +00001863 unsigned PathSize) {
Bruno Ricci49391652019-01-09 16:41:33 +00001864 void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
John McCallcf142162010-08-07 06:22:56 +00001865 return new (Buffer) ImplicitCastExpr(EmptyShell(), PathSize);
1866}
1867
1868
Craig Topper37932912013-08-18 10:09:15 +00001869CStyleCastExpr *CStyleCastExpr::Create(const ASTContext &C, QualType T,
John McCall7decc9e2010-11-18 06:31:45 +00001870 ExprValueKind VK, CastKind K, Expr *Op,
John McCallcf142162010-08-07 06:22:56 +00001871 const CXXCastPath *BasePath,
1872 TypeSourceInfo *WrittenTy,
1873 SourceLocation L, SourceLocation R) {
1874 unsigned PathSize = (BasePath ? BasePath->size() : 0);
Bruno Ricci49391652019-01-09 16:41:33 +00001875 void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
John McCallcf142162010-08-07 06:22:56 +00001876 CStyleCastExpr *E =
John McCall7decc9e2010-11-18 06:31:45 +00001877 new (Buffer) CStyleCastExpr(T, VK, K, Op, PathSize, WrittenTy, L, R);
James Y Knight1d75c5e2015-12-30 02:27:28 +00001878 if (PathSize)
1879 std::uninitialized_copy_n(BasePath->data(), BasePath->size(),
1880 E->getTrailingObjects<CXXBaseSpecifier *>());
John McCallcf142162010-08-07 06:22:56 +00001881 return E;
1882}
1883
Craig Topper37932912013-08-18 10:09:15 +00001884CStyleCastExpr *CStyleCastExpr::CreateEmpty(const ASTContext &C,
1885 unsigned PathSize) {
Bruno Ricci49391652019-01-09 16:41:33 +00001886 void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
John McCallcf142162010-08-07 06:22:56 +00001887 return new (Buffer) CStyleCastExpr(EmptyShell(), PathSize);
1888}
1889
Chris Lattner1b926492006-08-23 06:42:10 +00001890/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1891/// corresponds to, e.g. "<<=".
David Blaikie1d202a62012-10-08 01:11:04 +00001892StringRef BinaryOperator::getOpcodeStr(Opcode Op) {
Chris Lattner1b926492006-08-23 06:42:10 +00001893 switch (Op) {
Etienne Bergeron5356d962016-05-12 20:58:56 +00001894#define BINARY_OPERATION(Name, Spelling) case BO_##Name: return Spelling;
1895#include "clang/AST/OperationKinds.def"
Chris Lattner1b926492006-08-23 06:42:10 +00001896 }
David Blaikiee4d798f2012-01-20 21:50:17 +00001897 llvm_unreachable("Invalid OpCode!");
Chris Lattner1b926492006-08-23 06:42:10 +00001898}
Steve Naroff47500512007-04-19 23:00:49 +00001899
John McCalle3027922010-08-25 11:45:40 +00001900BinaryOperatorKind
Douglas Gregor1baf54e2009-03-13 18:40:31 +00001901BinaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO) {
1902 switch (OO) {
David Blaikie83d382b2011-09-23 05:06:16 +00001903 default: llvm_unreachable("Not an overloadable binary operator");
John McCalle3027922010-08-25 11:45:40 +00001904 case OO_Plus: return BO_Add;
1905 case OO_Minus: return BO_Sub;
1906 case OO_Star: return BO_Mul;
1907 case OO_Slash: return BO_Div;
1908 case OO_Percent: return BO_Rem;
1909 case OO_Caret: return BO_Xor;
1910 case OO_Amp: return BO_And;
1911 case OO_Pipe: return BO_Or;
1912 case OO_Equal: return BO_Assign;
Richard Smithc70f1d62017-12-14 15:16:18 +00001913 case OO_Spaceship: return BO_Cmp;
John McCalle3027922010-08-25 11:45:40 +00001914 case OO_Less: return BO_LT;
1915 case OO_Greater: return BO_GT;
1916 case OO_PlusEqual: return BO_AddAssign;
1917 case OO_MinusEqual: return BO_SubAssign;
1918 case OO_StarEqual: return BO_MulAssign;
1919 case OO_SlashEqual: return BO_DivAssign;
1920 case OO_PercentEqual: return BO_RemAssign;
1921 case OO_CaretEqual: return BO_XorAssign;
1922 case OO_AmpEqual: return BO_AndAssign;
1923 case OO_PipeEqual: return BO_OrAssign;
1924 case OO_LessLess: return BO_Shl;
1925 case OO_GreaterGreater: return BO_Shr;
1926 case OO_LessLessEqual: return BO_ShlAssign;
1927 case OO_GreaterGreaterEqual: return BO_ShrAssign;
1928 case OO_EqualEqual: return BO_EQ;
1929 case OO_ExclaimEqual: return BO_NE;
1930 case OO_LessEqual: return BO_LE;
1931 case OO_GreaterEqual: return BO_GE;
1932 case OO_AmpAmp: return BO_LAnd;
1933 case OO_PipePipe: return BO_LOr;
1934 case OO_Comma: return BO_Comma;
1935 case OO_ArrowStar: return BO_PtrMemI;
Douglas Gregor1baf54e2009-03-13 18:40:31 +00001936 }
1937}
1938
1939OverloadedOperatorKind BinaryOperator::getOverloadedOperator(Opcode Opc) {
1940 static const OverloadedOperatorKind OverOps[] = {
1941 /* .* Cannot be overloaded */OO_None, OO_ArrowStar,
1942 OO_Star, OO_Slash, OO_Percent,
1943 OO_Plus, OO_Minus,
1944 OO_LessLess, OO_GreaterGreater,
Richard Smithc70f1d62017-12-14 15:16:18 +00001945 OO_Spaceship,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00001946 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
1947 OO_EqualEqual, OO_ExclaimEqual,
1948 OO_Amp,
1949 OO_Caret,
1950 OO_Pipe,
1951 OO_AmpAmp,
1952 OO_PipePipe,
1953 OO_Equal, OO_StarEqual,
1954 OO_SlashEqual, OO_PercentEqual,
1955 OO_PlusEqual, OO_MinusEqual,
1956 OO_LessLessEqual, OO_GreaterGreaterEqual,
1957 OO_AmpEqual, OO_CaretEqual,
1958 OO_PipeEqual,
1959 OO_Comma
1960 };
1961 return OverOps[Opc];
1962}
1963
Andrew Kaylor3d0a5402017-09-19 20:26:40 +00001964bool BinaryOperator::isNullPointerArithmeticExtension(ASTContext &Ctx,
1965 Opcode Opc,
1966 Expr *LHS, Expr *RHS) {
1967 if (Opc != BO_Add)
1968 return false;
1969
1970 // Check that we have one pointer and one integer operand.
1971 Expr *PExp;
Andrew Kaylor3d0a5402017-09-19 20:26:40 +00001972 if (LHS->getType()->isPointerType()) {
1973 if (!RHS->getType()->isIntegerType())
1974 return false;
1975 PExp = LHS;
Andrew Kaylor3d0a5402017-09-19 20:26:40 +00001976 } else if (RHS->getType()->isPointerType()) {
1977 if (!LHS->getType()->isIntegerType())
1978 return false;
1979 PExp = RHS;
Andrew Kaylor3d0a5402017-09-19 20:26:40 +00001980 } else {
1981 return false;
1982 }
1983
1984 // Check that the pointer is a nullptr.
1985 if (!PExp->IgnoreParenCasts()
1986 ->isNullPointerConstant(Ctx, Expr::NPC_ValueDependentIsNotNull))
1987 return false;
1988
1989 // Check that the pointee type is char-sized.
1990 const PointerType *PTy = PExp->getType()->getAs<PointerType>();
1991 if (!PTy || !PTy->getPointeeType()->isCharType())
1992 return false;
1993
Andrew Kaylor3d0a5402017-09-19 20:26:40 +00001994 return true;
1995}
Eric Fiselier708afb52019-05-16 21:04:15 +00001996
1997static QualType getDecayedSourceLocExprType(const ASTContext &Ctx,
1998 SourceLocExpr::IdentKind Kind) {
1999 switch (Kind) {
2000 case SourceLocExpr::File:
2001 case SourceLocExpr::Function: {
2002 QualType ArrTy = Ctx.getStringLiteralArrayType(Ctx.CharTy, 0);
2003 return Ctx.getPointerType(ArrTy->getAsArrayTypeUnsafe()->getElementType());
2004 }
2005 case SourceLocExpr::Line:
2006 case SourceLocExpr::Column:
2007 return Ctx.UnsignedIntTy;
2008 }
2009 llvm_unreachable("unhandled case");
2010}
2011
2012SourceLocExpr::SourceLocExpr(const ASTContext &Ctx, IdentKind Kind,
2013 SourceLocation BLoc, SourceLocation RParenLoc,
2014 DeclContext *ParentContext)
2015 : Expr(SourceLocExprClass, getDecayedSourceLocExprType(Ctx, Kind),
2016 VK_RValue, OK_Ordinary, false, false, false, false),
2017 BuiltinLoc(BLoc), RParenLoc(RParenLoc), ParentContext(ParentContext) {
2018 SourceLocExprBits.Kind = Kind;
2019}
2020
2021StringRef SourceLocExpr::getBuiltinStr() const {
2022 switch (getIdentKind()) {
2023 case File:
2024 return "__builtin_FILE";
2025 case Function:
2026 return "__builtin_FUNCTION";
2027 case Line:
2028 return "__builtin_LINE";
2029 case Column:
2030 return "__builtin_COLUMN";
2031 }
2032 llvm_unreachable("unexpected IdentKind!");
2033}
2034
2035APValue SourceLocExpr::EvaluateInContext(const ASTContext &Ctx,
2036 const Expr *DefaultExpr) const {
2037 SourceLocation Loc;
2038 const DeclContext *Context;
2039
2040 std::tie(Loc,
2041 Context) = [&]() -> std::pair<SourceLocation, const DeclContext *> {
2042 if (auto *DIE = dyn_cast_or_null<CXXDefaultInitExpr>(DefaultExpr))
2043 return {DIE->getUsedLocation(), DIE->getUsedContext()};
2044 if (auto *DAE = dyn_cast_or_null<CXXDefaultArgExpr>(DefaultExpr))
2045 return {DAE->getUsedLocation(), DAE->getUsedContext()};
2046 return {this->getLocation(), this->getParentContext()};
2047 }();
2048
2049 PresumedLoc PLoc = Ctx.getSourceManager().getPresumedLoc(
2050 Ctx.getSourceManager().getExpansionRange(Loc).getEnd());
2051
2052 auto MakeStringLiteral = [&](StringRef Tmp) {
2053 using LValuePathEntry = APValue::LValuePathEntry;
2054 StringLiteral *Res = Ctx.getPredefinedStringLiteralFromCache(Tmp);
2055 // Decay the string to a pointer to the first character.
2056 LValuePathEntry Path[1] = {LValuePathEntry::ArrayIndex(0)};
2057 return APValue(Res, CharUnits::Zero(), Path, /*OnePastTheEnd=*/false);
2058 };
2059
2060 switch (getIdentKind()) {
2061 case SourceLocExpr::File:
2062 return MakeStringLiteral(PLoc.getFilename());
2063 case SourceLocExpr::Function: {
2064 const Decl *CurDecl = dyn_cast_or_null<Decl>(Context);
2065 return MakeStringLiteral(
2066 CurDecl ? PredefinedExpr::ComputeName(PredefinedExpr::Function, CurDecl)
2067 : std::string(""));
2068 }
2069 case SourceLocExpr::Line:
2070 case SourceLocExpr::Column: {
2071 llvm::APSInt IntVal(Ctx.getIntWidth(Ctx.UnsignedIntTy),
2072 /*IsUnsigned=*/true);
2073 IntVal = getIdentKind() == SourceLocExpr::Line ? PLoc.getLine()
2074 : PLoc.getColumn();
2075 return APValue(IntVal);
2076 }
2077 }
2078 llvm_unreachable("unhandled case");
2079}
2080
Craig Topper37932912013-08-18 10:09:15 +00002081InitListExpr::InitListExpr(const ASTContext &C, SourceLocation lbraceloc,
Benjamin Kramerc215e762012-08-24 11:54:20 +00002082 ArrayRef<Expr*> initExprs, SourceLocation rbraceloc)
Eugene Zelenkoae304b02017-11-17 18:09:48 +00002083 : Expr(InitListExprClass, QualType(), VK_RValue, OK_Ordinary, false, false,
2084 false, false),
2085 InitExprs(C, initExprs.size()),
2086 LBraceLoc(lbraceloc), RBraceLoc(rbraceloc), AltForm(nullptr, true)
2087{
Sebastian Redlc83ed822012-02-17 08:42:25 +00002088 sawArrayRangeDesignator(false);
Benjamin Kramerc215e762012-08-24 11:54:20 +00002089 for (unsigned I = 0; I != initExprs.size(); ++I) {
Ted Kremenek013041e2010-02-19 01:50:18 +00002090 if (initExprs[I]->isTypeDependent())
John McCall925b16622010-10-26 08:39:16 +00002091 ExprBits.TypeDependent = true;
Ted Kremenek013041e2010-02-19 01:50:18 +00002092 if (initExprs[I]->isValueDependent())
John McCall925b16622010-10-26 08:39:16 +00002093 ExprBits.ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +00002094 if (initExprs[I]->isInstantiationDependent())
2095 ExprBits.InstantiationDependent = true;
Douglas Gregora6e053e2010-12-15 01:34:56 +00002096 if (initExprs[I]->containsUnexpandedParameterPack())
2097 ExprBits.ContainsUnexpandedParameterPack = true;
Douglas Gregordeebf6e2009-11-19 23:25:22 +00002098 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002099
Benjamin Kramerc215e762012-08-24 11:54:20 +00002100 InitExprs.insert(C, InitExprs.end(), initExprs.begin(), initExprs.end());
Anders Carlsson4692db02007-08-31 04:56:16 +00002101}
Chris Lattner1ec5f562007-06-27 05:38:08 +00002102
Craig Topper37932912013-08-18 10:09:15 +00002103void InitListExpr::reserveInits(const ASTContext &C, unsigned NumInits) {
Ted Kremenek013041e2010-02-19 01:50:18 +00002104 if (NumInits > InitExprs.size())
Ted Kremenekac034612010-04-13 23:39:13 +00002105 InitExprs.reserve(C, NumInits);
Douglas Gregor6d00c992009-03-20 23:58:33 +00002106}
2107
Craig Topper37932912013-08-18 10:09:15 +00002108void InitListExpr::resizeInits(const ASTContext &C, unsigned NumInits) {
Craig Topper36250ad2014-05-12 05:36:57 +00002109 InitExprs.resize(C, NumInits, nullptr);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002110}
2111
Craig Topper37932912013-08-18 10:09:15 +00002112Expr *InitListExpr::updateInit(const ASTContext &C, unsigned Init, Expr *expr) {
Ted Kremenek013041e2010-02-19 01:50:18 +00002113 if (Init >= InitExprs.size()) {
Craig Topper36250ad2014-05-12 05:36:57 +00002114 InitExprs.insert(C, InitExprs.end(), Init - InitExprs.size() + 1, nullptr);
Richard Smithc275da62013-12-06 01:27:24 +00002115 setInit(Init, expr);
Craig Topper36250ad2014-05-12 05:36:57 +00002116 return nullptr;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002117 }
Mike Stump11289f42009-09-09 15:08:12 +00002118
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002119 Expr *Result = cast_or_null<Expr>(InitExprs[Init]);
Richard Smithc275da62013-12-06 01:27:24 +00002120 setInit(Init, expr);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002121 return Result;
2122}
2123
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +00002124void InitListExpr::setArrayFiller(Expr *filler) {
Argyrios Kyrtzidisd4590a5d2011-10-21 23:02:22 +00002125 assert(!hasArrayFiller() && "Filler already set!");
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +00002126 ArrayFillerOrUnionFieldInit = filler;
2127 // Fill out any "holes" in the array due to designated initializers.
2128 Expr **inits = getInits();
2129 for (unsigned i = 0, e = getNumInits(); i != e; ++i)
Craig Topper36250ad2014-05-12 05:36:57 +00002130 if (inits[i] == nullptr)
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +00002131 inits[i] = filler;
2132}
2133
Richard Smith9ec1e482012-04-15 02:50:59 +00002134bool InitListExpr::isStringLiteralInit() const {
2135 if (getNumInits() != 1)
2136 return false;
Eli Friedmancf4ab082012-08-20 20:55:45 +00002137 const ArrayType *AT = getType()->getAsArrayTypeUnsafe();
2138 if (!AT || !AT->getElementType()->isIntegerType())
Richard Smith9ec1e482012-04-15 02:50:59 +00002139 return false;
Ted Kremenek256bd962014-01-19 06:31:34 +00002140 // It is possible for getInit() to return null.
2141 const Expr *Init = getInit(0);
2142 if (!Init)
2143 return false;
2144 Init = Init->IgnoreParens();
Richard Smith9ec1e482012-04-15 02:50:59 +00002145 return isa<StringLiteral>(Init) || isa<ObjCEncodeExpr>(Init);
2146}
2147
Richard Smith122f88d2016-12-06 23:52:28 +00002148bool InitListExpr::isTransparent() const {
2149 assert(isSemanticForm() && "syntactic form never semantically transparent");
2150
2151 // A glvalue InitListExpr is always just sugar.
2152 if (isGLValue()) {
2153 assert(getNumInits() == 1 && "multiple inits in glvalue init list");
2154 return true;
2155 }
2156
2157 // Otherwise, we're sugar if and only if we have exactly one initializer that
2158 // is of the same type.
2159 if (getNumInits() != 1 || !getInit(0))
2160 return false;
2161
Richard Smith382bc512017-02-23 22:41:47 +00002162 // Don't confuse aggregate initialization of a struct X { X &x; }; with a
2163 // transparent struct copy.
2164 if (!getInit(0)->isRValue() && getType()->isRecordType())
2165 return false;
2166
Richard Smith122f88d2016-12-06 23:52:28 +00002167 return getType().getCanonicalType() ==
2168 getInit(0)->getType().getCanonicalType();
2169}
2170
Daniel Marjamaki817a3bf2017-09-29 09:44:41 +00002171bool InitListExpr::isIdiomaticZeroInitializer(const LangOptions &LangOpts) const {
2172 assert(isSyntacticForm() && "only test syntactic form as zero initializer");
2173
2174 if (LangOpts.CPlusPlus || getNumInits() != 1) {
2175 return false;
2176 }
2177
2178 const IntegerLiteral *Lit = dyn_cast<IntegerLiteral>(getInit(0));
2179 return Lit && Lit->getValue() == 0;
2180}
2181
Stephen Kelly724e9e52018-08-09 20:05:03 +00002182SourceLocation InitListExpr::getBeginLoc() const {
Abramo Bagnara8d16bd42012-11-08 18:41:43 +00002183 if (InitListExpr *SyntacticForm = getSyntacticForm())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002184 return SyntacticForm->getBeginLoc();
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002185 SourceLocation Beg = LBraceLoc;
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002186 if (Beg.isInvalid()) {
2187 // Find the first non-null initializer.
2188 for (InitExprsTy::const_iterator I = InitExprs.begin(),
Fangrui Song6907ce22018-07-30 19:24:48 +00002189 E = InitExprs.end();
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002190 I != E; ++I) {
2191 if (Stmt *S = *I) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002192 Beg = S->getBeginLoc();
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002193 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00002194 }
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002195 }
2196 }
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002197 return Beg;
2198}
2199
Stephen Kelly02a67ba2018-08-09 20:05:47 +00002200SourceLocation InitListExpr::getEndLoc() const {
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002201 if (InitListExpr *SyntacticForm = getSyntacticForm())
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002202 return SyntacticForm->getEndLoc();
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002203 SourceLocation End = RBraceLoc;
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002204 if (End.isInvalid()) {
2205 // Find the first non-null initializer from the end.
2206 for (InitExprsTy::const_reverse_iterator I = InitExprs.rbegin(),
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002207 E = InitExprs.rend();
2208 I != E; ++I) {
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002209 if (Stmt *S = *I) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002210 End = S->getEndLoc();
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002211 break;
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002212 }
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002213 }
2214 }
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002215 return End;
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002216}
2217
Steve Naroff991e99d2008-09-04 15:31:07 +00002218/// getFunctionType - Return the underlying function type for this block.
Eugene Zelenkoae304b02017-11-17 18:09:48 +00002219///
John McCallc833dea2012-02-17 03:32:35 +00002220const FunctionProtoType *BlockExpr::getFunctionType() const {
2221 // The block pointer is never sugared, but the function type might be.
2222 return cast<BlockPointerType>(getType())
2223 ->getPointeeType()->castAs<FunctionProtoType>();
Steve Naroffc540d662008-09-03 18:15:37 +00002224}
2225
Mike Stump11289f42009-09-09 15:08:12 +00002226SourceLocation BlockExpr::getCaretLocation() const {
2227 return TheBlock->getCaretLocation();
Steve Naroff415d3d52008-10-08 17:01:13 +00002228}
Mike Stump11289f42009-09-09 15:08:12 +00002229const Stmt *BlockExpr::getBody() const {
Douglas Gregore3dcb2d2009-04-18 00:02:19 +00002230 return TheBlock->getBody();
2231}
Mike Stump11289f42009-09-09 15:08:12 +00002232Stmt *BlockExpr::getBody() {
2233 return TheBlock->getBody();
Douglas Gregore3dcb2d2009-04-18 00:02:19 +00002234}
Steve Naroff415d3d52008-10-08 17:01:13 +00002235
Eugene Zelenkoae304b02017-11-17 18:09:48 +00002236
Chris Lattner1ec5f562007-06-27 05:38:08 +00002237//===----------------------------------------------------------------------===//
2238// Generic Expression Routines
2239//===----------------------------------------------------------------------===//
2240
Chris Lattner237f2752009-02-14 07:37:35 +00002241/// isUnusedResultAWarning - Return true if this immediate expression should
2242/// be warned about if the result is unused. If so, fill in Loc and Ranges
2243/// with location to warn on and the source range[s] to report with the
2244/// warning.
Fangrui Song6907ce22018-07-30 19:24:48 +00002245bool Expr::isUnusedResultAWarning(const Expr *&WarnE, SourceLocation &Loc,
Eli Friedmanc11535c2012-05-24 00:47:05 +00002246 SourceRange &R1, SourceRange &R2,
2247 ASTContext &Ctx) const {
Anders Carlsson789e2cc2009-05-15 23:10:19 +00002248 // Don't warn if the expr is type dependent. The type could end up
2249 // instantiating to void.
2250 if (isTypeDependent())
2251 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002252
Chris Lattner1ec5f562007-06-27 05:38:08 +00002253 switch (getStmtClass()) {
2254 default:
John McCallc493a732010-03-12 07:11:26 +00002255 if (getType()->isVoidType())
2256 return false;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002257 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002258 Loc = getExprLoc();
2259 R1 = getSourceRange();
2260 return true;
Chris Lattner1ec5f562007-06-27 05:38:08 +00002261 case ParenExprClass:
Chris Lattner237f2752009-02-14 07:37:35 +00002262 return cast<ParenExpr>(this)->getSubExpr()->
Eli Friedmanc11535c2012-05-24 00:47:05 +00002263 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00002264 case GenericSelectionExprClass:
2265 return cast<GenericSelectionExpr>(this)->getResultExpr()->
Eli Friedmanc11535c2012-05-24 00:47:05 +00002266 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Eric Fiselier16269a82018-03-27 00:58:16 +00002267 case CoawaitExprClass:
Eric Fiselier855c0922018-03-27 03:33:06 +00002268 case CoyieldExprClass:
2269 return cast<CoroutineSuspendExpr>(this)->getResumeExpr()->
Eric Fiselier16269a82018-03-27 00:58:16 +00002270 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Eli Friedman75807f22013-07-20 00:40:58 +00002271 case ChooseExprClass:
2272 return cast<ChooseExpr>(this)->getChosenSubExpr()->
2273 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Chris Lattner1ec5f562007-06-27 05:38:08 +00002274 case UnaryOperatorClass: {
2275 const UnaryOperator *UO = cast<UnaryOperator>(this);
Mike Stump11289f42009-09-09 15:08:12 +00002276
Chris Lattner1ec5f562007-06-27 05:38:08 +00002277 switch (UO->getOpcode()) {
Eli Friedmanc11535c2012-05-24 00:47:05 +00002278 case UO_Plus:
2279 case UO_Minus:
2280 case UO_AddrOf:
2281 case UO_Not:
2282 case UO_LNot:
2283 case UO_Deref:
2284 break;
Richard Smith9f690bd2015-10-27 06:02:45 +00002285 case UO_Coawait:
2286 // This is just the 'operator co_await' call inside the guts of a
2287 // dependent co_await call.
John McCalle3027922010-08-25 11:45:40 +00002288 case UO_PostInc:
2289 case UO_PostDec:
2290 case UO_PreInc:
2291 case UO_PreDec: // ++/--
Chris Lattner237f2752009-02-14 07:37:35 +00002292 return false; // Not a warning.
John McCalle3027922010-08-25 11:45:40 +00002293 case UO_Real:
2294 case UO_Imag:
Chris Lattnera44d1162007-06-27 05:58:59 +00002295 // accessing a piece of a volatile complex is a side-effect.
Mike Stump53f9ded2009-11-03 23:25:48 +00002296 if (Ctx.getCanonicalType(UO->getSubExpr()->getType())
2297 .isVolatileQualified())
Chris Lattner237f2752009-02-14 07:37:35 +00002298 return false;
2299 break;
John McCalle3027922010-08-25 11:45:40 +00002300 case UO_Extension:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002301 return UO->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Chris Lattner1ec5f562007-06-27 05:38:08 +00002302 }
Eli Friedmanc11535c2012-05-24 00:47:05 +00002303 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002304 Loc = UO->getOperatorLoc();
2305 R1 = UO->getSubExpr()->getSourceRange();
2306 return true;
Chris Lattner1ec5f562007-06-27 05:38:08 +00002307 }
Chris Lattnerae7a8342007-12-01 06:07:34 +00002308 case BinaryOperatorClass: {
Chris Lattner237f2752009-02-14 07:37:35 +00002309 const BinaryOperator *BO = cast<BinaryOperator>(this);
Ted Kremenek43a9c962010-04-07 18:49:21 +00002310 switch (BO->getOpcode()) {
2311 default:
2312 break;
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00002313 // Consider the RHS of comma for side effects. LHS was checked by
2314 // Sema::CheckCommaOperands.
John McCalle3027922010-08-25 11:45:40 +00002315 case BO_Comma:
Ted Kremenek43a9c962010-04-07 18:49:21 +00002316 // ((foo = <blah>), 0) is an idiom for hiding the result (and
2317 // lvalue-ness) of an assignment written in a macro.
2318 if (IntegerLiteral *IE =
2319 dyn_cast<IntegerLiteral>(BO->getRHS()->IgnoreParens()))
2320 if (IE->getValue() == 0)
2321 return false;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002322 return BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00002323 // Consider '||', '&&' to have side effects if the LHS or RHS does.
John McCalle3027922010-08-25 11:45:40 +00002324 case BO_LAnd:
2325 case BO_LOr:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002326 if (!BO->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx) ||
2327 !BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx))
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00002328 return false;
2329 break;
John McCall1e3715a2010-02-16 04:10:53 +00002330 }
Chris Lattner237f2752009-02-14 07:37:35 +00002331 if (BO->isAssignmentOp())
2332 return false;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002333 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002334 Loc = BO->getOperatorLoc();
2335 R1 = BO->getLHS()->getSourceRange();
2336 R2 = BO->getRHS()->getSourceRange();
2337 return true;
Chris Lattnerae7a8342007-12-01 06:07:34 +00002338 }
Chris Lattner86928112007-08-25 02:00:02 +00002339 case CompoundAssignOperatorClass:
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00002340 case VAArgExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002341 case AtomicExprClass:
Chris Lattner237f2752009-02-14 07:37:35 +00002342 return false;
Chris Lattner1ec5f562007-06-27 05:38:08 +00002343
Fariborz Jahanian9fac54d2007-12-01 19:58:28 +00002344 case ConditionalOperatorClass: {
Ted Kremeneke96dad92011-03-01 20:34:48 +00002345 // If only one of the LHS or RHS is a warning, the operator might
2346 // be being used for control flow. Only warn if both the LHS and
2347 // RHS are warnings.
Fariborz Jahanian9fac54d2007-12-01 19:58:28 +00002348 const ConditionalOperator *Exp = cast<ConditionalOperator>(this);
Eli Friedmanc11535c2012-05-24 00:47:05 +00002349 if (!Exp->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx))
Ted Kremeneke96dad92011-03-01 20:34:48 +00002350 return false;
2351 if (!Exp->getLHS())
Chris Lattner237f2752009-02-14 07:37:35 +00002352 return true;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002353 return Exp->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Fariborz Jahanian9fac54d2007-12-01 19:58:28 +00002354 }
2355
Chris Lattnera44d1162007-06-27 05:58:59 +00002356 case MemberExprClass:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002357 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002358 Loc = cast<MemberExpr>(this)->getMemberLoc();
2359 R1 = SourceRange(Loc, Loc);
2360 R2 = cast<MemberExpr>(this)->getBase()->getSourceRange();
2361 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002362
Chris Lattner1ec5f562007-06-27 05:38:08 +00002363 case ArraySubscriptExprClass:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002364 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002365 Loc = cast<ArraySubscriptExpr>(this)->getRBracketLoc();
2366 R1 = cast<ArraySubscriptExpr>(this)->getLHS()->getSourceRange();
2367 R2 = cast<ArraySubscriptExpr>(this)->getRHS()->getSourceRange();
2368 return true;
Eli Friedman824f8c12008-05-27 15:24:04 +00002369
Chandler Carruth46339472011-08-17 09:49:44 +00002370 case CXXOperatorCallExprClass: {
Richard Trieu99e1c952014-03-11 03:11:08 +00002371 // Warn about operator ==,!=,<,>,<=, and >= even when user-defined operator
Chandler Carruth46339472011-08-17 09:49:44 +00002372 // overloads as there is no reasonable way to define these such that they
2373 // have non-trivial, desirable side-effects. See the -Wunused-comparison
Richard Trieu99e1c952014-03-11 03:11:08 +00002374 // warning: operators == and != are commonly typo'ed, and so warning on them
Chandler Carruth46339472011-08-17 09:49:44 +00002375 // provides additional value as well. If this list is updated,
2376 // DiagnoseUnusedComparison should be as well.
2377 const CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(this);
Richard Trieu99e1c952014-03-11 03:11:08 +00002378 switch (Op->getOperator()) {
2379 default:
2380 break;
2381 case OO_EqualEqual:
2382 case OO_ExclaimEqual:
2383 case OO_Less:
2384 case OO_Greater:
2385 case OO_GreaterEqual:
2386 case OO_LessEqual:
David Majnemerced8bdf2015-02-25 17:36:15 +00002387 if (Op->getCallReturnType(Ctx)->isReferenceType() ||
2388 Op->getCallReturnType(Ctx)->isVoidType())
Richard Trieu161132b2014-05-14 23:22:10 +00002389 break;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002390 WarnE = this;
Matt Beaumont-Gaydcaacaa2011-09-19 18:51:20 +00002391 Loc = Op->getOperatorLoc();
2392 R1 = Op->getSourceRange();
Chandler Carruth46339472011-08-17 09:49:44 +00002393 return true;
Matt Beaumont-Gaydcaacaa2011-09-19 18:51:20 +00002394 }
Chandler Carruth46339472011-08-17 09:49:44 +00002395
2396 // Fallthrough for generic call handling.
Galina Kistanovaf87496d2017-06-03 06:31:42 +00002397 LLVM_FALLTHROUGH;
Chandler Carruth46339472011-08-17 09:49:44 +00002398 }
Chris Lattner1ec5f562007-06-27 05:38:08 +00002399 case CallExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00002400 case CXXMemberCallExprClass:
2401 case UserDefinedLiteralClass: {
Chris Lattner237f2752009-02-14 07:37:35 +00002402 // If this is a direct call, get the callee.
2403 const CallExpr *CE = cast<CallExpr>(this);
Nuno Lopes518e3702009-12-20 23:11:08 +00002404 if (const Decl *FD = CE->getCalleeDecl()) {
Chris Lattner237f2752009-02-14 07:37:35 +00002405 // If the callee has attribute pure, const, or warn_unused_result, warn
2406 // about it. void foo() { strlen("bar"); } should warn.
Chris Lattner1a6babf2009-10-13 04:53:48 +00002407 //
2408 // Note: If new cases are added here, DiagnoseUnusedExprResult should be
2409 // updated to match for QoI.
Aaron Ballmand23e9bc2019-01-03 14:24:31 +00002410 if (CE->hasUnusedResultAttr(Ctx) ||
Aaron Ballman9ead1242013-12-19 02:39:40 +00002411 FD->hasAttr<PureAttr>() || FD->hasAttr<ConstAttr>()) {
Eli Friedmanc11535c2012-05-24 00:47:05 +00002412 WarnE = this;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002413 Loc = CE->getCallee()->getBeginLoc();
Chris Lattner1a6babf2009-10-13 04:53:48 +00002414 R1 = CE->getCallee()->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002415
Chris Lattner1a6babf2009-10-13 04:53:48 +00002416 if (unsigned NumArgs = CE->getNumArgs())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002417 R2 = SourceRange(CE->getArg(0)->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002418 CE->getArg(NumArgs - 1)->getEndLoc());
Chris Lattner1a6babf2009-10-13 04:53:48 +00002419 return true;
2420 }
Chris Lattner237f2752009-02-14 07:37:35 +00002421 }
2422 return false;
2423 }
Anders Carlsson6aa50392009-11-17 17:11:23 +00002424
Matt Beaumont-Gayabf836c2012-10-23 06:15:26 +00002425 // If we don't know precisely what we're looking at, let's not warn.
2426 case UnresolvedLookupExprClass:
2427 case CXXUnresolvedConstructExprClass:
2428 return false;
2429
Anders Carlsson6aa50392009-11-17 17:11:23 +00002430 case CXXTemporaryObjectExprClass:
Eugene Zelenkoae304b02017-11-17 18:09:48 +00002431 case CXXConstructExprClass: {
Lubos Lunak1f490f32013-07-21 13:15:58 +00002432 if (const CXXRecordDecl *Type = getType()->getAsCXXRecordDecl()) {
2433 if (Type->hasAttr<WarnUnusedAttr>()) {
2434 WarnE = this;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002435 Loc = getBeginLoc();
Lubos Lunak1f490f32013-07-21 13:15:58 +00002436 R1 = getSourceRange();
2437 return true;
2438 }
2439 }
Anders Carlsson6aa50392009-11-17 17:11:23 +00002440 return false;
Eugene Zelenkoae304b02017-11-17 18:09:48 +00002441 }
Anders Carlsson6aa50392009-11-17 17:11:23 +00002442
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +00002443 case ObjCMessageExprClass: {
2444 const ObjCMessageExpr *ME = cast<ObjCMessageExpr>(this);
David Blaikiebbafb8a2012-03-11 07:00:24 +00002445 if (Ctx.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00002446 ME->isInstanceMessage() &&
2447 !ME->getType()->isVoidType() &&
Jean-Daniel Dupas06028a52013-07-19 20:25:56 +00002448 ME->getMethodFamily() == OMF_init) {
Eli Friedmanc11535c2012-05-24 00:47:05 +00002449 WarnE = this;
John McCall31168b02011-06-15 23:02:42 +00002450 Loc = getExprLoc();
2451 R1 = ME->getSourceRange();
2452 return true;
2453 }
2454
Fariborz Jahanianac6b4ef2014-07-18 22:59:10 +00002455 if (const ObjCMethodDecl *MD = ME->getMethodDecl())
Fariborz Jahanianb0553e22015-02-16 23:49:44 +00002456 if (MD->hasAttr<WarnUnusedResultAttr>()) {
Fariborz Jahanianac6b4ef2014-07-18 22:59:10 +00002457 WarnE = this;
2458 Loc = getExprLoc();
2459 return true;
2460 }
2461
Chris Lattner237f2752009-02-14 07:37:35 +00002462 return false;
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +00002463 }
Mike Stump11289f42009-09-09 15:08:12 +00002464
John McCallb7bd14f2010-12-02 01:19:52 +00002465 case ObjCPropertyRefExprClass:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002466 WarnE = this;
Chris Lattnerd37f61c2009-08-16 16:51:50 +00002467 Loc = getExprLoc();
2468 R1 = getSourceRange();
Chris Lattnerd8b800a2009-08-16 16:45:18 +00002469 return true;
John McCallb7bd14f2010-12-02 01:19:52 +00002470
John McCallfe96e0b2011-11-06 09:01:30 +00002471 case PseudoObjectExprClass: {
2472 const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this);
2473
2474 // Only complain about things that have the form of a getter.
2475 if (isa<UnaryOperator>(PO->getSyntacticForm()) ||
2476 isa<BinaryOperator>(PO->getSyntacticForm()))
2477 return false;
2478
Eli Friedmanc11535c2012-05-24 00:47:05 +00002479 WarnE = this;
John McCallfe96e0b2011-11-06 09:01:30 +00002480 Loc = getExprLoc();
2481 R1 = getSourceRange();
2482 return true;
2483 }
2484
Chris Lattner944d3062008-07-26 19:51:01 +00002485 case StmtExprClass: {
2486 // Statement exprs don't logically have side effects themselves, but are
2487 // sometimes used in macros in ways that give them a type that is unused.
2488 // For example ({ blah; foo(); }) will end up with a type if foo has a type.
2489 // however, if the result of the stmt expr is dead, we don't want to emit a
2490 // warning.
2491 const CompoundStmt *CS = cast<StmtExpr>(this)->getSubStmt();
Argyrios Kyrtzidis90963412010-09-19 21:21:10 +00002492 if (!CS->body_empty()) {
Chris Lattner944d3062008-07-26 19:51:01 +00002493 if (const Expr *E = dyn_cast<Expr>(CS->body_back()))
Eli Friedmanc11535c2012-05-24 00:47:05 +00002494 return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Argyrios Kyrtzidis90963412010-09-19 21:21:10 +00002495 if (const LabelStmt *Label = dyn_cast<LabelStmt>(CS->body_back()))
2496 if (const Expr *E = dyn_cast<Expr>(Label->getSubStmt()))
Eli Friedmanc11535c2012-05-24 00:47:05 +00002497 return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Argyrios Kyrtzidis90963412010-09-19 21:21:10 +00002498 }
Mike Stump11289f42009-09-09 15:08:12 +00002499
John McCallc493a732010-03-12 07:11:26 +00002500 if (getType()->isVoidType())
2501 return false;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002502 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002503 Loc = cast<StmtExpr>(this)->getLParenLoc();
2504 R1 = getSourceRange();
2505 return true;
Chris Lattner944d3062008-07-26 19:51:01 +00002506 }
Eli Friedmanbdd57532012-09-24 23:02:26 +00002507 case CXXFunctionalCastExprClass:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002508 case CStyleCastExprClass: {
Eli Friedmanf92f6452012-05-24 21:05:41 +00002509 // Ignore an explicit cast to void unless the operand is a non-trivial
Eli Friedmanc11535c2012-05-24 00:47:05 +00002510 // volatile lvalue.
Eli Friedmanf92f6452012-05-24 21:05:41 +00002511 const CastExpr *CE = cast<CastExpr>(this);
Eli Friedmanc11535c2012-05-24 00:47:05 +00002512 if (CE->getCastKind() == CK_ToVoid) {
2513 if (CE->getSubExpr()->isGLValue() &&
Eli Friedmanf92f6452012-05-24 21:05:41 +00002514 CE->getSubExpr()->getType().isVolatileQualified()) {
2515 const DeclRefExpr *DRE =
2516 dyn_cast<DeclRefExpr>(CE->getSubExpr()->IgnoreParens());
2517 if (!(DRE && isa<VarDecl>(DRE->getDecl()) &&
Erich Keane80b0fb02017-10-19 15:58:58 +00002518 cast<VarDecl>(DRE->getDecl())->hasLocalStorage()) &&
2519 !isa<CallExpr>(CE->getSubExpr()->IgnoreParens())) {
Eli Friedmanf92f6452012-05-24 21:05:41 +00002520 return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc,
2521 R1, R2, Ctx);
2522 }
2523 }
Chris Lattner2706a552009-07-28 18:25:28 +00002524 return false;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002525 }
Eli Friedmanf92f6452012-05-24 21:05:41 +00002526
Eli Friedmanc11535c2012-05-24 00:47:05 +00002527 // If this is a cast to a constructor conversion, check the operand.
Anders Carlsson6aa50392009-11-17 17:11:23 +00002528 // Otherwise, the result of the cast is unused.
Eli Friedmanc11535c2012-05-24 00:47:05 +00002529 if (CE->getCastKind() == CK_ConstructorConversion)
2530 return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Eli Friedmanf92f6452012-05-24 21:05:41 +00002531
Eli Friedmanc11535c2012-05-24 00:47:05 +00002532 WarnE = this;
Eli Friedmanf92f6452012-05-24 21:05:41 +00002533 if (const CXXFunctionalCastExpr *CXXCE =
2534 dyn_cast<CXXFunctionalCastExpr>(this)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002535 Loc = CXXCE->getBeginLoc();
Eli Friedmanf92f6452012-05-24 21:05:41 +00002536 R1 = CXXCE->getSubExpr()->getSourceRange();
2537 } else {
2538 const CStyleCastExpr *CStyleCE = cast<CStyleCastExpr>(this);
2539 Loc = CStyleCE->getLParenLoc();
2540 R1 = CStyleCE->getSubExpr()->getSourceRange();
2541 }
Chris Lattner237f2752009-02-14 07:37:35 +00002542 return true;
Anders Carlsson6aa50392009-11-17 17:11:23 +00002543 }
Eli Friedmanc11535c2012-05-24 00:47:05 +00002544 case ImplicitCastExprClass: {
2545 const CastExpr *ICE = cast<ImplicitCastExpr>(this);
Eli Friedmanca8da1d2008-05-19 21:24:43 +00002546
Eli Friedmanc11535c2012-05-24 00:47:05 +00002547 // lvalue-to-rvalue conversion on a volatile lvalue is a side-effect.
2548 if (ICE->getCastKind() == CK_LValueToRValue &&
2549 ICE->getSubExpr()->getType().isVolatileQualified())
2550 return false;
2551
2552 return ICE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2553 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002554 case CXXDefaultArgExprClass:
Mike Stump53f9ded2009-11-03 23:25:48 +00002555 return (cast<CXXDefaultArgExpr>(this)
Eli Friedmanc11535c2012-05-24 00:47:05 +00002556 ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
Richard Smith852c9db2013-04-20 22:23:05 +00002557 case CXXDefaultInitExprClass:
2558 return (cast<CXXDefaultInitExpr>(this)
2559 ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
Sebastian Redlbd150f42008-11-21 19:14:01 +00002560
2561 case CXXNewExprClass:
2562 // FIXME: In theory, there might be new expressions that don't have side
2563 // effects (e.g. a placement new with an uninitialized POD).
2564 case CXXDeleteExprClass:
Chris Lattner237f2752009-02-14 07:37:35 +00002565 return false;
Richard Smith122f88d2016-12-06 23:52:28 +00002566 case MaterializeTemporaryExprClass:
2567 return cast<MaterializeTemporaryExpr>(this)->GetTemporaryExpr()
2568 ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Anders Carlssone80ccac2009-08-16 04:11:06 +00002569 case CXXBindTemporaryExprClass:
Richard Smith122f88d2016-12-06 23:52:28 +00002570 return cast<CXXBindTemporaryExpr>(this)->getSubExpr()
2571 ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
John McCall5d413782010-12-06 08:20:24 +00002572 case ExprWithCleanupsClass:
Richard Smith122f88d2016-12-06 23:52:28 +00002573 return cast<ExprWithCleanups>(this)->getSubExpr()
2574 ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Sebastian Redlbd150f42008-11-21 19:14:01 +00002575 }
Chris Lattner1ec5f562007-06-27 05:38:08 +00002576}
2577
Fariborz Jahanian07735332009-02-22 18:40:18 +00002578/// isOBJCGCCandidate - Check if an expression is objc gc'able.
Fariborz Jahanian063c7722009-09-08 23:38:54 +00002579/// returns true, if it is; false otherwise.
Fariborz Jahanianc6d98002009-06-01 21:29:32 +00002580bool Expr::isOBJCGCCandidate(ASTContext &Ctx) const {
Peter Collingbourne91147592011-04-15 00:35:48 +00002581 const Expr *E = IgnoreParens();
2582 switch (E->getStmtClass()) {
Fariborz Jahanian07735332009-02-22 18:40:18 +00002583 default:
2584 return false;
2585 case ObjCIvarRefExprClass:
2586 return true;
Fariborz Jahanian392124c2009-02-23 18:59:50 +00002587 case Expr::UnaryOperatorClass:
Peter Collingbourne91147592011-04-15 00:35:48 +00002588 return cast<UnaryOperator>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
Fariborz Jahanian07735332009-02-22 18:40:18 +00002589 case ImplicitCastExprClass:
Peter Collingbourne91147592011-04-15 00:35:48 +00002590 return cast<ImplicitCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
Douglas Gregorfe314812011-06-21 17:03:29 +00002591 case MaterializeTemporaryExprClass:
2592 return cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr()
2593 ->isOBJCGCCandidate(Ctx);
Fariborz Jahaniana16904b2009-05-05 23:28:21 +00002594 case CStyleCastExprClass:
Peter Collingbourne91147592011-04-15 00:35:48 +00002595 return cast<CStyleCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002596 case DeclRefExprClass: {
John McCall113bee02012-03-10 09:33:50 +00002597 const Decl *D = cast<DeclRefExpr>(E)->getDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +00002598
Fariborz Jahanianc6d98002009-06-01 21:29:32 +00002599 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2600 if (VD->hasGlobalStorage())
2601 return true;
2602 QualType T = VD->getType();
Fariborz Jahaniancceedbf2009-09-16 18:09:18 +00002603 // dereferencing to a pointer is always a gc'able candidate,
2604 // unless it is __weak.
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00002605 return T->isPointerType() &&
John McCall8ccfcb52009-09-24 19:53:00 +00002606 (Ctx.getObjCGCAttrKind(T) != Qualifiers::Weak);
Fariborz Jahanianc6d98002009-06-01 21:29:32 +00002607 }
Fariborz Jahanian07735332009-02-22 18:40:18 +00002608 return false;
2609 }
Douglas Gregorf405d7e2009-08-31 23:41:50 +00002610 case MemberExprClass: {
Peter Collingbourne91147592011-04-15 00:35:48 +00002611 const MemberExpr *M = cast<MemberExpr>(E);
Fariborz Jahanianc6d98002009-06-01 21:29:32 +00002612 return M->getBase()->isOBJCGCCandidate(Ctx);
Fariborz Jahanian07735332009-02-22 18:40:18 +00002613 }
2614 case ArraySubscriptExprClass:
Peter Collingbourne91147592011-04-15 00:35:48 +00002615 return cast<ArraySubscriptExpr>(E)->getBase()->isOBJCGCCandidate(Ctx);
Fariborz Jahanian07735332009-02-22 18:40:18 +00002616 }
2617}
Sebastian Redlce354af2010-09-10 20:55:33 +00002618
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +00002619bool Expr::isBoundMemberFunction(ASTContext &Ctx) const {
2620 if (isTypeDependent())
2621 return false;
John McCall086a4642010-11-24 05:12:34 +00002622 return ClassifyLValue(Ctx) == Expr::LV_MemberFunction;
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +00002623}
2624
John McCall0009fcc2011-04-26 20:42:42 +00002625QualType Expr::findBoundMemberType(const Expr *expr) {
John McCalle314e272011-10-18 21:02:43 +00002626 assert(expr->hasPlaceholderType(BuiltinType::BoundMember));
John McCall0009fcc2011-04-26 20:42:42 +00002627
2628 // Bound member expressions are always one of these possibilities:
2629 // x->m x.m x->*y x.*y
2630 // (possibly parenthesized)
2631
2632 expr = expr->IgnoreParens();
2633 if (const MemberExpr *mem = dyn_cast<MemberExpr>(expr)) {
2634 assert(isa<CXXMethodDecl>(mem->getMemberDecl()));
2635 return mem->getMemberDecl()->getType();
2636 }
2637
2638 if (const BinaryOperator *op = dyn_cast<BinaryOperator>(expr)) {
2639 QualType type = op->getRHS()->getType()->castAs<MemberPointerType>()
2640 ->getPointeeType();
2641 assert(type->isFunctionType());
2642 return type;
2643 }
2644
David Majnemerced8bdf2015-02-25 17:36:15 +00002645 assert(isa<UnresolvedMemberExpr>(expr) || isa<CXXPseudoDestructorExpr>(expr));
John McCall0009fcc2011-04-26 20:42:42 +00002646 return QualType();
2647}
2648
Bruno Ricci46148f22019-02-17 18:50:51 +00002649static Expr *IgnoreImpCastsSingleStep(Expr *E) {
2650 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
2651 return ICE->getSubExpr();
2652
2653 if (auto *FE = dyn_cast<FullExpr>(E))
2654 return FE->getSubExpr();
2655
Bruno Riccid4038002019-02-17 13:47:29 +00002656 return E;
Ted Kremenek6f375e52014-04-16 07:26:09 +00002657}
2658
Bruno Ricci46148f22019-02-17 18:50:51 +00002659static Expr *IgnoreImpCastsExtraSingleStep(Expr *E) {
2660 // FIXME: Skip MaterializeTemporaryExpr and SubstNonTypeTemplateParmExpr in
2661 // addition to what IgnoreImpCasts() skips to account for the current
2662 // behaviour of IgnoreParenImpCasts().
2663 Expr *SubE = IgnoreImpCastsSingleStep(E);
2664 if (SubE != E)
2665 return SubE;
2666
2667 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
2668 return MTE->GetTemporaryExpr();
2669
2670 if (auto *NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E))
2671 return NTTP->getReplacement();
2672
2673 return E;
2674}
2675
2676static Expr *IgnoreCastsSingleStep(Expr *E) {
2677 if (auto *CE = dyn_cast<CastExpr>(E))
2678 return CE->getSubExpr();
2679
2680 if (auto *FE = dyn_cast<FullExpr>(E))
2681 return FE->getSubExpr();
2682
2683 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
2684 return MTE->GetTemporaryExpr();
2685
2686 if (auto *NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E))
2687 return NTTP->getReplacement();
2688
2689 return E;
2690}
2691
2692static Expr *IgnoreLValueCastsSingleStep(Expr *E) {
2693 // Skip what IgnoreCastsSingleStep skips, except that only
2694 // lvalue-to-rvalue casts are skipped.
2695 if (auto *CE = dyn_cast<CastExpr>(E))
2696 if (CE->getCastKind() != CK_LValueToRValue)
2697 return E;
2698
2699 return IgnoreCastsSingleStep(E);
2700}
2701
2702static Expr *IgnoreBaseCastsSingleStep(Expr *E) {
2703 if (auto *CE = dyn_cast<CastExpr>(E))
2704 if (CE->getCastKind() == CK_DerivedToBase ||
2705 CE->getCastKind() == CK_UncheckedDerivedToBase ||
2706 CE->getCastKind() == CK_NoOp)
2707 return CE->getSubExpr();
2708
2709 return E;
2710}
2711
2712static Expr *IgnoreImplicitSingleStep(Expr *E) {
2713 Expr *SubE = IgnoreImpCastsSingleStep(E);
2714 if (SubE != E)
2715 return SubE;
2716
2717 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
2718 return MTE->GetTemporaryExpr();
2719
2720 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(E))
2721 return BTE->getSubExpr();
2722
2723 return E;
2724}
2725
2726static Expr *IgnoreParensSingleStep(Expr *E) {
2727 if (auto *PE = dyn_cast<ParenExpr>(E))
2728 return PE->getSubExpr();
2729
2730 if (auto *UO = dyn_cast<UnaryOperator>(E)) {
2731 if (UO->getOpcode() == UO_Extension)
2732 return UO->getSubExpr();
2733 }
2734
2735 else if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
2736 if (!GSE->isResultDependent())
2737 return GSE->getResultExpr();
2738 }
2739
2740 else if (auto *CE = dyn_cast<ChooseExpr>(E)) {
2741 if (!CE->isConditionDependent())
2742 return CE->getChosenSubExpr();
2743 }
2744
2745 else if (auto *CE = dyn_cast<ConstantExpr>(E))
2746 return CE->getSubExpr();
2747
2748 return E;
2749}
2750
2751static Expr *IgnoreNoopCastsSingleStep(const ASTContext &Ctx, Expr *E) {
2752 if (auto *CE = dyn_cast<CastExpr>(E)) {
2753 // We ignore integer <-> casts that are of the same width, ptr<->ptr and
2754 // ptr<->int casts of the same width. We also ignore all identity casts.
2755 Expr *SubExpr = CE->getSubExpr();
2756 bool IsIdentityCast =
2757 Ctx.hasSameUnqualifiedType(E->getType(), SubExpr->getType());
2758 bool IsSameWidthCast =
2759 (E->getType()->isPointerType() || E->getType()->isIntegralType(Ctx)) &&
2760 (SubExpr->getType()->isPointerType() ||
2761 SubExpr->getType()->isIntegralType(Ctx)) &&
2762 (Ctx.getTypeSize(E->getType()) == Ctx.getTypeSize(SubExpr->getType()));
2763
2764 if (IsIdentityCast || IsSameWidthCast)
2765 return SubExpr;
2766 }
2767
2768 else if (auto *NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E))
2769 return NTTP->getReplacement();
2770
2771 return E;
2772}
2773
2774static Expr *IgnoreExprNodesImpl(Expr *E) { return E; }
2775template <typename FnTy, typename... FnTys>
2776static Expr *IgnoreExprNodesImpl(Expr *E, FnTy &&Fn, FnTys &&... Fns) {
2777 return IgnoreExprNodesImpl(Fn(E), std::forward<FnTys>(Fns)...);
2778}
2779
2780/// Given an expression E and functions Fn_1,...,Fn_n : Expr * -> Expr *,
2781/// Recursively apply each of the functions to E until reaching a fixed point.
2782/// Note that a null E is valid; in this case nothing is done.
2783template <typename... FnTys>
2784static Expr *IgnoreExprNodes(Expr *E, FnTys &&... Fns) {
Bruno Riccid4038002019-02-17 13:47:29 +00002785 Expr *LastE = nullptr;
2786 while (E != LastE) {
2787 LastE = E;
Bruno Ricci46148f22019-02-17 18:50:51 +00002788 E = IgnoreExprNodesImpl(E, std::forward<FnTys>(Fns)...);
Bruno Riccid4038002019-02-17 13:47:29 +00002789 }
2790 return E;
John McCall34376a62010-12-04 03:47:34 +00002791}
Rafael Espindolaecbe2e92012-06-28 01:56:38 +00002792
Bruno Ricci46148f22019-02-17 18:50:51 +00002793Expr *Expr::IgnoreImpCasts() {
2794 return IgnoreExprNodes(this, IgnoreImpCastsSingleStep);
Bruno Riccid4038002019-02-17 13:47:29 +00002795}
2796
2797Expr *Expr::IgnoreCasts() {
Bruno Ricci46148f22019-02-17 18:50:51 +00002798 return IgnoreExprNodes(this, IgnoreCastsSingleStep);
Bruno Riccid4038002019-02-17 13:47:29 +00002799}
2800
Bruno Ricci46148f22019-02-17 18:50:51 +00002801Expr *Expr::IgnoreImplicit() {
2802 return IgnoreExprNodes(this, IgnoreImplicitSingleStep);
Bruno Riccid4038002019-02-17 13:47:29 +00002803}
2804
Bruno Ricci46148f22019-02-17 18:50:51 +00002805Expr *Expr::IgnoreParens() {
2806 return IgnoreExprNodes(this, IgnoreParensSingleStep);
Rafael Espindolaecbe2e92012-06-28 01:56:38 +00002807}
2808
John McCalleebc8322010-05-05 22:59:52 +00002809Expr *Expr::IgnoreParenImpCasts() {
Bruno Ricci46148f22019-02-17 18:50:51 +00002810 return IgnoreExprNodes(this, IgnoreParensSingleStep,
2811 IgnoreImpCastsExtraSingleStep);
2812}
2813
2814Expr *Expr::IgnoreParenCasts() {
2815 return IgnoreExprNodes(this, IgnoreParensSingleStep, IgnoreCastsSingleStep);
John McCalleebc8322010-05-05 22:59:52 +00002816}
2817
Hans Wennborgde2e67e2011-06-09 17:06:51 +00002818Expr *Expr::IgnoreConversionOperator() {
Bruno Riccie64aee82019-02-03 19:50:56 +00002819 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(this)) {
Chandler Carruth4352b0b2011-06-21 17:22:09 +00002820 if (MCE->getMethodDecl() && isa<CXXConversionDecl>(MCE->getMethodDecl()))
Hans Wennborgde2e67e2011-06-09 17:06:51 +00002821 return MCE->getImplicitObjectArgument();
2822 }
2823 return this;
2824}
2825
Bruno Ricci46148f22019-02-17 18:50:51 +00002826Expr *Expr::IgnoreParenLValueCasts() {
2827 return IgnoreExprNodes(this, IgnoreParensSingleStep,
2828 IgnoreLValueCastsSingleStep);
2829}
2830
2831Expr *Expr::ignoreParenBaseCasts() {
2832 return IgnoreExprNodes(this, IgnoreParensSingleStep,
2833 IgnoreBaseCastsSingleStep);
2834}
2835
Bruno Riccie64aee82019-02-03 19:50:56 +00002836Expr *Expr::IgnoreParenNoopCasts(const ASTContext &Ctx) {
Bruno Ricci46148f22019-02-17 18:50:51 +00002837 return IgnoreExprNodes(this, IgnoreParensSingleStep, [&Ctx](Expr *E) {
2838 return IgnoreNoopCastsSingleStep(Ctx, E);
2839 });
Chris Lattneref26c772009-03-13 17:28:01 +00002840}
2841
Douglas Gregord196a582009-12-14 19:27:10 +00002842bool Expr::isDefaultArgument() const {
2843 const Expr *E = this;
Douglas Gregorfe314812011-06-21 17:03:29 +00002844 if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
2845 E = M->GetTemporaryExpr();
2846
Douglas Gregord196a582009-12-14 19:27:10 +00002847 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
2848 E = ICE->getSubExprAsWritten();
Fangrui Song6907ce22018-07-30 19:24:48 +00002849
Douglas Gregord196a582009-12-14 19:27:10 +00002850 return isa<CXXDefaultArgExpr>(E);
2851}
Chris Lattneref26c772009-03-13 17:28:01 +00002852
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002853/// Skip over any no-op casts and any temporary-binding
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002854/// expressions.
Anders Carlsson66bbf502010-11-28 16:40:49 +00002855static const Expr *skipTemporaryBindingsNoOpCastsAndParens(const Expr *E) {
Douglas Gregorfe314812011-06-21 17:03:29 +00002856 if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
2857 E = M->GetTemporaryExpr();
2858
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002859 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCalle3027922010-08-25 11:45:40 +00002860 if (ICE->getCastKind() == CK_NoOp)
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002861 E = ICE->getSubExpr();
2862 else
2863 break;
2864 }
2865
2866 while (const CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
2867 E = BE->getSubExpr();
2868
2869 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCalle3027922010-08-25 11:45:40 +00002870 if (ICE->getCastKind() == CK_NoOp)
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002871 E = ICE->getSubExpr();
2872 else
2873 break;
2874 }
Anders Carlsson66bbf502010-11-28 16:40:49 +00002875
2876 return E->IgnoreParens();
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002877}
2878
John McCall7a626f62010-09-15 10:14:12 +00002879/// isTemporaryObject - Determines if this expression produces a
2880/// temporary of the given class type.
2881bool Expr::isTemporaryObject(ASTContext &C, const CXXRecordDecl *TempTy) const {
2882 if (!C.hasSameUnqualifiedType(getType(), C.getTypeDeclType(TempTy)))
2883 return false;
2884
Anders Carlsson66bbf502010-11-28 16:40:49 +00002885 const Expr *E = skipTemporaryBindingsNoOpCastsAndParens(this);
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002886
John McCall02dc8c72010-09-15 20:59:13 +00002887 // Temporaries are by definition pr-values of class type.
Fariborz Jahanian30e8d582010-09-27 17:30:38 +00002888 if (!E->Classify(C).isPRValue()) {
2889 // In this context, property reference is a message call and is pr-value.
John McCallb7bd14f2010-12-02 01:19:52 +00002890 if (!isa<ObjCPropertyRefExpr>(E))
Fariborz Jahanian30e8d582010-09-27 17:30:38 +00002891 return false;
2892 }
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002893
John McCallf4ee1dd2010-09-16 06:57:56 +00002894 // Black-list a few cases which yield pr-values of class type that don't
2895 // refer to temporaries of that type:
2896
2897 // - implicit derived-to-base conversions
John McCall7a626f62010-09-15 10:14:12 +00002898 if (isa<ImplicitCastExpr>(E)) {
2899 switch (cast<ImplicitCastExpr>(E)->getCastKind()) {
2900 case CK_DerivedToBase:
2901 case CK_UncheckedDerivedToBase:
2902 return false;
2903 default:
2904 break;
2905 }
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002906 }
2907
John McCallf4ee1dd2010-09-16 06:57:56 +00002908 // - member expressions (all)
2909 if (isa<MemberExpr>(E))
2910 return false;
2911
Eli Friedman13ffdd82012-06-15 23:51:06 +00002912 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E))
2913 if (BO->isPtrMemOp())
2914 return false;
2915
John McCallc07a0c72011-02-17 10:25:35 +00002916 // - opaque values (all)
2917 if (isa<OpaqueValueExpr>(E))
2918 return false;
2919
John McCall7a626f62010-09-15 10:14:12 +00002920 return true;
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002921}
2922
Douglas Gregor25b7e052011-03-02 21:06:53 +00002923bool Expr::isImplicitCXXThis() const {
2924 const Expr *E = this;
Fangrui Song6907ce22018-07-30 19:24:48 +00002925
Douglas Gregor25b7e052011-03-02 21:06:53 +00002926 // Strip away parentheses and casts we don't care about.
2927 while (true) {
2928 if (const ParenExpr *Paren = dyn_cast<ParenExpr>(E)) {
2929 E = Paren->getSubExpr();
2930 continue;
2931 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002932
Douglas Gregor25b7e052011-03-02 21:06:53 +00002933 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2934 if (ICE->getCastKind() == CK_NoOp ||
2935 ICE->getCastKind() == CK_LValueToRValue ||
Fangrui Song6907ce22018-07-30 19:24:48 +00002936 ICE->getCastKind() == CK_DerivedToBase ||
Douglas Gregor25b7e052011-03-02 21:06:53 +00002937 ICE->getCastKind() == CK_UncheckedDerivedToBase) {
2938 E = ICE->getSubExpr();
2939 continue;
2940 }
2941 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002942
Douglas Gregor25b7e052011-03-02 21:06:53 +00002943 if (const UnaryOperator* UnOp = dyn_cast<UnaryOperator>(E)) {
2944 if (UnOp->getOpcode() == UO_Extension) {
2945 E = UnOp->getSubExpr();
2946 continue;
2947 }
2948 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002949
Douglas Gregorfe314812011-06-21 17:03:29 +00002950 if (const MaterializeTemporaryExpr *M
2951 = dyn_cast<MaterializeTemporaryExpr>(E)) {
2952 E = M->GetTemporaryExpr();
2953 continue;
2954 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002955
Douglas Gregor25b7e052011-03-02 21:06:53 +00002956 break;
2957 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002958
Douglas Gregor25b7e052011-03-02 21:06:53 +00002959 if (const CXXThisExpr *This = dyn_cast<CXXThisExpr>(E))
2960 return This->isImplicit();
Fangrui Song6907ce22018-07-30 19:24:48 +00002961
Douglas Gregor25b7e052011-03-02 21:06:53 +00002962 return false;
2963}
2964
Douglas Gregor4619e432008-12-05 23:32:09 +00002965/// hasAnyTypeDependentArguments - Determines if any of the expressions
2966/// in Exprs is type-dependent.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002967bool Expr::hasAnyTypeDependentArguments(ArrayRef<Expr *> Exprs) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002968 for (unsigned I = 0; I < Exprs.size(); ++I)
Douglas Gregor4619e432008-12-05 23:32:09 +00002969 if (Exprs[I]->isTypeDependent())
2970 return true;
2971
2972 return false;
2973}
2974
Abramo Bagnara847c6602014-05-22 19:20:46 +00002975bool Expr::isConstantInitializer(ASTContext &Ctx, bool IsForRef,
2976 const Expr **Culprit) const {
Eli Friedman384da272009-01-25 03:12:18 +00002977 // This function is attempting whether an expression is an initializer
Eli Friedman4c27ac22013-07-16 22:40:53 +00002978 // which can be evaluated at compile-time. It very closely parallels
2979 // ConstExprEmitter in CGExprConstant.cpp; if they don't match, it
2980 // will lead to unexpected results. Like ConstExprEmitter, it falls back
2981 // to isEvaluatable most of the time.
2982 //
John McCall8b0f4ff2010-08-02 21:13:48 +00002983 // If we ever capture reference-binding directly in the AST, we can
2984 // kill the second parameter.
2985
2986 if (IsForRef) {
2987 EvalResult Result;
Abramo Bagnara847c6602014-05-22 19:20:46 +00002988 if (EvaluateAsLValue(Result, Ctx) && !Result.HasSideEffects)
2989 return true;
2990 if (Culprit)
2991 *Culprit = this;
2992 return false;
John McCall8b0f4ff2010-08-02 21:13:48 +00002993 }
Eli Friedmancf7cbe72009-02-20 02:36:22 +00002994
Anders Carlssona7c5eb72008-11-24 05:23:59 +00002995 switch (getStmtClass()) {
Eli Friedman384da272009-01-25 03:12:18 +00002996 default: break;
Anders Carlssona7c5eb72008-11-24 05:23:59 +00002997 case StringLiteralClass:
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00002998 case ObjCEncodeExprClass:
Anders Carlssona7c5eb72008-11-24 05:23:59 +00002999 return true;
John McCall81c9cea2010-08-01 21:51:45 +00003000 case CXXTemporaryObjectExprClass:
3001 case CXXConstructExprClass: {
3002 const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
John McCall8b0f4ff2010-08-02 21:13:48 +00003003
Eli Friedman4c27ac22013-07-16 22:40:53 +00003004 if (CE->getConstructor()->isTrivial() &&
3005 CE->getConstructor()->getParent()->hasTrivialDestructor()) {
3006 // Trivial default constructor
Richard Smithd62306a2011-11-10 06:34:14 +00003007 if (!CE->getNumArgs()) return true;
John McCall8b0f4ff2010-08-02 21:13:48 +00003008
Eli Friedman4c27ac22013-07-16 22:40:53 +00003009 // Trivial copy constructor
3010 assert(CE->getNumArgs() == 1 && "trivial ctor with > 1 argument");
Abramo Bagnara847c6602014-05-22 19:20:46 +00003011 return CE->getArg(0)->isConstantInitializer(Ctx, false, Culprit);
Richard Smithd62306a2011-11-10 06:34:14 +00003012 }
3013
Richard Smithd62306a2011-11-10 06:34:14 +00003014 break;
John McCall81c9cea2010-08-01 21:51:45 +00003015 }
Fangrui Song407659a2018-11-30 23:41:18 +00003016 case ConstantExprClass: {
3017 // FIXME: We should be able to return "true" here, but it can lead to extra
3018 // error messages. E.g. in Sema/array-init.c.
3019 const Expr *Exp = cast<ConstantExpr>(this)->getSubExpr();
3020 return Exp->isConstantInitializer(Ctx, false, Culprit);
3021 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003022 case CompoundLiteralExprClass: {
Eli Friedmancf7cbe72009-02-20 02:36:22 +00003023 // This handles gcc's extension that allows global initializers like
3024 // "struct x {int x;} x = (struct x) {};".
3025 // FIXME: This accepts other cases it shouldn't!
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003026 const Expr *Exp = cast<CompoundLiteralExpr>(this)->getInitializer();
Abramo Bagnara847c6602014-05-22 19:20:46 +00003027 return Exp->isConstantInitializer(Ctx, false, Culprit);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003028 }
Yunzhong Gaocb779302015-06-10 00:27:52 +00003029 case DesignatedInitUpdateExprClass: {
3030 const DesignatedInitUpdateExpr *DIUE = cast<DesignatedInitUpdateExpr>(this);
3031 return DIUE->getBase()->isConstantInitializer(Ctx, false, Culprit) &&
3032 DIUE->getUpdater()->isConstantInitializer(Ctx, false, Culprit);
3033 }
Anders Carlssona7c5eb72008-11-24 05:23:59 +00003034 case InitListExprClass: {
Eli Friedman4c27ac22013-07-16 22:40:53 +00003035 const InitListExpr *ILE = cast<InitListExpr>(this);
Dmitri Gribenkoc5f25442019-05-10 06:39:20 +00003036 assert(ILE->isSemanticForm() && "InitListExpr must be in semantic form");
Eli Friedman4c27ac22013-07-16 22:40:53 +00003037 if (ILE->getType()->isArrayType()) {
3038 unsigned numInits = ILE->getNumInits();
3039 for (unsigned i = 0; i < numInits; i++) {
Abramo Bagnara847c6602014-05-22 19:20:46 +00003040 if (!ILE->getInit(i)->isConstantInitializer(Ctx, false, Culprit))
Eli Friedman4c27ac22013-07-16 22:40:53 +00003041 return false;
3042 }
3043 return true;
Anders Carlssona7c5eb72008-11-24 05:23:59 +00003044 }
Eli Friedman4c27ac22013-07-16 22:40:53 +00003045
3046 if (ILE->getType()->isRecordType()) {
3047 unsigned ElementNo = 0;
3048 RecordDecl *RD = ILE->getType()->getAs<RecordType>()->getDecl();
Hans Wennborga302cd92014-08-21 16:06:57 +00003049 for (const auto *Field : RD->fields()) {
Eli Friedman4c27ac22013-07-16 22:40:53 +00003050 // If this is a union, skip all the fields that aren't being initialized.
Hans Wennborga302cd92014-08-21 16:06:57 +00003051 if (RD->isUnion() && ILE->getInitializedFieldInUnion() != Field)
Eli Friedman4c27ac22013-07-16 22:40:53 +00003052 continue;
3053
3054 // Don't emit anonymous bitfields, they just affect layout.
3055 if (Field->isUnnamedBitfield())
3056 continue;
3057
3058 if (ElementNo < ILE->getNumInits()) {
3059 const Expr *Elt = ILE->getInit(ElementNo++);
3060 if (Field->isBitField()) {
3061 // Bitfields have to evaluate to an integer.
Fangrui Song407659a2018-11-30 23:41:18 +00003062 EvalResult Result;
3063 if (!Elt->EvaluateAsInt(Result, Ctx)) {
Abramo Bagnara847c6602014-05-22 19:20:46 +00003064 if (Culprit)
3065 *Culprit = Elt;
Eli Friedman4c27ac22013-07-16 22:40:53 +00003066 return false;
Abramo Bagnara847c6602014-05-22 19:20:46 +00003067 }
Eli Friedman4c27ac22013-07-16 22:40:53 +00003068 } else {
3069 bool RefType = Field->getType()->isReferenceType();
Abramo Bagnara847c6602014-05-22 19:20:46 +00003070 if (!Elt->isConstantInitializer(Ctx, RefType, Culprit))
Eli Friedman4c27ac22013-07-16 22:40:53 +00003071 return false;
3072 }
3073 }
3074 }
3075 return true;
3076 }
3077
3078 break;
Anders Carlssona7c5eb72008-11-24 05:23:59 +00003079 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00003080 case ImplicitValueInitExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00003081 case NoInitExprClass:
Douglas Gregor0202cb42009-01-29 17:44:32 +00003082 return true;
Chris Lattner3eb172a2009-10-13 07:14:16 +00003083 case ParenExprClass:
John McCall8b0f4ff2010-08-02 21:13:48 +00003084 return cast<ParenExpr>(this)->getSubExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00003085 ->isConstantInitializer(Ctx, IsForRef, Culprit);
Peter Collingbourne91147592011-04-15 00:35:48 +00003086 case GenericSelectionExprClass:
Peter Collingbourne91147592011-04-15 00:35:48 +00003087 return cast<GenericSelectionExpr>(this)->getResultExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00003088 ->isConstantInitializer(Ctx, IsForRef, Culprit);
Abramo Bagnarab59a5b62010-09-27 07:13:32 +00003089 case ChooseExprClass:
Abramo Bagnara847c6602014-05-22 19:20:46 +00003090 if (cast<ChooseExpr>(this)->isConditionDependent()) {
3091 if (Culprit)
3092 *Culprit = this;
Eli Friedman75807f22013-07-20 00:40:58 +00003093 return false;
Abramo Bagnara847c6602014-05-22 19:20:46 +00003094 }
Eli Friedman75807f22013-07-20 00:40:58 +00003095 return cast<ChooseExpr>(this)->getChosenSubExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00003096 ->isConstantInitializer(Ctx, IsForRef, Culprit);
Eli Friedman384da272009-01-25 03:12:18 +00003097 case UnaryOperatorClass: {
3098 const UnaryOperator* Exp = cast<UnaryOperator>(this);
John McCalle3027922010-08-25 11:45:40 +00003099 if (Exp->getOpcode() == UO_Extension)
Abramo Bagnara847c6602014-05-22 19:20:46 +00003100 return Exp->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
Eli Friedman384da272009-01-25 03:12:18 +00003101 break;
3102 }
John McCall8b0f4ff2010-08-02 21:13:48 +00003103 case CXXFunctionalCastExprClass:
John McCall81c9cea2010-08-01 21:51:45 +00003104 case CXXStaticCastExprClass:
Chris Lattner1f02e052009-04-21 05:19:11 +00003105 case ImplicitCastExprClass:
Eli Friedman4c27ac22013-07-16 22:40:53 +00003106 case CStyleCastExprClass:
3107 case ObjCBridgedCastExprClass:
3108 case CXXDynamicCastExprClass:
3109 case CXXReinterpretCastExprClass:
3110 case CXXConstCastExprClass: {
Richard Smith161f09a2011-12-06 22:44:34 +00003111 const CastExpr *CE = cast<CastExpr>(this);
3112
Eli Friedman13ec75b2011-12-21 00:43:02 +00003113 // Handle misc casts we want to ignore.
Eli Friedman13ec75b2011-12-21 00:43:02 +00003114 if (CE->getCastKind() == CK_NoOp ||
3115 CE->getCastKind() == CK_LValueToRValue ||
3116 CE->getCastKind() == CK_ToUnion ||
Eli Friedman4c27ac22013-07-16 22:40:53 +00003117 CE->getCastKind() == CK_ConstructorConversion ||
3118 CE->getCastKind() == CK_NonAtomicToAtomic ||
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00003119 CE->getCastKind() == CK_AtomicToNonAtomic ||
3120 CE->getCastKind() == CK_IntToOCLSampler)
Abramo Bagnara847c6602014-05-22 19:20:46 +00003121 return CE->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
Richard Smith161f09a2011-12-06 22:44:34 +00003122
Eli Friedman384da272009-01-25 03:12:18 +00003123 break;
Richard Smith161f09a2011-12-06 22:44:34 +00003124 }
Douglas Gregorfe314812011-06-21 17:03:29 +00003125 case MaterializeTemporaryExprClass:
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003126 return cast<MaterializeTemporaryExpr>(this)->GetTemporaryExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00003127 ->isConstantInitializer(Ctx, false, Culprit);
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003128
Eli Friedman4c27ac22013-07-16 22:40:53 +00003129 case SubstNonTypeTemplateParmExprClass:
3130 return cast<SubstNonTypeTemplateParmExpr>(this)->getReplacement()
Abramo Bagnara847c6602014-05-22 19:20:46 +00003131 ->isConstantInitializer(Ctx, false, Culprit);
Eli Friedman4c27ac22013-07-16 22:40:53 +00003132 case CXXDefaultArgExprClass:
3133 return cast<CXXDefaultArgExpr>(this)->getExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00003134 ->isConstantInitializer(Ctx, false, Culprit);
Eli Friedman4c27ac22013-07-16 22:40:53 +00003135 case CXXDefaultInitExprClass:
3136 return cast<CXXDefaultInitExpr>(this)->getExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00003137 ->isConstantInitializer(Ctx, false, Culprit);
Anders Carlssona7c5eb72008-11-24 05:23:59 +00003138 }
Richard Smithce8eca52015-12-08 03:21:47 +00003139 // Allow certain forms of UB in constant initializers: signed integer
3140 // overflow and floating-point division by zero. We'll give a warning on
3141 // these, but they're common enough that we have to accept them.
3142 if (isEvaluatable(Ctx, SE_AllowUndefinedBehavior))
Abramo Bagnara847c6602014-05-22 19:20:46 +00003143 return true;
3144 if (Culprit)
3145 *Culprit = this;
3146 return false;
Steve Naroffb03f5942007-09-02 20:30:18 +00003147}
3148
Nico Weber758fbac2018-02-13 21:31:47 +00003149bool CallExpr::isBuiltinAssumeFalse(const ASTContext &Ctx) const {
3150 const FunctionDecl* FD = getDirectCallee();
3151 if (!FD || (FD->getBuiltinID() != Builtin::BI__assume &&
3152 FD->getBuiltinID() != Builtin::BI__builtin_assume))
3153 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00003154
Nico Weber758fbac2018-02-13 21:31:47 +00003155 const Expr* Arg = getArg(0);
3156 bool ArgVal;
3157 return !Arg->isValueDependent() &&
3158 Arg->EvaluateAsBooleanCondition(ArgVal, Ctx) && !ArgVal;
3159}
3160
Scott Douglasscc013592015-06-10 15:18:23 +00003161namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003162 /// Look for any side effects within a Stmt.
Scott Douglasscc013592015-06-10 15:18:23 +00003163 class SideEffectFinder : public ConstEvaluatedExprVisitor<SideEffectFinder> {
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003164 typedef ConstEvaluatedExprVisitor<SideEffectFinder> Inherited;
Scott Douglasscc013592015-06-10 15:18:23 +00003165 const bool IncludePossibleEffects;
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003166 bool HasSideEffects;
Scott Douglasscc013592015-06-10 15:18:23 +00003167
3168 public:
3169 explicit SideEffectFinder(const ASTContext &Context, bool IncludePossible)
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003170 : Inherited(Context),
3171 IncludePossibleEffects(IncludePossible), HasSideEffects(false) { }
Scott Douglasscc013592015-06-10 15:18:23 +00003172
3173 bool hasSideEffects() const { return HasSideEffects; }
3174
3175 void VisitExpr(const Expr *E) {
3176 if (!HasSideEffects &&
3177 E->HasSideEffects(Context, IncludePossibleEffects))
3178 HasSideEffects = true;
3179 }
3180 };
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003181}
Scott Douglasscc013592015-06-10 15:18:23 +00003182
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003183bool Expr::HasSideEffects(const ASTContext &Ctx,
3184 bool IncludePossibleEffects) const {
3185 // In circumstances where we care about definite side effects instead of
3186 // potential side effects, we want to ignore expressions that are part of a
3187 // macro expansion as a potential side effect.
3188 if (!IncludePossibleEffects && getExprLoc().isMacroID())
3189 return false;
3190
Richard Smith0421ce72012-08-07 04:16:51 +00003191 if (isInstantiationDependent())
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003192 return IncludePossibleEffects;
Richard Smith0421ce72012-08-07 04:16:51 +00003193
3194 switch (getStmtClass()) {
3195 case NoStmtClass:
3196 #define ABSTRACT_STMT(Type)
3197 #define STMT(Type, Base) case Type##Class:
3198 #define EXPR(Type, Base)
3199 #include "clang/AST/StmtNodes.inc"
3200 llvm_unreachable("unexpected Expr kind");
3201
3202 case DependentScopeDeclRefExprClass:
3203 case CXXUnresolvedConstructExprClass:
3204 case CXXDependentScopeMemberExprClass:
3205 case UnresolvedLookupExprClass:
3206 case UnresolvedMemberExprClass:
3207 case PackExpansionExprClass:
3208 case SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +00003209 case FunctionParmPackExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +00003210 case TypoExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +00003211 case CXXFoldExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003212 llvm_unreachable("shouldn't see dependent / unresolved nodes here");
3213
Richard Smitha33e4fe2012-08-07 05:18:29 +00003214 case DeclRefExprClass:
3215 case ObjCIvarRefExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003216 case PredefinedExprClass:
3217 case IntegerLiteralClass:
Leonard Chandb01c3a2018-06-20 17:19:40 +00003218 case FixedPointLiteralClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003219 case FloatingLiteralClass:
3220 case ImaginaryLiteralClass:
3221 case StringLiteralClass:
3222 case CharacterLiteralClass:
3223 case OffsetOfExprClass:
3224 case ImplicitValueInitExprClass:
3225 case UnaryExprOrTypeTraitExprClass:
3226 case AddrLabelExprClass:
3227 case GNUNullExprClass:
Richard Smith410306b2016-12-12 02:53:20 +00003228 case ArrayInitIndexExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00003229 case NoInitExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003230 case CXXBoolLiteralExprClass:
3231 case CXXNullPtrLiteralExprClass:
3232 case CXXThisExprClass:
3233 case CXXScalarValueInitExprClass:
3234 case TypeTraitExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003235 case ArrayTypeTraitExprClass:
3236 case ExpressionTraitExprClass:
3237 case CXXNoexceptExprClass:
3238 case SizeOfPackExprClass:
3239 case ObjCStringLiteralClass:
3240 case ObjCEncodeExprClass:
3241 case ObjCBoolLiteralExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +00003242 case ObjCAvailabilityCheckExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003243 case CXXUuidofExprClass:
3244 case OpaqueValueExprClass:
Eric Fiselier708afb52019-05-16 21:04:15 +00003245 case SourceLocExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003246 // These never have a side-effect.
3247 return false;
3248
Bill Wendling7c44da22018-10-31 03:48:47 +00003249 case ConstantExprClass:
3250 // FIXME: Move this into the "return false;" block above.
3251 return cast<ConstantExpr>(this)->getSubExpr()->HasSideEffects(
3252 Ctx, IncludePossibleEffects);
3253
Richard Smith0421ce72012-08-07 04:16:51 +00003254 case CallExprClass:
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003255 case CXXOperatorCallExprClass:
3256 case CXXMemberCallExprClass:
3257 case CUDAKernelCallExprClass:
Michael Kupersteinaed5ccd2015-04-06 13:22:01 +00003258 case UserDefinedLiteralClass: {
3259 // We don't know a call definitely has side effects, except for calls
3260 // to pure/const functions that definitely don't.
3261 // If the call itself is considered side-effect free, check the operands.
3262 const Decl *FD = cast<CallExpr>(this)->getCalleeDecl();
3263 bool IsPure = FD && (FD->hasAttr<ConstAttr>() || FD->hasAttr<PureAttr>());
3264 if (IsPure || !IncludePossibleEffects)
3265 break;
3266 return true;
3267 }
3268
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003269 case BlockExprClass:
3270 case CXXBindTemporaryExprClass:
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003271 if (!IncludePossibleEffects)
3272 break;
3273 return true;
3274
John McCall5e77d762013-04-16 07:28:30 +00003275 case MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +00003276 case MSPropertySubscriptExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003277 case CompoundAssignOperatorClass:
3278 case VAArgExprClass:
3279 case AtomicExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003280 case CXXThrowExprClass:
3281 case CXXNewExprClass:
3282 case CXXDeleteExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +00003283 case CoawaitExprClass:
Eric Fiselier20f25cb2017-03-06 23:38:15 +00003284 case DependentCoawaitExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +00003285 case CoyieldExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003286 // These always have a side-effect.
3287 return true;
3288
Scott Douglasscc013592015-06-10 15:18:23 +00003289 case StmtExprClass: {
3290 // StmtExprs have a side-effect if any substatement does.
3291 SideEffectFinder Finder(Ctx, IncludePossibleEffects);
3292 Finder.Visit(cast<StmtExpr>(this)->getSubStmt());
3293 return Finder.hasSideEffects();
3294 }
3295
Tim Shen4a05bb82016-06-21 20:29:17 +00003296 case ExprWithCleanupsClass:
3297 if (IncludePossibleEffects)
3298 if (cast<ExprWithCleanups>(this)->cleanupsHaveSideEffects())
3299 return true;
3300 break;
3301
Richard Smith0421ce72012-08-07 04:16:51 +00003302 case ParenExprClass:
3303 case ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +00003304 case OMPArraySectionExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003305 case MemberExprClass:
3306 case ConditionalOperatorClass:
3307 case BinaryConditionalOperatorClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003308 case CompoundLiteralExprClass:
3309 case ExtVectorElementExprClass:
3310 case DesignatedInitExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00003311 case DesignatedInitUpdateExprClass:
Richard Smith410306b2016-12-12 02:53:20 +00003312 case ArrayInitLoopExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003313 case ParenListExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003314 case CXXPseudoDestructorExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +00003315 case CXXStdInitializerListExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003316 case SubstNonTypeTemplateParmExprClass:
3317 case MaterializeTemporaryExprClass:
3318 case ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +00003319 case ConvertVectorExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003320 case AsTypeExprClass:
3321 // These have a side-effect if any subexpression does.
3322 break;
3323
Richard Smitha33e4fe2012-08-07 05:18:29 +00003324 case UnaryOperatorClass:
3325 if (cast<UnaryOperator>(this)->isIncrementDecrementOp())
Richard Smith0421ce72012-08-07 04:16:51 +00003326 return true;
3327 break;
Richard Smith0421ce72012-08-07 04:16:51 +00003328
3329 case BinaryOperatorClass:
3330 if (cast<BinaryOperator>(this)->isAssignmentOp())
3331 return true;
3332 break;
3333
Richard Smith0421ce72012-08-07 04:16:51 +00003334 case InitListExprClass:
3335 // FIXME: The children for an InitListExpr doesn't include the array filler.
3336 if (const Expr *E = cast<InitListExpr>(this)->getArrayFiller())
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003337 if (E->HasSideEffects(Ctx, IncludePossibleEffects))
Richard Smith0421ce72012-08-07 04:16:51 +00003338 return true;
3339 break;
3340
3341 case GenericSelectionExprClass:
3342 return cast<GenericSelectionExpr>(this)->getResultExpr()->
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003343 HasSideEffects(Ctx, IncludePossibleEffects);
Richard Smith0421ce72012-08-07 04:16:51 +00003344
3345 case ChooseExprClass:
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003346 return cast<ChooseExpr>(this)->getChosenSubExpr()->HasSideEffects(
3347 Ctx, IncludePossibleEffects);
Richard Smith0421ce72012-08-07 04:16:51 +00003348
3349 case CXXDefaultArgExprClass:
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003350 return cast<CXXDefaultArgExpr>(this)->getExpr()->HasSideEffects(
3351 Ctx, IncludePossibleEffects);
Richard Smith0421ce72012-08-07 04:16:51 +00003352
Reid Klecknerd60b82f2014-11-17 23:36:45 +00003353 case CXXDefaultInitExprClass: {
3354 const FieldDecl *FD = cast<CXXDefaultInitExpr>(this)->getField();
3355 if (const Expr *E = FD->getInClassInitializer())
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003356 return E->HasSideEffects(Ctx, IncludePossibleEffects);
Richard Smith852c9db2013-04-20 22:23:05 +00003357 // If we've not yet parsed the initializer, assume it has side-effects.
3358 return true;
Reid Klecknerd60b82f2014-11-17 23:36:45 +00003359 }
Richard Smith852c9db2013-04-20 22:23:05 +00003360
Richard Smith0421ce72012-08-07 04:16:51 +00003361 case CXXDynamicCastExprClass: {
3362 // A dynamic_cast expression has side-effects if it can throw.
3363 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(this);
3364 if (DCE->getTypeAsWritten()->isReferenceType() &&
3365 DCE->getCastKind() == CK_Dynamic)
3366 return true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00003367 }
3368 LLVM_FALLTHROUGH;
Richard Smitha33e4fe2012-08-07 05:18:29 +00003369 case ImplicitCastExprClass:
3370 case CStyleCastExprClass:
3371 case CXXStaticCastExprClass:
3372 case CXXReinterpretCastExprClass:
3373 case CXXConstCastExprClass:
3374 case CXXFunctionalCastExprClass: {
Aaron Ballman409af502015-01-03 17:00:12 +00003375 // While volatile reads are side-effecting in both C and C++, we treat them
3376 // as having possible (not definite) side-effects. This allows idiomatic
3377 // code to behave without warning, such as sizeof(*v) for a volatile-
3378 // qualified pointer.
3379 if (!IncludePossibleEffects)
3380 break;
3381
Richard Smitha33e4fe2012-08-07 05:18:29 +00003382 const CastExpr *CE = cast<CastExpr>(this);
3383 if (CE->getCastKind() == CK_LValueToRValue &&
3384 CE->getSubExpr()->getType().isVolatileQualified())
3385 return true;
Richard Smith0421ce72012-08-07 04:16:51 +00003386 break;
3387 }
3388
Richard Smithef8bf432012-08-13 20:08:14 +00003389 case CXXTypeidExprClass:
3390 // typeid might throw if its subexpression is potentially-evaluated, so has
3391 // side-effects in that case whether or not its subexpression does.
3392 return cast<CXXTypeidExpr>(this)->isPotentiallyEvaluated();
Richard Smith0421ce72012-08-07 04:16:51 +00003393
3394 case CXXConstructExprClass:
3395 case CXXTemporaryObjectExprClass: {
3396 const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003397 if (!CE->getConstructor()->isTrivial() && IncludePossibleEffects)
Richard Smith0421ce72012-08-07 04:16:51 +00003398 return true;
Richard Smitha33e4fe2012-08-07 05:18:29 +00003399 // A trivial constructor does not add any side-effects of its own. Just look
3400 // at its arguments.
Richard Smith0421ce72012-08-07 04:16:51 +00003401 break;
3402 }
3403
Richard Smith5179eb72016-06-28 19:03:57 +00003404 case CXXInheritedCtorInitExprClass: {
3405 const auto *ICIE = cast<CXXInheritedCtorInitExpr>(this);
3406 if (!ICIE->getConstructor()->isTrivial() && IncludePossibleEffects)
3407 return true;
3408 break;
3409 }
3410
Richard Smith0421ce72012-08-07 04:16:51 +00003411 case LambdaExprClass: {
3412 const LambdaExpr *LE = cast<LambdaExpr>(this);
Richard Smithb3d203f2018-10-19 19:01:34 +00003413 for (Expr *E : LE->capture_inits())
3414 if (E->HasSideEffects(Ctx, IncludePossibleEffects))
Richard Smith0421ce72012-08-07 04:16:51 +00003415 return true;
3416 return false;
3417 }
3418
3419 case PseudoObjectExprClass: {
3420 // Only look for side-effects in the semantic form, and look past
3421 // OpaqueValueExpr bindings in that form.
3422 const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this);
3423 for (PseudoObjectExpr::const_semantics_iterator I = PO->semantics_begin(),
3424 E = PO->semantics_end();
3425 I != E; ++I) {
3426 const Expr *Subexpr = *I;
3427 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Subexpr))
3428 Subexpr = OVE->getSourceExpr();
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003429 if (Subexpr->HasSideEffects(Ctx, IncludePossibleEffects))
Richard Smith0421ce72012-08-07 04:16:51 +00003430 return true;
3431 }
3432 return false;
3433 }
3434
3435 case ObjCBoxedExprClass:
3436 case ObjCArrayLiteralClass:
3437 case ObjCDictionaryLiteralClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003438 case ObjCSelectorExprClass:
3439 case ObjCProtocolExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003440 case ObjCIsaExprClass:
3441 case ObjCIndirectCopyRestoreExprClass:
3442 case ObjCSubscriptRefExprClass:
3443 case ObjCBridgedCastExprClass:
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003444 case ObjCMessageExprClass:
3445 case ObjCPropertyRefExprClass:
3446 // FIXME: Classify these cases better.
3447 if (IncludePossibleEffects)
3448 return true;
3449 break;
Richard Smith0421ce72012-08-07 04:16:51 +00003450 }
3451
3452 // Recurse to children.
Benjamin Kramer642f1732015-07-02 21:03:14 +00003453 for (const Stmt *SubStmt : children())
3454 if (SubStmt &&
3455 cast<Expr>(SubStmt)->HasSideEffects(Ctx, IncludePossibleEffects))
3456 return true;
Richard Smith0421ce72012-08-07 04:16:51 +00003457
3458 return false;
3459}
3460
Douglas Gregor1be329d2012-02-23 07:33:15 +00003461namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003462 /// Look for a call to a non-trivial function within an expression.
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003463 class NonTrivialCallFinder : public ConstEvaluatedExprVisitor<NonTrivialCallFinder>
3464 {
3465 typedef ConstEvaluatedExprVisitor<NonTrivialCallFinder> Inherited;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003466
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003467 bool NonTrivial;
Fangrui Song6907ce22018-07-30 19:24:48 +00003468
Douglas Gregor1be329d2012-02-23 07:33:15 +00003469 public:
Scott Douglass503fc392015-06-10 13:53:15 +00003470 explicit NonTrivialCallFinder(const ASTContext &Context)
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003471 : Inherited(Context), NonTrivial(false) { }
Fangrui Song6907ce22018-07-30 19:24:48 +00003472
Douglas Gregor1be329d2012-02-23 07:33:15 +00003473 bool hasNonTrivialCall() const { return NonTrivial; }
Scott Douglass503fc392015-06-10 13:53:15 +00003474
3475 void VisitCallExpr(const CallExpr *E) {
3476 if (const CXXMethodDecl *Method
3477 = dyn_cast_or_null<const CXXMethodDecl>(E->getCalleeDecl())) {
Douglas Gregor1be329d2012-02-23 07:33:15 +00003478 if (Method->isTrivial()) {
3479 // Recurse to children of the call.
3480 Inherited::VisitStmt(E);
3481 return;
3482 }
3483 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003484
Douglas Gregor1be329d2012-02-23 07:33:15 +00003485 NonTrivial = true;
3486 }
Scott Douglass503fc392015-06-10 13:53:15 +00003487
3488 void VisitCXXConstructExpr(const CXXConstructExpr *E) {
Douglas Gregor1be329d2012-02-23 07:33:15 +00003489 if (E->getConstructor()->isTrivial()) {
3490 // Recurse to children of the call.
3491 Inherited::VisitStmt(E);
3492 return;
3493 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003494
Douglas Gregor1be329d2012-02-23 07:33:15 +00003495 NonTrivial = true;
3496 }
Scott Douglass503fc392015-06-10 13:53:15 +00003497
3498 void VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
Douglas Gregor1be329d2012-02-23 07:33:15 +00003499 if (E->getTemporary()->getDestructor()->isTrivial()) {
3500 Inherited::VisitStmt(E);
3501 return;
3502 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003503
Douglas Gregor1be329d2012-02-23 07:33:15 +00003504 NonTrivial = true;
3505 }
3506 };
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003507}
Douglas Gregor1be329d2012-02-23 07:33:15 +00003508
Scott Douglass503fc392015-06-10 13:53:15 +00003509bool Expr::hasNonTrivialCall(const ASTContext &Ctx) const {
Douglas Gregor1be329d2012-02-23 07:33:15 +00003510 NonTrivialCallFinder Finder(Ctx);
3511 Finder.Visit(this);
Fangrui Song6907ce22018-07-30 19:24:48 +00003512 return Finder.hasNonTrivialCall();
Douglas Gregor1be329d2012-02-23 07:33:15 +00003513}
3514
Fangrui Song6907ce22018-07-30 19:24:48 +00003515/// isNullPointerConstant - C99 6.3.2.3p3 - Return whether this is a null
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003516/// pointer constant or not, as well as the specific kind of constant detected.
3517/// Null pointer constants can be integer constant expressions with the
3518/// value zero, casts of zero to void*, nullptr (C++0X), or __null
3519/// (a GNU extension).
3520Expr::NullPointerConstantKind
3521Expr::isNullPointerConstant(ASTContext &Ctx,
3522 NullPointerConstantValueDependence NPC) const {
Reid Klecknera5eef142013-11-12 02:22:34 +00003523 if (isValueDependent() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00003524 (!Ctx.getLangOpts().CPlusPlus11 || Ctx.getLangOpts().MSVCCompat)) {
Douglas Gregor56751b52009-09-25 04:25:58 +00003525 switch (NPC) {
3526 case NPC_NeverValueDependent:
David Blaikie83d382b2011-09-23 05:06:16 +00003527 llvm_unreachable("Unexpected value dependent expression!");
Douglas Gregor56751b52009-09-25 04:25:58 +00003528 case NPC_ValueDependentIsNull:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003529 if (isTypeDependent() || getType()->isIntegralType(Ctx))
David Blaikie1c7c8f72012-08-08 17:33:31 +00003530 return NPCK_ZeroExpression;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003531 else
3532 return NPCK_NotNull;
Fangrui Song6907ce22018-07-30 19:24:48 +00003533
Douglas Gregor56751b52009-09-25 04:25:58 +00003534 case NPC_ValueDependentIsNotNull:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003535 return NPCK_NotNull;
Douglas Gregor56751b52009-09-25 04:25:58 +00003536 }
3537 }
Daniel Dunbarebc51402009-09-18 08:46:16 +00003538
Sebastian Redl72b8aef2008-10-31 14:43:28 +00003539 // Strip off a cast to void*, if it exists. Except in C++.
Argyrios Kyrtzidis3bab3d22008-08-18 23:01:59 +00003540 if (const ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(this)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003541 if (!Ctx.getLangOpts().CPlusPlus) {
Sebastian Redl72b8aef2008-10-31 14:43:28 +00003542 // Check that it is a cast to void*.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003543 if (const PointerType *PT = CE->getType()->getAs<PointerType>()) {
Sebastian Redl72b8aef2008-10-31 14:43:28 +00003544 QualType Pointee = PT->getPointeeType();
Richard Smithdab73ce2018-11-28 06:25:06 +00003545 Qualifiers Qs = Pointee.getQualifiers();
Yaxun Liub7318e02017-10-13 03:37:48 +00003546 // Only (void*)0 or equivalent are treated as nullptr. If pointee type
3547 // has non-default address space it is not treated as nullptr.
3548 // (__generic void*)0 in OpenCL 2.0 should not be treated as nullptr
3549 // since it cannot be assigned to a pointer to constant address space.
Richard Smithdab73ce2018-11-28 06:25:06 +00003550 if ((Ctx.getLangOpts().OpenCLVersion >= 200 &&
Yaxun Liub7318e02017-10-13 03:37:48 +00003551 Pointee.getAddressSpace() == LangAS::opencl_generic) ||
3552 (Ctx.getLangOpts().OpenCL &&
3553 Ctx.getLangOpts().OpenCLVersion < 200 &&
Richard Smithdab73ce2018-11-28 06:25:06 +00003554 Pointee.getAddressSpace() == LangAS::opencl_private))
3555 Qs.removeAddressSpace();
Anastasia Stulova2446b8b2015-12-11 17:41:19 +00003556
Richard Smithdab73ce2018-11-28 06:25:06 +00003557 if (Pointee->isVoidType() && Qs.empty() && // to void*
3558 CE->getSubExpr()->getType()->isIntegerType()) // from int
Douglas Gregor56751b52009-09-25 04:25:58 +00003559 return CE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
Sebastian Redl72b8aef2008-10-31 14:43:28 +00003560 }
Steve Naroffada7d422007-05-20 17:54:12 +00003561 }
Steve Naroff4871fe02008-01-14 16:10:57 +00003562 } else if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(this)) {
3563 // Ignore the ImplicitCastExpr type entirely.
Douglas Gregor56751b52009-09-25 04:25:58 +00003564 return ICE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
Steve Naroff4871fe02008-01-14 16:10:57 +00003565 } else if (const ParenExpr *PE = dyn_cast<ParenExpr>(this)) {
3566 // Accept ((void*)0) as a null pointer constant, as many other
3567 // implementations do.
Douglas Gregor56751b52009-09-25 04:25:58 +00003568 return PE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
Peter Collingbourne91147592011-04-15 00:35:48 +00003569 } else if (const GenericSelectionExpr *GE =
3570 dyn_cast<GenericSelectionExpr>(this)) {
Eli Friedman75807f22013-07-20 00:40:58 +00003571 if (GE->isResultDependent())
3572 return NPCK_NotNull;
Peter Collingbourne91147592011-04-15 00:35:48 +00003573 return GE->getResultExpr()->isNullPointerConstant(Ctx, NPC);
Eli Friedman75807f22013-07-20 00:40:58 +00003574 } else if (const ChooseExpr *CE = dyn_cast<ChooseExpr>(this)) {
3575 if (CE->isConditionDependent())
3576 return NPCK_NotNull;
3577 return CE->getChosenSubExpr()->isNullPointerConstant(Ctx, NPC);
Mike Stump11289f42009-09-09 15:08:12 +00003578 } else if (const CXXDefaultArgExpr *DefaultArg
Chris Lattner58258242008-04-10 02:22:51 +00003579 = dyn_cast<CXXDefaultArgExpr>(this)) {
Richard Smith852c9db2013-04-20 22:23:05 +00003580 // See through default argument expressions.
Douglas Gregor56751b52009-09-25 04:25:58 +00003581 return DefaultArg->getExpr()->isNullPointerConstant(Ctx, NPC);
Richard Smith852c9db2013-04-20 22:23:05 +00003582 } else if (const CXXDefaultInitExpr *DefaultInit
3583 = dyn_cast<CXXDefaultInitExpr>(this)) {
3584 // See through default initializer expressions.
3585 return DefaultInit->getExpr()->isNullPointerConstant(Ctx, NPC);
Douglas Gregor3be4b122008-11-29 04:51:27 +00003586 } else if (isa<GNUNullExpr>(this)) {
3587 // The GNU __null extension is always a null pointer constant.
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003588 return NPCK_GNUNull;
Fangrui Song6907ce22018-07-30 19:24:48 +00003589 } else if (const MaterializeTemporaryExpr *M
Douglas Gregorfe314812011-06-21 17:03:29 +00003590 = dyn_cast<MaterializeTemporaryExpr>(this)) {
3591 return M->GetTemporaryExpr()->isNullPointerConstant(Ctx, NPC);
John McCallfe96e0b2011-11-06 09:01:30 +00003592 } else if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(this)) {
3593 if (const Expr *Source = OVE->getSourceExpr())
3594 return Source->isNullPointerConstant(Ctx, NPC);
Steve Naroff09035312008-01-14 02:53:34 +00003595 }
Douglas Gregor3be4b122008-11-29 04:51:27 +00003596
Richard Smith89645bc2013-01-02 12:01:23 +00003597 // C++11 nullptr_t is always a null pointer constant.
Sebastian Redl576fd422009-05-10 18:38:11 +00003598 if (getType()->isNullPtrType())
Richard Smith89645bc2013-01-02 12:01:23 +00003599 return NPCK_CXX11_nullptr;
Sebastian Redl576fd422009-05-10 18:38:11 +00003600
Fariborz Jahanian3567c422010-09-27 22:42:37 +00003601 if (const RecordType *UT = getType()->getAsUnionType())
Richard Smith4055de42013-06-13 02:46:14 +00003602 if (!Ctx.getLangOpts().CPlusPlus11 &&
3603 UT && UT->getDecl()->hasAttr<TransparentUnionAttr>())
Fariborz Jahanian3567c422010-09-27 22:42:37 +00003604 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(this)){
3605 const Expr *InitExpr = CLE->getInitializer();
3606 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(InitExpr))
3607 return ILE->getInit(0)->isNullPointerConstant(Ctx, NPC);
3608 }
Steve Naroff4871fe02008-01-14 16:10:57 +00003609 // This expression must be an integer type.
Fangrui Song6907ce22018-07-30 19:24:48 +00003610 if (!getType()->isIntegerType() ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00003611 (Ctx.getLangOpts().CPlusPlus && getType()->isEnumeralType()))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003612 return NPCK_NotNull;
Mike Stump11289f42009-09-09 15:08:12 +00003613
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003614 if (Ctx.getLangOpts().CPlusPlus11) {
Richard Smith4055de42013-06-13 02:46:14 +00003615 // C++11 [conv.ptr]p1: A null pointer constant is an integer literal with
3616 // value zero or a prvalue of type std::nullptr_t.
Reid Klecknera5eef142013-11-12 02:22:34 +00003617 // Microsoft mode permits C++98 rules reflecting MSVC behavior.
Richard Smith4055de42013-06-13 02:46:14 +00003618 const IntegerLiteral *Lit = dyn_cast<IntegerLiteral>(this);
Reid Klecknera5eef142013-11-12 02:22:34 +00003619 if (Lit && !Lit->getValue())
3620 return NPCK_ZeroLiteral;
Alp Tokerbfa39342014-01-14 12:51:41 +00003621 else if (!Ctx.getLangOpts().MSVCCompat || !isCXX98IntegralConstantExpr(Ctx))
Reid Klecknera5eef142013-11-12 02:22:34 +00003622 return NPCK_NotNull;
Richard Smith98a0a492012-02-14 21:38:30 +00003623 } else {
Richard Smith4055de42013-06-13 02:46:14 +00003624 // If we have an integer constant expression, we need to *evaluate* it and
3625 // test for the value 0.
Richard Smith98a0a492012-02-14 21:38:30 +00003626 if (!isIntegerConstantExpr(Ctx))
3627 return NPCK_NotNull;
3628 }
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003629
David Blaikie1c7c8f72012-08-08 17:33:31 +00003630 if (EvaluateKnownConstInt(Ctx) != 0)
3631 return NPCK_NotNull;
3632
3633 if (isa<IntegerLiteral>(this))
3634 return NPCK_ZeroLiteral;
3635 return NPCK_ZeroExpression;
Steve Naroff218bc2b2007-05-04 21:54:46 +00003636}
Steve Narofff7a5da12007-07-28 23:10:27 +00003637
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003638/// If this expression is an l-value for an Objective C
John McCall34376a62010-12-04 03:47:34 +00003639/// property, find the underlying property reference expression.
3640const ObjCPropertyRefExpr *Expr::getObjCProperty() const {
3641 const Expr *E = this;
3642 while (true) {
3643 assert((E->getValueKind() == VK_LValue &&
3644 E->getObjectKind() == OK_ObjCProperty) &&
3645 "expression is not a property reference");
3646 E = E->IgnoreParenCasts();
3647 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3648 if (BO->getOpcode() == BO_Comma) {
3649 E = BO->getRHS();
3650 continue;
3651 }
3652 }
3653
3654 break;
3655 }
3656
3657 return cast<ObjCPropertyRefExpr>(E);
3658}
3659
Anna Zaks97c7ce32012-10-01 20:34:04 +00003660bool Expr::isObjCSelfExpr() const {
3661 const Expr *E = IgnoreParenImpCasts();
3662
3663 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
3664 if (!DRE)
3665 return false;
3666
3667 const ImplicitParamDecl *Param = dyn_cast<ImplicitParamDecl>(DRE->getDecl());
3668 if (!Param)
3669 return false;
3670
3671 const ObjCMethodDecl *M = dyn_cast<ObjCMethodDecl>(Param->getDeclContext());
3672 if (!M)
3673 return false;
3674
3675 return M->getSelfDecl() == Param;
3676}
3677
John McCalld25db7e2013-05-06 21:39:12 +00003678FieldDecl *Expr::getSourceBitField() {
Douglas Gregor19623dc2009-07-06 15:38:40 +00003679 Expr *E = this->IgnoreParens();
Douglas Gregor71235ec2009-05-02 02:18:30 +00003680
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003681 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall34376a62010-12-04 03:47:34 +00003682 if (ICE->getCastKind() == CK_LValueToRValue ||
3683 (ICE->getValueKind() != VK_RValue && ICE->getCastKind() == CK_NoOp))
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003684 E = ICE->getSubExpr()->IgnoreParens();
3685 else
3686 break;
3687 }
3688
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003689 if (MemberExpr *MemRef = dyn_cast<MemberExpr>(E))
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00003690 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemRef->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00003691 if (Field->isBitField())
3692 return Field;
3693
George Burgess IV00f70bd2018-03-01 05:43:23 +00003694 if (ObjCIvarRefExpr *IvarRef = dyn_cast<ObjCIvarRefExpr>(E)) {
3695 FieldDecl *Ivar = IvarRef->getDecl();
3696 if (Ivar->isBitField())
3697 return Ivar;
3698 }
John McCalld25db7e2013-05-06 21:39:12 +00003699
Richard Smith7873de02016-08-11 22:25:46 +00003700 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E)) {
Argyrios Kyrtzidisd3f00542010-10-30 19:52:22 +00003701 if (FieldDecl *Field = dyn_cast<FieldDecl>(DeclRef->getDecl()))
3702 if (Field->isBitField())
3703 return Field;
3704
Richard Smith7873de02016-08-11 22:25:46 +00003705 if (BindingDecl *BD = dyn_cast<BindingDecl>(DeclRef->getDecl()))
3706 if (Expr *E = BD->getBinding())
3707 return E->getSourceBitField();
3708 }
3709
Eli Friedman609ada22011-07-13 02:05:57 +00003710 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(E)) {
Douglas Gregor71235ec2009-05-02 02:18:30 +00003711 if (BinOp->isAssignmentOp() && BinOp->getLHS())
John McCalld25db7e2013-05-06 21:39:12 +00003712 return BinOp->getLHS()->getSourceBitField();
Douglas Gregor71235ec2009-05-02 02:18:30 +00003713
Eli Friedman609ada22011-07-13 02:05:57 +00003714 if (BinOp->getOpcode() == BO_Comma && BinOp->getRHS())
John McCalld25db7e2013-05-06 21:39:12 +00003715 return BinOp->getRHS()->getSourceBitField();
Eli Friedman609ada22011-07-13 02:05:57 +00003716 }
3717
Richard Smith5b571672014-09-24 23:55:00 +00003718 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E))
3719 if (UnOp->isPrefix() && UnOp->isIncrementDecrementOp())
3720 return UnOp->getSubExpr()->getSourceBitField();
3721
Craig Topper36250ad2014-05-12 05:36:57 +00003722 return nullptr;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003723}
3724
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003725bool Expr::refersToVectorElement() const {
Richard Smith7873de02016-08-11 22:25:46 +00003726 // FIXME: Why do we not just look at the ObjectKind here?
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003727 const Expr *E = this->IgnoreParens();
Fangrui Song6907ce22018-07-30 19:24:48 +00003728
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003729 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall2536c6d2010-08-25 10:28:54 +00003730 if (ICE->getValueKind() != VK_RValue &&
John McCalle3027922010-08-25 11:45:40 +00003731 ICE->getCastKind() == CK_NoOp)
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003732 E = ICE->getSubExpr()->IgnoreParens();
3733 else
3734 break;
3735 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003736
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003737 if (const ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(E))
3738 return ASE->getBase()->getType()->isVectorType();
3739
3740 if (isa<ExtVectorElementExpr>(E))
3741 return true;
3742
Richard Smith7873de02016-08-11 22:25:46 +00003743 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3744 if (auto *BD = dyn_cast<BindingDecl>(DRE->getDecl()))
3745 if (auto *E = BD->getBinding())
3746 return E->refersToVectorElement();
3747
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003748 return false;
3749}
3750
Andrey Bokhankod9eab9c2015-08-03 10:38:10 +00003751bool Expr::refersToGlobalRegisterVar() const {
3752 const Expr *E = this->IgnoreParenImpCasts();
3753
3754 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
3755 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
3756 if (VD->getStorageClass() == SC_Register &&
3757 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
3758 return true;
3759
3760 return false;
3761}
3762
Chris Lattnerb8211f62009-02-16 22:14:05 +00003763/// isArrow - Return true if the base expression is a pointer to vector,
3764/// return false if the base expression is a vector.
3765bool ExtVectorElementExpr::isArrow() const {
3766 return getBase()->getType()->isPointerType();
3767}
3768
Nate Begemance4d7fc2008-04-18 23:10:10 +00003769unsigned ExtVectorElementExpr::getNumElements() const {
John McCall9dd450b2009-09-21 23:43:11 +00003770 if (const VectorType *VT = getType()->getAs<VectorType>())
Nate Begemanf322eab2008-05-09 06:41:27 +00003771 return VT->getNumElements();
3772 return 1;
Chris Lattner177bd452007-08-03 16:00:20 +00003773}
3774
Nate Begemanf322eab2008-05-09 06:41:27 +00003775/// containsDuplicateElements - Return true if any element access is repeated.
Nate Begemance4d7fc2008-04-18 23:10:10 +00003776bool ExtVectorElementExpr::containsDuplicateElements() const {
Daniel Dunbarcb2a0562009-10-18 02:09:09 +00003777 // FIXME: Refactor this code to an accessor on the AST node which returns the
3778 // "type" of component access, and share with code below and in Sema.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003779 StringRef Comp = Accessor->getName();
Nate Begeman7e5185b2009-01-18 02:01:21 +00003780
3781 // Halving swizzles do not contain duplicate elements.
Daniel Dunbar125c9c92009-10-17 23:53:04 +00003782 if (Comp == "hi" || Comp == "lo" || Comp == "even" || Comp == "odd")
Nate Begeman7e5185b2009-01-18 02:01:21 +00003783 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003784
Nate Begeman7e5185b2009-01-18 02:01:21 +00003785 // Advance past s-char prefix on hex swizzles.
Daniel Dunbar125c9c92009-10-17 23:53:04 +00003786 if (Comp[0] == 's' || Comp[0] == 'S')
3787 Comp = Comp.substr(1);
Mike Stump11289f42009-09-09 15:08:12 +00003788
Daniel Dunbar125c9c92009-10-17 23:53:04 +00003789 for (unsigned i = 0, e = Comp.size(); i != e; ++i)
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003790 if (Comp.substr(i + 1).find(Comp[i]) != StringRef::npos)
Steve Naroff0d595ca2007-07-30 03:29:09 +00003791 return true;
Daniel Dunbar125c9c92009-10-17 23:53:04 +00003792
Steve Naroff0d595ca2007-07-30 03:29:09 +00003793 return false;
3794}
Chris Lattner885b4952007-08-02 23:36:59 +00003795
Nate Begemanf322eab2008-05-09 06:41:27 +00003796/// getEncodedElementAccess - We encode the fields as a llvm ConstantArray.
Nate Begemand3862152008-05-13 21:03:02 +00003797void ExtVectorElementExpr::getEncodedElementAccess(
Benjamin Kramer99383102015-07-28 16:25:32 +00003798 SmallVectorImpl<uint32_t> &Elts) const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003799 StringRef Comp = Accessor->getName();
Pirama Arumuga Nainar98eaa622016-07-22 18:49:43 +00003800 bool isNumericAccessor = false;
3801 if (Comp[0] == 's' || Comp[0] == 'S') {
Daniel Dunbarce5a0b32009-10-18 02:09:31 +00003802 Comp = Comp.substr(1);
Pirama Arumuga Nainar98eaa622016-07-22 18:49:43 +00003803 isNumericAccessor = true;
3804 }
Mike Stump11289f42009-09-09 15:08:12 +00003805
Daniel Dunbarce5a0b32009-10-18 02:09:31 +00003806 bool isHi = Comp == "hi";
3807 bool isLo = Comp == "lo";
3808 bool isEven = Comp == "even";
3809 bool isOdd = Comp == "odd";
Mike Stump11289f42009-09-09 15:08:12 +00003810
Nate Begemanf322eab2008-05-09 06:41:27 +00003811 for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
3812 uint64_t Index;
Mike Stump11289f42009-09-09 15:08:12 +00003813
Nate Begemanf322eab2008-05-09 06:41:27 +00003814 if (isHi)
3815 Index = e + i;
3816 else if (isLo)
3817 Index = i;
3818 else if (isEven)
3819 Index = 2 * i;
3820 else if (isOdd)
3821 Index = 2 * i + 1;
3822 else
Pirama Arumuga Nainar98eaa622016-07-22 18:49:43 +00003823 Index = ExtVectorType::getAccessorIdx(Comp[i], isNumericAccessor);
Chris Lattner885b4952007-08-02 23:36:59 +00003824
Nate Begemand3862152008-05-13 21:03:02 +00003825 Elts.push_back(Index);
Chris Lattner885b4952007-08-02 23:36:59 +00003826 }
Nate Begemanf322eab2008-05-09 06:41:27 +00003827}
3828
Craig Topper37932912013-08-18 10:09:15 +00003829ShuffleVectorExpr::ShuffleVectorExpr(const ASTContext &C, ArrayRef<Expr*> args,
Douglas Gregora6e053e2010-12-15 01:34:56 +00003830 QualType Type, SourceLocation BLoc,
Fangrui Song6907ce22018-07-30 19:24:48 +00003831 SourceLocation RP)
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003832 : Expr(ShuffleVectorExprClass, Type, VK_RValue, OK_Ordinary,
3833 Type->isDependentType(), Type->isDependentType(),
3834 Type->isInstantiationDependentType(),
3835 Type->containsUnexpandedParameterPack()),
3836 BuiltinLoc(BLoc), RParenLoc(RP), NumExprs(args.size())
3837{
Benjamin Kramerc215e762012-08-24 11:54:20 +00003838 SubExprs = new (C) Stmt*[args.size()];
3839 for (unsigned i = 0; i != args.size(); i++) {
Douglas Gregora6e053e2010-12-15 01:34:56 +00003840 if (args[i]->isTypeDependent())
3841 ExprBits.TypeDependent = true;
3842 if (args[i]->isValueDependent())
3843 ExprBits.ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003844 if (args[i]->isInstantiationDependent())
3845 ExprBits.InstantiationDependent = true;
Douglas Gregora6e053e2010-12-15 01:34:56 +00003846 if (args[i]->containsUnexpandedParameterPack())
3847 ExprBits.ContainsUnexpandedParameterPack = true;
3848
3849 SubExprs[i] = args[i];
3850 }
3851}
3852
Craig Topper37932912013-08-18 10:09:15 +00003853void ShuffleVectorExpr::setExprs(const ASTContext &C, ArrayRef<Expr *> Exprs) {
Nate Begeman48745922009-08-12 02:28:50 +00003854 if (SubExprs) C.Deallocate(SubExprs);
3855
Dmitri Gribenko674eaa22013-05-10 00:43:44 +00003856 this->NumExprs = Exprs.size();
Dmitri Gribenko48d6daf2013-05-10 17:30:13 +00003857 SubExprs = new (C) Stmt*[NumExprs];
Dmitri Gribenko674eaa22013-05-10 00:43:44 +00003858 memcpy(SubExprs, Exprs.data(), sizeof(Expr *) * Exprs.size());
Mike Stump11289f42009-09-09 15:08:12 +00003859}
Nate Begeman48745922009-08-12 02:28:50 +00003860
Bruno Ricci94498c72019-01-26 13:58:15 +00003861GenericSelectionExpr::GenericSelectionExpr(
Bruno Riccidb076832019-01-26 14:15:10 +00003862 const ASTContext &, SourceLocation GenericLoc, Expr *ControllingExpr,
Bruno Ricci94498c72019-01-26 13:58:15 +00003863 ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
3864 SourceLocation DefaultLoc, SourceLocation RParenLoc,
3865 bool ContainsUnexpandedParameterPack, unsigned ResultIndex)
3866 : Expr(GenericSelectionExprClass, AssocExprs[ResultIndex]->getType(),
3867 AssocExprs[ResultIndex]->getValueKind(),
3868 AssocExprs[ResultIndex]->getObjectKind(),
3869 AssocExprs[ResultIndex]->isTypeDependent(),
3870 AssocExprs[ResultIndex]->isValueDependent(),
3871 AssocExprs[ResultIndex]->isInstantiationDependent(),
3872 ContainsUnexpandedParameterPack),
3873 NumAssocs(AssocExprs.size()), ResultIndex(ResultIndex),
Bruno Riccidb076832019-01-26 14:15:10 +00003874 DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
Bruno Ricci94498c72019-01-26 13:58:15 +00003875 assert(AssocTypes.size() == AssocExprs.size() &&
3876 "Must have the same number of association expressions"
3877 " and TypeSourceInfo!");
3878 assert(ResultIndex < NumAssocs && "ResultIndex is out-of-bounds!");
3879
Bruno Riccidb076832019-01-26 14:15:10 +00003880 GenericSelectionExprBits.GenericLoc = GenericLoc;
3881 getTrailingObjects<Stmt *>()[ControllingIndex] = ControllingExpr;
Bruno Ricci94498c72019-01-26 13:58:15 +00003882 std::copy(AssocExprs.begin(), AssocExprs.end(),
Bruno Riccidb076832019-01-26 14:15:10 +00003883 getTrailingObjects<Stmt *>() + AssocExprStartIndex);
3884 std::copy(AssocTypes.begin(), AssocTypes.end(),
3885 getTrailingObjects<TypeSourceInfo *>());
Peter Collingbourne91147592011-04-15 00:35:48 +00003886}
3887
Bruno Ricci94498c72019-01-26 13:58:15 +00003888GenericSelectionExpr::GenericSelectionExpr(
3889 const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,
3890 ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
3891 SourceLocation DefaultLoc, SourceLocation RParenLoc,
3892 bool ContainsUnexpandedParameterPack)
3893 : Expr(GenericSelectionExprClass, Context.DependentTy, VK_RValue,
3894 OK_Ordinary,
3895 /*isTypeDependent=*/true,
3896 /*isValueDependent=*/true,
3897 /*isInstantiationDependent=*/true, ContainsUnexpandedParameterPack),
3898 NumAssocs(AssocExprs.size()), ResultIndex(ResultDependentIndex),
Bruno Riccidb076832019-01-26 14:15:10 +00003899 DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
Bruno Ricci94498c72019-01-26 13:58:15 +00003900 assert(AssocTypes.size() == AssocExprs.size() &&
3901 "Must have the same number of association expressions"
3902 " and TypeSourceInfo!");
3903
Bruno Riccidb076832019-01-26 14:15:10 +00003904 GenericSelectionExprBits.GenericLoc = GenericLoc;
3905 getTrailingObjects<Stmt *>()[ControllingIndex] = ControllingExpr;
Bruno Ricci94498c72019-01-26 13:58:15 +00003906 std::copy(AssocExprs.begin(), AssocExprs.end(),
Bruno Riccidb076832019-01-26 14:15:10 +00003907 getTrailingObjects<Stmt *>() + AssocExprStartIndex);
3908 std::copy(AssocTypes.begin(), AssocTypes.end(),
3909 getTrailingObjects<TypeSourceInfo *>());
3910}
3911
3912GenericSelectionExpr::GenericSelectionExpr(EmptyShell Empty, unsigned NumAssocs)
3913 : Expr(GenericSelectionExprClass, Empty), NumAssocs(NumAssocs) {}
3914
3915GenericSelectionExpr *GenericSelectionExpr::Create(
3916 const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,
3917 ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
3918 SourceLocation DefaultLoc, SourceLocation RParenLoc,
3919 bool ContainsUnexpandedParameterPack, unsigned ResultIndex) {
3920 unsigned NumAssocs = AssocExprs.size();
3921 void *Mem = Context.Allocate(
3922 totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
3923 alignof(GenericSelectionExpr));
3924 return new (Mem) GenericSelectionExpr(
3925 Context, GenericLoc, ControllingExpr, AssocTypes, AssocExprs, DefaultLoc,
3926 RParenLoc, ContainsUnexpandedParameterPack, ResultIndex);
3927}
3928
3929GenericSelectionExpr *GenericSelectionExpr::Create(
3930 const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,
3931 ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
3932 SourceLocation DefaultLoc, SourceLocation RParenLoc,
3933 bool ContainsUnexpandedParameterPack) {
3934 unsigned NumAssocs = AssocExprs.size();
3935 void *Mem = Context.Allocate(
3936 totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
3937 alignof(GenericSelectionExpr));
3938 return new (Mem) GenericSelectionExpr(
3939 Context, GenericLoc, ControllingExpr, AssocTypes, AssocExprs, DefaultLoc,
3940 RParenLoc, ContainsUnexpandedParameterPack);
3941}
3942
3943GenericSelectionExpr *
3944GenericSelectionExpr::CreateEmpty(const ASTContext &Context,
3945 unsigned NumAssocs) {
3946 void *Mem = Context.Allocate(
3947 totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
3948 alignof(GenericSelectionExpr));
3949 return new (Mem) GenericSelectionExpr(EmptyShell(), NumAssocs);
Peter Collingbourne91147592011-04-15 00:35:48 +00003950}
3951
Ted Kremenek85e92ec2007-08-24 18:13:47 +00003952//===----------------------------------------------------------------------===//
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003953// DesignatedInitExpr
3954//===----------------------------------------------------------------------===//
3955
Chandler Carruth631abd92011-06-16 06:47:06 +00003956IdentifierInfo *DesignatedInitExpr::Designator::getFieldName() const {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003957 assert(Kind == FieldDesignator && "Only valid on a field designator");
3958 if (Field.NameOrField & 0x01)
3959 return reinterpret_cast<IdentifierInfo *>(Field.NameOrField&~0x01);
3960 else
3961 return getField()->getIdentifier();
3962}
3963
Craig Topper37932912013-08-18 10:09:15 +00003964DesignatedInitExpr::DesignatedInitExpr(const ASTContext &C, QualType Ty,
David Majnemerf7e36092016-06-23 00:15:04 +00003965 llvm::ArrayRef<Designator> Designators,
Mike Stump11289f42009-09-09 15:08:12 +00003966 SourceLocation EqualOrColonLoc,
Douglas Gregord5846a12009-04-15 06:41:24 +00003967 bool GNUSyntax,
Benjamin Kramerc215e762012-08-24 11:54:20 +00003968 ArrayRef<Expr*> IndexExprs,
Douglas Gregorca1aeec2009-05-21 23:17:49 +00003969 Expr *Init)
Mike Stump11289f42009-09-09 15:08:12 +00003970 : Expr(DesignatedInitExprClass, Ty,
John McCall7decc9e2010-11-18 06:31:45 +00003971 Init->getValueKind(), Init->getObjectKind(),
Douglas Gregora6e053e2010-12-15 01:34:56 +00003972 Init->isTypeDependent(), Init->isValueDependent(),
Douglas Gregor678d76c2011-07-01 01:22:09 +00003973 Init->isInstantiationDependent(),
Douglas Gregora6e053e2010-12-15 01:34:56 +00003974 Init->containsUnexpandedParameterPack()),
Mike Stump11289f42009-09-09 15:08:12 +00003975 EqualOrColonLoc(EqualOrColonLoc), GNUSyntax(GNUSyntax),
David Majnemerf7e36092016-06-23 00:15:04 +00003976 NumDesignators(Designators.size()), NumSubExprs(IndexExprs.size() + 1) {
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00003977 this->Designators = new (C) Designator[NumDesignators];
Douglas Gregorca1aeec2009-05-21 23:17:49 +00003978
3979 // Record the initializer itself.
Benjamin Kramer5733e352015-07-18 17:09:36 +00003980 child_iterator Child = child_begin();
Douglas Gregorca1aeec2009-05-21 23:17:49 +00003981 *Child++ = Init;
3982
3983 // Copy the designators and their subexpressions, computing
3984 // value-dependence along the way.
3985 unsigned IndexIdx = 0;
3986 for (unsigned I = 0; I != NumDesignators; ++I) {
Douglas Gregord5846a12009-04-15 06:41:24 +00003987 this->Designators[I] = Designators[I];
Douglas Gregorca1aeec2009-05-21 23:17:49 +00003988
3989 if (this->Designators[I].isArrayDesignator()) {
3990 // Compute type- and value-dependence.
3991 Expr *Index = IndexExprs[IndexIdx];
Douglas Gregora6e053e2010-12-15 01:34:56 +00003992 if (Index->isTypeDependent() || Index->isValueDependent())
David Majnemer4f217682015-01-09 01:39:09 +00003993 ExprBits.TypeDependent = ExprBits.ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003994 if (Index->isInstantiationDependent())
3995 ExprBits.InstantiationDependent = true;
Douglas Gregora6e053e2010-12-15 01:34:56 +00003996 // Propagate unexpanded parameter packs.
3997 if (Index->containsUnexpandedParameterPack())
3998 ExprBits.ContainsUnexpandedParameterPack = true;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00003999
4000 // Copy the index expressions into permanent storage.
4001 *Child++ = IndexExprs[IndexIdx++];
4002 } else if (this->Designators[I].isArrayRangeDesignator()) {
4003 // Compute type- and value-dependence.
4004 Expr *Start = IndexExprs[IndexIdx];
4005 Expr *End = IndexExprs[IndexIdx + 1];
Douglas Gregora6e053e2010-12-15 01:34:56 +00004006 if (Start->isTypeDependent() || Start->isValueDependent() ||
Douglas Gregor678d76c2011-07-01 01:22:09 +00004007 End->isTypeDependent() || End->isValueDependent()) {
David Majnemer4f217682015-01-09 01:39:09 +00004008 ExprBits.TypeDependent = ExprBits.ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +00004009 ExprBits.InstantiationDependent = true;
Fangrui Song6907ce22018-07-30 19:24:48 +00004010 } else if (Start->isInstantiationDependent() ||
Douglas Gregor678d76c2011-07-01 01:22:09 +00004011 End->isInstantiationDependent()) {
4012 ExprBits.InstantiationDependent = true;
4013 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004014
Douglas Gregora6e053e2010-12-15 01:34:56 +00004015 // Propagate unexpanded parameter packs.
4016 if (Start->containsUnexpandedParameterPack() ||
4017 End->containsUnexpandedParameterPack())
4018 ExprBits.ContainsUnexpandedParameterPack = true;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00004019
4020 // Copy the start/end expressions into permanent storage.
4021 *Child++ = IndexExprs[IndexIdx++];
4022 *Child++ = IndexExprs[IndexIdx++];
4023 }
4024 }
4025
Benjamin Kramerc215e762012-08-24 11:54:20 +00004026 assert(IndexIdx == IndexExprs.size() && "Wrong number of index expressions");
Douglas Gregord5846a12009-04-15 06:41:24 +00004027}
4028
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004029DesignatedInitExpr *
David Majnemerf7e36092016-06-23 00:15:04 +00004030DesignatedInitExpr::Create(const ASTContext &C,
4031 llvm::ArrayRef<Designator> Designators,
Benjamin Kramerc215e762012-08-24 11:54:20 +00004032 ArrayRef<Expr*> IndexExprs,
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004033 SourceLocation ColonOrEqualLoc,
4034 bool UsesColonSyntax, Expr *Init) {
James Y Knighte00a67e2015-12-31 04:18:25 +00004035 void *Mem = C.Allocate(totalSizeToAlloc<Stmt *>(IndexExprs.size() + 1),
Benjamin Kramerc3f89252016-10-20 14:27:22 +00004036 alignof(DesignatedInitExpr));
David Majnemerf7e36092016-06-23 00:15:04 +00004037 return new (Mem) DesignatedInitExpr(C, C.VoidTy, Designators,
Douglas Gregorca1aeec2009-05-21 23:17:49 +00004038 ColonOrEqualLoc, UsesColonSyntax,
Benjamin Kramerc215e762012-08-24 11:54:20 +00004039 IndexExprs, Init);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004040}
4041
Craig Topper37932912013-08-18 10:09:15 +00004042DesignatedInitExpr *DesignatedInitExpr::CreateEmpty(const ASTContext &C,
Douglas Gregor38676d52009-04-16 00:55:48 +00004043 unsigned NumIndexExprs) {
James Y Knighte00a67e2015-12-31 04:18:25 +00004044 void *Mem = C.Allocate(totalSizeToAlloc<Stmt *>(NumIndexExprs + 1),
Benjamin Kramerc3f89252016-10-20 14:27:22 +00004045 alignof(DesignatedInitExpr));
Douglas Gregor38676d52009-04-16 00:55:48 +00004046 return new (Mem) DesignatedInitExpr(NumIndexExprs + 1);
4047}
4048
Craig Topper37932912013-08-18 10:09:15 +00004049void DesignatedInitExpr::setDesignators(const ASTContext &C,
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00004050 const Designator *Desigs,
Douglas Gregor38676d52009-04-16 00:55:48 +00004051 unsigned NumDesigs) {
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00004052 Designators = new (C) Designator[NumDesigs];
Douglas Gregor38676d52009-04-16 00:55:48 +00004053 NumDesignators = NumDesigs;
4054 for (unsigned I = 0; I != NumDesigs; ++I)
4055 Designators[I] = Desigs[I];
4056}
4057
Abramo Bagnara22f8cd72011-03-16 15:08:46 +00004058SourceRange DesignatedInitExpr::getDesignatorsSourceRange() const {
4059 DesignatedInitExpr *DIE = const_cast<DesignatedInitExpr*>(this);
4060 if (size() == 1)
4061 return DIE->getDesignator(0)->getSourceRange();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004062 return SourceRange(DIE->getDesignator(0)->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00004063 DIE->getDesignator(size() - 1)->getEndLoc());
Abramo Bagnara22f8cd72011-03-16 15:08:46 +00004064}
4065
Stephen Kelly724e9e52018-08-09 20:05:03 +00004066SourceLocation DesignatedInitExpr::getBeginLoc() const {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004067 SourceLocation StartLoc;
David Majnemerf7e36092016-06-23 00:15:04 +00004068 auto *DIE = const_cast<DesignatedInitExpr *>(this);
4069 Designator &First = *DIE->getDesignator(0);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004070 if (First.isFieldDesignator()) {
Douglas Gregor5c7c9cb2009-03-28 00:41:23 +00004071 if (GNUSyntax)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004072 StartLoc = SourceLocation::getFromRawEncoding(First.Field.FieldLoc);
4073 else
4074 StartLoc = SourceLocation::getFromRawEncoding(First.Field.DotLoc);
4075 } else
Chris Lattner8ba22472009-02-16 22:33:34 +00004076 StartLoc =
4077 SourceLocation::getFromRawEncoding(First.ArrayOrRange.LBracketLoc);
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00004078 return StartLoc;
4079}
4080
Stephen Kelly02a67ba2018-08-09 20:05:47 +00004081SourceLocation DesignatedInitExpr::getEndLoc() const {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00004082 return getInit()->getEndLoc();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004083}
4084
Dmitri Gribenkod06f7ff2013-01-26 15:15:52 +00004085Expr *DesignatedInitExpr::getArrayIndex(const Designator& D) const {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004086 assert(D.Kind == Designator::ArrayDesignator && "Requires array designator");
James Y Knighte00a67e2015-12-31 04:18:25 +00004087 return getSubExpr(D.ArrayOrRange.Index + 1);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004088}
4089
Dmitri Gribenkod06f7ff2013-01-26 15:15:52 +00004090Expr *DesignatedInitExpr::getArrayRangeStart(const Designator &D) const {
Mike Stump11289f42009-09-09 15:08:12 +00004091 assert(D.Kind == Designator::ArrayRangeDesignator &&
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004092 "Requires array range designator");
James Y Knighte00a67e2015-12-31 04:18:25 +00004093 return getSubExpr(D.ArrayOrRange.Index + 1);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004094}
4095
Dmitri Gribenkod06f7ff2013-01-26 15:15:52 +00004096Expr *DesignatedInitExpr::getArrayRangeEnd(const Designator &D) const {
Mike Stump11289f42009-09-09 15:08:12 +00004097 assert(D.Kind == Designator::ArrayRangeDesignator &&
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004098 "Requires array range designator");
James Y Knighte00a67e2015-12-31 04:18:25 +00004099 return getSubExpr(D.ArrayOrRange.Index + 2);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004100}
4101
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004102/// Replaces the designator at index @p Idx with the series
Douglas Gregord5846a12009-04-15 06:41:24 +00004103/// of designators in [First, Last).
Craig Topper37932912013-08-18 10:09:15 +00004104void DesignatedInitExpr::ExpandDesignator(const ASTContext &C, unsigned Idx,
Mike Stump11289f42009-09-09 15:08:12 +00004105 const Designator *First,
Douglas Gregord5846a12009-04-15 06:41:24 +00004106 const Designator *Last) {
4107 unsigned NumNewDesignators = Last - First;
4108 if (NumNewDesignators == 0) {
4109 std::copy_backward(Designators + Idx + 1,
4110 Designators + NumDesignators,
4111 Designators + Idx);
4112 --NumNewDesignators;
4113 return;
4114 } else if (NumNewDesignators == 1) {
4115 Designators[Idx] = *First;
4116 return;
4117 }
4118
Mike Stump11289f42009-09-09 15:08:12 +00004119 Designator *NewDesignators
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00004120 = new (C) Designator[NumDesignators - 1 + NumNewDesignators];
Douglas Gregord5846a12009-04-15 06:41:24 +00004121 std::copy(Designators, Designators + Idx, NewDesignators);
4122 std::copy(First, Last, NewDesignators + Idx);
4123 std::copy(Designators + Idx + 1, Designators + NumDesignators,
4124 NewDesignators + Idx + NumNewDesignators);
Douglas Gregord5846a12009-04-15 06:41:24 +00004125 Designators = NewDesignators;
4126 NumDesignators = NumDesignators - 1 + NumNewDesignators;
4127}
4128
Yunzhong Gaocb779302015-06-10 00:27:52 +00004129DesignatedInitUpdateExpr::DesignatedInitUpdateExpr(const ASTContext &C,
4130 SourceLocation lBraceLoc, Expr *baseExpr, SourceLocation rBraceLoc)
4131 : Expr(DesignatedInitUpdateExprClass, baseExpr->getType(), VK_RValue,
4132 OK_Ordinary, false, false, false, false) {
4133 BaseAndUpdaterExprs[0] = baseExpr;
4134
4135 InitListExpr *ILE = new (C) InitListExpr(C, lBraceLoc, None, rBraceLoc);
4136 ILE->setType(baseExpr->getType());
4137 BaseAndUpdaterExprs[1] = ILE;
4138}
4139
Stephen Kelly724e9e52018-08-09 20:05:03 +00004140SourceLocation DesignatedInitUpdateExpr::getBeginLoc() const {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004141 return getBase()->getBeginLoc();
Yunzhong Gaocb779302015-06-10 00:27:52 +00004142}
4143
Stephen Kelly02a67ba2018-08-09 20:05:47 +00004144SourceLocation DesignatedInitUpdateExpr::getEndLoc() const {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00004145 return getBase()->getEndLoc();
Yunzhong Gaocb779302015-06-10 00:27:52 +00004146}
4147
Bruno Riccif49e1ca2018-11-20 16:20:40 +00004148ParenListExpr::ParenListExpr(SourceLocation LParenLoc, ArrayRef<Expr *> Exprs,
4149 SourceLocation RParenLoc)
4150 : Expr(ParenListExprClass, QualType(), VK_RValue, OK_Ordinary, false, false,
4151 false, false),
4152 LParenLoc(LParenLoc), RParenLoc(RParenLoc) {
4153 ParenListExprBits.NumExprs = Exprs.size();
4154
4155 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
4156 if (Exprs[I]->isTypeDependent())
Douglas Gregora6e053e2010-12-15 01:34:56 +00004157 ExprBits.TypeDependent = true;
Bruno Riccif49e1ca2018-11-20 16:20:40 +00004158 if (Exprs[I]->isValueDependent())
Douglas Gregora6e053e2010-12-15 01:34:56 +00004159 ExprBits.ValueDependent = true;
Bruno Riccif49e1ca2018-11-20 16:20:40 +00004160 if (Exprs[I]->isInstantiationDependent())
Douglas Gregor678d76c2011-07-01 01:22:09 +00004161 ExprBits.InstantiationDependent = true;
Bruno Riccif49e1ca2018-11-20 16:20:40 +00004162 if (Exprs[I]->containsUnexpandedParameterPack())
Douglas Gregora6e053e2010-12-15 01:34:56 +00004163 ExprBits.ContainsUnexpandedParameterPack = true;
4164
Bruno Riccif49e1ca2018-11-20 16:20:40 +00004165 getTrailingObjects<Stmt *>()[I] = Exprs[I];
Douglas Gregora6e053e2010-12-15 01:34:56 +00004166 }
Nate Begeman5ec4b312009-08-10 23:49:36 +00004167}
4168
Bruno Riccif49e1ca2018-11-20 16:20:40 +00004169ParenListExpr::ParenListExpr(EmptyShell Empty, unsigned NumExprs)
4170 : Expr(ParenListExprClass, Empty) {
4171 ParenListExprBits.NumExprs = NumExprs;
4172}
4173
4174ParenListExpr *ParenListExpr::Create(const ASTContext &Ctx,
4175 SourceLocation LParenLoc,
4176 ArrayRef<Expr *> Exprs,
4177 SourceLocation RParenLoc) {
4178 void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *>(Exprs.size()),
4179 alignof(ParenListExpr));
4180 return new (Mem) ParenListExpr(LParenLoc, Exprs, RParenLoc);
4181}
4182
4183ParenListExpr *ParenListExpr::CreateEmpty(const ASTContext &Ctx,
4184 unsigned NumExprs) {
4185 void *Mem =
4186 Ctx.Allocate(totalSizeToAlloc<Stmt *>(NumExprs), alignof(ParenListExpr));
4187 return new (Mem) ParenListExpr(EmptyShell(), NumExprs);
4188}
4189
John McCall1bf58462011-02-16 08:02:54 +00004190const OpaqueValueExpr *OpaqueValueExpr::findInCopyConstruct(const Expr *e) {
4191 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(e))
4192 e = ewc->getSubExpr();
Douglas Gregorfe314812011-06-21 17:03:29 +00004193 if (const MaterializeTemporaryExpr *m = dyn_cast<MaterializeTemporaryExpr>(e))
4194 e = m->GetTemporaryExpr();
John McCall1bf58462011-02-16 08:02:54 +00004195 e = cast<CXXConstructExpr>(e)->getArg(0);
4196 while (const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
4197 e = ice->getSubExpr();
4198 return cast<OpaqueValueExpr>(e);
4199}
4200
Craig Topper37932912013-08-18 10:09:15 +00004201PseudoObjectExpr *PseudoObjectExpr::Create(const ASTContext &Context,
4202 EmptyShell sh,
John McCallfe96e0b2011-11-06 09:01:30 +00004203 unsigned numSemanticExprs) {
James Y Knighte00a67e2015-12-31 04:18:25 +00004204 void *buffer =
4205 Context.Allocate(totalSizeToAlloc<Expr *>(1 + numSemanticExprs),
Benjamin Kramerc3f89252016-10-20 14:27:22 +00004206 alignof(PseudoObjectExpr));
John McCallfe96e0b2011-11-06 09:01:30 +00004207 return new(buffer) PseudoObjectExpr(sh, numSemanticExprs);
4208}
4209
4210PseudoObjectExpr::PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs)
4211 : Expr(PseudoObjectExprClass, shell) {
4212 PseudoObjectExprBits.NumSubExprs = numSemanticExprs + 1;
4213}
4214
Craig Topper37932912013-08-18 10:09:15 +00004215PseudoObjectExpr *PseudoObjectExpr::Create(const ASTContext &C, Expr *syntax,
John McCallfe96e0b2011-11-06 09:01:30 +00004216 ArrayRef<Expr*> semantics,
4217 unsigned resultIndex) {
4218 assert(syntax && "no syntactic expression!");
Eugene Zelenkoae304b02017-11-17 18:09:48 +00004219 assert(semantics.size() && "no semantic expressions!");
John McCallfe96e0b2011-11-06 09:01:30 +00004220
4221 QualType type;
4222 ExprValueKind VK;
4223 if (resultIndex == NoResult) {
4224 type = C.VoidTy;
4225 VK = VK_RValue;
4226 } else {
4227 assert(resultIndex < semantics.size());
4228 type = semantics[resultIndex]->getType();
4229 VK = semantics[resultIndex]->getValueKind();
4230 assert(semantics[resultIndex]->getObjectKind() == OK_Ordinary);
4231 }
4232
James Y Knighte00a67e2015-12-31 04:18:25 +00004233 void *buffer = C.Allocate(totalSizeToAlloc<Expr *>(semantics.size() + 1),
Benjamin Kramerc3f89252016-10-20 14:27:22 +00004234 alignof(PseudoObjectExpr));
John McCallfe96e0b2011-11-06 09:01:30 +00004235 return new(buffer) PseudoObjectExpr(type, VK, syntax, semantics,
4236 resultIndex);
4237}
4238
4239PseudoObjectExpr::PseudoObjectExpr(QualType type, ExprValueKind VK,
4240 Expr *syntax, ArrayRef<Expr*> semantics,
4241 unsigned resultIndex)
4242 : Expr(PseudoObjectExprClass, type, VK, OK_Ordinary,
4243 /*filled in at end of ctor*/ false, false, false, false) {
4244 PseudoObjectExprBits.NumSubExprs = semantics.size() + 1;
4245 PseudoObjectExprBits.ResultIndex = resultIndex + 1;
4246
4247 for (unsigned i = 0, e = semantics.size() + 1; i != e; ++i) {
4248 Expr *E = (i == 0 ? syntax : semantics[i-1]);
4249 getSubExprsBuffer()[i] = E;
4250
4251 if (E->isTypeDependent())
4252 ExprBits.TypeDependent = true;
4253 if (E->isValueDependent())
4254 ExprBits.ValueDependent = true;
4255 if (E->isInstantiationDependent())
4256 ExprBits.InstantiationDependent = true;
4257 if (E->containsUnexpandedParameterPack())
4258 ExprBits.ContainsUnexpandedParameterPack = true;
4259
4260 if (isa<OpaqueValueExpr>(E))
Craig Topper36250ad2014-05-12 05:36:57 +00004261 assert(cast<OpaqueValueExpr>(E)->getSourceExpr() != nullptr &&
John McCallfe96e0b2011-11-06 09:01:30 +00004262 "opaque-value semantic expressions for pseudo-object "
4263 "operations must have sources");
4264 }
4265}
4266
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004267//===----------------------------------------------------------------------===//
Ted Kremenek85e92ec2007-08-24 18:13:47 +00004268// Child Iterators for iterating over subexpressions/substatements
4269//===----------------------------------------------------------------------===//
4270
Peter Collingbournee190dee2011-03-11 19:24:49 +00004271// UnaryExprOrTypeTraitExpr
4272Stmt::child_range UnaryExprOrTypeTraitExpr::children() {
Aaron Ballman4c54fe02017-04-11 20:21:30 +00004273 const_child_range CCR =
4274 const_cast<const UnaryExprOrTypeTraitExpr *>(this)->children();
4275 return child_range(cast_away_const(CCR.begin()), cast_away_const(CCR.end()));
4276}
4277
4278Stmt::const_child_range UnaryExprOrTypeTraitExpr::children() const {
Sebastian Redl6f282892008-11-11 17:56:53 +00004279 // If this is of a type and the type is a VLA type (and not a typedef), the
4280 // size expression of the VLA needs to be treated as an executable expression.
4281 // Why isn't this weirdness documented better in StmtIterator?
4282 if (isArgumentType()) {
Aaron Ballman4c54fe02017-04-11 20:21:30 +00004283 if (const VariableArrayType *T =
4284 dyn_cast<VariableArrayType>(getArgumentType().getTypePtr()))
4285 return const_child_range(const_child_iterator(T), const_child_iterator());
4286 return const_child_range(const_child_iterator(), const_child_iterator());
Sebastian Redl6f282892008-11-11 17:56:53 +00004287 }
Aaron Ballman4c54fe02017-04-11 20:21:30 +00004288 return const_child_range(&Argument.Ex, &Argument.Ex + 1);
Ted Kremenek04746ce2007-10-18 23:28:49 +00004289}
Fariborz Jahaniana32aaef2007-10-17 16:58:11 +00004290
Benjamin Kramerc215e762012-08-24 11:54:20 +00004291AtomicExpr::AtomicExpr(SourceLocation BLoc, ArrayRef<Expr*> args,
Eli Friedman8d3e43f2011-10-14 22:48:56 +00004292 QualType t, AtomicOp op, SourceLocation RP)
Eugene Zelenkoae304b02017-11-17 18:09:48 +00004293 : Expr(AtomicExprClass, t, VK_RValue, OK_Ordinary,
4294 false, false, false, false),
4295 NumSubExprs(args.size()), BuiltinLoc(BLoc), RParenLoc(RP), Op(op)
4296{
Benjamin Kramerc215e762012-08-24 11:54:20 +00004297 assert(args.size() == getNumSubExprs(op) && "wrong number of subexpressions");
4298 for (unsigned i = 0; i != args.size(); i++) {
Eli Friedman8d3e43f2011-10-14 22:48:56 +00004299 if (args[i]->isTypeDependent())
4300 ExprBits.TypeDependent = true;
4301 if (args[i]->isValueDependent())
4302 ExprBits.ValueDependent = true;
4303 if (args[i]->isInstantiationDependent())
4304 ExprBits.InstantiationDependent = true;
4305 if (args[i]->containsUnexpandedParameterPack())
4306 ExprBits.ContainsUnexpandedParameterPack = true;
4307
4308 SubExprs[i] = args[i];
4309 }
4310}
Richard Smithaa22a8c2012-04-10 22:49:28 +00004311
4312unsigned AtomicExpr::getNumSubExprs(AtomicOp Op) {
4313 switch (Op) {
Richard Smithfeea8832012-04-12 05:08:17 +00004314 case AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +00004315 case AO__opencl_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +00004316 case AO__c11_atomic_load:
Yaxun Liu39195062017-08-04 18:16:31 +00004317 case AO__atomic_load_n:
Yaxun Liu30d652a2017-08-15 16:02:49 +00004318 return 2;
Richard Smithfeea8832012-04-12 05:08:17 +00004319
Yaxun Liu30d652a2017-08-15 16:02:49 +00004320 case AO__opencl_atomic_load:
Richard Smithfeea8832012-04-12 05:08:17 +00004321 case AO__c11_atomic_store:
4322 case AO__c11_atomic_exchange:
4323 case AO__atomic_load:
4324 case AO__atomic_store:
4325 case AO__atomic_store_n:
4326 case AO__atomic_exchange_n:
4327 case AO__c11_atomic_fetch_add:
4328 case AO__c11_atomic_fetch_sub:
4329 case AO__c11_atomic_fetch_and:
4330 case AO__c11_atomic_fetch_or:
4331 case AO__c11_atomic_fetch_xor:
4332 case AO__atomic_fetch_add:
4333 case AO__atomic_fetch_sub:
4334 case AO__atomic_fetch_and:
4335 case AO__atomic_fetch_or:
4336 case AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00004337 case AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00004338 case AO__atomic_add_fetch:
4339 case AO__atomic_sub_fetch:
4340 case AO__atomic_and_fetch:
4341 case AO__atomic_or_fetch:
4342 case AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00004343 case AO__atomic_nand_fetch:
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00004344 case AO__atomic_fetch_min:
4345 case AO__atomic_fetch_max:
Yaxun Liu30d652a2017-08-15 16:02:49 +00004346 return 3;
Richard Smithfeea8832012-04-12 05:08:17 +00004347
Yaxun Liu30d652a2017-08-15 16:02:49 +00004348 case AO__opencl_atomic_store:
4349 case AO__opencl_atomic_exchange:
4350 case AO__opencl_atomic_fetch_add:
4351 case AO__opencl_atomic_fetch_sub:
4352 case AO__opencl_atomic_fetch_and:
4353 case AO__opencl_atomic_fetch_or:
4354 case AO__opencl_atomic_fetch_xor:
4355 case AO__opencl_atomic_fetch_min:
4356 case AO__opencl_atomic_fetch_max:
Richard Smithfeea8832012-04-12 05:08:17 +00004357 case AO__atomic_exchange:
Yaxun Liu30d652a2017-08-15 16:02:49 +00004358 return 4;
Richard Smithfeea8832012-04-12 05:08:17 +00004359
4360 case AO__c11_atomic_compare_exchange_strong:
4361 case AO__c11_atomic_compare_exchange_weak:
Yaxun Liu30d652a2017-08-15 16:02:49 +00004362 return 5;
4363
Yaxun Liu39195062017-08-04 18:16:31 +00004364 case AO__opencl_atomic_compare_exchange_strong:
4365 case AO__opencl_atomic_compare_exchange_weak:
Richard Smithfeea8832012-04-12 05:08:17 +00004366 case AO__atomic_compare_exchange:
4367 case AO__atomic_compare_exchange_n:
Yaxun Liu30d652a2017-08-15 16:02:49 +00004368 return 6;
Richard Smithaa22a8c2012-04-10 22:49:28 +00004369 }
4370 llvm_unreachable("unknown atomic op");
4371}
Alexey Bataeva1764212015-09-30 09:22:36 +00004372
Yaxun Liu39195062017-08-04 18:16:31 +00004373QualType AtomicExpr::getValueType() const {
4374 auto T = getPtr()->getType()->castAs<PointerType>()->getPointeeType();
4375 if (auto AT = T->getAs<AtomicType>())
4376 return AT->getValueType();
4377 return T;
4378}
4379
Alexey Bataev31300ed2016-02-04 11:27:03 +00004380QualType OMPArraySectionExpr::getBaseOriginalType(const Expr *Base) {
Alexey Bataeva1764212015-09-30 09:22:36 +00004381 unsigned ArraySectionCount = 0;
4382 while (auto *OASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParens())) {
4383 Base = OASE->getBase();
4384 ++ArraySectionCount;
4385 }
Alexey Bataev31300ed2016-02-04 11:27:03 +00004386 while (auto *ASE =
4387 dyn_cast<ArraySubscriptExpr>(Base->IgnoreParenImpCasts())) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004388 Base = ASE->getBase();
4389 ++ArraySectionCount;
4390 }
Alexey Bataev31300ed2016-02-04 11:27:03 +00004391 Base = Base->IgnoreParenImpCasts();
Alexey Bataeva1764212015-09-30 09:22:36 +00004392 auto OriginalTy = Base->getType();
4393 if (auto *DRE = dyn_cast<DeclRefExpr>(Base))
4394 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
4395 OriginalTy = PVD->getOriginalType().getNonReferenceType();
4396
4397 for (unsigned Cnt = 0; Cnt < ArraySectionCount; ++Cnt) {
4398 if (OriginalTy->isAnyPointerType())
4399 OriginalTy = OriginalTy->getPointeeType();
4400 else {
Eugene Zelenkoae304b02017-11-17 18:09:48 +00004401 assert (OriginalTy->isArrayType());
Alexey Bataeva1764212015-09-30 09:22:36 +00004402 OriginalTy = OriginalTy->castAsArrayTypeUnsafe()->getElementType();
4403 }
4404 }
4405 return OriginalTy;
4406}