blob: 4f7f807a84ed12395352dbebe2dd6fb60ba03801 [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//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner1b926492006-08-23 06:42:10 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expr class and subclasses.
11//
12//===----------------------------------------------------------------------===//
13
Chris Lattner5c4664e2007-07-15 23:32:58 +000014#include "clang/AST/ASTContext.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000015#include "clang/AST/Attr.h"
Douglas Gregor9a657932008-10-21 23:43:52 +000016#include "clang/AST/DeclCXX.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000018#include "clang/AST/DeclTemplate.h"
Douglas Gregor1be329d2012-02-23 07:33:15 +000019#include "clang/AST/EvaluatedExprVisitor.h"
Eugene Zelenkoae304b02017-11-17 18:09:48 +000020#include "clang/AST/Expr.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"
Eugene Zelenkoae304b02017-11-17 18:09:48 +000031#include "clang/Sema/SemaDiagnostic.h"
Douglas Gregor0840cc02009-11-01 20:32:48 +000032#include "llvm/Support/ErrorHandling.h"
Anders Carlsson2fb08242009-09-08 18:24:21 +000033#include "llvm/Support/raw_ostream.h"
Douglas Gregord5846a12009-04-15 06:41:24 +000034#include <algorithm>
Eli Friedmanfcec6302011-11-01 02:23:42 +000035#include <cstring>
Chris Lattner1b926492006-08-23 06:42:10 +000036using namespace clang;
37
Richard Smith018ac392016-11-03 18:55:18 +000038const Expr *Expr::getBestDynamicClassTypeExpr() const {
39 const Expr *E = this;
40 while (true) {
41 E = E->ignoreParenBaseCasts();
Rafael Espindola49e860b2012-06-26 17:45:31 +000042
Richard Smith018ac392016-11-03 18:55:18 +000043 // Follow the RHS of a comma operator.
44 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
45 if (BO->getOpcode() == BO_Comma) {
46 E = BO->getRHS();
47 continue;
48 }
49 }
50
51 // Step into initializer for materialized temporaries.
52 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
53 E = MTE->GetTemporaryExpr();
54 continue;
55 }
56
57 break;
58 }
59
60 return E;
61}
62
63const CXXRecordDecl *Expr::getBestDynamicClassType() const {
64 const Expr *E = getBestDynamicClassTypeExpr();
Rafael Espindola49e860b2012-06-26 17:45:31 +000065 QualType DerivedType = E->getType();
Rafael Espindola49e860b2012-06-26 17:45:31 +000066 if (const PointerType *PTy = DerivedType->getAs<PointerType>())
67 DerivedType = PTy->getPointeeType();
68
Rafael Espindola60a2bba2012-07-17 20:24:05 +000069 if (DerivedType->isDependentType())
Craig Topper36250ad2014-05-12 05:36:57 +000070 return nullptr;
Rafael Espindola60a2bba2012-07-17 20:24:05 +000071
Rafael Espindola49e860b2012-06-26 17:45:31 +000072 const RecordType *Ty = DerivedType->castAs<RecordType>();
Rafael Espindola49e860b2012-06-26 17:45:31 +000073 Decl *D = Ty->getDecl();
74 return cast<CXXRecordDecl>(D);
75}
76
Richard Smithf3fabd22013-06-03 00:17:11 +000077const Expr *Expr::skipRValueSubobjectAdjustments(
78 SmallVectorImpl<const Expr *> &CommaLHSs,
79 SmallVectorImpl<SubobjectAdjustment> &Adjustments) const {
Rafael Espindola9c006de2012-10-27 01:03:43 +000080 const Expr *E = this;
81 while (true) {
82 E = E->IgnoreParens();
83
84 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
85 if ((CE->getCastKind() == CK_DerivedToBase ||
86 CE->getCastKind() == CK_UncheckedDerivedToBase) &&
87 E->getType()->isRecordType()) {
88 E = CE->getSubExpr();
89 CXXRecordDecl *Derived
90 = cast<CXXRecordDecl>(E->getType()->getAs<RecordType>()->getDecl());
91 Adjustments.push_back(SubobjectAdjustment(CE, Derived));
92 continue;
93 }
94
95 if (CE->getCastKind() == CK_NoOp) {
96 E = CE->getSubExpr();
97 continue;
98 }
99 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
Richard Smith6b6f8aa2013-06-15 00:30:29 +0000100 if (!ME->isArrow()) {
Rafael Espindola9c006de2012-10-27 01:03:43 +0000101 assert(ME->getBase()->getType()->isRecordType());
102 if (FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
Richard Smith6b6f8aa2013-06-15 00:30:29 +0000103 if (!Field->isBitField() && !Field->getType()->isReferenceType()) {
Richard Smith2d187902013-06-03 07:13:35 +0000104 E = ME->getBase();
105 Adjustments.push_back(SubobjectAdjustment(Field));
106 continue;
107 }
Rafael Espindola9c006de2012-10-27 01:03:43 +0000108 }
109 }
110 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
Richard Smitha3fd1162018-07-24 21:18:30 +0000111 if (BO->getOpcode() == BO_PtrMemD) {
Rafael Espindola973aa202012-11-01 14:32:20 +0000112 assert(BO->getRHS()->isRValue());
Rafael Espindola9c006de2012-10-27 01:03:43 +0000113 E = BO->getLHS();
114 const MemberPointerType *MPT =
115 BO->getRHS()->getType()->getAs<MemberPointerType>();
116 Adjustments.push_back(SubobjectAdjustment(MPT, BO->getRHS()));
Richard Smithf3fabd22013-06-03 00:17:11 +0000117 continue;
118 } else if (BO->getOpcode() == BO_Comma) {
119 CommaLHSs.push_back(BO->getLHS());
120 E = BO->getRHS();
121 continue;
Rafael Espindola9c006de2012-10-27 01:03:43 +0000122 }
123 }
124
125 // Nothing changed.
126 break;
127 }
128 return E;
129}
130
Chris Lattner4ebae652010-04-16 23:34:13 +0000131/// isKnownToHaveBooleanValue - Return true if this is an integer expression
132/// that is known to return 0 or 1. This happens for _Bool/bool expressions
133/// but also int expressions which are produced by things like comparisons in
134/// C.
135bool Expr::isKnownToHaveBooleanValue() const {
Peter Collingbourne91147592011-04-15 00:35:48 +0000136 const Expr *E = IgnoreParens();
137
Chris Lattner4ebae652010-04-16 23:34:13 +0000138 // If this value has _Bool type, it is obvious 0/1.
Peter Collingbourne91147592011-04-15 00:35:48 +0000139 if (E->getType()->isBooleanType()) return true;
Fangrui Song6907ce22018-07-30 19:24:48 +0000140 // If this is a non-scalar-integer type, we don't care enough to try.
Peter Collingbourne91147592011-04-15 00:35:48 +0000141 if (!E->getType()->isIntegralOrEnumerationType()) return false;
Fangrui Song6907ce22018-07-30 19:24:48 +0000142
Peter Collingbourne91147592011-04-15 00:35:48 +0000143 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
Chris Lattner4ebae652010-04-16 23:34:13 +0000144 switch (UO->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +0000145 case UO_Plus:
Chris Lattner4ebae652010-04-16 23:34:13 +0000146 return UO->getSubExpr()->isKnownToHaveBooleanValue();
Richard Trieu0f097742014-04-04 04:13:47 +0000147 case UO_LNot:
148 return true;
Chris Lattner4ebae652010-04-16 23:34:13 +0000149 default:
150 return false;
151 }
152 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000153
John McCall45d30c32010-06-12 01:56:02 +0000154 // Only look through implicit casts. If the user writes
155 // '(int) (a && b)' treat it as an arbitrary int.
Peter Collingbourne91147592011-04-15 00:35:48 +0000156 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Chris Lattner4ebae652010-04-16 23:34:13 +0000157 return CE->getSubExpr()->isKnownToHaveBooleanValue();
Fangrui Song6907ce22018-07-30 19:24:48 +0000158
Peter Collingbourne91147592011-04-15 00:35:48 +0000159 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
Chris Lattner4ebae652010-04-16 23:34:13 +0000160 switch (BO->getOpcode()) {
161 default: return false;
John McCalle3027922010-08-25 11:45:40 +0000162 case BO_LT: // Relational operators.
163 case BO_GT:
164 case BO_LE:
165 case BO_GE:
166 case BO_EQ: // Equality operators.
167 case BO_NE:
168 case BO_LAnd: // AND operator.
169 case BO_LOr: // Logical OR operator.
Chris Lattner4ebae652010-04-16 23:34:13 +0000170 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +0000171
John McCalle3027922010-08-25 11:45:40 +0000172 case BO_And: // Bitwise AND operator.
173 case BO_Xor: // Bitwise XOR operator.
174 case BO_Or: // Bitwise OR operator.
Chris Lattner4ebae652010-04-16 23:34:13 +0000175 // Handle things like (x==2)|(y==12).
176 return BO->getLHS()->isKnownToHaveBooleanValue() &&
177 BO->getRHS()->isKnownToHaveBooleanValue();
Fangrui Song6907ce22018-07-30 19:24:48 +0000178
John McCalle3027922010-08-25 11:45:40 +0000179 case BO_Comma:
180 case BO_Assign:
Chris Lattner4ebae652010-04-16 23:34:13 +0000181 return BO->getRHS()->isKnownToHaveBooleanValue();
182 }
183 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000184
Peter Collingbourne91147592011-04-15 00:35:48 +0000185 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
Chris Lattner4ebae652010-04-16 23:34:13 +0000186 return CO->getTrueExpr()->isKnownToHaveBooleanValue() &&
187 CO->getFalseExpr()->isKnownToHaveBooleanValue();
Fangrui Song6907ce22018-07-30 19:24:48 +0000188
Chris Lattner4ebae652010-04-16 23:34:13 +0000189 return false;
190}
191
John McCallbd066782011-02-09 08:16:59 +0000192// Amusing macro metaprogramming hack: check whether a class provides
193// a more specific implementation of getExprLoc().
Daniel Dunbarb0ab5e92012-03-09 15:39:19 +0000194//
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000195// See also Stmt.cpp:{getBeginLoc(),getEndLoc()}.
Eugene Zelenkoae304b02017-11-17 18:09:48 +0000196namespace {
197 /// This implementation is used when a class provides a custom
198 /// implementation of getExprLoc.
199 template <class E, class T>
200 SourceLocation getExprLocImpl(const Expr *expr,
201 SourceLocation (T::*v)() const) {
202 return static_cast<const E*>(expr)->getExprLoc();
203 }
John McCallbd066782011-02-09 08:16:59 +0000204
Eugene Zelenkoae304b02017-11-17 18:09:48 +0000205 /// This implementation is used when a class doesn't provide
206 /// a custom implementation of getExprLoc. Overload resolution
207 /// should pick it over the implementation above because it's
208 /// more specialized according to function template partial ordering.
209 template <class E>
210 SourceLocation getExprLocImpl(const Expr *expr,
211 SourceLocation (Expr::*v)() const) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000212 return static_cast<const E *>(expr)->getBeginLoc();
Eugene Zelenkoae304b02017-11-17 18:09:48 +0000213 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000214}
John McCallbd066782011-02-09 08:16:59 +0000215
216SourceLocation Expr::getExprLoc() const {
217 switch (getStmtClass()) {
218 case Stmt::NoStmtClass: llvm_unreachable("statement without class");
219#define ABSTRACT_STMT(type)
220#define STMT(type, base) \
Richard Smitha0cbfc92014-07-26 00:47:13 +0000221 case Stmt::type##Class: break;
John McCallbd066782011-02-09 08:16:59 +0000222#define EXPR(type, base) \
223 case Stmt::type##Class: return getExprLocImpl<type>(this, &type::getExprLoc);
224#include "clang/AST/StmtNodes.inc"
225 }
Richard Smitha0cbfc92014-07-26 00:47:13 +0000226 llvm_unreachable("unknown expression kind");
John McCallbd066782011-02-09 08:16:59 +0000227}
228
Chris Lattner0eedafe2006-08-24 04:56:27 +0000229//===----------------------------------------------------------------------===//
230// Primary Expressions.
231//===----------------------------------------------------------------------===//
232
Fangrui Song6907ce22018-07-30 19:24:48 +0000233/// Compute the type-, value-, and instantiation-dependence of a
Douglas Gregor678d76c2011-07-01 01:22:09 +0000234/// declaration reference
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000235/// based on the declaration being referenced.
Craig Topperce7167c2013-08-22 04:58:56 +0000236static void computeDeclRefDependence(const ASTContext &Ctx, NamedDecl *D,
237 QualType T, bool &TypeDependent,
Douglas Gregor678d76c2011-07-01 01:22:09 +0000238 bool &ValueDependent,
239 bool &InstantiationDependent) {
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000240 TypeDependent = false;
241 ValueDependent = false;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000242 InstantiationDependent = false;
Douglas Gregored6c7442009-11-23 11:41:28 +0000243
244 // (TD) C++ [temp.dep.expr]p3:
245 // An id-expression is type-dependent if it contains:
246 //
Richard Smithcfaa5a32014-10-17 02:46:42 +0000247 // and
Douglas Gregored6c7442009-11-23 11:41:28 +0000248 //
249 // (VD) C++ [temp.dep.constexpr]p2:
250 // An identifier is value-dependent if it is:
Richard Smithcfaa5a32014-10-17 02:46:42 +0000251
Douglas Gregored6c7442009-11-23 11:41:28 +0000252 // (TD) - an identifier that was declared with dependent type
253 // (VD) - a name declared with a dependent type,
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000254 if (T->isDependentType()) {
255 TypeDependent = true;
256 ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000257 InstantiationDependent = true;
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000258 return;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000259 } else if (T->isInstantiationDependentType()) {
260 InstantiationDependent = true;
Douglas Gregored6c7442009-11-23 11:41:28 +0000261 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000262
Douglas Gregored6c7442009-11-23 11:41:28 +0000263 // (TD) - a conversion-function-id that specifies a dependent type
Fangrui Song6907ce22018-07-30 19:24:48 +0000264 if (D->getDeclName().getNameKind()
Douglas Gregor678d76c2011-07-01 01:22:09 +0000265 == DeclarationName::CXXConversionFunctionName) {
266 QualType T = D->getDeclName().getCXXNameType();
267 if (T->isDependentType()) {
268 TypeDependent = true;
269 ValueDependent = true;
270 InstantiationDependent = true;
271 return;
272 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000273
Douglas Gregor678d76c2011-07-01 01:22:09 +0000274 if (T->isInstantiationDependentType())
275 InstantiationDependent = true;
Douglas Gregored6c7442009-11-23 11:41:28 +0000276 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000277
Douglas Gregored6c7442009-11-23 11:41:28 +0000278 // (VD) - the name of a non-type template parameter,
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000279 if (isa<NonTypeTemplateParmDecl>(D)) {
280 ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000281 InstantiationDependent = true;
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000282 return;
283 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000284
Douglas Gregored6c7442009-11-23 11:41:28 +0000285 // (VD) - a constant with integral or enumeration type and is
286 // initialized with an expression that is value-dependent.
Richard Smithec8dcd22011-11-08 01:31:09 +0000287 // (VD) - a constant with literal type and is initialized with an
288 // expression that is value-dependent [C++11].
289 // (VD) - FIXME: Missing from the standard:
290 // - an entity with reference type and is initialized with an
291 // expression that is value-dependent [C++11]
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000292 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000293 if ((Ctx.getLangOpts().CPlusPlus11 ?
Richard Smithd9f663b2013-04-22 15:31:51 +0000294 Var->getType()->isLiteralType(Ctx) :
Richard Smithec8dcd22011-11-08 01:31:09 +0000295 Var->getType()->isIntegralOrEnumerationType()) &&
David Blaikief5697e52012-08-10 00:55:35 +0000296 (Var->getType().isConstQualified() ||
Richard Smithec8dcd22011-11-08 01:31:09 +0000297 Var->getType()->isReferenceType())) {
Sebastian Redl5ca79842010-02-01 20:16:42 +0000298 if (const Expr *Init = Var->getAnyInitializer())
Douglas Gregor678d76c2011-07-01 01:22:09 +0000299 if (Init->isValueDependent()) {
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000300 ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000301 InstantiationDependent = true;
302 }
Richard Smithec8dcd22011-11-08 01:31:09 +0000303 }
304
Fangrui Song6907ce22018-07-30 19:24:48 +0000305 // (VD) - FIXME: Missing from the standard:
306 // - a member function or a static data member of the current
Douglas Gregor0e4de762010-05-11 08:41:30 +0000307 // instantiation
Fangrui Song6907ce22018-07-30 19:24:48 +0000308 if (Var->isStaticDataMember() &&
Richard Smithec8dcd22011-11-08 01:31:09 +0000309 Var->getDeclContext()->isDependentContext()) {
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000310 ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000311 InstantiationDependent = true;
Richard Smith00f5d892013-11-14 22:40:45 +0000312 TypeSourceInfo *TInfo = Var->getFirstDecl()->getTypeSourceInfo();
313 if (TInfo->getType()->isIncompleteArrayType())
314 TypeDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000315 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000316
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000317 return;
318 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000319
320 // (VD) - FIXME: Missing from the standard:
321 // - a member function or a static data member of the current
Douglas Gregor0e4de762010-05-11 08:41:30 +0000322 // instantiation
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000323 if (isa<CXXMethodDecl>(D) && D->getDeclContext()->isDependentContext()) {
324 ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000325 InstantiationDependent = true;
Richard Smithec8dcd22011-11-08 01:31:09 +0000326 }
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000327}
Douglas Gregora6e053e2010-12-15 01:34:56 +0000328
Craig Topperce7167c2013-08-22 04:58:56 +0000329void DeclRefExpr::computeDependence(const ASTContext &Ctx) {
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000330 bool TypeDependent = false;
331 bool ValueDependent = false;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000332 bool InstantiationDependent = false;
Daniel Dunbar9d355812012-03-09 01:51:51 +0000333 computeDeclRefDependence(Ctx, getDecl(), getType(), TypeDependent,
334 ValueDependent, InstantiationDependent);
Richard Smithcfaa5a32014-10-17 02:46:42 +0000335
336 ExprBits.TypeDependent |= TypeDependent;
337 ExprBits.ValueDependent |= ValueDependent;
338 ExprBits.InstantiationDependent |= InstantiationDependent;
339
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000340 // Is the declaration a parameter pack?
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000341 if (getDecl()->isParameterPack())
Douglas Gregor3c6bd2a2011-01-05 21:11:38 +0000342 ExprBits.ContainsUnexpandedParameterPack = true;
Douglas Gregored6c7442009-11-23 11:41:28 +0000343}
344
Craig Topperce7167c2013-08-22 04:58:56 +0000345DeclRefExpr::DeclRefExpr(const ASTContext &Ctx,
Daniel Dunbar9d355812012-03-09 01:51:51 +0000346 NestedNameSpecifierLoc QualifierLoc,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000347 SourceLocation TemplateKWLoc,
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000348 ValueDecl *D, bool RefersToEnclosingVariableOrCapture,
John McCall113bee02012-03-10 09:33:50 +0000349 const DeclarationNameInfo &NameInfo,
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000350 NamedDecl *FoundD,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000351 const TemplateArgumentListInfo *TemplateArgs,
John McCall7decc9e2010-11-18 06:31:45 +0000352 QualType T, ExprValueKind VK)
Douglas Gregor678d76c2011-07-01 01:22:09 +0000353 : Expr(DeclRefExprClass, T, VK, OK_Ordinary, false, false, false, false),
Chandler Carruth0e439962011-05-01 21:29:53 +0000354 D(D), Loc(NameInfo.getLoc()), DNLoc(NameInfo.getInfo()) {
355 DeclRefExprBits.HasQualifier = QualifierLoc ? 1 : 0;
Richard Smithcfaa5a32014-10-17 02:46:42 +0000356 if (QualifierLoc) {
James Y Knighte7d82282015-12-29 18:15:14 +0000357 new (getTrailingObjects<NestedNameSpecifierLoc>())
358 NestedNameSpecifierLoc(QualifierLoc);
Richard Smithcfaa5a32014-10-17 02:46:42 +0000359 auto *NNS = QualifierLoc.getNestedNameSpecifier();
360 if (NNS->isInstantiationDependent())
361 ExprBits.InstantiationDependent = true;
362 if (NNS->containsUnexpandedParameterPack())
363 ExprBits.ContainsUnexpandedParameterPack = true;
364 }
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000365 DeclRefExprBits.HasFoundDecl = FoundD ? 1 : 0;
366 if (FoundD)
James Y Knighte7d82282015-12-29 18:15:14 +0000367 *getTrailingObjects<NamedDecl *>() = FoundD;
Abramo Bagnara7945c982012-01-27 09:46:47 +0000368 DeclRefExprBits.HasTemplateKWAndArgsInfo
369 = (TemplateArgs || TemplateKWLoc.isValid()) ? 1 : 0;
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000370 DeclRefExprBits.RefersToEnclosingVariableOrCapture =
371 RefersToEnclosingVariableOrCapture;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000372 if (TemplateArgs) {
373 bool Dependent = false;
374 bool InstantiationDependent = false;
375 bool ContainsUnexpandedParameterPack = false;
James Y Knighte7d82282015-12-29 18:15:14 +0000376 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
377 TemplateKWLoc, *TemplateArgs, getTrailingObjects<TemplateArgumentLoc>(),
378 Dependent, InstantiationDependent, ContainsUnexpandedParameterPack);
Richard Smithcfaa5a32014-10-17 02:46:42 +0000379 assert(!Dependent && "built a DeclRefExpr with dependent template args");
380 ExprBits.InstantiationDependent |= InstantiationDependent;
381 ExprBits.ContainsUnexpandedParameterPack |= ContainsUnexpandedParameterPack;
Abramo Bagnara7945c982012-01-27 09:46:47 +0000382 } else if (TemplateKWLoc.isValid()) {
James Y Knighte7d82282015-12-29 18:15:14 +0000383 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
384 TemplateKWLoc);
Douglas Gregor678d76c2011-07-01 01:22:09 +0000385 }
Benjamin Kramer138ef9c2011-10-10 12:54:05 +0000386 DeclRefExprBits.HadMultipleCandidates = 0;
387
Daniel Dunbar9d355812012-03-09 01:51:51 +0000388 computeDependence(Ctx);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000389}
390
Craig Topperce7167c2013-08-22 04:58:56 +0000391DeclRefExpr *DeclRefExpr::Create(const ASTContext &Context,
Douglas Gregorea972d32011-02-28 21:54:11 +0000392 NestedNameSpecifierLoc QualifierLoc,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000393 SourceLocation TemplateKWLoc,
John McCallce546572009-12-08 09:08:17 +0000394 ValueDecl *D,
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000395 bool RefersToEnclosingVariableOrCapture,
Douglas Gregor4bd90e52009-10-23 18:54:35 +0000396 SourceLocation NameLoc,
Douglas Gregored6c7442009-11-23 11:41:28 +0000397 QualType T,
John McCall7decc9e2010-11-18 06:31:45 +0000398 ExprValueKind VK,
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000399 NamedDecl *FoundD,
Douglas Gregored6c7442009-11-23 11:41:28 +0000400 const TemplateArgumentListInfo *TemplateArgs) {
Abramo Bagnara7945c982012-01-27 09:46:47 +0000401 return Create(Context, QualifierLoc, TemplateKWLoc, D,
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000402 RefersToEnclosingVariableOrCapture,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000403 DeclarationNameInfo(D->getDeclName(), NameLoc),
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000404 T, VK, FoundD, TemplateArgs);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000405}
406
Craig Topperce7167c2013-08-22 04:58:56 +0000407DeclRefExpr *DeclRefExpr::Create(const ASTContext &Context,
Douglas Gregorea972d32011-02-28 21:54:11 +0000408 NestedNameSpecifierLoc QualifierLoc,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000409 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000410 ValueDecl *D,
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000411 bool RefersToEnclosingVariableOrCapture,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000412 const DeclarationNameInfo &NameInfo,
413 QualType T,
John McCall7decc9e2010-11-18 06:31:45 +0000414 ExprValueKind VK,
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000415 NamedDecl *FoundD,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000416 const TemplateArgumentListInfo *TemplateArgs) {
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000417 // Filter out cases where the found Decl is the same as the value refenenced.
418 if (D == FoundD)
Craig Topper36250ad2014-05-12 05:36:57 +0000419 FoundD = nullptr;
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000420
James Y Knighte7d82282015-12-29 18:15:14 +0000421 bool HasTemplateKWAndArgsInfo = TemplateArgs || TemplateKWLoc.isValid();
422 std::size_t Size =
423 totalSizeToAlloc<NestedNameSpecifierLoc, NamedDecl *,
424 ASTTemplateKWAndArgsInfo, TemplateArgumentLoc>(
425 QualifierLoc ? 1 : 0, FoundD ? 1 : 0,
426 HasTemplateKWAndArgsInfo ? 1 : 0,
427 TemplateArgs ? TemplateArgs->size() : 0);
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000428
Benjamin Kramerc3f89252016-10-20 14:27:22 +0000429 void *Mem = Context.Allocate(Size, alignof(DeclRefExpr));
Daniel Dunbar9d355812012-03-09 01:51:51 +0000430 return new (Mem) DeclRefExpr(Context, QualifierLoc, TemplateKWLoc, D,
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000431 RefersToEnclosingVariableOrCapture,
Daniel Dunbar9d355812012-03-09 01:51:51 +0000432 NameInfo, FoundD, TemplateArgs, T, VK);
Douglas Gregor4bd90e52009-10-23 18:54:35 +0000433}
434
Craig Topperce7167c2013-08-22 04:58:56 +0000435DeclRefExpr *DeclRefExpr::CreateEmpty(const ASTContext &Context,
Douglas Gregor87866ce2011-02-04 12:01:24 +0000436 bool HasQualifier,
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000437 bool HasFoundDecl,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000438 bool HasTemplateKWAndArgsInfo,
Argyrios Kyrtzidis1985bb32010-07-08 13:09:47 +0000439 unsigned NumTemplateArgs) {
James Y Knighte7d82282015-12-29 18:15:14 +0000440 assert(NumTemplateArgs == 0 || HasTemplateKWAndArgsInfo);
441 std::size_t Size =
442 totalSizeToAlloc<NestedNameSpecifierLoc, NamedDecl *,
443 ASTTemplateKWAndArgsInfo, TemplateArgumentLoc>(
444 HasQualifier ? 1 : 0, HasFoundDecl ? 1 : 0, HasTemplateKWAndArgsInfo,
445 NumTemplateArgs);
Benjamin Kramerc3f89252016-10-20 14:27:22 +0000446 void *Mem = Context.Allocate(Size, alignof(DeclRefExpr));
Argyrios Kyrtzidis1985bb32010-07-08 13:09:47 +0000447 return new (Mem) DeclRefExpr(EmptyShell());
448}
449
Stephen Kelly724e9e52018-08-09 20:05:03 +0000450SourceLocation DeclRefExpr::getBeginLoc() const {
Daniel Dunbarb507f272012-03-09 15:39:15 +0000451 if (hasQualifier())
452 return getQualifierLoc().getBeginLoc();
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000453 return getNameInfo().getBeginLoc();
Daniel Dunbarb507f272012-03-09 15:39:15 +0000454}
Stephen Kelly02a67ba2018-08-09 20:05:47 +0000455SourceLocation DeclRefExpr::getEndLoc() const {
Daniel Dunbarb507f272012-03-09 15:39:15 +0000456 if (hasExplicitTemplateArgs())
457 return getRAngleLoc();
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000458 return getNameInfo().getEndLoc();
Daniel Dunbarb507f272012-03-09 15:39:15 +0000459}
Douglas Gregor4bd90e52009-10-23 18:54:35 +0000460
Bruno Ricci17ff0262018-10-27 19:21:19 +0000461PredefinedExpr::PredefinedExpr(SourceLocation L, QualType FNTy, IdentKind IK,
Alexey Bataevec474782014-10-09 08:45:04 +0000462 StringLiteral *SL)
463 : Expr(PredefinedExprClass, FNTy, VK_LValue, OK_Ordinary,
464 FNTy->isDependentType(), FNTy->isDependentType(),
465 FNTy->isInstantiationDependentType(),
Bruno Ricci17ff0262018-10-27 19:21:19 +0000466 /*ContainsUnexpandedParameterPack=*/false) {
467 PredefinedExprBits.Kind = IK;
468 assert((getIdentKind() == IK) &&
469 "IdentKind do not fit in PredefinedExprBitfields!");
470 bool HasFunctionName = SL != nullptr;
471 PredefinedExprBits.HasFunctionName = HasFunctionName;
472 PredefinedExprBits.Loc = L;
473 if (HasFunctionName)
474 setFunctionName(SL);
Alexey Bataevec474782014-10-09 08:45:04 +0000475}
476
Bruno Ricci17ff0262018-10-27 19:21:19 +0000477PredefinedExpr::PredefinedExpr(EmptyShell Empty, bool HasFunctionName)
478 : Expr(PredefinedExprClass, Empty) {
479 PredefinedExprBits.HasFunctionName = HasFunctionName;
480}
481
482PredefinedExpr *PredefinedExpr::Create(const ASTContext &Ctx, SourceLocation L,
483 QualType FNTy, IdentKind IK,
484 StringLiteral *SL) {
485 bool HasFunctionName = SL != nullptr;
486 void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *>(HasFunctionName),
487 alignof(PredefinedExpr));
488 return new (Mem) PredefinedExpr(L, FNTy, IK, SL);
489}
490
491PredefinedExpr *PredefinedExpr::CreateEmpty(const ASTContext &Ctx,
492 bool HasFunctionName) {
493 void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *>(HasFunctionName),
494 alignof(PredefinedExpr));
495 return new (Mem) PredefinedExpr(EmptyShell(), HasFunctionName);
496}
497
498StringRef PredefinedExpr::getIdentKindName(PredefinedExpr::IdentKind IK) {
499 switch (IK) {
Alexey Bataevec474782014-10-09 08:45:04 +0000500 case Func:
501 return "__func__";
502 case Function:
503 return "__FUNCTION__";
504 case FuncDName:
505 return "__FUNCDNAME__";
506 case LFunction:
507 return "L__FUNCTION__";
508 case PrettyFunction:
509 return "__PRETTY_FUNCTION__";
510 case FuncSig:
511 return "__FUNCSIG__";
Reid Kleckner4a83f0a2018-07-26 23:18:44 +0000512 case LFuncSig:
513 return "L__FUNCSIG__";
Alexey Bataevec474782014-10-09 08:45:04 +0000514 case PrettyFunctionNoVirtual:
515 break;
516 }
Bruno Ricci17ff0262018-10-27 19:21:19 +0000517 llvm_unreachable("Unknown ident kind for PredefinedExpr");
Alexey Bataevec474782014-10-09 08:45:04 +0000518}
519
Anders Carlsson2fb08242009-09-08 18:24:21 +0000520// FIXME: Maybe this should use DeclPrinter with a special "print predefined
521// expr" policy instead.
Bruno Ricci17ff0262018-10-27 19:21:19 +0000522std::string PredefinedExpr::ComputeName(IdentKind IK, const Decl *CurrentDecl) {
Anders Carlsson5bd8d192010-02-11 18:20:28 +0000523 ASTContext &Context = CurrentDecl->getASTContext();
524
Bruno Ricci17ff0262018-10-27 19:21:19 +0000525 if (IK == PredefinedExpr::FuncDName) {
David Majnemerbed356a2013-11-06 23:31:56 +0000526 if (const NamedDecl *ND = dyn_cast<NamedDecl>(CurrentDecl)) {
Ahmed Charlesb8984322014-03-07 20:03:18 +0000527 std::unique_ptr<MangleContext> MC;
David Majnemerbed356a2013-11-06 23:31:56 +0000528 MC.reset(Context.createMangleContext());
529
530 if (MC->shouldMangleDeclName(ND)) {
531 SmallString<256> Buffer;
532 llvm::raw_svector_ostream Out(Buffer);
533 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(ND))
534 MC->mangleCXXCtor(CD, Ctor_Base, Out);
535 else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(ND))
536 MC->mangleCXXDtor(DD, Dtor_Base, Out);
537 else
538 MC->mangleName(ND, Out);
539
David Majnemerbed356a2013-11-06 23:31:56 +0000540 if (!Buffer.empty() && Buffer.front() == '\01')
541 return Buffer.substr(1);
542 return Buffer.str();
543 } else
544 return ND->getIdentifier()->getName();
545 }
546 return "";
547 }
Mehdi Aminidc9bf8f2016-11-16 07:07:28 +0000548 if (isa<BlockDecl>(CurrentDecl)) {
549 // For blocks we only emit something if it is enclosed in a function
550 // For top-level block we'd like to include the name of variable, but we
551 // don't have it at this point.
Mehdi Aminif5f37ee2016-11-15 22:19:50 +0000552 auto DC = CurrentDecl->getDeclContext();
553 if (DC->isFileContext())
Mehdi Aminidc9bf8f2016-11-16 07:07:28 +0000554 return "";
555
556 SmallString<256> Buffer;
557 llvm::raw_svector_ostream Out(Buffer);
558 if (auto *DCBlock = dyn_cast<BlockDecl>(DC))
559 // For nested blocks, propagate up to the parent.
Bruno Ricci17ff0262018-10-27 19:21:19 +0000560 Out << ComputeName(IK, DCBlock);
Mehdi Aminidc9bf8f2016-11-16 07:07:28 +0000561 else if (auto *DCDecl = dyn_cast<Decl>(DC))
Bruno Ricci17ff0262018-10-27 19:21:19 +0000562 Out << ComputeName(IK, DCDecl) << "_block_invoke";
Alexey Bataevec474782014-10-09 08:45:04 +0000563 return Out.str();
564 }
Anders Carlsson2fb08242009-09-08 18:24:21 +0000565 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CurrentDecl)) {
Bruno Ricci17ff0262018-10-27 19:21:19 +0000566 if (IK != PrettyFunction && IK != PrettyFunctionNoVirtual &&
567 IK != FuncSig && IK != LFuncSig)
Anders Carlsson2fb08242009-09-08 18:24:21 +0000568 return FD->getNameAsString();
569
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000570 SmallString<256> Name;
Anders Carlsson2fb08242009-09-08 18:24:21 +0000571 llvm::raw_svector_ostream Out(Name);
572
573 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
Bruno Ricci17ff0262018-10-27 19:21:19 +0000574 if (MD->isVirtual() && IK != PrettyFunctionNoVirtual)
Anders Carlsson2fb08242009-09-08 18:24:21 +0000575 Out << "virtual ";
Sam Weinig4e83bd22009-12-27 01:38:20 +0000576 if (MD->isStatic())
577 Out << "static ";
Anders Carlsson2fb08242009-09-08 18:24:21 +0000578 }
579
David Blaikiebbafb8a2012-03-11 07:00:24 +0000580 PrintingPolicy Policy(Context.getLangOpts());
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +0000581 std::string Proto;
Douglas Gregor11a434a2012-04-10 20:14:15 +0000582 llvm::raw_string_ostream POut(Proto);
Anders Carlsson2fb08242009-09-08 18:24:21 +0000583
Douglas Gregor11a434a2012-04-10 20:14:15 +0000584 const FunctionDecl *Decl = FD;
585 if (const FunctionDecl* Pattern = FD->getTemplateInstantiationPattern())
586 Decl = Pattern;
587 const FunctionType *AFT = Decl->getType()->getAs<FunctionType>();
Craig Topper36250ad2014-05-12 05:36:57 +0000588 const FunctionProtoType *FT = nullptr;
Anders Carlsson2fb08242009-09-08 18:24:21 +0000589 if (FD->hasWrittenPrototype())
590 FT = dyn_cast<FunctionProtoType>(AFT);
591
Bruno Ricci17ff0262018-10-27 19:21:19 +0000592 if (IK == FuncSig || IK == LFuncSig) {
Richard Smith2f63d462017-01-09 21:40:40 +0000593 switch (AFT->getCallConv()) {
Reid Kleckner52eddda2014-04-08 18:13:24 +0000594 case CC_C: POut << "__cdecl "; break;
595 case CC_X86StdCall: POut << "__stdcall "; break;
596 case CC_X86FastCall: POut << "__fastcall "; break;
597 case CC_X86ThisCall: POut << "__thiscall "; break;
Reid Klecknerd7857f02014-10-24 17:42:17 +0000598 case CC_X86VectorCall: POut << "__vectorcall "; break;
Erich Keane757d3172016-11-02 18:29:35 +0000599 case CC_X86RegCall: POut << "__regcall "; break;
Reid Kleckner52eddda2014-04-08 18:13:24 +0000600 // Only bother printing the conventions that MSVC knows about.
601 default: break;
602 }
603 }
604
605 FD->printQualifiedName(POut, Policy);
606
Douglas Gregor11a434a2012-04-10 20:14:15 +0000607 POut << "(";
Anders Carlsson2fb08242009-09-08 18:24:21 +0000608 if (FT) {
Douglas Gregor11a434a2012-04-10 20:14:15 +0000609 for (unsigned i = 0, e = Decl->getNumParams(); i != e; ++i) {
Anders Carlsson2fb08242009-09-08 18:24:21 +0000610 if (i) POut << ", ";
Argyrios Kyrtzidisa18347e2012-05-05 04:20:37 +0000611 POut << Decl->getParamDecl(i)->getType().stream(Policy);
Anders Carlsson2fb08242009-09-08 18:24:21 +0000612 }
613
614 if (FT->isVariadic()) {
615 if (FD->getNumParams()) POut << ", ";
616 POut << "...";
Bruno Ricci17ff0262018-10-27 19:21:19 +0000617 } else if ((IK == FuncSig || IK == LFuncSig ||
Reid Kleckner4a83f0a2018-07-26 23:18:44 +0000618 !Context.getLangOpts().CPlusPlus) &&
Richard Smithcf63b842017-01-09 22:16:16 +0000619 !Decl->getNumParams()) {
620 POut << "void";
Anders Carlsson2fb08242009-09-08 18:24:21 +0000621 }
622 }
Douglas Gregor11a434a2012-04-10 20:14:15 +0000623 POut << ")";
Anders Carlsson2fb08242009-09-08 18:24:21 +0000624
Sam Weinig4e83bd22009-12-27 01:38:20 +0000625 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
Richard Smith2f63d462017-01-09 21:40:40 +0000626 assert(FT && "We must have a written prototype in this case.");
David Blaikief5697e52012-08-10 00:55:35 +0000627 if (FT->isConst())
Douglas Gregor11a434a2012-04-10 20:14:15 +0000628 POut << " const";
David Blaikief5697e52012-08-10 00:55:35 +0000629 if (FT->isVolatile())
Douglas Gregor11a434a2012-04-10 20:14:15 +0000630 POut << " volatile";
631 RefQualifierKind Ref = MD->getRefQualifier();
632 if (Ref == RQ_LValue)
633 POut << " &";
634 else if (Ref == RQ_RValue)
635 POut << " &&";
Sam Weinig4e83bd22009-12-27 01:38:20 +0000636 }
637
Eugene Zelenkoae304b02017-11-17 18:09:48 +0000638 typedef SmallVector<const ClassTemplateSpecializationDecl *, 8> SpecsTy;
Douglas Gregor11a434a2012-04-10 20:14:15 +0000639 SpecsTy Specs;
640 const DeclContext *Ctx = FD->getDeclContext();
641 while (Ctx && isa<NamedDecl>(Ctx)) {
642 const ClassTemplateSpecializationDecl *Spec
643 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx);
644 if (Spec && !Spec->isExplicitSpecialization())
645 Specs.push_back(Spec);
646 Ctx = Ctx->getParent();
647 }
648
649 std::string TemplateParams;
650 llvm::raw_string_ostream TOut(TemplateParams);
651 for (SpecsTy::reverse_iterator I = Specs.rbegin(), E = Specs.rend();
652 I != E; ++I) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000653 const TemplateParameterList *Params
Douglas Gregor11a434a2012-04-10 20:14:15 +0000654 = (*I)->getSpecializedTemplate()->getTemplateParameters();
655 const TemplateArgumentList &Args = (*I)->getTemplateArgs();
656 assert(Params->size() == Args.size());
657 for (unsigned i = 0, numParams = Params->size(); i != numParams; ++i) {
658 StringRef Param = Params->getParam(i)->getName();
659 if (Param.empty()) continue;
660 TOut << Param << " = ";
661 Args.get(i).print(Policy, TOut);
662 TOut << ", ";
663 }
664 }
665
Fangrui Song6907ce22018-07-30 19:24:48 +0000666 FunctionTemplateSpecializationInfo *FSI
Douglas Gregor11a434a2012-04-10 20:14:15 +0000667 = FD->getTemplateSpecializationInfo();
668 if (FSI && !FSI->isExplicitSpecialization()) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000669 const TemplateParameterList* Params
Douglas Gregor11a434a2012-04-10 20:14:15 +0000670 = FSI->getTemplate()->getTemplateParameters();
671 const TemplateArgumentList* Args = FSI->TemplateArguments;
672 assert(Params->size() == Args->size());
673 for (unsigned i = 0, e = Params->size(); i != e; ++i) {
674 StringRef Param = Params->getParam(i)->getName();
675 if (Param.empty()) continue;
676 TOut << Param << " = ";
677 Args->get(i).print(Policy, TOut);
678 TOut << ", ";
679 }
680 }
681
682 TOut.flush();
683 if (!TemplateParams.empty()) {
684 // remove the trailing comma and space
685 TemplateParams.resize(TemplateParams.size() - 2);
686 POut << " [" << TemplateParams << "]";
687 }
688
689 POut.flush();
690
Benjamin Kramer90f54222013-08-21 11:45:27 +0000691 // Print "auto" for all deduced return types. This includes C++1y return
692 // type deduction and lambdas. For trailing return types resolve the
693 // decltype expression. Otherwise print the real type when this is
694 // not a constructor or destructor.
Alexey Bataevec474782014-10-09 08:45:04 +0000695 if (isa<CXXMethodDecl>(FD) &&
696 cast<CXXMethodDecl>(FD)->getParent()->isLambda())
Benjamin Kramer90f54222013-08-21 11:45:27 +0000697 Proto = "auto " + Proto;
Alp Toker314cc812014-01-25 16:55:45 +0000698 else if (FT && FT->getReturnType()->getAs<DecltypeType>())
699 FT->getReturnType()
700 ->getAs<DecltypeType>()
701 ->getUnderlyingType()
Benjamin Kramer90f54222013-08-21 11:45:27 +0000702 .getAsStringInternal(Proto, Policy);
703 else if (!isa<CXXConstructorDecl>(FD) && !isa<CXXDestructorDecl>(FD))
Alp Toker314cc812014-01-25 16:55:45 +0000704 AFT->getReturnType().getAsStringInternal(Proto, Policy);
Anders Carlsson2fb08242009-09-08 18:24:21 +0000705
706 Out << Proto;
707
Anders Carlsson2fb08242009-09-08 18:24:21 +0000708 return Name.str().str();
709 }
Wei Pan8d6b19a2013-08-26 14:27:34 +0000710 if (const CapturedDecl *CD = dyn_cast<CapturedDecl>(CurrentDecl)) {
711 for (const DeclContext *DC = CD->getParent(); DC; DC = DC->getParent())
712 // Skip to its enclosing function or method, but not its enclosing
713 // CapturedDecl.
714 if (DC->isFunctionOrMethod() && (DC->getDeclKind() != Decl::Captured)) {
715 const Decl *D = Decl::castFromDeclContext(DC);
Bruno Ricci17ff0262018-10-27 19:21:19 +0000716 return ComputeName(IK, D);
Wei Pan8d6b19a2013-08-26 14:27:34 +0000717 }
718 llvm_unreachable("CapturedDecl not inside a function or method");
719 }
Anders Carlsson2fb08242009-09-08 18:24:21 +0000720 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurrentDecl)) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000721 SmallString<256> Name;
Anders Carlsson2fb08242009-09-08 18:24:21 +0000722 llvm::raw_svector_ostream Out(Name);
723 Out << (MD->isInstanceMethod() ? '-' : '+');
724 Out << '[';
Ted Kremenek361ffd92010-03-18 21:23:08 +0000725
726 // For incorrect code, there might not be an ObjCInterfaceDecl. Do
727 // a null check to avoid a crash.
728 if (const ObjCInterfaceDecl *ID = MD->getClassInterface())
Benjamin Kramerb89514a2011-10-14 18:45:37 +0000729 Out << *ID;
Ted Kremenek361ffd92010-03-18 21:23:08 +0000730
Anders Carlsson2fb08242009-09-08 18:24:21 +0000731 if (const ObjCCategoryImplDecl *CID =
Benjamin Kramerb11416d2010-04-17 09:33:03 +0000732 dyn_cast<ObjCCategoryImplDecl>(MD->getDeclContext()))
Benjamin Kramer2f569922012-02-07 11:57:45 +0000733 Out << '(' << *CID << ')';
Benjamin Kramerb11416d2010-04-17 09:33:03 +0000734
Anders Carlsson2fb08242009-09-08 18:24:21 +0000735 Out << ' ';
Aaron Ballmanb190f972014-01-03 17:59:55 +0000736 MD->getSelector().print(Out);
Anders Carlsson2fb08242009-09-08 18:24:21 +0000737 Out << ']';
738
Anders Carlsson2fb08242009-09-08 18:24:21 +0000739 return Name.str().str();
740 }
Bruno Ricci17ff0262018-10-27 19:21:19 +0000741 if (isa<TranslationUnitDecl>(CurrentDecl) && IK == PrettyFunction) {
Anders Carlsson2fb08242009-09-08 18:24:21 +0000742 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
743 return "top level";
744 }
745 return "";
746}
747
Craig Topper37932912013-08-18 10:09:15 +0000748void APNumericStorage::setIntValue(const ASTContext &C,
749 const llvm::APInt &Val) {
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000750 if (hasAllocation())
751 C.Deallocate(pVal);
752
753 BitWidth = Val.getBitWidth();
754 unsigned NumWords = Val.getNumWords();
755 const uint64_t* Words = Val.getRawData();
756 if (NumWords > 1) {
757 pVal = new (C) uint64_t[NumWords];
758 std::copy(Words, Words + NumWords, pVal);
759 } else if (NumWords == 1)
760 VAL = Words[0];
761 else
762 VAL = 0;
763}
764
Craig Topper37932912013-08-18 10:09:15 +0000765IntegerLiteral::IntegerLiteral(const ASTContext &C, const llvm::APInt &V,
Benjamin Kramer1ea8e092012-07-04 17:04:04 +0000766 QualType type, SourceLocation l)
767 : Expr(IntegerLiteralClass, type, VK_RValue, OK_Ordinary, false, false,
768 false, false),
769 Loc(l) {
770 assert(type->isIntegerType() && "Illegal type in IntegerLiteral");
771 assert(V.getBitWidth() == C.getIntWidth(type) &&
772 "Integer type is not the correct size for constant.");
773 setValue(C, V);
774}
775
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000776IntegerLiteral *
Craig Topper37932912013-08-18 10:09:15 +0000777IntegerLiteral::Create(const ASTContext &C, const llvm::APInt &V,
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000778 QualType type, SourceLocation l) {
779 return new (C) IntegerLiteral(C, V, type, l);
780}
781
782IntegerLiteral *
Craig Topper37932912013-08-18 10:09:15 +0000783IntegerLiteral::Create(const ASTContext &C, EmptyShell Empty) {
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000784 return new (C) IntegerLiteral(Empty);
785}
786
Leonard Chandb01c3a2018-06-20 17:19:40 +0000787FixedPointLiteral::FixedPointLiteral(const ASTContext &C, const llvm::APInt &V,
788 QualType type, SourceLocation l,
789 unsigned Scale)
790 : Expr(FixedPointLiteralClass, type, VK_RValue, OK_Ordinary, false, false,
791 false, false),
792 Loc(l), Scale(Scale) {
793 assert(type->isFixedPointType() && "Illegal type in FixedPointLiteral");
794 assert(V.getBitWidth() == C.getTypeInfo(type).Width &&
795 "Fixed point type is not the correct size for constant.");
796 setValue(C, V);
797}
798
799FixedPointLiteral *FixedPointLiteral::CreateFromRawInt(const ASTContext &C,
800 const llvm::APInt &V,
801 QualType type,
802 SourceLocation l,
803 unsigned Scale) {
804 return new (C) FixedPointLiteral(C, V, type, l, Scale);
805}
806
807std::string FixedPointLiteral::getValueAsString(unsigned Radix) const {
808 // Currently the longest decimal number that can be printed is the max for an
809 // unsigned long _Accum: 4294967295.99999999976716935634613037109375
810 // which is 43 characters.
811 SmallString<64> S;
812 FixedPointValueToString(
Leonard Chanc03642e2018-08-06 16:05:08 +0000813 S, llvm::APSInt::getUnsigned(getValue().getZExtValue()), Scale);
Leonard Chandb01c3a2018-06-20 17:19:40 +0000814 return S.str();
815}
816
Craig Topper37932912013-08-18 10:09:15 +0000817FloatingLiteral::FloatingLiteral(const ASTContext &C, const llvm::APFloat &V,
Benjamin Kramer1ea8e092012-07-04 17:04:04 +0000818 bool isexact, QualType Type, SourceLocation L)
819 : Expr(FloatingLiteralClass, Type, VK_RValue, OK_Ordinary, false, false,
820 false, false), Loc(L) {
Tim Northover178723a2013-01-22 09:46:51 +0000821 setSemantics(V.getSemantics());
Benjamin Kramer1ea8e092012-07-04 17:04:04 +0000822 FloatingLiteralBits.IsExact = isexact;
823 setValue(C, V);
824}
825
Craig Topper37932912013-08-18 10:09:15 +0000826FloatingLiteral::FloatingLiteral(const ASTContext &C, EmptyShell Empty)
Eugene Zelenkoae304b02017-11-17 18:09:48 +0000827 : Expr(FloatingLiteralClass, Empty) {
Tim Northover178723a2013-01-22 09:46:51 +0000828 setRawSemantics(IEEEhalf);
Benjamin Kramer1ea8e092012-07-04 17:04:04 +0000829 FloatingLiteralBits.IsExact = false;
830}
831
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000832FloatingLiteral *
Craig Topper37932912013-08-18 10:09:15 +0000833FloatingLiteral::Create(const ASTContext &C, const llvm::APFloat &V,
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000834 bool isexact, QualType Type, SourceLocation L) {
835 return new (C) FloatingLiteral(C, V, isexact, Type, L);
836}
837
838FloatingLiteral *
Craig Topper37932912013-08-18 10:09:15 +0000839FloatingLiteral::Create(const ASTContext &C, EmptyShell Empty) {
Akira Hatanaka428f5b22012-01-10 22:40:09 +0000840 return new (C) FloatingLiteral(C, Empty);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000841}
842
Tim Northover178723a2013-01-22 09:46:51 +0000843const llvm::fltSemantics &FloatingLiteral::getSemantics() const {
844 switch(FloatingLiteralBits.Semantics) {
845 case IEEEhalf:
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000846 return llvm::APFloat::IEEEhalf();
Tim Northover178723a2013-01-22 09:46:51 +0000847 case IEEEsingle:
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000848 return llvm::APFloat::IEEEsingle();
Tim Northover178723a2013-01-22 09:46:51 +0000849 case IEEEdouble:
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000850 return llvm::APFloat::IEEEdouble();
Tim Northover178723a2013-01-22 09:46:51 +0000851 case x87DoubleExtended:
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000852 return llvm::APFloat::x87DoubleExtended();
Tim Northover178723a2013-01-22 09:46:51 +0000853 case IEEEquad:
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000854 return llvm::APFloat::IEEEquad();
Tim Northover178723a2013-01-22 09:46:51 +0000855 case PPCDoubleDouble:
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000856 return llvm::APFloat::PPCDoubleDouble();
Tim Northover178723a2013-01-22 09:46:51 +0000857 }
858 llvm_unreachable("Unrecognised floating semantics");
859}
860
861void FloatingLiteral::setSemantics(const llvm::fltSemantics &Sem) {
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000862 if (&Sem == &llvm::APFloat::IEEEhalf())
Tim Northover178723a2013-01-22 09:46:51 +0000863 FloatingLiteralBits.Semantics = IEEEhalf;
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000864 else if (&Sem == &llvm::APFloat::IEEEsingle())
Tim Northover178723a2013-01-22 09:46:51 +0000865 FloatingLiteralBits.Semantics = IEEEsingle;
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000866 else if (&Sem == &llvm::APFloat::IEEEdouble())
Tim Northover178723a2013-01-22 09:46:51 +0000867 FloatingLiteralBits.Semantics = IEEEdouble;
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000868 else if (&Sem == &llvm::APFloat::x87DoubleExtended())
Tim Northover178723a2013-01-22 09:46:51 +0000869 FloatingLiteralBits.Semantics = x87DoubleExtended;
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000870 else if (&Sem == &llvm::APFloat::IEEEquad())
Tim Northover178723a2013-01-22 09:46:51 +0000871 FloatingLiteralBits.Semantics = IEEEquad;
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000872 else if (&Sem == &llvm::APFloat::PPCDoubleDouble())
Tim Northover178723a2013-01-22 09:46:51 +0000873 FloatingLiteralBits.Semantics = PPCDoubleDouble;
874 else
875 llvm_unreachable("Unknown floating semantics");
876}
877
Chris Lattnera0173132008-06-07 22:13:43 +0000878/// getValueAsApproximateDouble - This returns the value as an inaccurate
879/// double. Note that this may cause loss of precision, but is useful for
880/// debugging dumps, etc.
881double FloatingLiteral::getValueAsApproximateDouble() const {
882 llvm::APFloat V = getValue();
Dale Johannesenc48814b2008-10-09 23:02:32 +0000883 bool ignored;
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000884 V.convert(llvm::APFloat::IEEEdouble(), llvm::APFloat::rmNearestTiesToEven,
Dale Johannesenc48814b2008-10-09 23:02:32 +0000885 &ignored);
Chris Lattnera0173132008-06-07 22:13:43 +0000886 return V.convertToDouble();
887}
888
Nick Lewycky4ed84042012-02-24 09:07:53 +0000889int StringLiteral::mapCharByteWidth(TargetInfo const &target,StringKind k) {
Eli Friedman381f4312012-02-29 20:59:56 +0000890 int CharByteWidth = 0;
Nick Lewycky4ed84042012-02-24 09:07:53 +0000891 switch(k) {
Eli Friedmanfcec6302011-11-01 02:23:42 +0000892 case Ascii:
893 case UTF8:
Nick Lewycky4ed84042012-02-24 09:07:53 +0000894 CharByteWidth = target.getCharWidth();
Eli Friedmanfcec6302011-11-01 02:23:42 +0000895 break;
896 case Wide:
Nick Lewycky4ed84042012-02-24 09:07:53 +0000897 CharByteWidth = target.getWCharWidth();
Eli Friedmanfcec6302011-11-01 02:23:42 +0000898 break;
899 case UTF16:
Nick Lewycky4ed84042012-02-24 09:07:53 +0000900 CharByteWidth = target.getChar16Width();
Eli Friedmanfcec6302011-11-01 02:23:42 +0000901 break;
902 case UTF32:
Nick Lewycky4ed84042012-02-24 09:07:53 +0000903 CharByteWidth = target.getChar32Width();
Eli Friedman381f4312012-02-29 20:59:56 +0000904 break;
Eli Friedmanfcec6302011-11-01 02:23:42 +0000905 }
906 assert((CharByteWidth & 7) == 0 && "Assumes character size is byte multiple");
907 CharByteWidth /= 8;
Nick Lewycky4ed84042012-02-24 09:07:53 +0000908 assert((CharByteWidth==1 || CharByteWidth==2 || CharByteWidth==4)
Eli Friedmanfcec6302011-11-01 02:23:42 +0000909 && "character byte widths supported are 1, 2, and 4 only");
910 return CharByteWidth;
911}
912
Craig Topper37932912013-08-18 10:09:15 +0000913StringLiteral *StringLiteral::Create(const ASTContext &C, StringRef Str,
Douglas Gregorfb65e592011-07-27 05:40:30 +0000914 StringKind Kind, bool Pascal, QualType Ty,
Mike Stump11289f42009-09-09 15:08:12 +0000915 const SourceLocation *Loc,
Anders Carlssona3905812009-03-15 18:34:13 +0000916 unsigned NumStrs) {
Benjamin Kramercdac7612014-02-25 12:26:20 +0000917 assert(C.getAsConstantArrayType(Ty) &&
918 "StringLiteral must be of constant array type!");
919
Chris Lattnerf83b5af2009-02-18 06:40:38 +0000920 // Allocate enough space for the StringLiteral plus an array of locations for
921 // any concatenated string tokens.
Benjamin Kramerc3f89252016-10-20 14:27:22 +0000922 void *Mem =
923 C.Allocate(sizeof(StringLiteral) + sizeof(SourceLocation) * (NumStrs - 1),
924 alignof(StringLiteral));
Chris Lattnerf83b5af2009-02-18 06:40:38 +0000925 StringLiteral *SL = new (Mem) StringLiteral(Ty);
Mike Stump11289f42009-09-09 15:08:12 +0000926
Steve Naroffdf7855b2007-02-21 23:46:25 +0000927 // OPTIMIZE: could allocate this appended to the StringLiteral.
Eli Friedmanfcec6302011-11-01 02:23:42 +0000928 SL->setString(C,Str,Kind,Pascal);
929
Chris Lattnerf83b5af2009-02-18 06:40:38 +0000930 SL->TokLocs[0] = Loc[0];
931 SL->NumConcatenated = NumStrs;
Chris Lattnerd3e98952006-10-06 05:22:26 +0000932
Chris Lattner630970d2009-02-18 05:49:11 +0000933 if (NumStrs != 1)
Chris Lattnerf83b5af2009-02-18 06:40:38 +0000934 memcpy(&SL->TokLocs[1], Loc+1, sizeof(SourceLocation)*(NumStrs-1));
935 return SL;
Chris Lattner630970d2009-02-18 05:49:11 +0000936}
937
Craig Topper37932912013-08-18 10:09:15 +0000938StringLiteral *StringLiteral::CreateEmpty(const ASTContext &C,
939 unsigned NumStrs) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +0000940 void *Mem =
941 C.Allocate(sizeof(StringLiteral) + sizeof(SourceLocation) * (NumStrs - 1),
942 alignof(StringLiteral));
Anastasia Stulova59055b92018-05-09 13:23:26 +0000943 StringLiteral *SL =
944 new (Mem) StringLiteral(C.adjustStringLiteralBaseType(QualType()));
Eli Friedmanfcec6302011-11-01 02:23:42 +0000945 SL->CharByteWidth = 0;
946 SL->Length = 0;
Douglas Gregor958dfc92009-04-15 16:35:07 +0000947 SL->NumConcatenated = NumStrs;
948 return SL;
949}
950
Alexander Kornienko540bacb2013-02-01 12:35:51 +0000951void StringLiteral::outputString(raw_ostream &OS) const {
Richard Trieudc355912012-06-13 20:25:24 +0000952 switch (getKind()) {
953 case Ascii: break; // no prefix.
954 case Wide: OS << 'L'; break;
955 case UTF8: OS << "u8"; break;
956 case UTF16: OS << 'u'; break;
957 case UTF32: OS << 'U'; break;
958 }
959 OS << '"';
960 static const char Hex[] = "0123456789ABCDEF";
961
962 unsigned LastSlashX = getLength();
963 for (unsigned I = 0, N = getLength(); I != N; ++I) {
964 switch (uint32_t Char = getCodeUnit(I)) {
965 default:
966 // FIXME: Convert UTF-8 back to codepoints before rendering.
967
968 // Convert UTF-16 surrogate pairs back to codepoints before rendering.
969 // Leave invalid surrogates alone; we'll use \x for those.
Fangrui Song6907ce22018-07-30 19:24:48 +0000970 if (getKind() == UTF16 && I != N - 1 && Char >= 0xd800 &&
Richard Trieudc355912012-06-13 20:25:24 +0000971 Char <= 0xdbff) {
972 uint32_t Trail = getCodeUnit(I + 1);
973 if (Trail >= 0xdc00 && Trail <= 0xdfff) {
974 Char = 0x10000 + ((Char - 0xd800) << 10) + (Trail - 0xdc00);
975 ++I;
976 }
977 }
978
979 if (Char > 0xff) {
980 // If this is a wide string, output characters over 0xff using \x
981 // escapes. Otherwise, this is a UTF-16 or UTF-32 string, and Char is a
982 // codepoint: use \x escapes for invalid codepoints.
983 if (getKind() == Wide ||
984 (Char >= 0xd800 && Char <= 0xdfff) || Char >= 0x110000) {
985 // FIXME: Is this the best way to print wchar_t?
986 OS << "\\x";
987 int Shift = 28;
988 while ((Char >> Shift) == 0)
989 Shift -= 4;
990 for (/**/; Shift >= 0; Shift -= 4)
991 OS << Hex[(Char >> Shift) & 15];
992 LastSlashX = I;
993 break;
994 }
995
996 if (Char > 0xffff)
997 OS << "\\U00"
998 << Hex[(Char >> 20) & 15]
999 << Hex[(Char >> 16) & 15];
1000 else
1001 OS << "\\u";
1002 OS << Hex[(Char >> 12) & 15]
1003 << Hex[(Char >> 8) & 15]
1004 << Hex[(Char >> 4) & 15]
1005 << Hex[(Char >> 0) & 15];
1006 break;
1007 }
1008
1009 // If we used \x... for the previous character, and this character is a
1010 // hexadecimal digit, prevent it being slurped as part of the \x.
1011 if (LastSlashX + 1 == I) {
1012 switch (Char) {
1013 case '0': case '1': case '2': case '3': case '4':
1014 case '5': case '6': case '7': case '8': case '9':
1015 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
1016 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
1017 OS << "\"\"";
1018 }
1019 }
1020
1021 assert(Char <= 0xff &&
1022 "Characters above 0xff should already have been handled.");
1023
Jordan Rosea7d03842013-02-08 22:30:41 +00001024 if (isPrintable(Char))
Richard Trieudc355912012-06-13 20:25:24 +00001025 OS << (char)Char;
1026 else // Output anything hard as an octal escape.
1027 OS << '\\'
1028 << (char)('0' + ((Char >> 6) & 7))
1029 << (char)('0' + ((Char >> 3) & 7))
1030 << (char)('0' + ((Char >> 0) & 7));
1031 break;
1032 // Handle some common non-printable cases to make dumps prettier.
1033 case '\\': OS << "\\\\"; break;
1034 case '"': OS << "\\\""; break;
Richard Trieudc355912012-06-13 20:25:24 +00001035 case '\a': OS << "\\a"; break;
1036 case '\b': OS << "\\b"; break;
Benjamin Kramer60a53d52016-11-24 09:41:33 +00001037 case '\f': OS << "\\f"; break;
1038 case '\n': OS << "\\n"; break;
1039 case '\r': OS << "\\r"; break;
1040 case '\t': OS << "\\t"; break;
1041 case '\v': OS << "\\v"; break;
Richard Trieudc355912012-06-13 20:25:24 +00001042 }
1043 }
1044 OS << '"';
1045}
1046
Craig Topper37932912013-08-18 10:09:15 +00001047void StringLiteral::setString(const ASTContext &C, StringRef Str,
Eli Friedmanfcec6302011-11-01 02:23:42 +00001048 StringKind Kind, bool IsPascal) {
1049 //FIXME: we assume that the string data comes from a target that uses the same
Simon Pilgrim2c518802017-03-30 14:13:19 +00001050 // code unit size and endianness for the type of string.
Eli Friedmanfcec6302011-11-01 02:23:42 +00001051 this->Kind = Kind;
1052 this->IsPascal = IsPascal;
Fangrui Song6907ce22018-07-30 19:24:48 +00001053
Nick Lewycky4ed84042012-02-24 09:07:53 +00001054 CharByteWidth = mapCharByteWidth(C.getTargetInfo(),Kind);
Eli Friedmanfcec6302011-11-01 02:23:42 +00001055 assert((Str.size()%CharByteWidth == 0)
1056 && "size of data must be multiple of CharByteWidth");
1057 Length = Str.size()/CharByteWidth;
1058
1059 switch(CharByteWidth) {
1060 case 1: {
1061 char *AStrData = new (C) char[Length];
Argyrios Kyrtzidis61710892012-09-14 21:17:41 +00001062 std::memcpy(AStrData,Str.data(),Length*sizeof(*AStrData));
Eli Friedmanfcec6302011-11-01 02:23:42 +00001063 StrData.asChar = AStrData;
1064 break;
1065 }
1066 case 2: {
1067 uint16_t *AStrData = new (C) uint16_t[Length];
Argyrios Kyrtzidis61710892012-09-14 21:17:41 +00001068 std::memcpy(AStrData,Str.data(),Length*sizeof(*AStrData));
Eli Friedmanfcec6302011-11-01 02:23:42 +00001069 StrData.asUInt16 = AStrData;
1070 break;
1071 }
1072 case 4: {
1073 uint32_t *AStrData = new (C) uint32_t[Length];
Argyrios Kyrtzidis61710892012-09-14 21:17:41 +00001074 std::memcpy(AStrData,Str.data(),Length*sizeof(*AStrData));
Eli Friedmanfcec6302011-11-01 02:23:42 +00001075 StrData.asUInt32 = AStrData;
1076 break;
1077 }
1078 default:
Davide Italiano04839a52016-01-30 08:03:54 +00001079 llvm_unreachable("unsupported CharByteWidth");
Eli Friedmanfcec6302011-11-01 02:23:42 +00001080 }
Douglas Gregor958dfc92009-04-15 16:35:07 +00001081}
1082
Chris Lattnere925d612010-11-17 07:37:15 +00001083/// getLocationOfByte - Return a source location that points to the specified
1084/// byte of this string literal.
1085///
1086/// Strings are amazingly complex. They can be formed from multiple tokens and
1087/// can have escape sequences in them in addition to the usual trigraph and
1088/// escaped newline business. This routine handles this complexity.
1089///
Richard Smithefb116f2015-12-10 01:11:47 +00001090/// The *StartToken sets the first token to be searched in this function and
1091/// the *StartTokenByteOffset is the byte offset of the first token. Before
1092/// returning, it updates the *StartToken to the TokNo of the token being found
1093/// and sets *StartTokenByteOffset to the byte offset of the token in the
1094/// string.
1095/// Using these two parameters can reduce the time complexity from O(n^2) to
1096/// O(n) if one wants to get the location of byte for all the tokens in a
1097/// string.
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001098///
Richard Smithefb116f2015-12-10 01:11:47 +00001099SourceLocation
1100StringLiteral::getLocationOfByte(unsigned ByteNo, const SourceManager &SM,
1101 const LangOptions &Features,
1102 const TargetInfo &Target, unsigned *StartToken,
1103 unsigned *StartTokenByteOffset) const {
Richard Smith4060f772012-06-13 05:37:23 +00001104 assert((Kind == StringLiteral::Ascii || Kind == StringLiteral::UTF8) &&
1105 "Only narrow string literals are currently supported");
Douglas Gregorfb65e592011-07-27 05:40:30 +00001106
Chris Lattnere925d612010-11-17 07:37:15 +00001107 // Loop over all of the tokens in this string until we find the one that
1108 // contains the byte we're looking for.
1109 unsigned TokNo = 0;
Richard Smithefb116f2015-12-10 01:11:47 +00001110 unsigned StringOffset = 0;
1111 if (StartToken)
1112 TokNo = *StartToken;
1113 if (StartTokenByteOffset) {
1114 StringOffset = *StartTokenByteOffset;
1115 ByteNo -= StringOffset;
1116 }
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001117 while (1) {
Chris Lattnere925d612010-11-17 07:37:15 +00001118 assert(TokNo < getNumConcatenated() && "Invalid byte number!");
1119 SourceLocation StrTokLoc = getStrTokenLoc(TokNo);
Fangrui Song6907ce22018-07-30 19:24:48 +00001120
Chris Lattnere925d612010-11-17 07:37:15 +00001121 // Get the spelling of the string so that we can get the data that makes up
1122 // the string literal, not the identifier for the macro it is potentially
1123 // expanded through.
1124 SourceLocation StrTokSpellingLoc = SM.getSpellingLoc(StrTokLoc);
Richard Smithefb116f2015-12-10 01:11:47 +00001125
Chris Lattnere925d612010-11-17 07:37:15 +00001126 // Re-lex the token to get its length and original spelling.
Richard Smithefb116f2015-12-10 01:11:47 +00001127 std::pair<FileID, unsigned> LocInfo =
1128 SM.getDecomposedLoc(StrTokSpellingLoc);
Chris Lattnere925d612010-11-17 07:37:15 +00001129 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001130 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
Richard Smithefb116f2015-12-10 01:11:47 +00001131 if (Invalid) {
1132 if (StartTokenByteOffset != nullptr)
1133 *StartTokenByteOffset = StringOffset;
1134 if (StartToken != nullptr)
1135 *StartToken = TokNo;
Chris Lattnere925d612010-11-17 07:37:15 +00001136 return StrTokSpellingLoc;
Richard Smithefb116f2015-12-10 01:11:47 +00001137 }
1138
Chris Lattnere925d612010-11-17 07:37:15 +00001139 const char *StrData = Buffer.data()+LocInfo.second;
Fangrui Song6907ce22018-07-30 19:24:48 +00001140
Chris Lattnere925d612010-11-17 07:37:15 +00001141 // Create a lexer starting at the beginning of this token.
Argyrios Kyrtzidis45f51182012-05-11 21:39:18 +00001142 Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), Features,
1143 Buffer.begin(), StrData, Buffer.end());
Chris Lattnere925d612010-11-17 07:37:15 +00001144 Token TheTok;
1145 TheLexer.LexFromRawLexer(TheTok);
Fangrui Song6907ce22018-07-30 19:24:48 +00001146
Chris Lattnere925d612010-11-17 07:37:15 +00001147 // Use the StringLiteralParser to compute the length of the string in bytes.
Craig Topper9d5583e2014-06-26 04:58:39 +00001148 StringLiteralParser SLP(TheTok, SM, Features, Target);
Chris Lattnere925d612010-11-17 07:37:15 +00001149 unsigned TokNumBytes = SLP.GetStringLength();
Fangrui Song6907ce22018-07-30 19:24:48 +00001150
Chris Lattnere925d612010-11-17 07:37:15 +00001151 // If the byte is in this token, return the location of the byte.
1152 if (ByteNo < TokNumBytes ||
Hans Wennborg77d1abe2011-06-30 20:17:41 +00001153 (ByteNo == TokNumBytes && TokNo == getNumConcatenated() - 1)) {
Richard Smithefb116f2015-12-10 01:11:47 +00001154 unsigned Offset = SLP.getOffsetOfStringByte(TheTok, ByteNo);
1155
Chris Lattnere925d612010-11-17 07:37:15 +00001156 // Now that we know the offset of the token in the spelling, use the
1157 // preprocessor to get the offset in the original source.
Richard Smithefb116f2015-12-10 01:11:47 +00001158 if (StartTokenByteOffset != nullptr)
1159 *StartTokenByteOffset = StringOffset;
1160 if (StartToken != nullptr)
1161 *StartToken = TokNo;
Chris Lattnere925d612010-11-17 07:37:15 +00001162 return Lexer::AdvanceToTokenCharacter(StrTokLoc, Offset, SM, Features);
1163 }
Richard Smithefb116f2015-12-10 01:11:47 +00001164
Chris Lattnere925d612010-11-17 07:37:15 +00001165 // Move to the next string token.
Richard Smithefb116f2015-12-10 01:11:47 +00001166 StringOffset += TokNumBytes;
Chris Lattnere925d612010-11-17 07:37:15 +00001167 ++TokNo;
1168 ByteNo -= TokNumBytes;
1169 }
1170}
1171
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001172
1173
Chris Lattner1b926492006-08-23 06:42:10 +00001174/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1175/// corresponds to, e.g. "sizeof" or "[pre]++".
David Blaikie1d202a62012-10-08 01:11:04 +00001176StringRef UnaryOperator::getOpcodeStr(Opcode Op) {
Chris Lattner1b926492006-08-23 06:42:10 +00001177 switch (Op) {
Etienne Bergeron5356d962016-05-12 20:58:56 +00001178#define UNARY_OPERATION(Name, Spelling) case UO_##Name: return Spelling;
1179#include "clang/AST/OperationKinds.def"
Chris Lattner1b926492006-08-23 06:42:10 +00001180 }
David Blaikief47fa302012-01-17 02:30:50 +00001181 llvm_unreachable("Unknown unary operator");
Chris Lattner1b926492006-08-23 06:42:10 +00001182}
1183
John McCalle3027922010-08-25 11:45:40 +00001184UnaryOperatorKind
Douglas Gregor084d8552009-03-13 23:49:33 +00001185UnaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix) {
1186 switch (OO) {
David Blaikie83d382b2011-09-23 05:06:16 +00001187 default: llvm_unreachable("No unary operator for overloaded function");
John McCalle3027922010-08-25 11:45:40 +00001188 case OO_PlusPlus: return Postfix ? UO_PostInc : UO_PreInc;
1189 case OO_MinusMinus: return Postfix ? UO_PostDec : UO_PreDec;
1190 case OO_Amp: return UO_AddrOf;
1191 case OO_Star: return UO_Deref;
1192 case OO_Plus: return UO_Plus;
1193 case OO_Minus: return UO_Minus;
1194 case OO_Tilde: return UO_Not;
1195 case OO_Exclaim: return UO_LNot;
Richard Smith9f690bd2015-10-27 06:02:45 +00001196 case OO_Coawait: return UO_Coawait;
Douglas Gregor084d8552009-03-13 23:49:33 +00001197 }
1198}
1199
1200OverloadedOperatorKind UnaryOperator::getOverloadedOperator(Opcode Opc) {
1201 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00001202 case UO_PostInc: case UO_PreInc: return OO_PlusPlus;
1203 case UO_PostDec: case UO_PreDec: return OO_MinusMinus;
1204 case UO_AddrOf: return OO_Amp;
1205 case UO_Deref: return OO_Star;
1206 case UO_Plus: return OO_Plus;
1207 case UO_Minus: return OO_Minus;
1208 case UO_Not: return OO_Tilde;
1209 case UO_LNot: return OO_Exclaim;
Richard Smith9f690bd2015-10-27 06:02:45 +00001210 case UO_Coawait: return OO_Coawait;
Douglas Gregor084d8552009-03-13 23:49:33 +00001211 default: return OO_None;
1212 }
1213}
1214
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001215
Chris Lattner0eedafe2006-08-24 04:56:27 +00001216//===----------------------------------------------------------------------===//
1217// Postfix Operators.
1218//===----------------------------------------------------------------------===//
Chris Lattnere165d942006-08-24 04:40:38 +00001219
Justin Lebarf8bdacb2016-01-14 23:31:30 +00001220CallExpr::CallExpr(const ASTContext &C, StmtClass SC, Expr *fn,
1221 ArrayRef<Expr *> preargs, ArrayRef<Expr *> args, QualType t,
Craig Topper37932912013-08-18 10:09:15 +00001222 ExprValueKind VK, SourceLocation rparenloc)
Justin Lebarf8bdacb2016-01-14 23:31:30 +00001223 : Expr(SC, t, VK, OK_Ordinary, fn->isTypeDependent(),
1224 fn->isValueDependent(), fn->isInstantiationDependent(),
1225 fn->containsUnexpandedParameterPack()),
1226 NumArgs(args.size()) {
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001227
Justin Lebarf8bdacb2016-01-14 23:31:30 +00001228 unsigned NumPreArgs = preargs.size();
1229 SubExprs = new (C) Stmt *[args.size()+PREARGS_START+NumPreArgs];
Douglas Gregor993603d2008-11-14 16:09:21 +00001230 SubExprs[FN] = fn;
Justin Lebarf8bdacb2016-01-14 23:31:30 +00001231 for (unsigned i = 0; i != NumPreArgs; ++i) {
1232 updateDependenciesFromArg(preargs[i]);
1233 SubExprs[i+PREARGS_START] = preargs[i];
1234 }
Benjamin Kramerc215e762012-08-24 11:54:20 +00001235 for (unsigned i = 0; i != args.size(); ++i) {
Justin Lebarf8bdacb2016-01-14 23:31:30 +00001236 updateDependenciesFromArg(args[i]);
Peter Collingbourne3a347252011-02-08 21:18:02 +00001237 SubExprs[i+PREARGS_START+NumPreArgs] = args[i];
Douglas Gregora6e053e2010-12-15 01:34:56 +00001238 }
Ted Kremenekd7b4f402009-02-09 20:51:47 +00001239
Peter Collingbourne3a347252011-02-08 21:18:02 +00001240 CallExprBits.NumPreArgs = NumPreArgs;
Douglas Gregor993603d2008-11-14 16:09:21 +00001241 RParenLoc = rparenloc;
1242}
Nate Begeman1e36a852008-01-17 17:46:27 +00001243
Justin Lebarf8bdacb2016-01-14 23:31:30 +00001244CallExpr::CallExpr(const ASTContext &C, StmtClass SC, Expr *fn,
1245 ArrayRef<Expr *> args, QualType t, ExprValueKind VK,
1246 SourceLocation rparenloc)
1247 : CallExpr(C, SC, fn, ArrayRef<Expr *>(), args, t, VK, rparenloc) {}
1248
Benjamin Kramerf04f98d2015-03-06 14:15:57 +00001249CallExpr::CallExpr(const ASTContext &C, Expr *fn, ArrayRef<Expr *> args,
John McCall7decc9e2010-11-18 06:31:45 +00001250 QualType t, ExprValueKind VK, SourceLocation rparenloc)
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001251 : CallExpr(C, CallExprClass, fn, ArrayRef<Expr *>(), args, t, VK, rparenloc) {
1252}
Chris Lattnere165d942006-08-24 04:40:38 +00001253
Craig Topper37932912013-08-18 10:09:15 +00001254CallExpr::CallExpr(const ASTContext &C, StmtClass SC, EmptyShell Empty)
Benjamin Kramerf04f98d2015-03-06 14:15:57 +00001255 : CallExpr(C, SC, /*NumPreArgs=*/0, Empty) {}
Peter Collingbourne3a347252011-02-08 21:18:02 +00001256
Craig Topper37932912013-08-18 10:09:15 +00001257CallExpr::CallExpr(const ASTContext &C, StmtClass SC, unsigned NumPreArgs,
Peter Collingbourne3a347252011-02-08 21:18:02 +00001258 EmptyShell Empty)
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001259 : Expr(SC, Empty), SubExprs(nullptr), NumArgs(0) {
Peter Collingbourne3a347252011-02-08 21:18:02 +00001260 // FIXME: Why do we allocate this?
Justin Lebarf8bdacb2016-01-14 23:31:30 +00001261 SubExprs = new (C) Stmt*[PREARGS_START+NumPreArgs]();
Peter Collingbourne3a347252011-02-08 21:18:02 +00001262 CallExprBits.NumPreArgs = NumPreArgs;
Douglas Gregore20a2e52009-04-15 17:43:59 +00001263}
1264
Justin Lebarf8bdacb2016-01-14 23:31:30 +00001265void CallExpr::updateDependenciesFromArg(Expr *Arg) {
1266 if (Arg->isTypeDependent())
1267 ExprBits.TypeDependent = true;
1268 if (Arg->isValueDependent())
1269 ExprBits.ValueDependent = true;
1270 if (Arg->isInstantiationDependent())
1271 ExprBits.InstantiationDependent = true;
1272 if (Arg->containsUnexpandedParameterPack())
1273 ExprBits.ContainsUnexpandedParameterPack = true;
1274}
1275
John McCallb92ab1a2016-10-26 23:46:34 +00001276FunctionDecl *CallExpr::getDirectCallee() {
1277 return dyn_cast_or_null<FunctionDecl>(getCalleeDecl());
1278}
1279
Nuno Lopes518e3702009-12-20 23:11:08 +00001280Decl *CallExpr::getCalleeDecl() {
John McCallb92ab1a2016-10-26 23:46:34 +00001281 return getCallee()->getReferencedDeclOfCallee();
1282}
1283
1284Decl *Expr::getReferencedDeclOfCallee() {
1285 Expr *CEE = IgnoreParenImpCasts();
Fangrui Song6907ce22018-07-30 19:24:48 +00001286
Douglas Gregore0e96302011-09-06 21:41:04 +00001287 while (SubstNonTypeTemplateParmExpr *NTTP
1288 = dyn_cast<SubstNonTypeTemplateParmExpr>(CEE)) {
1289 CEE = NTTP->getReplacement()->IgnoreParenCasts();
1290 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001291
Sebastian Redl2b1832e2010-09-10 20:55:30 +00001292 // If we're calling a dereference, look at the pointer instead.
1293 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CEE)) {
1294 if (BO->isPtrMemOp())
1295 CEE = BO->getRHS()->IgnoreParenCasts();
1296 } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(CEE)) {
1297 if (UO->getOpcode() == UO_Deref)
1298 CEE = UO->getSubExpr()->IgnoreParenCasts();
1299 }
Chris Lattner52301912009-07-17 15:46:27 +00001300 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CEE))
Nuno Lopes518e3702009-12-20 23:11:08 +00001301 return DRE->getDecl();
Nuno Lopesc095b532009-12-24 00:28:18 +00001302 if (MemberExpr *ME = dyn_cast<MemberExpr>(CEE))
1303 return ME->getMemberDecl();
Zhongxing Xu3c8fa972009-07-17 07:29:51 +00001304
Craig Topper36250ad2014-05-12 05:36:57 +00001305 return nullptr;
Zhongxing Xu3c8fa972009-07-17 07:29:51 +00001306}
1307
Chris Lattnere4407ed2007-12-28 05:25:02 +00001308/// setNumArgs - This changes the number of arguments present in this call.
1309/// Any orphaned expressions are deleted by this, and any new operands are set
1310/// to null.
Craig Topper37932912013-08-18 10:09:15 +00001311void CallExpr::setNumArgs(const ASTContext& C, unsigned NumArgs) {
Chris Lattnere4407ed2007-12-28 05:25:02 +00001312 // No change, just return.
1313 if (NumArgs == getNumArgs()) return;
Mike Stump11289f42009-09-09 15:08:12 +00001314
Chris Lattnere4407ed2007-12-28 05:25:02 +00001315 // If shrinking # arguments, just delete the extras and forgot them.
1316 if (NumArgs < getNumArgs()) {
Chris Lattnere4407ed2007-12-28 05:25:02 +00001317 this->NumArgs = NumArgs;
1318 return;
1319 }
1320
1321 // Otherwise, we are growing the # arguments. New an bigger argument array.
Peter Collingbourne3a347252011-02-08 21:18:02 +00001322 unsigned NumPreArgs = getNumPreArgs();
1323 Stmt **NewSubExprs = new (C) Stmt*[NumArgs+PREARGS_START+NumPreArgs];
Chris Lattnere4407ed2007-12-28 05:25:02 +00001324 // Copy over args.
Peter Collingbourne3a347252011-02-08 21:18:02 +00001325 for (unsigned i = 0; i != getNumArgs()+PREARGS_START+NumPreArgs; ++i)
Chris Lattnere4407ed2007-12-28 05:25:02 +00001326 NewSubExprs[i] = SubExprs[i];
1327 // Null out new args.
Peter Collingbourne3a347252011-02-08 21:18:02 +00001328 for (unsigned i = getNumArgs()+PREARGS_START+NumPreArgs;
1329 i != NumArgs+PREARGS_START+NumPreArgs; ++i)
Craig Topper36250ad2014-05-12 05:36:57 +00001330 NewSubExprs[i] = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001331
Douglas Gregorba6e5572009-04-17 21:46:47 +00001332 if (SubExprs) C.Deallocate(SubExprs);
Chris Lattnere4407ed2007-12-28 05:25:02 +00001333 SubExprs = NewSubExprs;
1334 this->NumArgs = NumArgs;
1335}
1336
Alp Tokera724cff2013-12-28 21:59:02 +00001337/// getBuiltinCallee - If this is a call to a builtin, return the builtin ID. If
Chris Lattner01ff98a2008-10-06 05:00:53 +00001338/// not, return 0.
Alp Tokera724cff2013-12-28 21:59:02 +00001339unsigned CallExpr::getBuiltinCallee() const {
Steve Narofff6e3b3292008-01-31 01:07:12 +00001340 // All simple function calls (e.g. func()) are implicitly cast to pointer to
Mike Stump11289f42009-09-09 15:08:12 +00001341 // function. As a result, we try and obtain the DeclRefExpr from the
Steve Narofff6e3b3292008-01-31 01:07:12 +00001342 // ImplicitCastExpr.
1343 const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(getCallee());
1344 if (!ICE) // FIXME: deal with more complex calls (e.g. (func)(), (*func)()).
Chris Lattner01ff98a2008-10-06 05:00:53 +00001345 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001346
Steve Narofff6e3b3292008-01-31 01:07:12 +00001347 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr());
1348 if (!DRE)
Chris Lattner01ff98a2008-10-06 05:00:53 +00001349 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001350
Anders Carlssonfbcf6762008-01-31 02:13:57 +00001351 const FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
1352 if (!FDecl)
Chris Lattner01ff98a2008-10-06 05:00:53 +00001353 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001354
Douglas Gregor9eb16ea2008-11-21 15:30:19 +00001355 if (!FDecl->getIdentifier())
1356 return 0;
1357
Douglas Gregor15fc9562009-09-12 00:22:50 +00001358 return FDecl->getBuiltinID();
Chris Lattner01ff98a2008-10-06 05:00:53 +00001359}
Anders Carlssonfbcf6762008-01-31 02:13:57 +00001360
Scott Douglass503fc392015-06-10 13:53:15 +00001361bool CallExpr::isUnevaluatedBuiltinCall(const ASTContext &Ctx) const {
Alp Tokera724cff2013-12-28 21:59:02 +00001362 if (unsigned BI = getBuiltinCallee())
Richard Smith5011a002013-01-17 23:46:04 +00001363 return Ctx.BuiltinInfo.isUnevaluated(BI);
1364 return false;
1365}
1366
David Majnemerced8bdf2015-02-25 17:36:15 +00001367QualType CallExpr::getCallReturnType(const ASTContext &Ctx) const {
1368 const Expr *Callee = getCallee();
1369 QualType CalleeType = Callee->getType();
1370 if (const auto *FnTypePtr = CalleeType->getAs<PointerType>()) {
Anders Carlsson00a27592009-05-26 04:57:27 +00001371 CalleeType = FnTypePtr->getPointeeType();
David Majnemerced8bdf2015-02-25 17:36:15 +00001372 } else if (const auto *BPT = CalleeType->getAs<BlockPointerType>()) {
Anders Carlsson00a27592009-05-26 04:57:27 +00001373 CalleeType = BPT->getPointeeType();
David Majnemerced8bdf2015-02-25 17:36:15 +00001374 } else if (CalleeType->isSpecificPlaceholderType(BuiltinType::BoundMember)) {
1375 if (isa<CXXPseudoDestructorExpr>(Callee->IgnoreParens()))
1376 return Ctx.VoidTy;
1377
John McCall0009fcc2011-04-26 20:42:42 +00001378 // This should never be overloaded and so should never return null.
David Majnemerced8bdf2015-02-25 17:36:15 +00001379 CalleeType = Expr::findBoundMemberType(Callee);
1380 }
1381
John McCall0009fcc2011-04-26 20:42:42 +00001382 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00001383 return FnType->getReturnType();
Anders Carlsson00a27592009-05-26 04:57:27 +00001384}
Chris Lattner01ff98a2008-10-06 05:00:53 +00001385
Stephen Kelly724e9e52018-08-09 20:05:03 +00001386SourceLocation CallExpr::getBeginLoc() const {
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001387 if (isa<CXXOperatorCallExpr>(this))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001388 return cast<CXXOperatorCallExpr>(this)->getBeginLoc();
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001389
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001390 SourceLocation begin = getCallee()->getBeginLoc();
Keno Fischer070db172014-08-15 01:39:12 +00001391 if (begin.isInvalid() && getNumArgs() > 0 && getArg(0))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001392 begin = getArg(0)->getBeginLoc();
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001393 return begin;
1394}
Stephen Kelly02a67ba2018-08-09 20:05:47 +00001395SourceLocation CallExpr::getEndLoc() const {
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001396 if (isa<CXXOperatorCallExpr>(this))
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001397 return cast<CXXOperatorCallExpr>(this)->getEndLoc();
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001398
1399 SourceLocation end = getRParenLoc();
Keno Fischer070db172014-08-15 01:39:12 +00001400 if (end.isInvalid() && getNumArgs() > 0 && getArg(getNumArgs() - 1))
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001401 end = getArg(getNumArgs() - 1)->getEndLoc();
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001402 return end;
1403}
John McCall701417a2011-02-21 06:23:05 +00001404
Craig Topper37932912013-08-18 10:09:15 +00001405OffsetOfExpr *OffsetOfExpr::Create(const ASTContext &C, QualType type,
Douglas Gregor882211c2010-04-28 22:16:22 +00001406 SourceLocation OperatorLoc,
Fangrui Song6907ce22018-07-30 19:24:48 +00001407 TypeSourceInfo *tsi,
Benjamin Kramerc215e762012-08-24 11:54:20 +00001408 ArrayRef<OffsetOfNode> comps,
1409 ArrayRef<Expr*> exprs,
Douglas Gregor882211c2010-04-28 22:16:22 +00001410 SourceLocation RParenLoc) {
James Y Knight7281c352015-12-29 22:31:18 +00001411 void *Mem = C.Allocate(
1412 totalSizeToAlloc<OffsetOfNode, Expr *>(comps.size(), exprs.size()));
Douglas Gregor882211c2010-04-28 22:16:22 +00001413
Benjamin Kramerc215e762012-08-24 11:54:20 +00001414 return new (Mem) OffsetOfExpr(C, type, OperatorLoc, tsi, comps, exprs,
1415 RParenLoc);
Douglas Gregor882211c2010-04-28 22:16:22 +00001416}
1417
Craig Topper37932912013-08-18 10:09:15 +00001418OffsetOfExpr *OffsetOfExpr::CreateEmpty(const ASTContext &C,
Douglas Gregor882211c2010-04-28 22:16:22 +00001419 unsigned numComps, unsigned numExprs) {
James Y Knight7281c352015-12-29 22:31:18 +00001420 void *Mem =
1421 C.Allocate(totalSizeToAlloc<OffsetOfNode, Expr *>(numComps, numExprs));
Douglas Gregor882211c2010-04-28 22:16:22 +00001422 return new (Mem) OffsetOfExpr(numComps, numExprs);
1423}
1424
Craig Topper37932912013-08-18 10:09:15 +00001425OffsetOfExpr::OffsetOfExpr(const ASTContext &C, QualType type,
Douglas Gregor882211c2010-04-28 22:16:22 +00001426 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
Benjamin Kramerc215e762012-08-24 11:54:20 +00001427 ArrayRef<OffsetOfNode> comps, ArrayRef<Expr*> exprs,
Douglas Gregor882211c2010-04-28 22:16:22 +00001428 SourceLocation RParenLoc)
John McCall7decc9e2010-11-18 06:31:45 +00001429 : Expr(OffsetOfExprClass, type, VK_RValue, OK_Ordinary,
Fangrui Song6907ce22018-07-30 19:24:48 +00001430 /*TypeDependent=*/false,
Douglas Gregora6e053e2010-12-15 01:34:56 +00001431 /*ValueDependent=*/tsi->getType()->isDependentType(),
Douglas Gregor678d76c2011-07-01 01:22:09 +00001432 tsi->getType()->isInstantiationDependentType(),
Douglas Gregora6e053e2010-12-15 01:34:56 +00001433 tsi->getType()->containsUnexpandedParameterPack()),
Fangrui Song6907ce22018-07-30 19:24:48 +00001434 OperatorLoc(OperatorLoc), RParenLoc(RParenLoc), TSInfo(tsi),
Benjamin Kramerc215e762012-08-24 11:54:20 +00001435 NumComps(comps.size()), NumExprs(exprs.size())
Douglas Gregor882211c2010-04-28 22:16:22 +00001436{
Benjamin Kramerc215e762012-08-24 11:54:20 +00001437 for (unsigned i = 0; i != comps.size(); ++i) {
1438 setComponent(i, comps[i]);
Douglas Gregor882211c2010-04-28 22:16:22 +00001439 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001440
Benjamin Kramerc215e762012-08-24 11:54:20 +00001441 for (unsigned i = 0; i != exprs.size(); ++i) {
1442 if (exprs[i]->isTypeDependent() || exprs[i]->isValueDependent())
Douglas Gregora6e053e2010-12-15 01:34:56 +00001443 ExprBits.ValueDependent = true;
Benjamin Kramerc215e762012-08-24 11:54:20 +00001444 if (exprs[i]->containsUnexpandedParameterPack())
Douglas Gregora6e053e2010-12-15 01:34:56 +00001445 ExprBits.ContainsUnexpandedParameterPack = true;
1446
Benjamin Kramerc215e762012-08-24 11:54:20 +00001447 setIndexExpr(i, exprs[i]);
Douglas Gregor882211c2010-04-28 22:16:22 +00001448 }
1449}
1450
James Y Knight7281c352015-12-29 22:31:18 +00001451IdentifierInfo *OffsetOfNode::getFieldName() const {
Douglas Gregor882211c2010-04-28 22:16:22 +00001452 assert(getKind() == Field || getKind() == Identifier);
1453 if (getKind() == Field)
1454 return getField()->getIdentifier();
Fangrui Song6907ce22018-07-30 19:24:48 +00001455
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001456 return reinterpret_cast<IdentifierInfo *> (Data & ~(uintptr_t)Mask);
Douglas Gregor882211c2010-04-28 22:16:22 +00001457}
1458
David Majnemer10fd83d2015-01-15 10:04:14 +00001459UnaryExprOrTypeTraitExpr::UnaryExprOrTypeTraitExpr(
1460 UnaryExprOrTypeTrait ExprKind, Expr *E, QualType resultType,
1461 SourceLocation op, SourceLocation rp)
1462 : Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_RValue, OK_Ordinary,
1463 false, // Never type-dependent (C++ [temp.dep.expr]p3).
1464 // Value-dependent if the argument is type-dependent.
1465 E->isTypeDependent(), E->isInstantiationDependent(),
1466 E->containsUnexpandedParameterPack()),
1467 OpLoc(op), RParenLoc(rp) {
1468 UnaryExprOrTypeTraitExprBits.Kind = ExprKind;
1469 UnaryExprOrTypeTraitExprBits.IsType = false;
1470 Argument.Ex = E;
1471
1472 // Check to see if we are in the situation where alignof(decl) should be
1473 // dependent because decl's alignment is dependent.
Richard Smith6822bd72018-10-26 19:26:45 +00001474 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
David Majnemer10fd83d2015-01-15 10:04:14 +00001475 if (!isValueDependent() || !isInstantiationDependent()) {
1476 E = E->IgnoreParens();
1477
1478 const ValueDecl *D = nullptr;
1479 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
1480 D = DRE->getDecl();
1481 else if (const auto *ME = dyn_cast<MemberExpr>(E))
1482 D = ME->getMemberDecl();
1483
1484 if (D) {
1485 for (const auto *I : D->specific_attrs<AlignedAttr>()) {
1486 if (I->isAlignmentDependent()) {
1487 setValueDependent(true);
1488 setInstantiationDependent(true);
1489 break;
1490 }
1491 }
1492 }
1493 }
1494 }
1495}
1496
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00001497MemberExpr *MemberExpr::Create(
1498 const ASTContext &C, Expr *base, bool isarrow, SourceLocation OperatorLoc,
1499 NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,
1500 ValueDecl *memberdecl, DeclAccessPair founddecl,
1501 DeclarationNameInfo nameinfo, const TemplateArgumentListInfo *targs,
1502 QualType ty, ExprValueKind vk, ExprObjectKind ok) {
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001503
Douglas Gregorea972d32011-02-28 21:54:11 +00001504 bool hasQualOrFound = (QualifierLoc ||
John McCalla8ae2222010-04-06 21:38:20 +00001505 founddecl.getDecl() != memberdecl ||
1506 founddecl.getAccess() != memberdecl->getAccess());
Mike Stump11289f42009-09-09 15:08:12 +00001507
James Y Knighte7d82282015-12-29 18:15:14 +00001508 bool HasTemplateKWAndArgsInfo = targs || TemplateKWLoc.isValid();
1509 std::size_t Size =
1510 totalSizeToAlloc<MemberExprNameQualifier, ASTTemplateKWAndArgsInfo,
1511 TemplateArgumentLoc>(hasQualOrFound ? 1 : 0,
1512 HasTemplateKWAndArgsInfo ? 1 : 0,
1513 targs ? targs->size() : 0);
Mike Stump11289f42009-09-09 15:08:12 +00001514
Benjamin Kramerc3f89252016-10-20 14:27:22 +00001515 void *Mem = C.Allocate(Size, alignof(MemberExpr));
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00001516 MemberExpr *E = new (Mem)
1517 MemberExpr(base, isarrow, OperatorLoc, memberdecl, nameinfo, ty, vk, ok);
John McCall16df1e52010-03-30 21:47:33 +00001518
1519 if (hasQualOrFound) {
Douglas Gregorea972d32011-02-28 21:54:11 +00001520 // FIXME: Wrong. We should be looking at the member declaration we found.
1521 if (QualifierLoc && QualifierLoc.getNestedNameSpecifier()->isDependent()) {
John McCall16df1e52010-03-30 21:47:33 +00001522 E->setValueDependent(true);
1523 E->setTypeDependent(true);
Douglas Gregor678d76c2011-07-01 01:22:09 +00001524 E->setInstantiationDependent(true);
Fangrui Song6907ce22018-07-30 19:24:48 +00001525 }
1526 else if (QualifierLoc &&
1527 QualifierLoc.getNestedNameSpecifier()->isInstantiationDependent())
Douglas Gregor678d76c2011-07-01 01:22:09 +00001528 E->setInstantiationDependent(true);
Fangrui Song6907ce22018-07-30 19:24:48 +00001529
John McCall16df1e52010-03-30 21:47:33 +00001530 E->HasQualifierOrFoundDecl = true;
1531
James Y Knighte7d82282015-12-29 18:15:14 +00001532 MemberExprNameQualifier *NQ =
1533 E->getTrailingObjects<MemberExprNameQualifier>();
Douglas Gregorea972d32011-02-28 21:54:11 +00001534 NQ->QualifierLoc = QualifierLoc;
John McCall16df1e52010-03-30 21:47:33 +00001535 NQ->FoundDecl = founddecl;
1536 }
1537
Abramo Bagnara7945c982012-01-27 09:46:47 +00001538 E->HasTemplateKWAndArgsInfo = (targs || TemplateKWLoc.isValid());
1539
John McCall16df1e52010-03-30 21:47:33 +00001540 if (targs) {
Douglas Gregor678d76c2011-07-01 01:22:09 +00001541 bool Dependent = false;
1542 bool InstantiationDependent = false;
1543 bool ContainsUnexpandedParameterPack = false;
James Y Knighte7d82282015-12-29 18:15:14 +00001544 E->getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
1545 TemplateKWLoc, *targs, E->getTrailingObjects<TemplateArgumentLoc>(),
1546 Dependent, InstantiationDependent, ContainsUnexpandedParameterPack);
Douglas Gregor678d76c2011-07-01 01:22:09 +00001547 if (InstantiationDependent)
1548 E->setInstantiationDependent(true);
Abramo Bagnara7945c982012-01-27 09:46:47 +00001549 } else if (TemplateKWLoc.isValid()) {
James Y Knighte7d82282015-12-29 18:15:14 +00001550 E->getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
1551 TemplateKWLoc);
John McCall16df1e52010-03-30 21:47:33 +00001552 }
1553
1554 return E;
Douglas Gregorf405d7e2009-08-31 23:41:50 +00001555}
1556
Stephen Kelly724e9e52018-08-09 20:05:03 +00001557SourceLocation MemberExpr::getBeginLoc() const {
Douglas Gregor25b7e052011-03-02 21:06:53 +00001558 if (isImplicitAccess()) {
1559 if (hasQualifier())
Daniel Dunbarb507f272012-03-09 15:39:15 +00001560 return getQualifierLoc().getBeginLoc();
1561 return MemberLoc;
Douglas Gregor25b7e052011-03-02 21:06:53 +00001562 }
Abramo Bagnara7945c982012-01-27 09:46:47 +00001563
Daniel Dunbarb507f272012-03-09 15:39:15 +00001564 // FIXME: We don't want this to happen. Rather, we should be able to
1565 // detect all kinds of implicit accesses more cleanly.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001566 SourceLocation BaseStartLoc = getBase()->getBeginLoc();
Daniel Dunbarb507f272012-03-09 15:39:15 +00001567 if (BaseStartLoc.isValid())
1568 return BaseStartLoc;
1569 return MemberLoc;
1570}
Stephen Kelly02a67ba2018-08-09 20:05:47 +00001571SourceLocation MemberExpr::getEndLoc() const {
Abramo Bagnara9b836fb2012-11-08 13:52:58 +00001572 SourceLocation EndLoc = getMemberNameInfo().getEndLoc();
Daniel Dunbarb507f272012-03-09 15:39:15 +00001573 if (hasExplicitTemplateArgs())
Abramo Bagnara9b836fb2012-11-08 13:52:58 +00001574 EndLoc = getRAngleLoc();
1575 else if (EndLoc.isInvalid())
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001576 EndLoc = getBase()->getEndLoc();
Abramo Bagnara9b836fb2012-11-08 13:52:58 +00001577 return EndLoc;
Douglas Gregor25b7e052011-03-02 21:06:53 +00001578}
1579
Alp Tokerc1086762013-12-07 13:51:35 +00001580bool CastExpr::CastConsistency() const {
John McCall9320b872011-09-09 05:25:32 +00001581 switch (getCastKind()) {
1582 case CK_DerivedToBase:
1583 case CK_UncheckedDerivedToBase:
1584 case CK_DerivedToBaseMemberPointer:
1585 case CK_BaseToDerived:
1586 case CK_BaseToDerivedMemberPointer:
1587 assert(!path_empty() && "Cast kind should have a base path!");
1588 break;
1589
1590 case CK_CPointerToObjCPointerCast:
1591 assert(getType()->isObjCObjectPointerType());
1592 assert(getSubExpr()->getType()->isPointerType());
1593 goto CheckNoBasePath;
1594
1595 case CK_BlockPointerToObjCPointerCast:
1596 assert(getType()->isObjCObjectPointerType());
1597 assert(getSubExpr()->getType()->isBlockPointerType());
1598 goto CheckNoBasePath;
1599
John McCallc62bb392012-02-15 01:22:51 +00001600 case CK_ReinterpretMemberPointer:
1601 assert(getType()->isMemberPointerType());
1602 assert(getSubExpr()->getType()->isMemberPointerType());
1603 goto CheckNoBasePath;
1604
John McCall9320b872011-09-09 05:25:32 +00001605 case CK_BitCast:
1606 // Arbitrary casts to C pointer types count as bitcasts.
1607 // Otherwise, we should only have block and ObjC pointer casts
1608 // here if they stay within the type kind.
1609 if (!getType()->isPointerType()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001610 assert(getType()->isObjCObjectPointerType() ==
John McCall9320b872011-09-09 05:25:32 +00001611 getSubExpr()->getType()->isObjCObjectPointerType());
Fangrui Song6907ce22018-07-30 19:24:48 +00001612 assert(getType()->isBlockPointerType() ==
John McCall9320b872011-09-09 05:25:32 +00001613 getSubExpr()->getType()->isBlockPointerType());
1614 }
1615 goto CheckNoBasePath;
1616
1617 case CK_AnyPointerToBlockPointerCast:
1618 assert(getType()->isBlockPointerType());
1619 assert(getSubExpr()->getType()->isAnyPointerType() &&
1620 !getSubExpr()->getType()->isBlockPointerType());
1621 goto CheckNoBasePath;
1622
Douglas Gregored90df32012-02-22 05:02:47 +00001623 case CK_CopyAndAutoreleaseBlockObject:
1624 assert(getType()->isBlockPointerType());
1625 assert(getSubExpr()->getType()->isBlockPointerType());
1626 goto CheckNoBasePath;
Eli Friedman34866c72012-08-31 00:14:07 +00001627
1628 case CK_FunctionToPointerDecay:
1629 assert(getType()->isPointerType());
1630 assert(getSubExpr()->getType()->isFunctionType());
1631 goto CheckNoBasePath;
1632
David Tweede1468322013-12-11 13:39:46 +00001633 case CK_AddressSpaceConversion:
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001634 assert(getType()->isPointerType() || getType()->isBlockPointerType());
1635 assert(getSubExpr()->getType()->isPointerType() ||
1636 getSubExpr()->getType()->isBlockPointerType());
David Tweede1468322013-12-11 13:39:46 +00001637 assert(getType()->getPointeeType().getAddressSpace() !=
1638 getSubExpr()->getType()->getPointeeType().getAddressSpace());
Galina Kistanovaf87496d2017-06-03 06:31:42 +00001639 LLVM_FALLTHROUGH;
John McCall9320b872011-09-09 05:25:32 +00001640 // These should not have an inheritance path.
1641 case CK_Dynamic:
1642 case CK_ToUnion:
1643 case CK_ArrayToPointerDecay:
John McCall9320b872011-09-09 05:25:32 +00001644 case CK_NullToMemberPointer:
1645 case CK_NullToPointer:
1646 case CK_ConstructorConversion:
1647 case CK_IntegralToPointer:
1648 case CK_PointerToIntegral:
1649 case CK_ToVoid:
1650 case CK_VectorSplat:
1651 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +00001652 case CK_BooleanToSignedIntegral:
John McCall9320b872011-09-09 05:25:32 +00001653 case CK_IntegralToFloating:
1654 case CK_FloatingToIntegral:
1655 case CK_FloatingCast:
1656 case CK_ObjCObjectLValueCast:
1657 case CK_FloatingRealToComplex:
1658 case CK_FloatingComplexToReal:
1659 case CK_FloatingComplexCast:
1660 case CK_FloatingComplexToIntegralComplex:
1661 case CK_IntegralRealToComplex:
1662 case CK_IntegralComplexToReal:
1663 case CK_IntegralComplexCast:
1664 case CK_IntegralComplexToFloatingComplex:
John McCall2d637d22011-09-10 06:18:15 +00001665 case CK_ARCProduceObject:
1666 case CK_ARCConsumeObject:
1667 case CK_ARCReclaimReturnedObject:
1668 case CK_ARCExtendBlockObject:
Andrew Savonichevb555b762018-10-23 15:19:20 +00001669 case CK_ZeroToOCLOpaqueType:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00001670 case CK_IntToOCLSampler:
Leonard Chan99bda372018-10-15 16:07:02 +00001671 case CK_FixedPointCast:
John McCall9320b872011-09-09 05:25:32 +00001672 assert(!getType()->isBooleanType() && "unheralded conversion to bool");
1673 goto CheckNoBasePath;
1674
1675 case CK_Dependent:
1676 case CK_LValueToRValue:
John McCall9320b872011-09-09 05:25:32 +00001677 case CK_NoOp:
David Chisnallfa35df62012-01-16 17:27:18 +00001678 case CK_AtomicToNonAtomic:
1679 case CK_NonAtomicToAtomic:
John McCall9320b872011-09-09 05:25:32 +00001680 case CK_PointerToBoolean:
1681 case CK_IntegralToBoolean:
1682 case CK_FloatingToBoolean:
1683 case CK_MemberPointerToBoolean:
1684 case CK_FloatingComplexToBoolean:
1685 case CK_IntegralComplexToBoolean:
1686 case CK_LValueBitCast: // -> bool&
1687 case CK_UserDefinedConversion: // operator bool()
Eli Friedman34866c72012-08-31 00:14:07 +00001688 case CK_BuiltinFnToFnPtr:
Leonard Chanb4ba4672018-10-23 17:55:35 +00001689 case CK_FixedPointToBoolean:
John McCall9320b872011-09-09 05:25:32 +00001690 CheckNoBasePath:
1691 assert(path_empty() && "Cast kind should not have a base path!");
1692 break;
1693 }
Alp Tokerc1086762013-12-07 13:51:35 +00001694 return true;
John McCall9320b872011-09-09 05:25:32 +00001695}
1696
Eric Fiselier0683c0e2018-05-07 21:07:10 +00001697const char *CastExpr::getCastKindName(CastKind CK) {
1698 switch (CK) {
Etienne Bergeron5356d962016-05-12 20:58:56 +00001699#define CAST_OPERATION(Name) case CK_##Name: return #Name;
1700#include "clang/AST/OperationKinds.def"
Anders Carlsson496335e2009-09-03 00:59:21 +00001701 }
John McCallc5e62b42010-11-13 09:02:35 +00001702 llvm_unreachable("Unhandled cast kind!");
Anders Carlsson496335e2009-09-03 00:59:21 +00001703}
1704
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001705namespace {
Richard Smith1ef75542018-06-27 20:30:34 +00001706 const Expr *skipImplicitTemporary(const Expr *E) {
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001707 // Skip through reference binding to temporary.
Richard Smith1ef75542018-06-27 20:30:34 +00001708 if (auto *Materialize = dyn_cast<MaterializeTemporaryExpr>(E))
1709 E = Materialize->GetTemporaryExpr();
Stephan Bergmannf31b0dc2017-06-27 08:19:09 +00001710
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001711 // Skip any temporary bindings; they're implicit.
Richard Smith1ef75542018-06-27 20:30:34 +00001712 if (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
1713 E = Binder->getSubExpr();
Stephan Bergmannf31b0dc2017-06-27 08:19:09 +00001714
Richard Smith1ef75542018-06-27 20:30:34 +00001715 return E;
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001716 }
Stephan Bergmannf31b0dc2017-06-27 08:19:09 +00001717}
1718
Douglas Gregord196a582009-12-14 19:27:10 +00001719Expr *CastExpr::getSubExprAsWritten() {
Richard Smith1ef75542018-06-27 20:30:34 +00001720 const Expr *SubExpr = nullptr;
1721 const CastExpr *E = this;
Douglas Gregord196a582009-12-14 19:27:10 +00001722 do {
Stephan Bergmannf31b0dc2017-06-27 08:19:09 +00001723 SubExpr = skipImplicitTemporary(E->getSubExpr());
Douglas Gregorfe314812011-06-21 17:03:29 +00001724
Douglas Gregord196a582009-12-14 19:27:10 +00001725 // Conversions by constructor and conversion functions have a
1726 // subexpression describing the call; strip it off.
John McCalle3027922010-08-25 11:45:40 +00001727 if (E->getCastKind() == CK_ConstructorConversion)
Stephan Bergmannf31b0dc2017-06-27 08:19:09 +00001728 SubExpr =
1729 skipImplicitTemporary(cast<CXXConstructExpr>(SubExpr)->getArg(0));
Manman Ren8abc2e52016-02-02 22:23:03 +00001730 else if (E->getCastKind() == CK_UserDefinedConversion) {
1731 assert((isa<CXXMemberCallExpr>(SubExpr) ||
1732 isa<BlockExpr>(SubExpr)) &&
1733 "Unexpected SubExpr for CK_UserDefinedConversion.");
Richard Smith1ef75542018-06-27 20:30:34 +00001734 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SubExpr))
1735 SubExpr = MCE->getImplicitObjectArgument();
Manman Ren8abc2e52016-02-02 22:23:03 +00001736 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001737
Douglas Gregord196a582009-12-14 19:27:10 +00001738 // If the subexpression we're left with is an implicit cast, look
1739 // through that, too.
Fangrui Song6907ce22018-07-30 19:24:48 +00001740 } while ((E = dyn_cast<ImplicitCastExpr>(SubExpr)));
1741
Richard Smith1ef75542018-06-27 20:30:34 +00001742 return const_cast<Expr*>(SubExpr);
1743}
1744
1745NamedDecl *CastExpr::getConversionFunction() const {
1746 const Expr *SubExpr = nullptr;
1747
1748 for (const CastExpr *E = this; E; E = dyn_cast<ImplicitCastExpr>(SubExpr)) {
1749 SubExpr = skipImplicitTemporary(E->getSubExpr());
1750
1751 if (E->getCastKind() == CK_ConstructorConversion)
1752 return cast<CXXConstructExpr>(SubExpr)->getConstructor();
1753
1754 if (E->getCastKind() == CK_UserDefinedConversion) {
1755 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SubExpr))
1756 return MCE->getMethodDecl();
1757 }
1758 }
1759
1760 return nullptr;
Douglas Gregord196a582009-12-14 19:27:10 +00001761}
1762
Roman Lebedev4aaf1dc2018-08-01 06:06:16 +00001763CastExpr::BasePathSizeTy *CastExpr::BasePathSize() {
1764 assert(!path_empty());
1765 switch (getStmtClass()) {
1766#define ABSTRACT_STMT(x)
1767#define CASTEXPR(Type, Base) \
1768 case Stmt::Type##Class: \
1769 return static_cast<Type *>(this) \
1770 ->getTrailingObjects<CastExpr::BasePathSizeTy>();
1771#define STMT(Type, Base)
1772#include "clang/AST/StmtNodes.inc"
1773 default:
1774 llvm_unreachable("non-cast expressions not possible here");
1775 }
1776}
1777
John McCallcf142162010-08-07 06:22:56 +00001778CXXBaseSpecifier **CastExpr::path_buffer() {
1779 switch (getStmtClass()) {
1780#define ABSTRACT_STMT(x)
James Y Knight1d75c5e2015-12-30 02:27:28 +00001781#define CASTEXPR(Type, Base) \
1782 case Stmt::Type##Class: \
1783 return static_cast<Type *>(this)->getTrailingObjects<CXXBaseSpecifier *>();
John McCallcf142162010-08-07 06:22:56 +00001784#define STMT(Type, Base)
1785#include "clang/AST/StmtNodes.inc"
1786 default:
1787 llvm_unreachable("non-cast expressions not possible here");
John McCallcf142162010-08-07 06:22:56 +00001788 }
1789}
1790
John McCallf1ef7962017-08-15 21:42:47 +00001791const FieldDecl *CastExpr::getTargetFieldForToUnionCast(QualType unionType,
1792 QualType opType) {
1793 auto RD = unionType->castAs<RecordType>()->getDecl();
1794 return getTargetFieldForToUnionCast(RD, opType);
1795}
1796
1797const FieldDecl *CastExpr::getTargetFieldForToUnionCast(const RecordDecl *RD,
1798 QualType OpType) {
1799 auto &Ctx = RD->getASTContext();
1800 RecordDecl::field_iterator Field, FieldEnd;
1801 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
1802 Field != FieldEnd; ++Field) {
1803 if (Ctx.hasSameUnqualifiedType(Field->getType(), OpType) &&
1804 !Field->isUnnamedBitfield()) {
1805 return *Field;
1806 }
1807 }
1808 return nullptr;
1809}
1810
Craig Topper37932912013-08-18 10:09:15 +00001811ImplicitCastExpr *ImplicitCastExpr::Create(const ASTContext &C, QualType T,
John McCallcf142162010-08-07 06:22:56 +00001812 CastKind Kind, Expr *Operand,
1813 const CXXCastPath *BasePath,
John McCall2536c6d2010-08-25 10:28:54 +00001814 ExprValueKind VK) {
John McCallcf142162010-08-07 06:22:56 +00001815 unsigned PathSize = (BasePath ? BasePath->size() : 0);
Roman Lebedev4aaf1dc2018-08-01 06:06:16 +00001816 void *Buffer =
1817 C.Allocate(totalSizeToAlloc<CastExpr::BasePathSizeTy, CXXBaseSpecifier *>(
1818 PathSize ? 1 : 0, PathSize));
Richard Smithd2e69df2018-10-30 02:02:49 +00001819 // Per C++ [conv.lval]p3, lvalue-to-rvalue conversions on class and
1820 // std::nullptr_t have special semantics not captured by CK_LValueToRValue.
1821 assert((Kind != CK_LValueToRValue ||
1822 !(T->isNullPtrType() || T->getAsCXXRecordDecl())) &&
1823 "invalid type for lvalue-to-rvalue conversion");
John McCallcf142162010-08-07 06:22:56 +00001824 ImplicitCastExpr *E =
John McCall2536c6d2010-08-25 10:28:54 +00001825 new (Buffer) ImplicitCastExpr(T, Kind, Operand, PathSize, VK);
James Y Knight1d75c5e2015-12-30 02:27:28 +00001826 if (PathSize)
1827 std::uninitialized_copy_n(BasePath->data(), BasePath->size(),
1828 E->getTrailingObjects<CXXBaseSpecifier *>());
John McCallcf142162010-08-07 06:22:56 +00001829 return E;
1830}
1831
Craig Topper37932912013-08-18 10:09:15 +00001832ImplicitCastExpr *ImplicitCastExpr::CreateEmpty(const ASTContext &C,
John McCallcf142162010-08-07 06:22:56 +00001833 unsigned PathSize) {
Roman Lebedev4aaf1dc2018-08-01 06:06:16 +00001834 void *Buffer =
1835 C.Allocate(totalSizeToAlloc<CastExpr::BasePathSizeTy, CXXBaseSpecifier *>(
1836 PathSize ? 1 : 0, PathSize));
John McCallcf142162010-08-07 06:22:56 +00001837 return new (Buffer) ImplicitCastExpr(EmptyShell(), PathSize);
1838}
1839
1840
Craig Topper37932912013-08-18 10:09:15 +00001841CStyleCastExpr *CStyleCastExpr::Create(const ASTContext &C, QualType T,
John McCall7decc9e2010-11-18 06:31:45 +00001842 ExprValueKind VK, CastKind K, Expr *Op,
John McCallcf142162010-08-07 06:22:56 +00001843 const CXXCastPath *BasePath,
1844 TypeSourceInfo *WrittenTy,
1845 SourceLocation L, SourceLocation R) {
1846 unsigned PathSize = (BasePath ? BasePath->size() : 0);
Roman Lebedev4aaf1dc2018-08-01 06:06:16 +00001847 void *Buffer =
1848 C.Allocate(totalSizeToAlloc<CastExpr::BasePathSizeTy, CXXBaseSpecifier *>(
1849 PathSize ? 1 : 0, PathSize));
John McCallcf142162010-08-07 06:22:56 +00001850 CStyleCastExpr *E =
John McCall7decc9e2010-11-18 06:31:45 +00001851 new (Buffer) CStyleCastExpr(T, VK, K, Op, PathSize, WrittenTy, L, R);
James Y Knight1d75c5e2015-12-30 02:27:28 +00001852 if (PathSize)
1853 std::uninitialized_copy_n(BasePath->data(), BasePath->size(),
1854 E->getTrailingObjects<CXXBaseSpecifier *>());
John McCallcf142162010-08-07 06:22:56 +00001855 return E;
1856}
1857
Craig Topper37932912013-08-18 10:09:15 +00001858CStyleCastExpr *CStyleCastExpr::CreateEmpty(const ASTContext &C,
1859 unsigned PathSize) {
Roman Lebedev4aaf1dc2018-08-01 06:06:16 +00001860 void *Buffer =
1861 C.Allocate(totalSizeToAlloc<CastExpr::BasePathSizeTy, CXXBaseSpecifier *>(
1862 PathSize ? 1 : 0, PathSize));
John McCallcf142162010-08-07 06:22:56 +00001863 return new (Buffer) CStyleCastExpr(EmptyShell(), PathSize);
1864}
1865
Chris Lattner1b926492006-08-23 06:42:10 +00001866/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1867/// corresponds to, e.g. "<<=".
David Blaikie1d202a62012-10-08 01:11:04 +00001868StringRef BinaryOperator::getOpcodeStr(Opcode Op) {
Chris Lattner1b926492006-08-23 06:42:10 +00001869 switch (Op) {
Etienne Bergeron5356d962016-05-12 20:58:56 +00001870#define BINARY_OPERATION(Name, Spelling) case BO_##Name: return Spelling;
1871#include "clang/AST/OperationKinds.def"
Chris Lattner1b926492006-08-23 06:42:10 +00001872 }
David Blaikiee4d798f2012-01-20 21:50:17 +00001873 llvm_unreachable("Invalid OpCode!");
Chris Lattner1b926492006-08-23 06:42:10 +00001874}
Steve Naroff47500512007-04-19 23:00:49 +00001875
John McCalle3027922010-08-25 11:45:40 +00001876BinaryOperatorKind
Douglas Gregor1baf54e2009-03-13 18:40:31 +00001877BinaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO) {
1878 switch (OO) {
David Blaikie83d382b2011-09-23 05:06:16 +00001879 default: llvm_unreachable("Not an overloadable binary operator");
John McCalle3027922010-08-25 11:45:40 +00001880 case OO_Plus: return BO_Add;
1881 case OO_Minus: return BO_Sub;
1882 case OO_Star: return BO_Mul;
1883 case OO_Slash: return BO_Div;
1884 case OO_Percent: return BO_Rem;
1885 case OO_Caret: return BO_Xor;
1886 case OO_Amp: return BO_And;
1887 case OO_Pipe: return BO_Or;
1888 case OO_Equal: return BO_Assign;
Richard Smithc70f1d62017-12-14 15:16:18 +00001889 case OO_Spaceship: return BO_Cmp;
John McCalle3027922010-08-25 11:45:40 +00001890 case OO_Less: return BO_LT;
1891 case OO_Greater: return BO_GT;
1892 case OO_PlusEqual: return BO_AddAssign;
1893 case OO_MinusEqual: return BO_SubAssign;
1894 case OO_StarEqual: return BO_MulAssign;
1895 case OO_SlashEqual: return BO_DivAssign;
1896 case OO_PercentEqual: return BO_RemAssign;
1897 case OO_CaretEqual: return BO_XorAssign;
1898 case OO_AmpEqual: return BO_AndAssign;
1899 case OO_PipeEqual: return BO_OrAssign;
1900 case OO_LessLess: return BO_Shl;
1901 case OO_GreaterGreater: return BO_Shr;
1902 case OO_LessLessEqual: return BO_ShlAssign;
1903 case OO_GreaterGreaterEqual: return BO_ShrAssign;
1904 case OO_EqualEqual: return BO_EQ;
1905 case OO_ExclaimEqual: return BO_NE;
1906 case OO_LessEqual: return BO_LE;
1907 case OO_GreaterEqual: return BO_GE;
1908 case OO_AmpAmp: return BO_LAnd;
1909 case OO_PipePipe: return BO_LOr;
1910 case OO_Comma: return BO_Comma;
1911 case OO_ArrowStar: return BO_PtrMemI;
Douglas Gregor1baf54e2009-03-13 18:40:31 +00001912 }
1913}
1914
1915OverloadedOperatorKind BinaryOperator::getOverloadedOperator(Opcode Opc) {
1916 static const OverloadedOperatorKind OverOps[] = {
1917 /* .* Cannot be overloaded */OO_None, OO_ArrowStar,
1918 OO_Star, OO_Slash, OO_Percent,
1919 OO_Plus, OO_Minus,
1920 OO_LessLess, OO_GreaterGreater,
Richard Smithc70f1d62017-12-14 15:16:18 +00001921 OO_Spaceship,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00001922 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
1923 OO_EqualEqual, OO_ExclaimEqual,
1924 OO_Amp,
1925 OO_Caret,
1926 OO_Pipe,
1927 OO_AmpAmp,
1928 OO_PipePipe,
1929 OO_Equal, OO_StarEqual,
1930 OO_SlashEqual, OO_PercentEqual,
1931 OO_PlusEqual, OO_MinusEqual,
1932 OO_LessLessEqual, OO_GreaterGreaterEqual,
1933 OO_AmpEqual, OO_CaretEqual,
1934 OO_PipeEqual,
1935 OO_Comma
1936 };
1937 return OverOps[Opc];
1938}
1939
Andrew Kaylor3d0a5402017-09-19 20:26:40 +00001940bool BinaryOperator::isNullPointerArithmeticExtension(ASTContext &Ctx,
1941 Opcode Opc,
1942 Expr *LHS, Expr *RHS) {
1943 if (Opc != BO_Add)
1944 return false;
1945
1946 // Check that we have one pointer and one integer operand.
1947 Expr *PExp;
Andrew Kaylor3d0a5402017-09-19 20:26:40 +00001948 if (LHS->getType()->isPointerType()) {
1949 if (!RHS->getType()->isIntegerType())
1950 return false;
1951 PExp = LHS;
Andrew Kaylor3d0a5402017-09-19 20:26:40 +00001952 } else if (RHS->getType()->isPointerType()) {
1953 if (!LHS->getType()->isIntegerType())
1954 return false;
1955 PExp = RHS;
Andrew Kaylor3d0a5402017-09-19 20:26:40 +00001956 } else {
1957 return false;
1958 }
1959
1960 // Check that the pointer is a nullptr.
1961 if (!PExp->IgnoreParenCasts()
1962 ->isNullPointerConstant(Ctx, Expr::NPC_ValueDependentIsNotNull))
1963 return false;
1964
1965 // Check that the pointee type is char-sized.
1966 const PointerType *PTy = PExp->getType()->getAs<PointerType>();
1967 if (!PTy || !PTy->getPointeeType()->isCharType())
1968 return false;
1969
Andrew Kaylor3d0a5402017-09-19 20:26:40 +00001970 return true;
1971}
Craig Topper37932912013-08-18 10:09:15 +00001972InitListExpr::InitListExpr(const ASTContext &C, SourceLocation lbraceloc,
Benjamin Kramerc215e762012-08-24 11:54:20 +00001973 ArrayRef<Expr*> initExprs, SourceLocation rbraceloc)
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001974 : Expr(InitListExprClass, QualType(), VK_RValue, OK_Ordinary, false, false,
1975 false, false),
1976 InitExprs(C, initExprs.size()),
1977 LBraceLoc(lbraceloc), RBraceLoc(rbraceloc), AltForm(nullptr, true)
1978{
Sebastian Redlc83ed822012-02-17 08:42:25 +00001979 sawArrayRangeDesignator(false);
Benjamin Kramerc215e762012-08-24 11:54:20 +00001980 for (unsigned I = 0; I != initExprs.size(); ++I) {
Ted Kremenek013041e2010-02-19 01:50:18 +00001981 if (initExprs[I]->isTypeDependent())
John McCall925b16622010-10-26 08:39:16 +00001982 ExprBits.TypeDependent = true;
Ted Kremenek013041e2010-02-19 01:50:18 +00001983 if (initExprs[I]->isValueDependent())
John McCall925b16622010-10-26 08:39:16 +00001984 ExprBits.ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +00001985 if (initExprs[I]->isInstantiationDependent())
1986 ExprBits.InstantiationDependent = true;
Douglas Gregora6e053e2010-12-15 01:34:56 +00001987 if (initExprs[I]->containsUnexpandedParameterPack())
1988 ExprBits.ContainsUnexpandedParameterPack = true;
Douglas Gregordeebf6e2009-11-19 23:25:22 +00001989 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001990
Benjamin Kramerc215e762012-08-24 11:54:20 +00001991 InitExprs.insert(C, InitExprs.end(), initExprs.begin(), initExprs.end());
Anders Carlsson4692db02007-08-31 04:56:16 +00001992}
Chris Lattner1ec5f562007-06-27 05:38:08 +00001993
Craig Topper37932912013-08-18 10:09:15 +00001994void InitListExpr::reserveInits(const ASTContext &C, unsigned NumInits) {
Ted Kremenek013041e2010-02-19 01:50:18 +00001995 if (NumInits > InitExprs.size())
Ted Kremenekac034612010-04-13 23:39:13 +00001996 InitExprs.reserve(C, NumInits);
Douglas Gregor6d00c992009-03-20 23:58:33 +00001997}
1998
Craig Topper37932912013-08-18 10:09:15 +00001999void InitListExpr::resizeInits(const ASTContext &C, unsigned NumInits) {
Craig Topper36250ad2014-05-12 05:36:57 +00002000 InitExprs.resize(C, NumInits, nullptr);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002001}
2002
Craig Topper37932912013-08-18 10:09:15 +00002003Expr *InitListExpr::updateInit(const ASTContext &C, unsigned Init, Expr *expr) {
Ted Kremenek013041e2010-02-19 01:50:18 +00002004 if (Init >= InitExprs.size()) {
Craig Topper36250ad2014-05-12 05:36:57 +00002005 InitExprs.insert(C, InitExprs.end(), Init - InitExprs.size() + 1, nullptr);
Richard Smithc275da62013-12-06 01:27:24 +00002006 setInit(Init, expr);
Craig Topper36250ad2014-05-12 05:36:57 +00002007 return nullptr;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002008 }
Mike Stump11289f42009-09-09 15:08:12 +00002009
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002010 Expr *Result = cast_or_null<Expr>(InitExprs[Init]);
Richard Smithc275da62013-12-06 01:27:24 +00002011 setInit(Init, expr);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002012 return Result;
2013}
2014
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +00002015void InitListExpr::setArrayFiller(Expr *filler) {
Argyrios Kyrtzidisd4590a5d2011-10-21 23:02:22 +00002016 assert(!hasArrayFiller() && "Filler already set!");
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +00002017 ArrayFillerOrUnionFieldInit = filler;
2018 // Fill out any "holes" in the array due to designated initializers.
2019 Expr **inits = getInits();
2020 for (unsigned i = 0, e = getNumInits(); i != e; ++i)
Craig Topper36250ad2014-05-12 05:36:57 +00002021 if (inits[i] == nullptr)
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +00002022 inits[i] = filler;
2023}
2024
Richard Smith9ec1e482012-04-15 02:50:59 +00002025bool InitListExpr::isStringLiteralInit() const {
2026 if (getNumInits() != 1)
2027 return false;
Eli Friedmancf4ab082012-08-20 20:55:45 +00002028 const ArrayType *AT = getType()->getAsArrayTypeUnsafe();
2029 if (!AT || !AT->getElementType()->isIntegerType())
Richard Smith9ec1e482012-04-15 02:50:59 +00002030 return false;
Ted Kremenek256bd962014-01-19 06:31:34 +00002031 // It is possible for getInit() to return null.
2032 const Expr *Init = getInit(0);
2033 if (!Init)
2034 return false;
2035 Init = Init->IgnoreParens();
Richard Smith9ec1e482012-04-15 02:50:59 +00002036 return isa<StringLiteral>(Init) || isa<ObjCEncodeExpr>(Init);
2037}
2038
Richard Smith122f88d2016-12-06 23:52:28 +00002039bool InitListExpr::isTransparent() const {
2040 assert(isSemanticForm() && "syntactic form never semantically transparent");
2041
2042 // A glvalue InitListExpr is always just sugar.
2043 if (isGLValue()) {
2044 assert(getNumInits() == 1 && "multiple inits in glvalue init list");
2045 return true;
2046 }
2047
2048 // Otherwise, we're sugar if and only if we have exactly one initializer that
2049 // is of the same type.
2050 if (getNumInits() != 1 || !getInit(0))
2051 return false;
2052
Richard Smith382bc512017-02-23 22:41:47 +00002053 // Don't confuse aggregate initialization of a struct X { X &x; }; with a
2054 // transparent struct copy.
2055 if (!getInit(0)->isRValue() && getType()->isRecordType())
2056 return false;
2057
Richard Smith122f88d2016-12-06 23:52:28 +00002058 return getType().getCanonicalType() ==
2059 getInit(0)->getType().getCanonicalType();
2060}
2061
Daniel Marjamaki817a3bf2017-09-29 09:44:41 +00002062bool InitListExpr::isIdiomaticZeroInitializer(const LangOptions &LangOpts) const {
2063 assert(isSyntacticForm() && "only test syntactic form as zero initializer");
2064
2065 if (LangOpts.CPlusPlus || getNumInits() != 1) {
2066 return false;
2067 }
2068
2069 const IntegerLiteral *Lit = dyn_cast<IntegerLiteral>(getInit(0));
2070 return Lit && Lit->getValue() == 0;
2071}
2072
Stephen Kelly724e9e52018-08-09 20:05:03 +00002073SourceLocation InitListExpr::getBeginLoc() const {
Abramo Bagnara8d16bd42012-11-08 18:41:43 +00002074 if (InitListExpr *SyntacticForm = getSyntacticForm())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002075 return SyntacticForm->getBeginLoc();
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002076 SourceLocation Beg = LBraceLoc;
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002077 if (Beg.isInvalid()) {
2078 // Find the first non-null initializer.
2079 for (InitExprsTy::const_iterator I = InitExprs.begin(),
Fangrui Song6907ce22018-07-30 19:24:48 +00002080 E = InitExprs.end();
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002081 I != E; ++I) {
2082 if (Stmt *S = *I) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002083 Beg = S->getBeginLoc();
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002084 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00002085 }
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002086 }
2087 }
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002088 return Beg;
2089}
2090
Stephen Kelly02a67ba2018-08-09 20:05:47 +00002091SourceLocation InitListExpr::getEndLoc() const {
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002092 if (InitListExpr *SyntacticForm = getSyntacticForm())
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002093 return SyntacticForm->getEndLoc();
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002094 SourceLocation End = RBraceLoc;
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002095 if (End.isInvalid()) {
2096 // Find the first non-null initializer from the end.
2097 for (InitExprsTy::const_reverse_iterator I = InitExprs.rbegin(),
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002098 E = InitExprs.rend();
2099 I != E; ++I) {
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002100 if (Stmt *S = *I) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002101 End = S->getEndLoc();
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002102 break;
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002103 }
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002104 }
2105 }
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002106 return End;
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002107}
2108
Steve Naroff991e99d2008-09-04 15:31:07 +00002109/// getFunctionType - Return the underlying function type for this block.
Eugene Zelenkoae304b02017-11-17 18:09:48 +00002110///
John McCallc833dea2012-02-17 03:32:35 +00002111const FunctionProtoType *BlockExpr::getFunctionType() const {
2112 // The block pointer is never sugared, but the function type might be.
2113 return cast<BlockPointerType>(getType())
2114 ->getPointeeType()->castAs<FunctionProtoType>();
Steve Naroffc540d662008-09-03 18:15:37 +00002115}
2116
Mike Stump11289f42009-09-09 15:08:12 +00002117SourceLocation BlockExpr::getCaretLocation() const {
2118 return TheBlock->getCaretLocation();
Steve Naroff415d3d52008-10-08 17:01:13 +00002119}
Mike Stump11289f42009-09-09 15:08:12 +00002120const Stmt *BlockExpr::getBody() const {
Douglas Gregore3dcb2d2009-04-18 00:02:19 +00002121 return TheBlock->getBody();
2122}
Mike Stump11289f42009-09-09 15:08:12 +00002123Stmt *BlockExpr::getBody() {
2124 return TheBlock->getBody();
Douglas Gregore3dcb2d2009-04-18 00:02:19 +00002125}
Steve Naroff415d3d52008-10-08 17:01:13 +00002126
Eugene Zelenkoae304b02017-11-17 18:09:48 +00002127
Chris Lattner1ec5f562007-06-27 05:38:08 +00002128//===----------------------------------------------------------------------===//
2129// Generic Expression Routines
2130//===----------------------------------------------------------------------===//
2131
Chris Lattner237f2752009-02-14 07:37:35 +00002132/// isUnusedResultAWarning - Return true if this immediate expression should
2133/// be warned about if the result is unused. If so, fill in Loc and Ranges
2134/// with location to warn on and the source range[s] to report with the
2135/// warning.
Fangrui Song6907ce22018-07-30 19:24:48 +00002136bool Expr::isUnusedResultAWarning(const Expr *&WarnE, SourceLocation &Loc,
Eli Friedmanc11535c2012-05-24 00:47:05 +00002137 SourceRange &R1, SourceRange &R2,
2138 ASTContext &Ctx) const {
Anders Carlsson789e2cc2009-05-15 23:10:19 +00002139 // Don't warn if the expr is type dependent. The type could end up
2140 // instantiating to void.
2141 if (isTypeDependent())
2142 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002143
Chris Lattner1ec5f562007-06-27 05:38:08 +00002144 switch (getStmtClass()) {
2145 default:
John McCallc493a732010-03-12 07:11:26 +00002146 if (getType()->isVoidType())
2147 return false;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002148 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002149 Loc = getExprLoc();
2150 R1 = getSourceRange();
2151 return true;
Chris Lattner1ec5f562007-06-27 05:38:08 +00002152 case ParenExprClass:
Chris Lattner237f2752009-02-14 07:37:35 +00002153 return cast<ParenExpr>(this)->getSubExpr()->
Eli Friedmanc11535c2012-05-24 00:47:05 +00002154 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00002155 case GenericSelectionExprClass:
2156 return cast<GenericSelectionExpr>(this)->getResultExpr()->
Eli Friedmanc11535c2012-05-24 00:47:05 +00002157 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Eric Fiselier16269a82018-03-27 00:58:16 +00002158 case CoawaitExprClass:
Eric Fiselier855c0922018-03-27 03:33:06 +00002159 case CoyieldExprClass:
2160 return cast<CoroutineSuspendExpr>(this)->getResumeExpr()->
Eric Fiselier16269a82018-03-27 00:58:16 +00002161 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Eli Friedman75807f22013-07-20 00:40:58 +00002162 case ChooseExprClass:
2163 return cast<ChooseExpr>(this)->getChosenSubExpr()->
2164 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Chris Lattner1ec5f562007-06-27 05:38:08 +00002165 case UnaryOperatorClass: {
2166 const UnaryOperator *UO = cast<UnaryOperator>(this);
Mike Stump11289f42009-09-09 15:08:12 +00002167
Chris Lattner1ec5f562007-06-27 05:38:08 +00002168 switch (UO->getOpcode()) {
Eli Friedmanc11535c2012-05-24 00:47:05 +00002169 case UO_Plus:
2170 case UO_Minus:
2171 case UO_AddrOf:
2172 case UO_Not:
2173 case UO_LNot:
2174 case UO_Deref:
2175 break;
Richard Smith9f690bd2015-10-27 06:02:45 +00002176 case UO_Coawait:
2177 // This is just the 'operator co_await' call inside the guts of a
2178 // dependent co_await call.
John McCalle3027922010-08-25 11:45:40 +00002179 case UO_PostInc:
2180 case UO_PostDec:
2181 case UO_PreInc:
2182 case UO_PreDec: // ++/--
Chris Lattner237f2752009-02-14 07:37:35 +00002183 return false; // Not a warning.
John McCalle3027922010-08-25 11:45:40 +00002184 case UO_Real:
2185 case UO_Imag:
Chris Lattnera44d1162007-06-27 05:58:59 +00002186 // accessing a piece of a volatile complex is a side-effect.
Mike Stump53f9ded2009-11-03 23:25:48 +00002187 if (Ctx.getCanonicalType(UO->getSubExpr()->getType())
2188 .isVolatileQualified())
Chris Lattner237f2752009-02-14 07:37:35 +00002189 return false;
2190 break;
John McCalle3027922010-08-25 11:45:40 +00002191 case UO_Extension:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002192 return UO->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Chris Lattner1ec5f562007-06-27 05:38:08 +00002193 }
Eli Friedmanc11535c2012-05-24 00:47:05 +00002194 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002195 Loc = UO->getOperatorLoc();
2196 R1 = UO->getSubExpr()->getSourceRange();
2197 return true;
Chris Lattner1ec5f562007-06-27 05:38:08 +00002198 }
Chris Lattnerae7a8342007-12-01 06:07:34 +00002199 case BinaryOperatorClass: {
Chris Lattner237f2752009-02-14 07:37:35 +00002200 const BinaryOperator *BO = cast<BinaryOperator>(this);
Ted Kremenek43a9c962010-04-07 18:49:21 +00002201 switch (BO->getOpcode()) {
2202 default:
2203 break;
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00002204 // Consider the RHS of comma for side effects. LHS was checked by
2205 // Sema::CheckCommaOperands.
John McCalle3027922010-08-25 11:45:40 +00002206 case BO_Comma:
Ted Kremenek43a9c962010-04-07 18:49:21 +00002207 // ((foo = <blah>), 0) is an idiom for hiding the result (and
2208 // lvalue-ness) of an assignment written in a macro.
2209 if (IntegerLiteral *IE =
2210 dyn_cast<IntegerLiteral>(BO->getRHS()->IgnoreParens()))
2211 if (IE->getValue() == 0)
2212 return false;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002213 return BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00002214 // Consider '||', '&&' to have side effects if the LHS or RHS does.
John McCalle3027922010-08-25 11:45:40 +00002215 case BO_LAnd:
2216 case BO_LOr:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002217 if (!BO->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx) ||
2218 !BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx))
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00002219 return false;
2220 break;
John McCall1e3715a2010-02-16 04:10:53 +00002221 }
Chris Lattner237f2752009-02-14 07:37:35 +00002222 if (BO->isAssignmentOp())
2223 return false;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002224 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002225 Loc = BO->getOperatorLoc();
2226 R1 = BO->getLHS()->getSourceRange();
2227 R2 = BO->getRHS()->getSourceRange();
2228 return true;
Chris Lattnerae7a8342007-12-01 06:07:34 +00002229 }
Chris Lattner86928112007-08-25 02:00:02 +00002230 case CompoundAssignOperatorClass:
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00002231 case VAArgExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002232 case AtomicExprClass:
Chris Lattner237f2752009-02-14 07:37:35 +00002233 return false;
Chris Lattner1ec5f562007-06-27 05:38:08 +00002234
Fariborz Jahanian9fac54d2007-12-01 19:58:28 +00002235 case ConditionalOperatorClass: {
Ted Kremeneke96dad92011-03-01 20:34:48 +00002236 // If only one of the LHS or RHS is a warning, the operator might
2237 // be being used for control flow. Only warn if both the LHS and
2238 // RHS are warnings.
Fariborz Jahanian9fac54d2007-12-01 19:58:28 +00002239 const ConditionalOperator *Exp = cast<ConditionalOperator>(this);
Eli Friedmanc11535c2012-05-24 00:47:05 +00002240 if (!Exp->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx))
Ted Kremeneke96dad92011-03-01 20:34:48 +00002241 return false;
2242 if (!Exp->getLHS())
Chris Lattner237f2752009-02-14 07:37:35 +00002243 return true;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002244 return Exp->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Fariborz Jahanian9fac54d2007-12-01 19:58:28 +00002245 }
2246
Chris Lattnera44d1162007-06-27 05:58:59 +00002247 case MemberExprClass:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002248 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002249 Loc = cast<MemberExpr>(this)->getMemberLoc();
2250 R1 = SourceRange(Loc, Loc);
2251 R2 = cast<MemberExpr>(this)->getBase()->getSourceRange();
2252 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002253
Chris Lattner1ec5f562007-06-27 05:38:08 +00002254 case ArraySubscriptExprClass:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002255 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002256 Loc = cast<ArraySubscriptExpr>(this)->getRBracketLoc();
2257 R1 = cast<ArraySubscriptExpr>(this)->getLHS()->getSourceRange();
2258 R2 = cast<ArraySubscriptExpr>(this)->getRHS()->getSourceRange();
2259 return true;
Eli Friedman824f8c12008-05-27 15:24:04 +00002260
Chandler Carruth46339472011-08-17 09:49:44 +00002261 case CXXOperatorCallExprClass: {
Richard Trieu99e1c952014-03-11 03:11:08 +00002262 // Warn about operator ==,!=,<,>,<=, and >= even when user-defined operator
Chandler Carruth46339472011-08-17 09:49:44 +00002263 // overloads as there is no reasonable way to define these such that they
2264 // have non-trivial, desirable side-effects. See the -Wunused-comparison
Richard Trieu99e1c952014-03-11 03:11:08 +00002265 // warning: operators == and != are commonly typo'ed, and so warning on them
Chandler Carruth46339472011-08-17 09:49:44 +00002266 // provides additional value as well. If this list is updated,
2267 // DiagnoseUnusedComparison should be as well.
2268 const CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(this);
Richard Trieu99e1c952014-03-11 03:11:08 +00002269 switch (Op->getOperator()) {
2270 default:
2271 break;
2272 case OO_EqualEqual:
2273 case OO_ExclaimEqual:
2274 case OO_Less:
2275 case OO_Greater:
2276 case OO_GreaterEqual:
2277 case OO_LessEqual:
David Majnemerced8bdf2015-02-25 17:36:15 +00002278 if (Op->getCallReturnType(Ctx)->isReferenceType() ||
2279 Op->getCallReturnType(Ctx)->isVoidType())
Richard Trieu161132b2014-05-14 23:22:10 +00002280 break;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002281 WarnE = this;
Matt Beaumont-Gaydcaacaa2011-09-19 18:51:20 +00002282 Loc = Op->getOperatorLoc();
2283 R1 = Op->getSourceRange();
Chandler Carruth46339472011-08-17 09:49:44 +00002284 return true;
Matt Beaumont-Gaydcaacaa2011-09-19 18:51:20 +00002285 }
Chandler Carruth46339472011-08-17 09:49:44 +00002286
2287 // Fallthrough for generic call handling.
Galina Kistanovaf87496d2017-06-03 06:31:42 +00002288 LLVM_FALLTHROUGH;
Chandler Carruth46339472011-08-17 09:49:44 +00002289 }
Chris Lattner1ec5f562007-06-27 05:38:08 +00002290 case CallExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00002291 case CXXMemberCallExprClass:
2292 case UserDefinedLiteralClass: {
Chris Lattner237f2752009-02-14 07:37:35 +00002293 // If this is a direct call, get the callee.
2294 const CallExpr *CE = cast<CallExpr>(this);
Nuno Lopes518e3702009-12-20 23:11:08 +00002295 if (const Decl *FD = CE->getCalleeDecl()) {
Kaelyn Takata0a2e84c2015-04-09 19:43:04 +00002296 const FunctionDecl *Func = dyn_cast<FunctionDecl>(FD);
2297 bool HasWarnUnusedResultAttr = Func ? Func->hasUnusedResultAttr()
2298 : FD->hasAttr<WarnUnusedResultAttr>();
2299
Chris Lattner237f2752009-02-14 07:37:35 +00002300 // If the callee has attribute pure, const, or warn_unused_result, warn
2301 // about it. void foo() { strlen("bar"); } should warn.
Chris Lattner1a6babf2009-10-13 04:53:48 +00002302 //
2303 // Note: If new cases are added here, DiagnoseUnusedExprResult should be
2304 // updated to match for QoI.
Kaelyn Takata0a2e84c2015-04-09 19:43:04 +00002305 if (HasWarnUnusedResultAttr ||
Aaron Ballman9ead1242013-12-19 02:39:40 +00002306 FD->hasAttr<PureAttr>() || FD->hasAttr<ConstAttr>()) {
Eli Friedmanc11535c2012-05-24 00:47:05 +00002307 WarnE = this;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002308 Loc = CE->getCallee()->getBeginLoc();
Chris Lattner1a6babf2009-10-13 04:53:48 +00002309 R1 = CE->getCallee()->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002310
Chris Lattner1a6babf2009-10-13 04:53:48 +00002311 if (unsigned NumArgs = CE->getNumArgs())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002312 R2 = SourceRange(CE->getArg(0)->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002313 CE->getArg(NumArgs - 1)->getEndLoc());
Chris Lattner1a6babf2009-10-13 04:53:48 +00002314 return true;
2315 }
Chris Lattner237f2752009-02-14 07:37:35 +00002316 }
2317 return false;
2318 }
Anders Carlsson6aa50392009-11-17 17:11:23 +00002319
Matt Beaumont-Gayabf836c2012-10-23 06:15:26 +00002320 // If we don't know precisely what we're looking at, let's not warn.
2321 case UnresolvedLookupExprClass:
2322 case CXXUnresolvedConstructExprClass:
2323 return false;
2324
Anders Carlsson6aa50392009-11-17 17:11:23 +00002325 case CXXTemporaryObjectExprClass:
Eugene Zelenkoae304b02017-11-17 18:09:48 +00002326 case CXXConstructExprClass: {
Lubos Lunak1f490f32013-07-21 13:15:58 +00002327 if (const CXXRecordDecl *Type = getType()->getAsCXXRecordDecl()) {
2328 if (Type->hasAttr<WarnUnusedAttr>()) {
2329 WarnE = this;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002330 Loc = getBeginLoc();
Lubos Lunak1f490f32013-07-21 13:15:58 +00002331 R1 = getSourceRange();
2332 return true;
2333 }
2334 }
Anders Carlsson6aa50392009-11-17 17:11:23 +00002335 return false;
Eugene Zelenkoae304b02017-11-17 18:09:48 +00002336 }
Anders Carlsson6aa50392009-11-17 17:11:23 +00002337
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +00002338 case ObjCMessageExprClass: {
2339 const ObjCMessageExpr *ME = cast<ObjCMessageExpr>(this);
David Blaikiebbafb8a2012-03-11 07:00:24 +00002340 if (Ctx.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00002341 ME->isInstanceMessage() &&
2342 !ME->getType()->isVoidType() &&
Jean-Daniel Dupas06028a52013-07-19 20:25:56 +00002343 ME->getMethodFamily() == OMF_init) {
Eli Friedmanc11535c2012-05-24 00:47:05 +00002344 WarnE = this;
John McCall31168b02011-06-15 23:02:42 +00002345 Loc = getExprLoc();
2346 R1 = ME->getSourceRange();
2347 return true;
2348 }
2349
Fariborz Jahanianac6b4ef2014-07-18 22:59:10 +00002350 if (const ObjCMethodDecl *MD = ME->getMethodDecl())
Fariborz Jahanianb0553e22015-02-16 23:49:44 +00002351 if (MD->hasAttr<WarnUnusedResultAttr>()) {
Fariborz Jahanianac6b4ef2014-07-18 22:59:10 +00002352 WarnE = this;
2353 Loc = getExprLoc();
2354 return true;
2355 }
2356
Chris Lattner237f2752009-02-14 07:37:35 +00002357 return false;
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +00002358 }
Mike Stump11289f42009-09-09 15:08:12 +00002359
John McCallb7bd14f2010-12-02 01:19:52 +00002360 case ObjCPropertyRefExprClass:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002361 WarnE = this;
Chris Lattnerd37f61c2009-08-16 16:51:50 +00002362 Loc = getExprLoc();
2363 R1 = getSourceRange();
Chris Lattnerd8b800a2009-08-16 16:45:18 +00002364 return true;
John McCallb7bd14f2010-12-02 01:19:52 +00002365
John McCallfe96e0b2011-11-06 09:01:30 +00002366 case PseudoObjectExprClass: {
2367 const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this);
2368
2369 // Only complain about things that have the form of a getter.
2370 if (isa<UnaryOperator>(PO->getSyntacticForm()) ||
2371 isa<BinaryOperator>(PO->getSyntacticForm()))
2372 return false;
2373
Eli Friedmanc11535c2012-05-24 00:47:05 +00002374 WarnE = this;
John McCallfe96e0b2011-11-06 09:01:30 +00002375 Loc = getExprLoc();
2376 R1 = getSourceRange();
2377 return true;
2378 }
2379
Chris Lattner944d3062008-07-26 19:51:01 +00002380 case StmtExprClass: {
2381 // Statement exprs don't logically have side effects themselves, but are
2382 // sometimes used in macros in ways that give them a type that is unused.
2383 // For example ({ blah; foo(); }) will end up with a type if foo has a type.
2384 // however, if the result of the stmt expr is dead, we don't want to emit a
2385 // warning.
2386 const CompoundStmt *CS = cast<StmtExpr>(this)->getSubStmt();
Argyrios Kyrtzidis90963412010-09-19 21:21:10 +00002387 if (!CS->body_empty()) {
Chris Lattner944d3062008-07-26 19:51:01 +00002388 if (const Expr *E = dyn_cast<Expr>(CS->body_back()))
Eli Friedmanc11535c2012-05-24 00:47:05 +00002389 return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Argyrios Kyrtzidis90963412010-09-19 21:21:10 +00002390 if (const LabelStmt *Label = dyn_cast<LabelStmt>(CS->body_back()))
2391 if (const Expr *E = dyn_cast<Expr>(Label->getSubStmt()))
Eli Friedmanc11535c2012-05-24 00:47:05 +00002392 return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Argyrios Kyrtzidis90963412010-09-19 21:21:10 +00002393 }
Mike Stump11289f42009-09-09 15:08:12 +00002394
John McCallc493a732010-03-12 07:11:26 +00002395 if (getType()->isVoidType())
2396 return false;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002397 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002398 Loc = cast<StmtExpr>(this)->getLParenLoc();
2399 R1 = getSourceRange();
2400 return true;
Chris Lattner944d3062008-07-26 19:51:01 +00002401 }
Eli Friedmanbdd57532012-09-24 23:02:26 +00002402 case CXXFunctionalCastExprClass:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002403 case CStyleCastExprClass: {
Eli Friedmanf92f6452012-05-24 21:05:41 +00002404 // Ignore an explicit cast to void unless the operand is a non-trivial
Eli Friedmanc11535c2012-05-24 00:47:05 +00002405 // volatile lvalue.
Eli Friedmanf92f6452012-05-24 21:05:41 +00002406 const CastExpr *CE = cast<CastExpr>(this);
Eli Friedmanc11535c2012-05-24 00:47:05 +00002407 if (CE->getCastKind() == CK_ToVoid) {
2408 if (CE->getSubExpr()->isGLValue() &&
Eli Friedmanf92f6452012-05-24 21:05:41 +00002409 CE->getSubExpr()->getType().isVolatileQualified()) {
2410 const DeclRefExpr *DRE =
2411 dyn_cast<DeclRefExpr>(CE->getSubExpr()->IgnoreParens());
2412 if (!(DRE && isa<VarDecl>(DRE->getDecl()) &&
Erich Keane80b0fb02017-10-19 15:58:58 +00002413 cast<VarDecl>(DRE->getDecl())->hasLocalStorage()) &&
2414 !isa<CallExpr>(CE->getSubExpr()->IgnoreParens())) {
Eli Friedmanf92f6452012-05-24 21:05:41 +00002415 return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc,
2416 R1, R2, Ctx);
2417 }
2418 }
Chris Lattner2706a552009-07-28 18:25:28 +00002419 return false;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002420 }
Eli Friedmanf92f6452012-05-24 21:05:41 +00002421
Eli Friedmanc11535c2012-05-24 00:47:05 +00002422 // If this is a cast to a constructor conversion, check the operand.
Anders Carlsson6aa50392009-11-17 17:11:23 +00002423 // Otherwise, the result of the cast is unused.
Eli Friedmanc11535c2012-05-24 00:47:05 +00002424 if (CE->getCastKind() == CK_ConstructorConversion)
2425 return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Eli Friedmanf92f6452012-05-24 21:05:41 +00002426
Eli Friedmanc11535c2012-05-24 00:47:05 +00002427 WarnE = this;
Eli Friedmanf92f6452012-05-24 21:05:41 +00002428 if (const CXXFunctionalCastExpr *CXXCE =
2429 dyn_cast<CXXFunctionalCastExpr>(this)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002430 Loc = CXXCE->getBeginLoc();
Eli Friedmanf92f6452012-05-24 21:05:41 +00002431 R1 = CXXCE->getSubExpr()->getSourceRange();
2432 } else {
2433 const CStyleCastExpr *CStyleCE = cast<CStyleCastExpr>(this);
2434 Loc = CStyleCE->getLParenLoc();
2435 R1 = CStyleCE->getSubExpr()->getSourceRange();
2436 }
Chris Lattner237f2752009-02-14 07:37:35 +00002437 return true;
Anders Carlsson6aa50392009-11-17 17:11:23 +00002438 }
Eli Friedmanc11535c2012-05-24 00:47:05 +00002439 case ImplicitCastExprClass: {
2440 const CastExpr *ICE = cast<ImplicitCastExpr>(this);
Eli Friedmanca8da1d2008-05-19 21:24:43 +00002441
Eli Friedmanc11535c2012-05-24 00:47:05 +00002442 // lvalue-to-rvalue conversion on a volatile lvalue is a side-effect.
2443 if (ICE->getCastKind() == CK_LValueToRValue &&
2444 ICE->getSubExpr()->getType().isVolatileQualified())
2445 return false;
2446
2447 return ICE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2448 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002449 case CXXDefaultArgExprClass:
Mike Stump53f9ded2009-11-03 23:25:48 +00002450 return (cast<CXXDefaultArgExpr>(this)
Eli Friedmanc11535c2012-05-24 00:47:05 +00002451 ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
Richard Smith852c9db2013-04-20 22:23:05 +00002452 case CXXDefaultInitExprClass:
2453 return (cast<CXXDefaultInitExpr>(this)
2454 ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
Sebastian Redlbd150f42008-11-21 19:14:01 +00002455
2456 case CXXNewExprClass:
2457 // FIXME: In theory, there might be new expressions that don't have side
2458 // effects (e.g. a placement new with an uninitialized POD).
2459 case CXXDeleteExprClass:
Chris Lattner237f2752009-02-14 07:37:35 +00002460 return false;
Richard Smith122f88d2016-12-06 23:52:28 +00002461 case MaterializeTemporaryExprClass:
2462 return cast<MaterializeTemporaryExpr>(this)->GetTemporaryExpr()
2463 ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Anders Carlssone80ccac2009-08-16 04:11:06 +00002464 case CXXBindTemporaryExprClass:
Richard Smith122f88d2016-12-06 23:52:28 +00002465 return cast<CXXBindTemporaryExpr>(this)->getSubExpr()
2466 ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
John McCall5d413782010-12-06 08:20:24 +00002467 case ExprWithCleanupsClass:
Richard Smith122f88d2016-12-06 23:52:28 +00002468 return cast<ExprWithCleanups>(this)->getSubExpr()
2469 ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Sebastian Redlbd150f42008-11-21 19:14:01 +00002470 }
Chris Lattner1ec5f562007-06-27 05:38:08 +00002471}
2472
Fariborz Jahanian07735332009-02-22 18:40:18 +00002473/// isOBJCGCCandidate - Check if an expression is objc gc'able.
Fariborz Jahanian063c7722009-09-08 23:38:54 +00002474/// returns true, if it is; false otherwise.
Fariborz Jahanianc6d98002009-06-01 21:29:32 +00002475bool Expr::isOBJCGCCandidate(ASTContext &Ctx) const {
Peter Collingbourne91147592011-04-15 00:35:48 +00002476 const Expr *E = IgnoreParens();
2477 switch (E->getStmtClass()) {
Fariborz Jahanian07735332009-02-22 18:40:18 +00002478 default:
2479 return false;
2480 case ObjCIvarRefExprClass:
2481 return true;
Fariborz Jahanian392124c2009-02-23 18:59:50 +00002482 case Expr::UnaryOperatorClass:
Peter Collingbourne91147592011-04-15 00:35:48 +00002483 return cast<UnaryOperator>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
Fariborz Jahanian07735332009-02-22 18:40:18 +00002484 case ImplicitCastExprClass:
Peter Collingbourne91147592011-04-15 00:35:48 +00002485 return cast<ImplicitCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
Douglas Gregorfe314812011-06-21 17:03:29 +00002486 case MaterializeTemporaryExprClass:
2487 return cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr()
2488 ->isOBJCGCCandidate(Ctx);
Fariborz Jahaniana16904b2009-05-05 23:28:21 +00002489 case CStyleCastExprClass:
Peter Collingbourne91147592011-04-15 00:35:48 +00002490 return cast<CStyleCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002491 case DeclRefExprClass: {
John McCall113bee02012-03-10 09:33:50 +00002492 const Decl *D = cast<DeclRefExpr>(E)->getDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +00002493
Fariborz Jahanianc6d98002009-06-01 21:29:32 +00002494 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2495 if (VD->hasGlobalStorage())
2496 return true;
2497 QualType T = VD->getType();
Fariborz Jahaniancceedbf2009-09-16 18:09:18 +00002498 // dereferencing to a pointer is always a gc'able candidate,
2499 // unless it is __weak.
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00002500 return T->isPointerType() &&
John McCall8ccfcb52009-09-24 19:53:00 +00002501 (Ctx.getObjCGCAttrKind(T) != Qualifiers::Weak);
Fariborz Jahanianc6d98002009-06-01 21:29:32 +00002502 }
Fariborz Jahanian07735332009-02-22 18:40:18 +00002503 return false;
2504 }
Douglas Gregorf405d7e2009-08-31 23:41:50 +00002505 case MemberExprClass: {
Peter Collingbourne91147592011-04-15 00:35:48 +00002506 const MemberExpr *M = cast<MemberExpr>(E);
Fariborz Jahanianc6d98002009-06-01 21:29:32 +00002507 return M->getBase()->isOBJCGCCandidate(Ctx);
Fariborz Jahanian07735332009-02-22 18:40:18 +00002508 }
2509 case ArraySubscriptExprClass:
Peter Collingbourne91147592011-04-15 00:35:48 +00002510 return cast<ArraySubscriptExpr>(E)->getBase()->isOBJCGCCandidate(Ctx);
Fariborz Jahanian07735332009-02-22 18:40:18 +00002511 }
2512}
Sebastian Redlce354af2010-09-10 20:55:33 +00002513
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +00002514bool Expr::isBoundMemberFunction(ASTContext &Ctx) const {
2515 if (isTypeDependent())
2516 return false;
John McCall086a4642010-11-24 05:12:34 +00002517 return ClassifyLValue(Ctx) == Expr::LV_MemberFunction;
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +00002518}
2519
John McCall0009fcc2011-04-26 20:42:42 +00002520QualType Expr::findBoundMemberType(const Expr *expr) {
John McCalle314e272011-10-18 21:02:43 +00002521 assert(expr->hasPlaceholderType(BuiltinType::BoundMember));
John McCall0009fcc2011-04-26 20:42:42 +00002522
2523 // Bound member expressions are always one of these possibilities:
2524 // x->m x.m x->*y x.*y
2525 // (possibly parenthesized)
2526
2527 expr = expr->IgnoreParens();
2528 if (const MemberExpr *mem = dyn_cast<MemberExpr>(expr)) {
2529 assert(isa<CXXMethodDecl>(mem->getMemberDecl()));
2530 return mem->getMemberDecl()->getType();
2531 }
2532
2533 if (const BinaryOperator *op = dyn_cast<BinaryOperator>(expr)) {
2534 QualType type = op->getRHS()->getType()->castAs<MemberPointerType>()
2535 ->getPointeeType();
2536 assert(type->isFunctionType());
2537 return type;
2538 }
2539
David Majnemerced8bdf2015-02-25 17:36:15 +00002540 assert(isa<UnresolvedMemberExpr>(expr) || isa<CXXPseudoDestructorExpr>(expr));
John McCall0009fcc2011-04-26 20:42:42 +00002541 return QualType();
2542}
2543
Ted Kremenekfff70962008-01-17 16:57:34 +00002544Expr* Expr::IgnoreParens() {
2545 Expr* E = this;
Abramo Bagnara932e3932010-10-15 07:51:18 +00002546 while (true) {
2547 if (ParenExpr* P = dyn_cast<ParenExpr>(E)) {
2548 E = P->getSubExpr();
2549 continue;
2550 }
2551 if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) {
2552 if (P->getOpcode() == UO_Extension) {
2553 E = P->getSubExpr();
2554 continue;
2555 }
2556 }
Peter Collingbourne91147592011-04-15 00:35:48 +00002557 if (GenericSelectionExpr* P = dyn_cast<GenericSelectionExpr>(E)) {
2558 if (!P->isResultDependent()) {
2559 E = P->getResultExpr();
2560 continue;
2561 }
2562 }
Eli Friedman75807f22013-07-20 00:40:58 +00002563 if (ChooseExpr* P = dyn_cast<ChooseExpr>(E)) {
2564 if (!P->isConditionDependent()) {
2565 E = P->getChosenSubExpr();
2566 continue;
2567 }
2568 }
Abramo Bagnara932e3932010-10-15 07:51:18 +00002569 return E;
2570 }
Ted Kremenekfff70962008-01-17 16:57:34 +00002571}
2572
Chris Lattnerf2660962008-02-13 01:02:39 +00002573/// IgnoreParenCasts - Ignore parentheses and casts. Strip off any ParenExpr
2574/// or CastExprs or ImplicitCastExprs, returning their operand.
2575Expr *Expr::IgnoreParenCasts() {
2576 Expr *E = this;
2577 while (true) {
Eli Friedman75807f22013-07-20 00:40:58 +00002578 E = E->IgnoreParens();
Abramo Bagnara932e3932010-10-15 07:51:18 +00002579 if (CastExpr *P = dyn_cast<CastExpr>(E)) {
Chris Lattnerf2660962008-02-13 01:02:39 +00002580 E = P->getSubExpr();
Abramo Bagnara932e3932010-10-15 07:51:18 +00002581 continue;
2582 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002583 if (MaterializeTemporaryExpr *Materialize
Douglas Gregorfe314812011-06-21 17:03:29 +00002584 = dyn_cast<MaterializeTemporaryExpr>(E)) {
2585 E = Materialize->GetTemporaryExpr();
2586 continue;
2587 }
Douglas Gregor6a40b082011-09-08 17:56:33 +00002588 if (SubstNonTypeTemplateParmExpr *NTTP
2589 = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2590 E = NTTP->getReplacement();
2591 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +00002592 }
Abramo Bagnara932e3932010-10-15 07:51:18 +00002593 return E;
Chris Lattnerf2660962008-02-13 01:02:39 +00002594 }
2595}
2596
Ted Kremenek6f375e52014-04-16 07:26:09 +00002597Expr *Expr::IgnoreCasts() {
2598 Expr *E = this;
2599 while (true) {
2600 if (CastExpr *P = dyn_cast<CastExpr>(E)) {
2601 E = P->getSubExpr();
2602 continue;
2603 }
2604 if (MaterializeTemporaryExpr *Materialize
2605 = dyn_cast<MaterializeTemporaryExpr>(E)) {
2606 E = Materialize->GetTemporaryExpr();
2607 continue;
2608 }
2609 if (SubstNonTypeTemplateParmExpr *NTTP
2610 = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2611 E = NTTP->getReplacement();
2612 continue;
2613 }
2614 return E;
2615 }
2616}
2617
John McCall5a4ce8b2010-12-04 08:24:19 +00002618/// IgnoreParenLValueCasts - Ignore parentheses and lvalue-to-rvalue
2619/// casts. This is intended purely as a temporary workaround for code
2620/// that hasn't yet been rewritten to do the right thing about those
2621/// casts, and may disappear along with the last internal use.
John McCall34376a62010-12-04 03:47:34 +00002622Expr *Expr::IgnoreParenLValueCasts() {
2623 Expr *E = this;
John McCall5a4ce8b2010-12-04 08:24:19 +00002624 while (true) {
Eli Friedman75807f22013-07-20 00:40:58 +00002625 E = E->IgnoreParens();
2626 if (CastExpr *P = dyn_cast<CastExpr>(E)) {
John McCall34376a62010-12-04 03:47:34 +00002627 if (P->getCastKind() == CK_LValueToRValue) {
2628 E = P->getSubExpr();
2629 continue;
2630 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002631 } else if (MaterializeTemporaryExpr *Materialize
Douglas Gregorfe314812011-06-21 17:03:29 +00002632 = dyn_cast<MaterializeTemporaryExpr>(E)) {
2633 E = Materialize->GetTemporaryExpr();
2634 continue;
Douglas Gregor6a40b082011-09-08 17:56:33 +00002635 } else if (SubstNonTypeTemplateParmExpr *NTTP
2636 = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2637 E = NTTP->getReplacement();
2638 continue;
John McCall34376a62010-12-04 03:47:34 +00002639 }
2640 break;
2641 }
2642 return E;
2643}
Rafael Espindolaecbe2e92012-06-28 01:56:38 +00002644
2645Expr *Expr::ignoreParenBaseCasts() {
2646 Expr *E = this;
2647 while (true) {
Eli Friedman75807f22013-07-20 00:40:58 +00002648 E = E->IgnoreParens();
Rafael Espindolaecbe2e92012-06-28 01:56:38 +00002649 if (CastExpr *CE = dyn_cast<CastExpr>(E)) {
2650 if (CE->getCastKind() == CK_DerivedToBase ||
2651 CE->getCastKind() == CK_UncheckedDerivedToBase ||
2652 CE->getCastKind() == CK_NoOp) {
2653 E = CE->getSubExpr();
2654 continue;
2655 }
2656 }
2657
2658 return E;
2659 }
2660}
2661
John McCalleebc8322010-05-05 22:59:52 +00002662Expr *Expr::IgnoreParenImpCasts() {
2663 Expr *E = this;
2664 while (true) {
Eli Friedman75807f22013-07-20 00:40:58 +00002665 E = E->IgnoreParens();
Abramo Bagnara932e3932010-10-15 07:51:18 +00002666 if (ImplicitCastExpr *P = dyn_cast<ImplicitCastExpr>(E)) {
John McCalleebc8322010-05-05 22:59:52 +00002667 E = P->getSubExpr();
Abramo Bagnara932e3932010-10-15 07:51:18 +00002668 continue;
2669 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002670 if (MaterializeTemporaryExpr *Materialize
Douglas Gregorfe314812011-06-21 17:03:29 +00002671 = dyn_cast<MaterializeTemporaryExpr>(E)) {
2672 E = Materialize->GetTemporaryExpr();
2673 continue;
2674 }
Douglas Gregor6a40b082011-09-08 17:56:33 +00002675 if (SubstNonTypeTemplateParmExpr *NTTP
2676 = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2677 E = NTTP->getReplacement();
2678 continue;
2679 }
Abramo Bagnara932e3932010-10-15 07:51:18 +00002680 return E;
John McCalleebc8322010-05-05 22:59:52 +00002681 }
2682}
2683
Hans Wennborgde2e67e2011-06-09 17:06:51 +00002684Expr *Expr::IgnoreConversionOperator() {
2685 if (CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(this)) {
Chandler Carruth4352b0b2011-06-21 17:22:09 +00002686 if (MCE->getMethodDecl() && isa<CXXConversionDecl>(MCE->getMethodDecl()))
Hans Wennborgde2e67e2011-06-09 17:06:51 +00002687 return MCE->getImplicitObjectArgument();
2688 }
2689 return this;
2690}
2691
Chris Lattneref26c772009-03-13 17:28:01 +00002692/// IgnoreParenNoopCasts - Ignore parentheses and casts that do not change the
2693/// value (including ptr->int casts of the same size). Strip off any
2694/// ParenExpr or CastExprs, returning their operand.
2695Expr *Expr::IgnoreParenNoopCasts(ASTContext &Ctx) {
2696 Expr *E = this;
2697 while (true) {
Eli Friedman75807f22013-07-20 00:40:58 +00002698 E = E->IgnoreParens();
Mike Stump11289f42009-09-09 15:08:12 +00002699
Chris Lattneref26c772009-03-13 17:28:01 +00002700 if (CastExpr *P = dyn_cast<CastExpr>(E)) {
2701 // We ignore integer <-> casts that are of the same width, ptr<->ptr and
Douglas Gregorb90df602010-06-16 00:17:44 +00002702 // ptr<->int casts of the same width. We also ignore all identity casts.
Chris Lattneref26c772009-03-13 17:28:01 +00002703 Expr *SE = P->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002704
Chris Lattneref26c772009-03-13 17:28:01 +00002705 if (Ctx.hasSameUnqualifiedType(E->getType(), SE->getType())) {
2706 E = SE;
2707 continue;
2708 }
Mike Stump11289f42009-09-09 15:08:12 +00002709
Abramo Bagnara932e3932010-10-15 07:51:18 +00002710 if ((E->getType()->isPointerType() ||
Douglas Gregor6972a622010-06-16 00:35:25 +00002711 E->getType()->isIntegralType(Ctx)) &&
Abramo Bagnara932e3932010-10-15 07:51:18 +00002712 (SE->getType()->isPointerType() ||
Douglas Gregor6972a622010-06-16 00:35:25 +00002713 SE->getType()->isIntegralType(Ctx)) &&
Chris Lattneref26c772009-03-13 17:28:01 +00002714 Ctx.getTypeSize(E->getType()) == Ctx.getTypeSize(SE->getType())) {
2715 E = SE;
2716 continue;
2717 }
2718 }
Mike Stump11289f42009-09-09 15:08:12 +00002719
Douglas Gregor6a40b082011-09-08 17:56:33 +00002720 if (SubstNonTypeTemplateParmExpr *NTTP
2721 = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2722 E = NTTP->getReplacement();
2723 continue;
2724 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002725
Chris Lattneref26c772009-03-13 17:28:01 +00002726 return E;
2727 }
2728}
2729
Douglas Gregord196a582009-12-14 19:27:10 +00002730bool Expr::isDefaultArgument() const {
2731 const Expr *E = this;
Douglas Gregorfe314812011-06-21 17:03:29 +00002732 if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
2733 E = M->GetTemporaryExpr();
2734
Douglas Gregord196a582009-12-14 19:27:10 +00002735 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
2736 E = ICE->getSubExprAsWritten();
Fangrui Song6907ce22018-07-30 19:24:48 +00002737
Douglas Gregord196a582009-12-14 19:27:10 +00002738 return isa<CXXDefaultArgExpr>(E);
2739}
Chris Lattneref26c772009-03-13 17:28:01 +00002740
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002741/// Skip over any no-op casts and any temporary-binding
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002742/// expressions.
Anders Carlsson66bbf502010-11-28 16:40:49 +00002743static const Expr *skipTemporaryBindingsNoOpCastsAndParens(const Expr *E) {
Douglas Gregorfe314812011-06-21 17:03:29 +00002744 if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
2745 E = M->GetTemporaryExpr();
2746
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002747 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCalle3027922010-08-25 11:45:40 +00002748 if (ICE->getCastKind() == CK_NoOp)
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002749 E = ICE->getSubExpr();
2750 else
2751 break;
2752 }
2753
2754 while (const CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
2755 E = BE->getSubExpr();
2756
2757 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCalle3027922010-08-25 11:45:40 +00002758 if (ICE->getCastKind() == CK_NoOp)
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002759 E = ICE->getSubExpr();
2760 else
2761 break;
2762 }
Anders Carlsson66bbf502010-11-28 16:40:49 +00002763
2764 return E->IgnoreParens();
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002765}
2766
John McCall7a626f62010-09-15 10:14:12 +00002767/// isTemporaryObject - Determines if this expression produces a
2768/// temporary of the given class type.
2769bool Expr::isTemporaryObject(ASTContext &C, const CXXRecordDecl *TempTy) const {
2770 if (!C.hasSameUnqualifiedType(getType(), C.getTypeDeclType(TempTy)))
2771 return false;
2772
Anders Carlsson66bbf502010-11-28 16:40:49 +00002773 const Expr *E = skipTemporaryBindingsNoOpCastsAndParens(this);
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002774
John McCall02dc8c72010-09-15 20:59:13 +00002775 // Temporaries are by definition pr-values of class type.
Fariborz Jahanian30e8d582010-09-27 17:30:38 +00002776 if (!E->Classify(C).isPRValue()) {
2777 // In this context, property reference is a message call and is pr-value.
John McCallb7bd14f2010-12-02 01:19:52 +00002778 if (!isa<ObjCPropertyRefExpr>(E))
Fariborz Jahanian30e8d582010-09-27 17:30:38 +00002779 return false;
2780 }
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002781
John McCallf4ee1dd2010-09-16 06:57:56 +00002782 // Black-list a few cases which yield pr-values of class type that don't
2783 // refer to temporaries of that type:
2784
2785 // - implicit derived-to-base conversions
John McCall7a626f62010-09-15 10:14:12 +00002786 if (isa<ImplicitCastExpr>(E)) {
2787 switch (cast<ImplicitCastExpr>(E)->getCastKind()) {
2788 case CK_DerivedToBase:
2789 case CK_UncheckedDerivedToBase:
2790 return false;
2791 default:
2792 break;
2793 }
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002794 }
2795
John McCallf4ee1dd2010-09-16 06:57:56 +00002796 // - member expressions (all)
2797 if (isa<MemberExpr>(E))
2798 return false;
2799
Eli Friedman13ffdd82012-06-15 23:51:06 +00002800 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E))
2801 if (BO->isPtrMemOp())
2802 return false;
2803
John McCallc07a0c72011-02-17 10:25:35 +00002804 // - opaque values (all)
2805 if (isa<OpaqueValueExpr>(E))
2806 return false;
2807
John McCall7a626f62010-09-15 10:14:12 +00002808 return true;
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002809}
2810
Douglas Gregor25b7e052011-03-02 21:06:53 +00002811bool Expr::isImplicitCXXThis() const {
2812 const Expr *E = this;
Fangrui Song6907ce22018-07-30 19:24:48 +00002813
Douglas Gregor25b7e052011-03-02 21:06:53 +00002814 // Strip away parentheses and casts we don't care about.
2815 while (true) {
2816 if (const ParenExpr *Paren = dyn_cast<ParenExpr>(E)) {
2817 E = Paren->getSubExpr();
2818 continue;
2819 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002820
Douglas Gregor25b7e052011-03-02 21:06:53 +00002821 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2822 if (ICE->getCastKind() == CK_NoOp ||
2823 ICE->getCastKind() == CK_LValueToRValue ||
Fangrui Song6907ce22018-07-30 19:24:48 +00002824 ICE->getCastKind() == CK_DerivedToBase ||
Douglas Gregor25b7e052011-03-02 21:06:53 +00002825 ICE->getCastKind() == CK_UncheckedDerivedToBase) {
2826 E = ICE->getSubExpr();
2827 continue;
2828 }
2829 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002830
Douglas Gregor25b7e052011-03-02 21:06:53 +00002831 if (const UnaryOperator* UnOp = dyn_cast<UnaryOperator>(E)) {
2832 if (UnOp->getOpcode() == UO_Extension) {
2833 E = UnOp->getSubExpr();
2834 continue;
2835 }
2836 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002837
Douglas Gregorfe314812011-06-21 17:03:29 +00002838 if (const MaterializeTemporaryExpr *M
2839 = dyn_cast<MaterializeTemporaryExpr>(E)) {
2840 E = M->GetTemporaryExpr();
2841 continue;
2842 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002843
Douglas Gregor25b7e052011-03-02 21:06:53 +00002844 break;
2845 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002846
Douglas Gregor25b7e052011-03-02 21:06:53 +00002847 if (const CXXThisExpr *This = dyn_cast<CXXThisExpr>(E))
2848 return This->isImplicit();
Fangrui Song6907ce22018-07-30 19:24:48 +00002849
Douglas Gregor25b7e052011-03-02 21:06:53 +00002850 return false;
2851}
2852
Douglas Gregor4619e432008-12-05 23:32:09 +00002853/// hasAnyTypeDependentArguments - Determines if any of the expressions
2854/// in Exprs is type-dependent.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002855bool Expr::hasAnyTypeDependentArguments(ArrayRef<Expr *> Exprs) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002856 for (unsigned I = 0; I < Exprs.size(); ++I)
Douglas Gregor4619e432008-12-05 23:32:09 +00002857 if (Exprs[I]->isTypeDependent())
2858 return true;
2859
2860 return false;
2861}
2862
Abramo Bagnara847c6602014-05-22 19:20:46 +00002863bool Expr::isConstantInitializer(ASTContext &Ctx, bool IsForRef,
2864 const Expr **Culprit) const {
Eli Friedman384da272009-01-25 03:12:18 +00002865 // This function is attempting whether an expression is an initializer
Eli Friedman4c27ac22013-07-16 22:40:53 +00002866 // which can be evaluated at compile-time. It very closely parallels
2867 // ConstExprEmitter in CGExprConstant.cpp; if they don't match, it
2868 // will lead to unexpected results. Like ConstExprEmitter, it falls back
2869 // to isEvaluatable most of the time.
2870 //
John McCall8b0f4ff2010-08-02 21:13:48 +00002871 // If we ever capture reference-binding directly in the AST, we can
2872 // kill the second parameter.
2873
2874 if (IsForRef) {
2875 EvalResult Result;
Abramo Bagnara847c6602014-05-22 19:20:46 +00002876 if (EvaluateAsLValue(Result, Ctx) && !Result.HasSideEffects)
2877 return true;
2878 if (Culprit)
2879 *Culprit = this;
2880 return false;
John McCall8b0f4ff2010-08-02 21:13:48 +00002881 }
Eli Friedmancf7cbe72009-02-20 02:36:22 +00002882
Anders Carlssona7c5eb72008-11-24 05:23:59 +00002883 switch (getStmtClass()) {
Eli Friedman384da272009-01-25 03:12:18 +00002884 default: break;
Anders Carlssona7c5eb72008-11-24 05:23:59 +00002885 case StringLiteralClass:
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00002886 case ObjCEncodeExprClass:
Anders Carlssona7c5eb72008-11-24 05:23:59 +00002887 return true;
John McCall81c9cea2010-08-01 21:51:45 +00002888 case CXXTemporaryObjectExprClass:
2889 case CXXConstructExprClass: {
2890 const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
John McCall8b0f4ff2010-08-02 21:13:48 +00002891
Eli Friedman4c27ac22013-07-16 22:40:53 +00002892 if (CE->getConstructor()->isTrivial() &&
2893 CE->getConstructor()->getParent()->hasTrivialDestructor()) {
2894 // Trivial default constructor
Richard Smithd62306a2011-11-10 06:34:14 +00002895 if (!CE->getNumArgs()) return true;
John McCall8b0f4ff2010-08-02 21:13:48 +00002896
Eli Friedman4c27ac22013-07-16 22:40:53 +00002897 // Trivial copy constructor
2898 assert(CE->getNumArgs() == 1 && "trivial ctor with > 1 argument");
Abramo Bagnara847c6602014-05-22 19:20:46 +00002899 return CE->getArg(0)->isConstantInitializer(Ctx, false, Culprit);
Richard Smithd62306a2011-11-10 06:34:14 +00002900 }
2901
Richard Smithd62306a2011-11-10 06:34:14 +00002902 break;
John McCall81c9cea2010-08-01 21:51:45 +00002903 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002904 case CompoundLiteralExprClass: {
Eli Friedmancf7cbe72009-02-20 02:36:22 +00002905 // This handles gcc's extension that allows global initializers like
2906 // "struct x {int x;} x = (struct x) {};".
2907 // FIXME: This accepts other cases it shouldn't!
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002908 const Expr *Exp = cast<CompoundLiteralExpr>(this)->getInitializer();
Abramo Bagnara847c6602014-05-22 19:20:46 +00002909 return Exp->isConstantInitializer(Ctx, false, Culprit);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002910 }
Yunzhong Gaocb779302015-06-10 00:27:52 +00002911 case DesignatedInitUpdateExprClass: {
2912 const DesignatedInitUpdateExpr *DIUE = cast<DesignatedInitUpdateExpr>(this);
2913 return DIUE->getBase()->isConstantInitializer(Ctx, false, Culprit) &&
2914 DIUE->getUpdater()->isConstantInitializer(Ctx, false, Culprit);
2915 }
Anders Carlssona7c5eb72008-11-24 05:23:59 +00002916 case InitListExprClass: {
Eli Friedman4c27ac22013-07-16 22:40:53 +00002917 const InitListExpr *ILE = cast<InitListExpr>(this);
2918 if (ILE->getType()->isArrayType()) {
2919 unsigned numInits = ILE->getNumInits();
2920 for (unsigned i = 0; i < numInits; i++) {
Abramo Bagnara847c6602014-05-22 19:20:46 +00002921 if (!ILE->getInit(i)->isConstantInitializer(Ctx, false, Culprit))
Eli Friedman4c27ac22013-07-16 22:40:53 +00002922 return false;
2923 }
2924 return true;
Anders Carlssona7c5eb72008-11-24 05:23:59 +00002925 }
Eli Friedman4c27ac22013-07-16 22:40:53 +00002926
2927 if (ILE->getType()->isRecordType()) {
2928 unsigned ElementNo = 0;
2929 RecordDecl *RD = ILE->getType()->getAs<RecordType>()->getDecl();
Hans Wennborga302cd92014-08-21 16:06:57 +00002930 for (const auto *Field : RD->fields()) {
Eli Friedman4c27ac22013-07-16 22:40:53 +00002931 // If this is a union, skip all the fields that aren't being initialized.
Hans Wennborga302cd92014-08-21 16:06:57 +00002932 if (RD->isUnion() && ILE->getInitializedFieldInUnion() != Field)
Eli Friedman4c27ac22013-07-16 22:40:53 +00002933 continue;
2934
2935 // Don't emit anonymous bitfields, they just affect layout.
2936 if (Field->isUnnamedBitfield())
2937 continue;
2938
2939 if (ElementNo < ILE->getNumInits()) {
2940 const Expr *Elt = ILE->getInit(ElementNo++);
2941 if (Field->isBitField()) {
2942 // Bitfields have to evaluate to an integer.
2943 llvm::APSInt ResultTmp;
Abramo Bagnara847c6602014-05-22 19:20:46 +00002944 if (!Elt->EvaluateAsInt(ResultTmp, Ctx)) {
2945 if (Culprit)
2946 *Culprit = Elt;
Eli Friedman4c27ac22013-07-16 22:40:53 +00002947 return false;
Abramo Bagnara847c6602014-05-22 19:20:46 +00002948 }
Eli Friedman4c27ac22013-07-16 22:40:53 +00002949 } else {
2950 bool RefType = Field->getType()->isReferenceType();
Abramo Bagnara847c6602014-05-22 19:20:46 +00002951 if (!Elt->isConstantInitializer(Ctx, RefType, Culprit))
Eli Friedman4c27ac22013-07-16 22:40:53 +00002952 return false;
2953 }
2954 }
2955 }
2956 return true;
2957 }
2958
2959 break;
Anders Carlssona7c5eb72008-11-24 05:23:59 +00002960 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00002961 case ImplicitValueInitExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00002962 case NoInitExprClass:
Douglas Gregor0202cb42009-01-29 17:44:32 +00002963 return true;
Chris Lattner3eb172a2009-10-13 07:14:16 +00002964 case ParenExprClass:
John McCall8b0f4ff2010-08-02 21:13:48 +00002965 return cast<ParenExpr>(this)->getSubExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00002966 ->isConstantInitializer(Ctx, IsForRef, Culprit);
Peter Collingbourne91147592011-04-15 00:35:48 +00002967 case GenericSelectionExprClass:
Peter Collingbourne91147592011-04-15 00:35:48 +00002968 return cast<GenericSelectionExpr>(this)->getResultExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00002969 ->isConstantInitializer(Ctx, IsForRef, Culprit);
Abramo Bagnarab59a5b62010-09-27 07:13:32 +00002970 case ChooseExprClass:
Abramo Bagnara847c6602014-05-22 19:20:46 +00002971 if (cast<ChooseExpr>(this)->isConditionDependent()) {
2972 if (Culprit)
2973 *Culprit = this;
Eli Friedman75807f22013-07-20 00:40:58 +00002974 return false;
Abramo Bagnara847c6602014-05-22 19:20:46 +00002975 }
Eli Friedman75807f22013-07-20 00:40:58 +00002976 return cast<ChooseExpr>(this)->getChosenSubExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00002977 ->isConstantInitializer(Ctx, IsForRef, Culprit);
Eli Friedman384da272009-01-25 03:12:18 +00002978 case UnaryOperatorClass: {
2979 const UnaryOperator* Exp = cast<UnaryOperator>(this);
John McCalle3027922010-08-25 11:45:40 +00002980 if (Exp->getOpcode() == UO_Extension)
Abramo Bagnara847c6602014-05-22 19:20:46 +00002981 return Exp->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
Eli Friedman384da272009-01-25 03:12:18 +00002982 break;
2983 }
John McCall8b0f4ff2010-08-02 21:13:48 +00002984 case CXXFunctionalCastExprClass:
John McCall81c9cea2010-08-01 21:51:45 +00002985 case CXXStaticCastExprClass:
Chris Lattner1f02e052009-04-21 05:19:11 +00002986 case ImplicitCastExprClass:
Eli Friedman4c27ac22013-07-16 22:40:53 +00002987 case CStyleCastExprClass:
2988 case ObjCBridgedCastExprClass:
2989 case CXXDynamicCastExprClass:
2990 case CXXReinterpretCastExprClass:
2991 case CXXConstCastExprClass: {
Richard Smith161f09a2011-12-06 22:44:34 +00002992 const CastExpr *CE = cast<CastExpr>(this);
2993
Eli Friedman13ec75b2011-12-21 00:43:02 +00002994 // Handle misc casts we want to ignore.
Eli Friedman13ec75b2011-12-21 00:43:02 +00002995 if (CE->getCastKind() == CK_NoOp ||
2996 CE->getCastKind() == CK_LValueToRValue ||
2997 CE->getCastKind() == CK_ToUnion ||
Eli Friedman4c27ac22013-07-16 22:40:53 +00002998 CE->getCastKind() == CK_ConstructorConversion ||
2999 CE->getCastKind() == CK_NonAtomicToAtomic ||
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00003000 CE->getCastKind() == CK_AtomicToNonAtomic ||
3001 CE->getCastKind() == CK_IntToOCLSampler)
Abramo Bagnara847c6602014-05-22 19:20:46 +00003002 return CE->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
Richard Smith161f09a2011-12-06 22:44:34 +00003003
Eli Friedman384da272009-01-25 03:12:18 +00003004 break;
Richard Smith161f09a2011-12-06 22:44:34 +00003005 }
Douglas Gregorfe314812011-06-21 17:03:29 +00003006 case MaterializeTemporaryExprClass:
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003007 return cast<MaterializeTemporaryExpr>(this)->GetTemporaryExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00003008 ->isConstantInitializer(Ctx, false, Culprit);
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003009
Eli Friedman4c27ac22013-07-16 22:40:53 +00003010 case SubstNonTypeTemplateParmExprClass:
3011 return cast<SubstNonTypeTemplateParmExpr>(this)->getReplacement()
Abramo Bagnara847c6602014-05-22 19:20:46 +00003012 ->isConstantInitializer(Ctx, false, Culprit);
Eli Friedman4c27ac22013-07-16 22:40:53 +00003013 case CXXDefaultArgExprClass:
3014 return cast<CXXDefaultArgExpr>(this)->getExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00003015 ->isConstantInitializer(Ctx, false, Culprit);
Eli Friedman4c27ac22013-07-16 22:40:53 +00003016 case CXXDefaultInitExprClass:
3017 return cast<CXXDefaultInitExpr>(this)->getExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00003018 ->isConstantInitializer(Ctx, false, Culprit);
Anders Carlssona7c5eb72008-11-24 05:23:59 +00003019 }
Richard Smithce8eca52015-12-08 03:21:47 +00003020 // Allow certain forms of UB in constant initializers: signed integer
3021 // overflow and floating-point division by zero. We'll give a warning on
3022 // these, but they're common enough that we have to accept them.
3023 if (isEvaluatable(Ctx, SE_AllowUndefinedBehavior))
Abramo Bagnara847c6602014-05-22 19:20:46 +00003024 return true;
3025 if (Culprit)
3026 *Culprit = this;
3027 return false;
Steve Naroffb03f5942007-09-02 20:30:18 +00003028}
3029
Nico Weber758fbac2018-02-13 21:31:47 +00003030bool CallExpr::isBuiltinAssumeFalse(const ASTContext &Ctx) const {
3031 const FunctionDecl* FD = getDirectCallee();
3032 if (!FD || (FD->getBuiltinID() != Builtin::BI__assume &&
3033 FD->getBuiltinID() != Builtin::BI__builtin_assume))
3034 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00003035
Nico Weber758fbac2018-02-13 21:31:47 +00003036 const Expr* Arg = getArg(0);
3037 bool ArgVal;
3038 return !Arg->isValueDependent() &&
3039 Arg->EvaluateAsBooleanCondition(ArgVal, Ctx) && !ArgVal;
3040}
3041
Scott Douglasscc013592015-06-10 15:18:23 +00003042namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003043 /// Look for any side effects within a Stmt.
Scott Douglasscc013592015-06-10 15:18:23 +00003044 class SideEffectFinder : public ConstEvaluatedExprVisitor<SideEffectFinder> {
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003045 typedef ConstEvaluatedExprVisitor<SideEffectFinder> Inherited;
Scott Douglasscc013592015-06-10 15:18:23 +00003046 const bool IncludePossibleEffects;
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003047 bool HasSideEffects;
Scott Douglasscc013592015-06-10 15:18:23 +00003048
3049 public:
3050 explicit SideEffectFinder(const ASTContext &Context, bool IncludePossible)
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003051 : Inherited(Context),
3052 IncludePossibleEffects(IncludePossible), HasSideEffects(false) { }
Scott Douglasscc013592015-06-10 15:18:23 +00003053
3054 bool hasSideEffects() const { return HasSideEffects; }
3055
3056 void VisitExpr(const Expr *E) {
3057 if (!HasSideEffects &&
3058 E->HasSideEffects(Context, IncludePossibleEffects))
3059 HasSideEffects = true;
3060 }
3061 };
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003062}
Scott Douglasscc013592015-06-10 15:18:23 +00003063
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003064bool Expr::HasSideEffects(const ASTContext &Ctx,
3065 bool IncludePossibleEffects) const {
3066 // In circumstances where we care about definite side effects instead of
3067 // potential side effects, we want to ignore expressions that are part of a
3068 // macro expansion as a potential side effect.
3069 if (!IncludePossibleEffects && getExprLoc().isMacroID())
3070 return false;
3071
Richard Smith0421ce72012-08-07 04:16:51 +00003072 if (isInstantiationDependent())
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003073 return IncludePossibleEffects;
Richard Smith0421ce72012-08-07 04:16:51 +00003074
3075 switch (getStmtClass()) {
3076 case NoStmtClass:
3077 #define ABSTRACT_STMT(Type)
3078 #define STMT(Type, Base) case Type##Class:
3079 #define EXPR(Type, Base)
3080 #include "clang/AST/StmtNodes.inc"
3081 llvm_unreachable("unexpected Expr kind");
3082
3083 case DependentScopeDeclRefExprClass:
3084 case CXXUnresolvedConstructExprClass:
3085 case CXXDependentScopeMemberExprClass:
3086 case UnresolvedLookupExprClass:
3087 case UnresolvedMemberExprClass:
3088 case PackExpansionExprClass:
3089 case SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +00003090 case FunctionParmPackExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +00003091 case TypoExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +00003092 case CXXFoldExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003093 llvm_unreachable("shouldn't see dependent / unresolved nodes here");
3094
Richard Smitha33e4fe2012-08-07 05:18:29 +00003095 case DeclRefExprClass:
3096 case ObjCIvarRefExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003097 case PredefinedExprClass:
3098 case IntegerLiteralClass:
Leonard Chandb01c3a2018-06-20 17:19:40 +00003099 case FixedPointLiteralClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003100 case FloatingLiteralClass:
3101 case ImaginaryLiteralClass:
3102 case StringLiteralClass:
3103 case CharacterLiteralClass:
3104 case OffsetOfExprClass:
3105 case ImplicitValueInitExprClass:
3106 case UnaryExprOrTypeTraitExprClass:
3107 case AddrLabelExprClass:
3108 case GNUNullExprClass:
Richard Smith410306b2016-12-12 02:53:20 +00003109 case ArrayInitIndexExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00003110 case NoInitExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003111 case CXXBoolLiteralExprClass:
3112 case CXXNullPtrLiteralExprClass:
3113 case CXXThisExprClass:
3114 case CXXScalarValueInitExprClass:
3115 case TypeTraitExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003116 case ArrayTypeTraitExprClass:
3117 case ExpressionTraitExprClass:
3118 case CXXNoexceptExprClass:
3119 case SizeOfPackExprClass:
3120 case ObjCStringLiteralClass:
3121 case ObjCEncodeExprClass:
3122 case ObjCBoolLiteralExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +00003123 case ObjCAvailabilityCheckExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003124 case CXXUuidofExprClass:
3125 case OpaqueValueExprClass:
3126 // These never have a side-effect.
3127 return false;
3128
Bill Wendling7c44da22018-10-31 03:48:47 +00003129 case ConstantExprClass:
3130 // FIXME: Move this into the "return false;" block above.
3131 return cast<ConstantExpr>(this)->getSubExpr()->HasSideEffects(
3132 Ctx, IncludePossibleEffects);
3133
Richard Smith0421ce72012-08-07 04:16:51 +00003134 case CallExprClass:
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003135 case CXXOperatorCallExprClass:
3136 case CXXMemberCallExprClass:
3137 case CUDAKernelCallExprClass:
Michael Kupersteinaed5ccd2015-04-06 13:22:01 +00003138 case UserDefinedLiteralClass: {
3139 // We don't know a call definitely has side effects, except for calls
3140 // to pure/const functions that definitely don't.
3141 // If the call itself is considered side-effect free, check the operands.
3142 const Decl *FD = cast<CallExpr>(this)->getCalleeDecl();
3143 bool IsPure = FD && (FD->hasAttr<ConstAttr>() || FD->hasAttr<PureAttr>());
3144 if (IsPure || !IncludePossibleEffects)
3145 break;
3146 return true;
3147 }
3148
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003149 case BlockExprClass:
3150 case CXXBindTemporaryExprClass:
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003151 if (!IncludePossibleEffects)
3152 break;
3153 return true;
3154
John McCall5e77d762013-04-16 07:28:30 +00003155 case MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +00003156 case MSPropertySubscriptExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003157 case CompoundAssignOperatorClass:
3158 case VAArgExprClass:
3159 case AtomicExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003160 case CXXThrowExprClass:
3161 case CXXNewExprClass:
3162 case CXXDeleteExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +00003163 case CoawaitExprClass:
Eric Fiselier20f25cb2017-03-06 23:38:15 +00003164 case DependentCoawaitExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +00003165 case CoyieldExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003166 // These always have a side-effect.
3167 return true;
3168
Scott Douglasscc013592015-06-10 15:18:23 +00003169 case StmtExprClass: {
3170 // StmtExprs have a side-effect if any substatement does.
3171 SideEffectFinder Finder(Ctx, IncludePossibleEffects);
3172 Finder.Visit(cast<StmtExpr>(this)->getSubStmt());
3173 return Finder.hasSideEffects();
3174 }
3175
Tim Shen4a05bb82016-06-21 20:29:17 +00003176 case ExprWithCleanupsClass:
3177 if (IncludePossibleEffects)
3178 if (cast<ExprWithCleanups>(this)->cleanupsHaveSideEffects())
3179 return true;
3180 break;
3181
Richard Smith0421ce72012-08-07 04:16:51 +00003182 case ParenExprClass:
3183 case ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +00003184 case OMPArraySectionExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003185 case MemberExprClass:
3186 case ConditionalOperatorClass:
3187 case BinaryConditionalOperatorClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003188 case CompoundLiteralExprClass:
3189 case ExtVectorElementExprClass:
3190 case DesignatedInitExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00003191 case DesignatedInitUpdateExprClass:
Richard Smith410306b2016-12-12 02:53:20 +00003192 case ArrayInitLoopExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003193 case ParenListExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003194 case CXXPseudoDestructorExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +00003195 case CXXStdInitializerListExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003196 case SubstNonTypeTemplateParmExprClass:
3197 case MaterializeTemporaryExprClass:
3198 case ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +00003199 case ConvertVectorExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003200 case AsTypeExprClass:
3201 // These have a side-effect if any subexpression does.
3202 break;
3203
Richard Smitha33e4fe2012-08-07 05:18:29 +00003204 case UnaryOperatorClass:
3205 if (cast<UnaryOperator>(this)->isIncrementDecrementOp())
Richard Smith0421ce72012-08-07 04:16:51 +00003206 return true;
3207 break;
Richard Smith0421ce72012-08-07 04:16:51 +00003208
3209 case BinaryOperatorClass:
3210 if (cast<BinaryOperator>(this)->isAssignmentOp())
3211 return true;
3212 break;
3213
Richard Smith0421ce72012-08-07 04:16:51 +00003214 case InitListExprClass:
3215 // FIXME: The children for an InitListExpr doesn't include the array filler.
3216 if (const Expr *E = cast<InitListExpr>(this)->getArrayFiller())
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003217 if (E->HasSideEffects(Ctx, IncludePossibleEffects))
Richard Smith0421ce72012-08-07 04:16:51 +00003218 return true;
3219 break;
3220
3221 case GenericSelectionExprClass:
3222 return cast<GenericSelectionExpr>(this)->getResultExpr()->
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003223 HasSideEffects(Ctx, IncludePossibleEffects);
Richard Smith0421ce72012-08-07 04:16:51 +00003224
3225 case ChooseExprClass:
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003226 return cast<ChooseExpr>(this)->getChosenSubExpr()->HasSideEffects(
3227 Ctx, IncludePossibleEffects);
Richard Smith0421ce72012-08-07 04:16:51 +00003228
3229 case CXXDefaultArgExprClass:
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003230 return cast<CXXDefaultArgExpr>(this)->getExpr()->HasSideEffects(
3231 Ctx, IncludePossibleEffects);
Richard Smith0421ce72012-08-07 04:16:51 +00003232
Reid Klecknerd60b82f2014-11-17 23:36:45 +00003233 case CXXDefaultInitExprClass: {
3234 const FieldDecl *FD = cast<CXXDefaultInitExpr>(this)->getField();
3235 if (const Expr *E = FD->getInClassInitializer())
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003236 return E->HasSideEffects(Ctx, IncludePossibleEffects);
Richard Smith852c9db2013-04-20 22:23:05 +00003237 // If we've not yet parsed the initializer, assume it has side-effects.
3238 return true;
Reid Klecknerd60b82f2014-11-17 23:36:45 +00003239 }
Richard Smith852c9db2013-04-20 22:23:05 +00003240
Richard Smith0421ce72012-08-07 04:16:51 +00003241 case CXXDynamicCastExprClass: {
3242 // A dynamic_cast expression has side-effects if it can throw.
3243 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(this);
3244 if (DCE->getTypeAsWritten()->isReferenceType() &&
3245 DCE->getCastKind() == CK_Dynamic)
3246 return true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00003247 }
3248 LLVM_FALLTHROUGH;
Richard Smitha33e4fe2012-08-07 05:18:29 +00003249 case ImplicitCastExprClass:
3250 case CStyleCastExprClass:
3251 case CXXStaticCastExprClass:
3252 case CXXReinterpretCastExprClass:
3253 case CXXConstCastExprClass:
3254 case CXXFunctionalCastExprClass: {
Aaron Ballman409af502015-01-03 17:00:12 +00003255 // While volatile reads are side-effecting in both C and C++, we treat them
3256 // as having possible (not definite) side-effects. This allows idiomatic
3257 // code to behave without warning, such as sizeof(*v) for a volatile-
3258 // qualified pointer.
3259 if (!IncludePossibleEffects)
3260 break;
3261
Richard Smitha33e4fe2012-08-07 05:18:29 +00003262 const CastExpr *CE = cast<CastExpr>(this);
3263 if (CE->getCastKind() == CK_LValueToRValue &&
3264 CE->getSubExpr()->getType().isVolatileQualified())
3265 return true;
Richard Smith0421ce72012-08-07 04:16:51 +00003266 break;
3267 }
3268
Richard Smithef8bf432012-08-13 20:08:14 +00003269 case CXXTypeidExprClass:
3270 // typeid might throw if its subexpression is potentially-evaluated, so has
3271 // side-effects in that case whether or not its subexpression does.
3272 return cast<CXXTypeidExpr>(this)->isPotentiallyEvaluated();
Richard Smith0421ce72012-08-07 04:16:51 +00003273
3274 case CXXConstructExprClass:
3275 case CXXTemporaryObjectExprClass: {
3276 const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003277 if (!CE->getConstructor()->isTrivial() && IncludePossibleEffects)
Richard Smith0421ce72012-08-07 04:16:51 +00003278 return true;
Richard Smitha33e4fe2012-08-07 05:18:29 +00003279 // A trivial constructor does not add any side-effects of its own. Just look
3280 // at its arguments.
Richard Smith0421ce72012-08-07 04:16:51 +00003281 break;
3282 }
3283
Richard Smith5179eb72016-06-28 19:03:57 +00003284 case CXXInheritedCtorInitExprClass: {
3285 const auto *ICIE = cast<CXXInheritedCtorInitExpr>(this);
3286 if (!ICIE->getConstructor()->isTrivial() && IncludePossibleEffects)
3287 return true;
3288 break;
3289 }
3290
Richard Smith0421ce72012-08-07 04:16:51 +00003291 case LambdaExprClass: {
3292 const LambdaExpr *LE = cast<LambdaExpr>(this);
Richard Smithb3d203f2018-10-19 19:01:34 +00003293 for (Expr *E : LE->capture_inits())
3294 if (E->HasSideEffects(Ctx, IncludePossibleEffects))
Richard Smith0421ce72012-08-07 04:16:51 +00003295 return true;
3296 return false;
3297 }
3298
3299 case PseudoObjectExprClass: {
3300 // Only look for side-effects in the semantic form, and look past
3301 // OpaqueValueExpr bindings in that form.
3302 const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this);
3303 for (PseudoObjectExpr::const_semantics_iterator I = PO->semantics_begin(),
3304 E = PO->semantics_end();
3305 I != E; ++I) {
3306 const Expr *Subexpr = *I;
3307 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Subexpr))
3308 Subexpr = OVE->getSourceExpr();
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003309 if (Subexpr->HasSideEffects(Ctx, IncludePossibleEffects))
Richard Smith0421ce72012-08-07 04:16:51 +00003310 return true;
3311 }
3312 return false;
3313 }
3314
3315 case ObjCBoxedExprClass:
3316 case ObjCArrayLiteralClass:
3317 case ObjCDictionaryLiteralClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003318 case ObjCSelectorExprClass:
3319 case ObjCProtocolExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003320 case ObjCIsaExprClass:
3321 case ObjCIndirectCopyRestoreExprClass:
3322 case ObjCSubscriptRefExprClass:
3323 case ObjCBridgedCastExprClass:
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003324 case ObjCMessageExprClass:
3325 case ObjCPropertyRefExprClass:
3326 // FIXME: Classify these cases better.
3327 if (IncludePossibleEffects)
3328 return true;
3329 break;
Richard Smith0421ce72012-08-07 04:16:51 +00003330 }
3331
3332 // Recurse to children.
Benjamin Kramer642f1732015-07-02 21:03:14 +00003333 for (const Stmt *SubStmt : children())
3334 if (SubStmt &&
3335 cast<Expr>(SubStmt)->HasSideEffects(Ctx, IncludePossibleEffects))
3336 return true;
Richard Smith0421ce72012-08-07 04:16:51 +00003337
3338 return false;
3339}
3340
Douglas Gregor1be329d2012-02-23 07:33:15 +00003341namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003342 /// Look for a call to a non-trivial function within an expression.
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003343 class NonTrivialCallFinder : public ConstEvaluatedExprVisitor<NonTrivialCallFinder>
3344 {
3345 typedef ConstEvaluatedExprVisitor<NonTrivialCallFinder> Inherited;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003346
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003347 bool NonTrivial;
Fangrui Song6907ce22018-07-30 19:24:48 +00003348
Douglas Gregor1be329d2012-02-23 07:33:15 +00003349 public:
Scott Douglass503fc392015-06-10 13:53:15 +00003350 explicit NonTrivialCallFinder(const ASTContext &Context)
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003351 : Inherited(Context), NonTrivial(false) { }
Fangrui Song6907ce22018-07-30 19:24:48 +00003352
Douglas Gregor1be329d2012-02-23 07:33:15 +00003353 bool hasNonTrivialCall() const { return NonTrivial; }
Scott Douglass503fc392015-06-10 13:53:15 +00003354
3355 void VisitCallExpr(const CallExpr *E) {
3356 if (const CXXMethodDecl *Method
3357 = dyn_cast_or_null<const CXXMethodDecl>(E->getCalleeDecl())) {
Douglas Gregor1be329d2012-02-23 07:33:15 +00003358 if (Method->isTrivial()) {
3359 // Recurse to children of the call.
3360 Inherited::VisitStmt(E);
3361 return;
3362 }
3363 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003364
Douglas Gregor1be329d2012-02-23 07:33:15 +00003365 NonTrivial = true;
3366 }
Scott Douglass503fc392015-06-10 13:53:15 +00003367
3368 void VisitCXXConstructExpr(const CXXConstructExpr *E) {
Douglas Gregor1be329d2012-02-23 07:33:15 +00003369 if (E->getConstructor()->isTrivial()) {
3370 // Recurse to children of the call.
3371 Inherited::VisitStmt(E);
3372 return;
3373 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003374
Douglas Gregor1be329d2012-02-23 07:33:15 +00003375 NonTrivial = true;
3376 }
Scott Douglass503fc392015-06-10 13:53:15 +00003377
3378 void VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
Douglas Gregor1be329d2012-02-23 07:33:15 +00003379 if (E->getTemporary()->getDestructor()->isTrivial()) {
3380 Inherited::VisitStmt(E);
3381 return;
3382 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003383
Douglas Gregor1be329d2012-02-23 07:33:15 +00003384 NonTrivial = true;
3385 }
3386 };
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003387}
Douglas Gregor1be329d2012-02-23 07:33:15 +00003388
Scott Douglass503fc392015-06-10 13:53:15 +00003389bool Expr::hasNonTrivialCall(const ASTContext &Ctx) const {
Douglas Gregor1be329d2012-02-23 07:33:15 +00003390 NonTrivialCallFinder Finder(Ctx);
3391 Finder.Visit(this);
Fangrui Song6907ce22018-07-30 19:24:48 +00003392 return Finder.hasNonTrivialCall();
Douglas Gregor1be329d2012-02-23 07:33:15 +00003393}
3394
Fangrui Song6907ce22018-07-30 19:24:48 +00003395/// isNullPointerConstant - C99 6.3.2.3p3 - Return whether this is a null
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003396/// pointer constant or not, as well as the specific kind of constant detected.
3397/// Null pointer constants can be integer constant expressions with the
3398/// value zero, casts of zero to void*, nullptr (C++0X), or __null
3399/// (a GNU extension).
3400Expr::NullPointerConstantKind
3401Expr::isNullPointerConstant(ASTContext &Ctx,
3402 NullPointerConstantValueDependence NPC) const {
Reid Klecknera5eef142013-11-12 02:22:34 +00003403 if (isValueDependent() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00003404 (!Ctx.getLangOpts().CPlusPlus11 || Ctx.getLangOpts().MSVCCompat)) {
Douglas Gregor56751b52009-09-25 04:25:58 +00003405 switch (NPC) {
3406 case NPC_NeverValueDependent:
David Blaikie83d382b2011-09-23 05:06:16 +00003407 llvm_unreachable("Unexpected value dependent expression!");
Douglas Gregor56751b52009-09-25 04:25:58 +00003408 case NPC_ValueDependentIsNull:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003409 if (isTypeDependent() || getType()->isIntegralType(Ctx))
David Blaikie1c7c8f72012-08-08 17:33:31 +00003410 return NPCK_ZeroExpression;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003411 else
3412 return NPCK_NotNull;
Fangrui Song6907ce22018-07-30 19:24:48 +00003413
Douglas Gregor56751b52009-09-25 04:25:58 +00003414 case NPC_ValueDependentIsNotNull:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003415 return NPCK_NotNull;
Douglas Gregor56751b52009-09-25 04:25:58 +00003416 }
3417 }
Daniel Dunbarebc51402009-09-18 08:46:16 +00003418
Sebastian Redl72b8aef2008-10-31 14:43:28 +00003419 // Strip off a cast to void*, if it exists. Except in C++.
Argyrios Kyrtzidis3bab3d22008-08-18 23:01:59 +00003420 if (const ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(this)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003421 if (!Ctx.getLangOpts().CPlusPlus) {
Sebastian Redl72b8aef2008-10-31 14:43:28 +00003422 // Check that it is a cast to void*.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003423 if (const PointerType *PT = CE->getType()->getAs<PointerType>()) {
Sebastian Redl72b8aef2008-10-31 14:43:28 +00003424 QualType Pointee = PT->getPointeeType();
Yaxun Liub7318e02017-10-13 03:37:48 +00003425 // Only (void*)0 or equivalent are treated as nullptr. If pointee type
3426 // has non-default address space it is not treated as nullptr.
3427 // (__generic void*)0 in OpenCL 2.0 should not be treated as nullptr
3428 // since it cannot be assigned to a pointer to constant address space.
3429 bool PointeeHasDefaultAS =
3430 Pointee.getAddressSpace() == LangAS::Default ||
3431 (Ctx.getLangOpts().OpenCLVersion >= 200 &&
3432 Pointee.getAddressSpace() == LangAS::opencl_generic) ||
3433 (Ctx.getLangOpts().OpenCL &&
3434 Ctx.getLangOpts().OpenCLVersion < 200 &&
3435 Pointee.getAddressSpace() == LangAS::opencl_private);
Anastasia Stulova2446b8b2015-12-11 17:41:19 +00003436
Yaxun Liub7318e02017-10-13 03:37:48 +00003437 if (PointeeHasDefaultAS && Pointee->isVoidType() && // to void*
3438 CE->getSubExpr()->getType()->isIntegerType()) // from int.
Douglas Gregor56751b52009-09-25 04:25:58 +00003439 return CE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
Sebastian Redl72b8aef2008-10-31 14:43:28 +00003440 }
Steve Naroffada7d422007-05-20 17:54:12 +00003441 }
Steve Naroff4871fe02008-01-14 16:10:57 +00003442 } else if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(this)) {
3443 // Ignore the ImplicitCastExpr type entirely.
Douglas Gregor56751b52009-09-25 04:25:58 +00003444 return ICE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
Steve Naroff4871fe02008-01-14 16:10:57 +00003445 } else if (const ParenExpr *PE = dyn_cast<ParenExpr>(this)) {
3446 // Accept ((void*)0) as a null pointer constant, as many other
3447 // implementations do.
Douglas Gregor56751b52009-09-25 04:25:58 +00003448 return PE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
Peter Collingbourne91147592011-04-15 00:35:48 +00003449 } else if (const GenericSelectionExpr *GE =
3450 dyn_cast<GenericSelectionExpr>(this)) {
Eli Friedman75807f22013-07-20 00:40:58 +00003451 if (GE->isResultDependent())
3452 return NPCK_NotNull;
Peter Collingbourne91147592011-04-15 00:35:48 +00003453 return GE->getResultExpr()->isNullPointerConstant(Ctx, NPC);
Eli Friedman75807f22013-07-20 00:40:58 +00003454 } else if (const ChooseExpr *CE = dyn_cast<ChooseExpr>(this)) {
3455 if (CE->isConditionDependent())
3456 return NPCK_NotNull;
3457 return CE->getChosenSubExpr()->isNullPointerConstant(Ctx, NPC);
Mike Stump11289f42009-09-09 15:08:12 +00003458 } else if (const CXXDefaultArgExpr *DefaultArg
Chris Lattner58258242008-04-10 02:22:51 +00003459 = dyn_cast<CXXDefaultArgExpr>(this)) {
Richard Smith852c9db2013-04-20 22:23:05 +00003460 // See through default argument expressions.
Douglas Gregor56751b52009-09-25 04:25:58 +00003461 return DefaultArg->getExpr()->isNullPointerConstant(Ctx, NPC);
Richard Smith852c9db2013-04-20 22:23:05 +00003462 } else if (const CXXDefaultInitExpr *DefaultInit
3463 = dyn_cast<CXXDefaultInitExpr>(this)) {
3464 // See through default initializer expressions.
3465 return DefaultInit->getExpr()->isNullPointerConstant(Ctx, NPC);
Douglas Gregor3be4b122008-11-29 04:51:27 +00003466 } else if (isa<GNUNullExpr>(this)) {
3467 // The GNU __null extension is always a null pointer constant.
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003468 return NPCK_GNUNull;
Fangrui Song6907ce22018-07-30 19:24:48 +00003469 } else if (const MaterializeTemporaryExpr *M
Douglas Gregorfe314812011-06-21 17:03:29 +00003470 = dyn_cast<MaterializeTemporaryExpr>(this)) {
3471 return M->GetTemporaryExpr()->isNullPointerConstant(Ctx, NPC);
John McCallfe96e0b2011-11-06 09:01:30 +00003472 } else if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(this)) {
3473 if (const Expr *Source = OVE->getSourceExpr())
3474 return Source->isNullPointerConstant(Ctx, NPC);
Steve Naroff09035312008-01-14 02:53:34 +00003475 }
Douglas Gregor3be4b122008-11-29 04:51:27 +00003476
Richard Smith89645bc2013-01-02 12:01:23 +00003477 // C++11 nullptr_t is always a null pointer constant.
Sebastian Redl576fd422009-05-10 18:38:11 +00003478 if (getType()->isNullPtrType())
Richard Smith89645bc2013-01-02 12:01:23 +00003479 return NPCK_CXX11_nullptr;
Sebastian Redl576fd422009-05-10 18:38:11 +00003480
Fariborz Jahanian3567c422010-09-27 22:42:37 +00003481 if (const RecordType *UT = getType()->getAsUnionType())
Richard Smith4055de42013-06-13 02:46:14 +00003482 if (!Ctx.getLangOpts().CPlusPlus11 &&
3483 UT && UT->getDecl()->hasAttr<TransparentUnionAttr>())
Fariborz Jahanian3567c422010-09-27 22:42:37 +00003484 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(this)){
3485 const Expr *InitExpr = CLE->getInitializer();
3486 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(InitExpr))
3487 return ILE->getInit(0)->isNullPointerConstant(Ctx, NPC);
3488 }
Steve Naroff4871fe02008-01-14 16:10:57 +00003489 // This expression must be an integer type.
Fangrui Song6907ce22018-07-30 19:24:48 +00003490 if (!getType()->isIntegerType() ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00003491 (Ctx.getLangOpts().CPlusPlus && getType()->isEnumeralType()))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003492 return NPCK_NotNull;
Mike Stump11289f42009-09-09 15:08:12 +00003493
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003494 if (Ctx.getLangOpts().CPlusPlus11) {
Richard Smith4055de42013-06-13 02:46:14 +00003495 // C++11 [conv.ptr]p1: A null pointer constant is an integer literal with
3496 // value zero or a prvalue of type std::nullptr_t.
Reid Klecknera5eef142013-11-12 02:22:34 +00003497 // Microsoft mode permits C++98 rules reflecting MSVC behavior.
Richard Smith4055de42013-06-13 02:46:14 +00003498 const IntegerLiteral *Lit = dyn_cast<IntegerLiteral>(this);
Reid Klecknera5eef142013-11-12 02:22:34 +00003499 if (Lit && !Lit->getValue())
3500 return NPCK_ZeroLiteral;
Alp Tokerbfa39342014-01-14 12:51:41 +00003501 else if (!Ctx.getLangOpts().MSVCCompat || !isCXX98IntegralConstantExpr(Ctx))
Reid Klecknera5eef142013-11-12 02:22:34 +00003502 return NPCK_NotNull;
Richard Smith98a0a492012-02-14 21:38:30 +00003503 } else {
Richard Smith4055de42013-06-13 02:46:14 +00003504 // If we have an integer constant expression, we need to *evaluate* it and
3505 // test for the value 0.
Richard Smith98a0a492012-02-14 21:38:30 +00003506 if (!isIntegerConstantExpr(Ctx))
3507 return NPCK_NotNull;
3508 }
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003509
David Blaikie1c7c8f72012-08-08 17:33:31 +00003510 if (EvaluateKnownConstInt(Ctx) != 0)
3511 return NPCK_NotNull;
3512
3513 if (isa<IntegerLiteral>(this))
3514 return NPCK_ZeroLiteral;
3515 return NPCK_ZeroExpression;
Steve Naroff218bc2b2007-05-04 21:54:46 +00003516}
Steve Narofff7a5da12007-07-28 23:10:27 +00003517
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003518/// If this expression is an l-value for an Objective C
John McCall34376a62010-12-04 03:47:34 +00003519/// property, find the underlying property reference expression.
3520const ObjCPropertyRefExpr *Expr::getObjCProperty() const {
3521 const Expr *E = this;
3522 while (true) {
3523 assert((E->getValueKind() == VK_LValue &&
3524 E->getObjectKind() == OK_ObjCProperty) &&
3525 "expression is not a property reference");
3526 E = E->IgnoreParenCasts();
3527 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3528 if (BO->getOpcode() == BO_Comma) {
3529 E = BO->getRHS();
3530 continue;
3531 }
3532 }
3533
3534 break;
3535 }
3536
3537 return cast<ObjCPropertyRefExpr>(E);
3538}
3539
Anna Zaks97c7ce32012-10-01 20:34:04 +00003540bool Expr::isObjCSelfExpr() const {
3541 const Expr *E = IgnoreParenImpCasts();
3542
3543 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
3544 if (!DRE)
3545 return false;
3546
3547 const ImplicitParamDecl *Param = dyn_cast<ImplicitParamDecl>(DRE->getDecl());
3548 if (!Param)
3549 return false;
3550
3551 const ObjCMethodDecl *M = dyn_cast<ObjCMethodDecl>(Param->getDeclContext());
3552 if (!M)
3553 return false;
3554
3555 return M->getSelfDecl() == Param;
3556}
3557
John McCalld25db7e2013-05-06 21:39:12 +00003558FieldDecl *Expr::getSourceBitField() {
Douglas Gregor19623dc2009-07-06 15:38:40 +00003559 Expr *E = this->IgnoreParens();
Douglas Gregor71235ec2009-05-02 02:18:30 +00003560
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003561 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall34376a62010-12-04 03:47:34 +00003562 if (ICE->getCastKind() == CK_LValueToRValue ||
3563 (ICE->getValueKind() != VK_RValue && ICE->getCastKind() == CK_NoOp))
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003564 E = ICE->getSubExpr()->IgnoreParens();
3565 else
3566 break;
3567 }
3568
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003569 if (MemberExpr *MemRef = dyn_cast<MemberExpr>(E))
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00003570 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemRef->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00003571 if (Field->isBitField())
3572 return Field;
3573
George Burgess IV00f70bd2018-03-01 05:43:23 +00003574 if (ObjCIvarRefExpr *IvarRef = dyn_cast<ObjCIvarRefExpr>(E)) {
3575 FieldDecl *Ivar = IvarRef->getDecl();
3576 if (Ivar->isBitField())
3577 return Ivar;
3578 }
John McCalld25db7e2013-05-06 21:39:12 +00003579
Richard Smith7873de02016-08-11 22:25:46 +00003580 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E)) {
Argyrios Kyrtzidisd3f00542010-10-30 19:52:22 +00003581 if (FieldDecl *Field = dyn_cast<FieldDecl>(DeclRef->getDecl()))
3582 if (Field->isBitField())
3583 return Field;
3584
Richard Smith7873de02016-08-11 22:25:46 +00003585 if (BindingDecl *BD = dyn_cast<BindingDecl>(DeclRef->getDecl()))
3586 if (Expr *E = BD->getBinding())
3587 return E->getSourceBitField();
3588 }
3589
Eli Friedman609ada22011-07-13 02:05:57 +00003590 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(E)) {
Douglas Gregor71235ec2009-05-02 02:18:30 +00003591 if (BinOp->isAssignmentOp() && BinOp->getLHS())
John McCalld25db7e2013-05-06 21:39:12 +00003592 return BinOp->getLHS()->getSourceBitField();
Douglas Gregor71235ec2009-05-02 02:18:30 +00003593
Eli Friedman609ada22011-07-13 02:05:57 +00003594 if (BinOp->getOpcode() == BO_Comma && BinOp->getRHS())
John McCalld25db7e2013-05-06 21:39:12 +00003595 return BinOp->getRHS()->getSourceBitField();
Eli Friedman609ada22011-07-13 02:05:57 +00003596 }
3597
Richard Smith5b571672014-09-24 23:55:00 +00003598 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E))
3599 if (UnOp->isPrefix() && UnOp->isIncrementDecrementOp())
3600 return UnOp->getSubExpr()->getSourceBitField();
3601
Craig Topper36250ad2014-05-12 05:36:57 +00003602 return nullptr;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003603}
3604
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003605bool Expr::refersToVectorElement() const {
Richard Smith7873de02016-08-11 22:25:46 +00003606 // FIXME: Why do we not just look at the ObjectKind here?
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003607 const Expr *E = this->IgnoreParens();
Fangrui Song6907ce22018-07-30 19:24:48 +00003608
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003609 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall2536c6d2010-08-25 10:28:54 +00003610 if (ICE->getValueKind() != VK_RValue &&
John McCalle3027922010-08-25 11:45:40 +00003611 ICE->getCastKind() == CK_NoOp)
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003612 E = ICE->getSubExpr()->IgnoreParens();
3613 else
3614 break;
3615 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003616
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003617 if (const ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(E))
3618 return ASE->getBase()->getType()->isVectorType();
3619
3620 if (isa<ExtVectorElementExpr>(E))
3621 return true;
3622
Richard Smith7873de02016-08-11 22:25:46 +00003623 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3624 if (auto *BD = dyn_cast<BindingDecl>(DRE->getDecl()))
3625 if (auto *E = BD->getBinding())
3626 return E->refersToVectorElement();
3627
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003628 return false;
3629}
3630
Andrey Bokhankod9eab9c2015-08-03 10:38:10 +00003631bool Expr::refersToGlobalRegisterVar() const {
3632 const Expr *E = this->IgnoreParenImpCasts();
3633
3634 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
3635 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
3636 if (VD->getStorageClass() == SC_Register &&
3637 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
3638 return true;
3639
3640 return false;
3641}
3642
Chris Lattnerb8211f62009-02-16 22:14:05 +00003643/// isArrow - Return true if the base expression is a pointer to vector,
3644/// return false if the base expression is a vector.
3645bool ExtVectorElementExpr::isArrow() const {
3646 return getBase()->getType()->isPointerType();
3647}
3648
Nate Begemance4d7fc2008-04-18 23:10:10 +00003649unsigned ExtVectorElementExpr::getNumElements() const {
John McCall9dd450b2009-09-21 23:43:11 +00003650 if (const VectorType *VT = getType()->getAs<VectorType>())
Nate Begemanf322eab2008-05-09 06:41:27 +00003651 return VT->getNumElements();
3652 return 1;
Chris Lattner177bd452007-08-03 16:00:20 +00003653}
3654
Nate Begemanf322eab2008-05-09 06:41:27 +00003655/// containsDuplicateElements - Return true if any element access is repeated.
Nate Begemance4d7fc2008-04-18 23:10:10 +00003656bool ExtVectorElementExpr::containsDuplicateElements() const {
Daniel Dunbarcb2a0562009-10-18 02:09:09 +00003657 // FIXME: Refactor this code to an accessor on the AST node which returns the
3658 // "type" of component access, and share with code below and in Sema.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003659 StringRef Comp = Accessor->getName();
Nate Begeman7e5185b2009-01-18 02:01:21 +00003660
3661 // Halving swizzles do not contain duplicate elements.
Daniel Dunbar125c9c92009-10-17 23:53:04 +00003662 if (Comp == "hi" || Comp == "lo" || Comp == "even" || Comp == "odd")
Nate Begeman7e5185b2009-01-18 02:01:21 +00003663 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003664
Nate Begeman7e5185b2009-01-18 02:01:21 +00003665 // Advance past s-char prefix on hex swizzles.
Daniel Dunbar125c9c92009-10-17 23:53:04 +00003666 if (Comp[0] == 's' || Comp[0] == 'S')
3667 Comp = Comp.substr(1);
Mike Stump11289f42009-09-09 15:08:12 +00003668
Daniel Dunbar125c9c92009-10-17 23:53:04 +00003669 for (unsigned i = 0, e = Comp.size(); i != e; ++i)
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003670 if (Comp.substr(i + 1).find(Comp[i]) != StringRef::npos)
Steve Naroff0d595ca2007-07-30 03:29:09 +00003671 return true;
Daniel Dunbar125c9c92009-10-17 23:53:04 +00003672
Steve Naroff0d595ca2007-07-30 03:29:09 +00003673 return false;
3674}
Chris Lattner885b4952007-08-02 23:36:59 +00003675
Nate Begemanf322eab2008-05-09 06:41:27 +00003676/// getEncodedElementAccess - We encode the fields as a llvm ConstantArray.
Nate Begemand3862152008-05-13 21:03:02 +00003677void ExtVectorElementExpr::getEncodedElementAccess(
Benjamin Kramer99383102015-07-28 16:25:32 +00003678 SmallVectorImpl<uint32_t> &Elts) const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003679 StringRef Comp = Accessor->getName();
Pirama Arumuga Nainar98eaa622016-07-22 18:49:43 +00003680 bool isNumericAccessor = false;
3681 if (Comp[0] == 's' || Comp[0] == 'S') {
Daniel Dunbarce5a0b32009-10-18 02:09:31 +00003682 Comp = Comp.substr(1);
Pirama Arumuga Nainar98eaa622016-07-22 18:49:43 +00003683 isNumericAccessor = true;
3684 }
Mike Stump11289f42009-09-09 15:08:12 +00003685
Daniel Dunbarce5a0b32009-10-18 02:09:31 +00003686 bool isHi = Comp == "hi";
3687 bool isLo = Comp == "lo";
3688 bool isEven = Comp == "even";
3689 bool isOdd = Comp == "odd";
Mike Stump11289f42009-09-09 15:08:12 +00003690
Nate Begemanf322eab2008-05-09 06:41:27 +00003691 for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
3692 uint64_t Index;
Mike Stump11289f42009-09-09 15:08:12 +00003693
Nate Begemanf322eab2008-05-09 06:41:27 +00003694 if (isHi)
3695 Index = e + i;
3696 else if (isLo)
3697 Index = i;
3698 else if (isEven)
3699 Index = 2 * i;
3700 else if (isOdd)
3701 Index = 2 * i + 1;
3702 else
Pirama Arumuga Nainar98eaa622016-07-22 18:49:43 +00003703 Index = ExtVectorType::getAccessorIdx(Comp[i], isNumericAccessor);
Chris Lattner885b4952007-08-02 23:36:59 +00003704
Nate Begemand3862152008-05-13 21:03:02 +00003705 Elts.push_back(Index);
Chris Lattner885b4952007-08-02 23:36:59 +00003706 }
Nate Begemanf322eab2008-05-09 06:41:27 +00003707}
3708
Craig Topper37932912013-08-18 10:09:15 +00003709ShuffleVectorExpr::ShuffleVectorExpr(const ASTContext &C, ArrayRef<Expr*> args,
Douglas Gregora6e053e2010-12-15 01:34:56 +00003710 QualType Type, SourceLocation BLoc,
Fangrui Song6907ce22018-07-30 19:24:48 +00003711 SourceLocation RP)
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003712 : Expr(ShuffleVectorExprClass, Type, VK_RValue, OK_Ordinary,
3713 Type->isDependentType(), Type->isDependentType(),
3714 Type->isInstantiationDependentType(),
3715 Type->containsUnexpandedParameterPack()),
3716 BuiltinLoc(BLoc), RParenLoc(RP), NumExprs(args.size())
3717{
Benjamin Kramerc215e762012-08-24 11:54:20 +00003718 SubExprs = new (C) Stmt*[args.size()];
3719 for (unsigned i = 0; i != args.size(); i++) {
Douglas Gregora6e053e2010-12-15 01:34:56 +00003720 if (args[i]->isTypeDependent())
3721 ExprBits.TypeDependent = true;
3722 if (args[i]->isValueDependent())
3723 ExprBits.ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003724 if (args[i]->isInstantiationDependent())
3725 ExprBits.InstantiationDependent = true;
Douglas Gregora6e053e2010-12-15 01:34:56 +00003726 if (args[i]->containsUnexpandedParameterPack())
3727 ExprBits.ContainsUnexpandedParameterPack = true;
3728
3729 SubExprs[i] = args[i];
3730 }
3731}
3732
Craig Topper37932912013-08-18 10:09:15 +00003733void ShuffleVectorExpr::setExprs(const ASTContext &C, ArrayRef<Expr *> Exprs) {
Nate Begeman48745922009-08-12 02:28:50 +00003734 if (SubExprs) C.Deallocate(SubExprs);
3735
Dmitri Gribenko674eaa22013-05-10 00:43:44 +00003736 this->NumExprs = Exprs.size();
Dmitri Gribenko48d6daf2013-05-10 17:30:13 +00003737 SubExprs = new (C) Stmt*[NumExprs];
Dmitri Gribenko674eaa22013-05-10 00:43:44 +00003738 memcpy(SubExprs, Exprs.data(), sizeof(Expr *) * Exprs.size());
Mike Stump11289f42009-09-09 15:08:12 +00003739}
Nate Begeman48745922009-08-12 02:28:50 +00003740
Craig Topper37932912013-08-18 10:09:15 +00003741GenericSelectionExpr::GenericSelectionExpr(const ASTContext &Context,
Peter Collingbourne91147592011-04-15 00:35:48 +00003742 SourceLocation GenericLoc, Expr *ControllingExpr,
Benjamin Kramerc215e762012-08-24 11:54:20 +00003743 ArrayRef<TypeSourceInfo*> AssocTypes,
3744 ArrayRef<Expr*> AssocExprs,
3745 SourceLocation DefaultLoc,
Peter Collingbourne91147592011-04-15 00:35:48 +00003746 SourceLocation RParenLoc,
3747 bool ContainsUnexpandedParameterPack,
3748 unsigned ResultIndex)
3749 : Expr(GenericSelectionExprClass,
3750 AssocExprs[ResultIndex]->getType(),
3751 AssocExprs[ResultIndex]->getValueKind(),
3752 AssocExprs[ResultIndex]->getObjectKind(),
3753 AssocExprs[ResultIndex]->isTypeDependent(),
3754 AssocExprs[ResultIndex]->isValueDependent(),
Douglas Gregor678d76c2011-07-01 01:22:09 +00003755 AssocExprs[ResultIndex]->isInstantiationDependent(),
Peter Collingbourne91147592011-04-15 00:35:48 +00003756 ContainsUnexpandedParameterPack),
Benjamin Kramerc215e762012-08-24 11:54:20 +00003757 AssocTypes(new (Context) TypeSourceInfo*[AssocTypes.size()]),
3758 SubExprs(new (Context) Stmt*[END_EXPR+AssocExprs.size()]),
3759 NumAssocs(AssocExprs.size()), ResultIndex(ResultIndex),
3760 GenericLoc(GenericLoc), DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
Peter Collingbourne91147592011-04-15 00:35:48 +00003761 SubExprs[CONTROLLING] = ControllingExpr;
Benjamin Kramerc215e762012-08-24 11:54:20 +00003762 assert(AssocTypes.size() == AssocExprs.size());
3763 std::copy(AssocTypes.begin(), AssocTypes.end(), this->AssocTypes);
3764 std::copy(AssocExprs.begin(), AssocExprs.end(), SubExprs+END_EXPR);
Peter Collingbourne91147592011-04-15 00:35:48 +00003765}
3766
Craig Topper37932912013-08-18 10:09:15 +00003767GenericSelectionExpr::GenericSelectionExpr(const ASTContext &Context,
Peter Collingbourne91147592011-04-15 00:35:48 +00003768 SourceLocation GenericLoc, Expr *ControllingExpr,
Benjamin Kramerc215e762012-08-24 11:54:20 +00003769 ArrayRef<TypeSourceInfo*> AssocTypes,
3770 ArrayRef<Expr*> AssocExprs,
3771 SourceLocation DefaultLoc,
Peter Collingbourne91147592011-04-15 00:35:48 +00003772 SourceLocation RParenLoc,
3773 bool ContainsUnexpandedParameterPack)
3774 : Expr(GenericSelectionExprClass,
3775 Context.DependentTy,
3776 VK_RValue,
3777 OK_Ordinary,
Douglas Gregor678d76c2011-07-01 01:22:09 +00003778 /*isTypeDependent=*/true,
3779 /*isValueDependent=*/true,
3780 /*isInstantiationDependent=*/true,
Peter Collingbourne91147592011-04-15 00:35:48 +00003781 ContainsUnexpandedParameterPack),
Benjamin Kramerc215e762012-08-24 11:54:20 +00003782 AssocTypes(new (Context) TypeSourceInfo*[AssocTypes.size()]),
3783 SubExprs(new (Context) Stmt*[END_EXPR+AssocExprs.size()]),
3784 NumAssocs(AssocExprs.size()), ResultIndex(-1U), GenericLoc(GenericLoc),
3785 DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
Peter Collingbourne91147592011-04-15 00:35:48 +00003786 SubExprs[CONTROLLING] = ControllingExpr;
Benjamin Kramerc215e762012-08-24 11:54:20 +00003787 assert(AssocTypes.size() == AssocExprs.size());
3788 std::copy(AssocTypes.begin(), AssocTypes.end(), this->AssocTypes);
3789 std::copy(AssocExprs.begin(), AssocExprs.end(), SubExprs+END_EXPR);
Peter Collingbourne91147592011-04-15 00:35:48 +00003790}
3791
Ted Kremenek85e92ec2007-08-24 18:13:47 +00003792//===----------------------------------------------------------------------===//
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003793// DesignatedInitExpr
3794//===----------------------------------------------------------------------===//
3795
Chandler Carruth631abd92011-06-16 06:47:06 +00003796IdentifierInfo *DesignatedInitExpr::Designator::getFieldName() const {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003797 assert(Kind == FieldDesignator && "Only valid on a field designator");
3798 if (Field.NameOrField & 0x01)
3799 return reinterpret_cast<IdentifierInfo *>(Field.NameOrField&~0x01);
3800 else
3801 return getField()->getIdentifier();
3802}
3803
Craig Topper37932912013-08-18 10:09:15 +00003804DesignatedInitExpr::DesignatedInitExpr(const ASTContext &C, QualType Ty,
David Majnemerf7e36092016-06-23 00:15:04 +00003805 llvm::ArrayRef<Designator> Designators,
Mike Stump11289f42009-09-09 15:08:12 +00003806 SourceLocation EqualOrColonLoc,
Douglas Gregord5846a12009-04-15 06:41:24 +00003807 bool GNUSyntax,
Benjamin Kramerc215e762012-08-24 11:54:20 +00003808 ArrayRef<Expr*> IndexExprs,
Douglas Gregorca1aeec2009-05-21 23:17:49 +00003809 Expr *Init)
Mike Stump11289f42009-09-09 15:08:12 +00003810 : Expr(DesignatedInitExprClass, Ty,
John McCall7decc9e2010-11-18 06:31:45 +00003811 Init->getValueKind(), Init->getObjectKind(),
Douglas Gregora6e053e2010-12-15 01:34:56 +00003812 Init->isTypeDependent(), Init->isValueDependent(),
Douglas Gregor678d76c2011-07-01 01:22:09 +00003813 Init->isInstantiationDependent(),
Douglas Gregora6e053e2010-12-15 01:34:56 +00003814 Init->containsUnexpandedParameterPack()),
Mike Stump11289f42009-09-09 15:08:12 +00003815 EqualOrColonLoc(EqualOrColonLoc), GNUSyntax(GNUSyntax),
David Majnemerf7e36092016-06-23 00:15:04 +00003816 NumDesignators(Designators.size()), NumSubExprs(IndexExprs.size() + 1) {
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00003817 this->Designators = new (C) Designator[NumDesignators];
Douglas Gregorca1aeec2009-05-21 23:17:49 +00003818
3819 // Record the initializer itself.
Benjamin Kramer5733e352015-07-18 17:09:36 +00003820 child_iterator Child = child_begin();
Douglas Gregorca1aeec2009-05-21 23:17:49 +00003821 *Child++ = Init;
3822
3823 // Copy the designators and their subexpressions, computing
3824 // value-dependence along the way.
3825 unsigned IndexIdx = 0;
3826 for (unsigned I = 0; I != NumDesignators; ++I) {
Douglas Gregord5846a12009-04-15 06:41:24 +00003827 this->Designators[I] = Designators[I];
Douglas Gregorca1aeec2009-05-21 23:17:49 +00003828
3829 if (this->Designators[I].isArrayDesignator()) {
3830 // Compute type- and value-dependence.
3831 Expr *Index = IndexExprs[IndexIdx];
Douglas Gregora6e053e2010-12-15 01:34:56 +00003832 if (Index->isTypeDependent() || Index->isValueDependent())
David Majnemer4f217682015-01-09 01:39:09 +00003833 ExprBits.TypeDependent = ExprBits.ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003834 if (Index->isInstantiationDependent())
3835 ExprBits.InstantiationDependent = true;
Douglas Gregora6e053e2010-12-15 01:34:56 +00003836 // Propagate unexpanded parameter packs.
3837 if (Index->containsUnexpandedParameterPack())
3838 ExprBits.ContainsUnexpandedParameterPack = true;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00003839
3840 // Copy the index expressions into permanent storage.
3841 *Child++ = IndexExprs[IndexIdx++];
3842 } else if (this->Designators[I].isArrayRangeDesignator()) {
3843 // Compute type- and value-dependence.
3844 Expr *Start = IndexExprs[IndexIdx];
3845 Expr *End = IndexExprs[IndexIdx + 1];
Douglas Gregora6e053e2010-12-15 01:34:56 +00003846 if (Start->isTypeDependent() || Start->isValueDependent() ||
Douglas Gregor678d76c2011-07-01 01:22:09 +00003847 End->isTypeDependent() || End->isValueDependent()) {
David Majnemer4f217682015-01-09 01:39:09 +00003848 ExprBits.TypeDependent = ExprBits.ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003849 ExprBits.InstantiationDependent = true;
Fangrui Song6907ce22018-07-30 19:24:48 +00003850 } else if (Start->isInstantiationDependent() ||
Douglas Gregor678d76c2011-07-01 01:22:09 +00003851 End->isInstantiationDependent()) {
3852 ExprBits.InstantiationDependent = true;
3853 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003854
Douglas Gregora6e053e2010-12-15 01:34:56 +00003855 // Propagate unexpanded parameter packs.
3856 if (Start->containsUnexpandedParameterPack() ||
3857 End->containsUnexpandedParameterPack())
3858 ExprBits.ContainsUnexpandedParameterPack = true;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00003859
3860 // Copy the start/end expressions into permanent storage.
3861 *Child++ = IndexExprs[IndexIdx++];
3862 *Child++ = IndexExprs[IndexIdx++];
3863 }
3864 }
3865
Benjamin Kramerc215e762012-08-24 11:54:20 +00003866 assert(IndexIdx == IndexExprs.size() && "Wrong number of index expressions");
Douglas Gregord5846a12009-04-15 06:41:24 +00003867}
3868
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003869DesignatedInitExpr *
David Majnemerf7e36092016-06-23 00:15:04 +00003870DesignatedInitExpr::Create(const ASTContext &C,
3871 llvm::ArrayRef<Designator> Designators,
Benjamin Kramerc215e762012-08-24 11:54:20 +00003872 ArrayRef<Expr*> IndexExprs,
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003873 SourceLocation ColonOrEqualLoc,
3874 bool UsesColonSyntax, Expr *Init) {
James Y Knighte00a67e2015-12-31 04:18:25 +00003875 void *Mem = C.Allocate(totalSizeToAlloc<Stmt *>(IndexExprs.size() + 1),
Benjamin Kramerc3f89252016-10-20 14:27:22 +00003876 alignof(DesignatedInitExpr));
David Majnemerf7e36092016-06-23 00:15:04 +00003877 return new (Mem) DesignatedInitExpr(C, C.VoidTy, Designators,
Douglas Gregorca1aeec2009-05-21 23:17:49 +00003878 ColonOrEqualLoc, UsesColonSyntax,
Benjamin Kramerc215e762012-08-24 11:54:20 +00003879 IndexExprs, Init);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003880}
3881
Craig Topper37932912013-08-18 10:09:15 +00003882DesignatedInitExpr *DesignatedInitExpr::CreateEmpty(const ASTContext &C,
Douglas Gregor38676d52009-04-16 00:55:48 +00003883 unsigned NumIndexExprs) {
James Y Knighte00a67e2015-12-31 04:18:25 +00003884 void *Mem = C.Allocate(totalSizeToAlloc<Stmt *>(NumIndexExprs + 1),
Benjamin Kramerc3f89252016-10-20 14:27:22 +00003885 alignof(DesignatedInitExpr));
Douglas Gregor38676d52009-04-16 00:55:48 +00003886 return new (Mem) DesignatedInitExpr(NumIndexExprs + 1);
3887}
3888
Craig Topper37932912013-08-18 10:09:15 +00003889void DesignatedInitExpr::setDesignators(const ASTContext &C,
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00003890 const Designator *Desigs,
Douglas Gregor38676d52009-04-16 00:55:48 +00003891 unsigned NumDesigs) {
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00003892 Designators = new (C) Designator[NumDesigs];
Douglas Gregor38676d52009-04-16 00:55:48 +00003893 NumDesignators = NumDesigs;
3894 for (unsigned I = 0; I != NumDesigs; ++I)
3895 Designators[I] = Desigs[I];
3896}
3897
Abramo Bagnara22f8cd72011-03-16 15:08:46 +00003898SourceRange DesignatedInitExpr::getDesignatorsSourceRange() const {
3899 DesignatedInitExpr *DIE = const_cast<DesignatedInitExpr*>(this);
3900 if (size() == 1)
3901 return DIE->getDesignator(0)->getSourceRange();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003902 return SourceRange(DIE->getDesignator(0)->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00003903 DIE->getDesignator(size() - 1)->getEndLoc());
Abramo Bagnara22f8cd72011-03-16 15:08:46 +00003904}
3905
Stephen Kelly724e9e52018-08-09 20:05:03 +00003906SourceLocation DesignatedInitExpr::getBeginLoc() const {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003907 SourceLocation StartLoc;
David Majnemerf7e36092016-06-23 00:15:04 +00003908 auto *DIE = const_cast<DesignatedInitExpr *>(this);
3909 Designator &First = *DIE->getDesignator(0);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003910 if (First.isFieldDesignator()) {
Douglas Gregor5c7c9cb2009-03-28 00:41:23 +00003911 if (GNUSyntax)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003912 StartLoc = SourceLocation::getFromRawEncoding(First.Field.FieldLoc);
3913 else
3914 StartLoc = SourceLocation::getFromRawEncoding(First.Field.DotLoc);
3915 } else
Chris Lattner8ba22472009-02-16 22:33:34 +00003916 StartLoc =
3917 SourceLocation::getFromRawEncoding(First.ArrayOrRange.LBracketLoc);
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00003918 return StartLoc;
3919}
3920
Stephen Kelly02a67ba2018-08-09 20:05:47 +00003921SourceLocation DesignatedInitExpr::getEndLoc() const {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00003922 return getInit()->getEndLoc();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003923}
3924
Dmitri Gribenkod06f7ff2013-01-26 15:15:52 +00003925Expr *DesignatedInitExpr::getArrayIndex(const Designator& D) const {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003926 assert(D.Kind == Designator::ArrayDesignator && "Requires array designator");
James Y Knighte00a67e2015-12-31 04:18:25 +00003927 return getSubExpr(D.ArrayOrRange.Index + 1);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003928}
3929
Dmitri Gribenkod06f7ff2013-01-26 15:15:52 +00003930Expr *DesignatedInitExpr::getArrayRangeStart(const Designator &D) const {
Mike Stump11289f42009-09-09 15:08:12 +00003931 assert(D.Kind == Designator::ArrayRangeDesignator &&
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003932 "Requires array range designator");
James Y Knighte00a67e2015-12-31 04:18:25 +00003933 return getSubExpr(D.ArrayOrRange.Index + 1);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003934}
3935
Dmitri Gribenkod06f7ff2013-01-26 15:15:52 +00003936Expr *DesignatedInitExpr::getArrayRangeEnd(const Designator &D) const {
Mike Stump11289f42009-09-09 15:08:12 +00003937 assert(D.Kind == Designator::ArrayRangeDesignator &&
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003938 "Requires array range designator");
James Y Knighte00a67e2015-12-31 04:18:25 +00003939 return getSubExpr(D.ArrayOrRange.Index + 2);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003940}
3941
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003942/// Replaces the designator at index @p Idx with the series
Douglas Gregord5846a12009-04-15 06:41:24 +00003943/// of designators in [First, Last).
Craig Topper37932912013-08-18 10:09:15 +00003944void DesignatedInitExpr::ExpandDesignator(const ASTContext &C, unsigned Idx,
Mike Stump11289f42009-09-09 15:08:12 +00003945 const Designator *First,
Douglas Gregord5846a12009-04-15 06:41:24 +00003946 const Designator *Last) {
3947 unsigned NumNewDesignators = Last - First;
3948 if (NumNewDesignators == 0) {
3949 std::copy_backward(Designators + Idx + 1,
3950 Designators + NumDesignators,
3951 Designators + Idx);
3952 --NumNewDesignators;
3953 return;
3954 } else if (NumNewDesignators == 1) {
3955 Designators[Idx] = *First;
3956 return;
3957 }
3958
Mike Stump11289f42009-09-09 15:08:12 +00003959 Designator *NewDesignators
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00003960 = new (C) Designator[NumDesignators - 1 + NumNewDesignators];
Douglas Gregord5846a12009-04-15 06:41:24 +00003961 std::copy(Designators, Designators + Idx, NewDesignators);
3962 std::copy(First, Last, NewDesignators + Idx);
3963 std::copy(Designators + Idx + 1, Designators + NumDesignators,
3964 NewDesignators + Idx + NumNewDesignators);
Douglas Gregord5846a12009-04-15 06:41:24 +00003965 Designators = NewDesignators;
3966 NumDesignators = NumDesignators - 1 + NumNewDesignators;
3967}
3968
Yunzhong Gaocb779302015-06-10 00:27:52 +00003969DesignatedInitUpdateExpr::DesignatedInitUpdateExpr(const ASTContext &C,
3970 SourceLocation lBraceLoc, Expr *baseExpr, SourceLocation rBraceLoc)
3971 : Expr(DesignatedInitUpdateExprClass, baseExpr->getType(), VK_RValue,
3972 OK_Ordinary, false, false, false, false) {
3973 BaseAndUpdaterExprs[0] = baseExpr;
3974
3975 InitListExpr *ILE = new (C) InitListExpr(C, lBraceLoc, None, rBraceLoc);
3976 ILE->setType(baseExpr->getType());
3977 BaseAndUpdaterExprs[1] = ILE;
3978}
3979
Stephen Kelly724e9e52018-08-09 20:05:03 +00003980SourceLocation DesignatedInitUpdateExpr::getBeginLoc() const {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003981 return getBase()->getBeginLoc();
Yunzhong Gaocb779302015-06-10 00:27:52 +00003982}
3983
Stephen Kelly02a67ba2018-08-09 20:05:47 +00003984SourceLocation DesignatedInitUpdateExpr::getEndLoc() const {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00003985 return getBase()->getEndLoc();
Yunzhong Gaocb779302015-06-10 00:27:52 +00003986}
3987
Craig Topper37932912013-08-18 10:09:15 +00003988ParenListExpr::ParenListExpr(const ASTContext& C, SourceLocation lparenloc,
Benjamin Kramerc215e762012-08-24 11:54:20 +00003989 ArrayRef<Expr*> exprs,
Sebastian Redla9351792012-02-11 23:51:47 +00003990 SourceLocation rparenloc)
3991 : Expr(ParenListExprClass, QualType(), VK_RValue, OK_Ordinary,
Douglas Gregor678d76c2011-07-01 01:22:09 +00003992 false, false, false, false),
Benjamin Kramerc215e762012-08-24 11:54:20 +00003993 NumExprs(exprs.size()), LParenLoc(lparenloc), RParenLoc(rparenloc) {
3994 Exprs = new (C) Stmt*[exprs.size()];
3995 for (unsigned i = 0; i != exprs.size(); ++i) {
Douglas Gregora6e053e2010-12-15 01:34:56 +00003996 if (exprs[i]->isTypeDependent())
3997 ExprBits.TypeDependent = true;
3998 if (exprs[i]->isValueDependent())
3999 ExprBits.ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +00004000 if (exprs[i]->isInstantiationDependent())
4001 ExprBits.InstantiationDependent = true;
Douglas Gregora6e053e2010-12-15 01:34:56 +00004002 if (exprs[i]->containsUnexpandedParameterPack())
4003 ExprBits.ContainsUnexpandedParameterPack = true;
4004
Nate Begeman5ec4b312009-08-10 23:49:36 +00004005 Exprs[i] = exprs[i];
Douglas Gregora6e053e2010-12-15 01:34:56 +00004006 }
Nate Begeman5ec4b312009-08-10 23:49:36 +00004007}
4008
John McCall1bf58462011-02-16 08:02:54 +00004009const OpaqueValueExpr *OpaqueValueExpr::findInCopyConstruct(const Expr *e) {
4010 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(e))
4011 e = ewc->getSubExpr();
Douglas Gregorfe314812011-06-21 17:03:29 +00004012 if (const MaterializeTemporaryExpr *m = dyn_cast<MaterializeTemporaryExpr>(e))
4013 e = m->GetTemporaryExpr();
John McCall1bf58462011-02-16 08:02:54 +00004014 e = cast<CXXConstructExpr>(e)->getArg(0);
4015 while (const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
4016 e = ice->getSubExpr();
4017 return cast<OpaqueValueExpr>(e);
4018}
4019
Craig Topper37932912013-08-18 10:09:15 +00004020PseudoObjectExpr *PseudoObjectExpr::Create(const ASTContext &Context,
4021 EmptyShell sh,
John McCallfe96e0b2011-11-06 09:01:30 +00004022 unsigned numSemanticExprs) {
James Y Knighte00a67e2015-12-31 04:18:25 +00004023 void *buffer =
4024 Context.Allocate(totalSizeToAlloc<Expr *>(1 + numSemanticExprs),
Benjamin Kramerc3f89252016-10-20 14:27:22 +00004025 alignof(PseudoObjectExpr));
John McCallfe96e0b2011-11-06 09:01:30 +00004026 return new(buffer) PseudoObjectExpr(sh, numSemanticExprs);
4027}
4028
4029PseudoObjectExpr::PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs)
4030 : Expr(PseudoObjectExprClass, shell) {
4031 PseudoObjectExprBits.NumSubExprs = numSemanticExprs + 1;
4032}
4033
Craig Topper37932912013-08-18 10:09:15 +00004034PseudoObjectExpr *PseudoObjectExpr::Create(const ASTContext &C, Expr *syntax,
John McCallfe96e0b2011-11-06 09:01:30 +00004035 ArrayRef<Expr*> semantics,
4036 unsigned resultIndex) {
4037 assert(syntax && "no syntactic expression!");
Eugene Zelenkoae304b02017-11-17 18:09:48 +00004038 assert(semantics.size() && "no semantic expressions!");
John McCallfe96e0b2011-11-06 09:01:30 +00004039
4040 QualType type;
4041 ExprValueKind VK;
4042 if (resultIndex == NoResult) {
4043 type = C.VoidTy;
4044 VK = VK_RValue;
4045 } else {
4046 assert(resultIndex < semantics.size());
4047 type = semantics[resultIndex]->getType();
4048 VK = semantics[resultIndex]->getValueKind();
4049 assert(semantics[resultIndex]->getObjectKind() == OK_Ordinary);
4050 }
4051
James Y Knighte00a67e2015-12-31 04:18:25 +00004052 void *buffer = C.Allocate(totalSizeToAlloc<Expr *>(semantics.size() + 1),
Benjamin Kramerc3f89252016-10-20 14:27:22 +00004053 alignof(PseudoObjectExpr));
John McCallfe96e0b2011-11-06 09:01:30 +00004054 return new(buffer) PseudoObjectExpr(type, VK, syntax, semantics,
4055 resultIndex);
4056}
4057
4058PseudoObjectExpr::PseudoObjectExpr(QualType type, ExprValueKind VK,
4059 Expr *syntax, ArrayRef<Expr*> semantics,
4060 unsigned resultIndex)
4061 : Expr(PseudoObjectExprClass, type, VK, OK_Ordinary,
4062 /*filled in at end of ctor*/ false, false, false, false) {
4063 PseudoObjectExprBits.NumSubExprs = semantics.size() + 1;
4064 PseudoObjectExprBits.ResultIndex = resultIndex + 1;
4065
4066 for (unsigned i = 0, e = semantics.size() + 1; i != e; ++i) {
4067 Expr *E = (i == 0 ? syntax : semantics[i-1]);
4068 getSubExprsBuffer()[i] = E;
4069
4070 if (E->isTypeDependent())
4071 ExprBits.TypeDependent = true;
4072 if (E->isValueDependent())
4073 ExprBits.ValueDependent = true;
4074 if (E->isInstantiationDependent())
4075 ExprBits.InstantiationDependent = true;
4076 if (E->containsUnexpandedParameterPack())
4077 ExprBits.ContainsUnexpandedParameterPack = true;
4078
4079 if (isa<OpaqueValueExpr>(E))
Craig Topper36250ad2014-05-12 05:36:57 +00004080 assert(cast<OpaqueValueExpr>(E)->getSourceExpr() != nullptr &&
John McCallfe96e0b2011-11-06 09:01:30 +00004081 "opaque-value semantic expressions for pseudo-object "
4082 "operations must have sources");
4083 }
4084}
4085
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004086//===----------------------------------------------------------------------===//
Ted Kremenek85e92ec2007-08-24 18:13:47 +00004087// Child Iterators for iterating over subexpressions/substatements
4088//===----------------------------------------------------------------------===//
4089
Peter Collingbournee190dee2011-03-11 19:24:49 +00004090// UnaryExprOrTypeTraitExpr
4091Stmt::child_range UnaryExprOrTypeTraitExpr::children() {
Aaron Ballman4c54fe02017-04-11 20:21:30 +00004092 const_child_range CCR =
4093 const_cast<const UnaryExprOrTypeTraitExpr *>(this)->children();
4094 return child_range(cast_away_const(CCR.begin()), cast_away_const(CCR.end()));
4095}
4096
4097Stmt::const_child_range UnaryExprOrTypeTraitExpr::children() const {
Sebastian Redl6f282892008-11-11 17:56:53 +00004098 // If this is of a type and the type is a VLA type (and not a typedef), the
4099 // size expression of the VLA needs to be treated as an executable expression.
4100 // Why isn't this weirdness documented better in StmtIterator?
4101 if (isArgumentType()) {
Aaron Ballman4c54fe02017-04-11 20:21:30 +00004102 if (const VariableArrayType *T =
4103 dyn_cast<VariableArrayType>(getArgumentType().getTypePtr()))
4104 return const_child_range(const_child_iterator(T), const_child_iterator());
4105 return const_child_range(const_child_iterator(), const_child_iterator());
Sebastian Redl6f282892008-11-11 17:56:53 +00004106 }
Aaron Ballman4c54fe02017-04-11 20:21:30 +00004107 return const_child_range(&Argument.Ex, &Argument.Ex + 1);
Ted Kremenek04746ce2007-10-18 23:28:49 +00004108}
Fariborz Jahaniana32aaef2007-10-17 16:58:11 +00004109
Benjamin Kramerc215e762012-08-24 11:54:20 +00004110AtomicExpr::AtomicExpr(SourceLocation BLoc, ArrayRef<Expr*> args,
Eli Friedman8d3e43f2011-10-14 22:48:56 +00004111 QualType t, AtomicOp op, SourceLocation RP)
Eugene Zelenkoae304b02017-11-17 18:09:48 +00004112 : Expr(AtomicExprClass, t, VK_RValue, OK_Ordinary,
4113 false, false, false, false),
4114 NumSubExprs(args.size()), BuiltinLoc(BLoc), RParenLoc(RP), Op(op)
4115{
Benjamin Kramerc215e762012-08-24 11:54:20 +00004116 assert(args.size() == getNumSubExprs(op) && "wrong number of subexpressions");
4117 for (unsigned i = 0; i != args.size(); i++) {
Eli Friedman8d3e43f2011-10-14 22:48:56 +00004118 if (args[i]->isTypeDependent())
4119 ExprBits.TypeDependent = true;
4120 if (args[i]->isValueDependent())
4121 ExprBits.ValueDependent = true;
4122 if (args[i]->isInstantiationDependent())
4123 ExprBits.InstantiationDependent = true;
4124 if (args[i]->containsUnexpandedParameterPack())
4125 ExprBits.ContainsUnexpandedParameterPack = true;
4126
4127 SubExprs[i] = args[i];
4128 }
4129}
Richard Smithaa22a8c2012-04-10 22:49:28 +00004130
4131unsigned AtomicExpr::getNumSubExprs(AtomicOp Op) {
4132 switch (Op) {
Richard Smithfeea8832012-04-12 05:08:17 +00004133 case AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +00004134 case AO__opencl_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +00004135 case AO__c11_atomic_load:
Yaxun Liu39195062017-08-04 18:16:31 +00004136 case AO__atomic_load_n:
Yaxun Liu30d652a2017-08-15 16:02:49 +00004137 return 2;
Richard Smithfeea8832012-04-12 05:08:17 +00004138
Yaxun Liu30d652a2017-08-15 16:02:49 +00004139 case AO__opencl_atomic_load:
Richard Smithfeea8832012-04-12 05:08:17 +00004140 case AO__c11_atomic_store:
4141 case AO__c11_atomic_exchange:
4142 case AO__atomic_load:
4143 case AO__atomic_store:
4144 case AO__atomic_store_n:
4145 case AO__atomic_exchange_n:
4146 case AO__c11_atomic_fetch_add:
4147 case AO__c11_atomic_fetch_sub:
4148 case AO__c11_atomic_fetch_and:
4149 case AO__c11_atomic_fetch_or:
4150 case AO__c11_atomic_fetch_xor:
4151 case AO__atomic_fetch_add:
4152 case AO__atomic_fetch_sub:
4153 case AO__atomic_fetch_and:
4154 case AO__atomic_fetch_or:
4155 case AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00004156 case AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00004157 case AO__atomic_add_fetch:
4158 case AO__atomic_sub_fetch:
4159 case AO__atomic_and_fetch:
4160 case AO__atomic_or_fetch:
4161 case AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00004162 case AO__atomic_nand_fetch:
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00004163 case AO__atomic_fetch_min:
4164 case AO__atomic_fetch_max:
Yaxun Liu30d652a2017-08-15 16:02:49 +00004165 return 3;
Richard Smithfeea8832012-04-12 05:08:17 +00004166
Yaxun Liu30d652a2017-08-15 16:02:49 +00004167 case AO__opencl_atomic_store:
4168 case AO__opencl_atomic_exchange:
4169 case AO__opencl_atomic_fetch_add:
4170 case AO__opencl_atomic_fetch_sub:
4171 case AO__opencl_atomic_fetch_and:
4172 case AO__opencl_atomic_fetch_or:
4173 case AO__opencl_atomic_fetch_xor:
4174 case AO__opencl_atomic_fetch_min:
4175 case AO__opencl_atomic_fetch_max:
Richard Smithfeea8832012-04-12 05:08:17 +00004176 case AO__atomic_exchange:
Yaxun Liu30d652a2017-08-15 16:02:49 +00004177 return 4;
Richard Smithfeea8832012-04-12 05:08:17 +00004178
4179 case AO__c11_atomic_compare_exchange_strong:
4180 case AO__c11_atomic_compare_exchange_weak:
Yaxun Liu30d652a2017-08-15 16:02:49 +00004181 return 5;
4182
Yaxun Liu39195062017-08-04 18:16:31 +00004183 case AO__opencl_atomic_compare_exchange_strong:
4184 case AO__opencl_atomic_compare_exchange_weak:
Richard Smithfeea8832012-04-12 05:08:17 +00004185 case AO__atomic_compare_exchange:
4186 case AO__atomic_compare_exchange_n:
Yaxun Liu30d652a2017-08-15 16:02:49 +00004187 return 6;
Richard Smithaa22a8c2012-04-10 22:49:28 +00004188 }
4189 llvm_unreachable("unknown atomic op");
4190}
Alexey Bataeva1764212015-09-30 09:22:36 +00004191
Yaxun Liu39195062017-08-04 18:16:31 +00004192QualType AtomicExpr::getValueType() const {
4193 auto T = getPtr()->getType()->castAs<PointerType>()->getPointeeType();
4194 if (auto AT = T->getAs<AtomicType>())
4195 return AT->getValueType();
4196 return T;
4197}
4198
Alexey Bataev31300ed2016-02-04 11:27:03 +00004199QualType OMPArraySectionExpr::getBaseOriginalType(const Expr *Base) {
Alexey Bataeva1764212015-09-30 09:22:36 +00004200 unsigned ArraySectionCount = 0;
4201 while (auto *OASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParens())) {
4202 Base = OASE->getBase();
4203 ++ArraySectionCount;
4204 }
Alexey Bataev31300ed2016-02-04 11:27:03 +00004205 while (auto *ASE =
4206 dyn_cast<ArraySubscriptExpr>(Base->IgnoreParenImpCasts())) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004207 Base = ASE->getBase();
4208 ++ArraySectionCount;
4209 }
Alexey Bataev31300ed2016-02-04 11:27:03 +00004210 Base = Base->IgnoreParenImpCasts();
Alexey Bataeva1764212015-09-30 09:22:36 +00004211 auto OriginalTy = Base->getType();
4212 if (auto *DRE = dyn_cast<DeclRefExpr>(Base))
4213 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
4214 OriginalTy = PVD->getOriginalType().getNonReferenceType();
4215
4216 for (unsigned Cnt = 0; Cnt < ArraySectionCount; ++Cnt) {
4217 if (OriginalTy->isAnyPointerType())
4218 OriginalTy = OriginalTy->getPointeeType();
4219 else {
Eugene Zelenkoae304b02017-11-17 18:09:48 +00004220 assert (OriginalTy->isArrayType());
Alexey Bataeva1764212015-09-30 09:22:36 +00004221 OriginalTy = OriginalTy->castAsArrayTypeUnsafe()->getElementType();
4222 }
4223 }
4224 return OriginalTy;
4225}