blob: 4f3c5b33442042dd1530e6709887b255f4c110c2 [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"
Douglas Gregor0840cc02009-11-01 20:32:48 +000031#include "llvm/Support/ErrorHandling.h"
Anders Carlsson2fb08242009-09-08 18:24:21 +000032#include "llvm/Support/raw_ostream.h"
Douglas Gregord5846a12009-04-15 06:41:24 +000033#include <algorithm>
Eli Friedmanfcec6302011-11-01 02:23:42 +000034#include <cstring>
Chris Lattner1b926492006-08-23 06:42:10 +000035using namespace clang;
36
Richard Smith018ac392016-11-03 18:55:18 +000037const Expr *Expr::getBestDynamicClassTypeExpr() const {
38 const Expr *E = this;
39 while (true) {
40 E = E->ignoreParenBaseCasts();
Rafael Espindola49e860b2012-06-26 17:45:31 +000041
Richard Smith018ac392016-11-03 18:55:18 +000042 // Follow the RHS of a comma operator.
43 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
44 if (BO->getOpcode() == BO_Comma) {
45 E = BO->getRHS();
46 continue;
47 }
48 }
49
50 // Step into initializer for materialized temporaries.
51 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
52 E = MTE->GetTemporaryExpr();
53 continue;
54 }
55
56 break;
57 }
58
59 return E;
60}
61
62const CXXRecordDecl *Expr::getBestDynamicClassType() const {
63 const Expr *E = getBestDynamicClassTypeExpr();
Rafael Espindola49e860b2012-06-26 17:45:31 +000064 QualType DerivedType = E->getType();
Rafael Espindola49e860b2012-06-26 17:45:31 +000065 if (const PointerType *PTy = DerivedType->getAs<PointerType>())
66 DerivedType = PTy->getPointeeType();
67
Rafael Espindola60a2bba2012-07-17 20:24:05 +000068 if (DerivedType->isDependentType())
Craig Topper36250ad2014-05-12 05:36:57 +000069 return nullptr;
Rafael Espindola60a2bba2012-07-17 20:24:05 +000070
Rafael Espindola49e860b2012-06-26 17:45:31 +000071 const RecordType *Ty = DerivedType->castAs<RecordType>();
Rafael Espindola49e860b2012-06-26 17:45:31 +000072 Decl *D = Ty->getDecl();
73 return cast<CXXRecordDecl>(D);
74}
75
Richard Smithf3fabd22013-06-03 00:17:11 +000076const Expr *Expr::skipRValueSubobjectAdjustments(
77 SmallVectorImpl<const Expr *> &CommaLHSs,
78 SmallVectorImpl<SubobjectAdjustment> &Adjustments) const {
Rafael Espindola9c006de2012-10-27 01:03:43 +000079 const Expr *E = this;
80 while (true) {
81 E = E->IgnoreParens();
82
83 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
84 if ((CE->getCastKind() == CK_DerivedToBase ||
85 CE->getCastKind() == CK_UncheckedDerivedToBase) &&
86 E->getType()->isRecordType()) {
87 E = CE->getSubExpr();
88 CXXRecordDecl *Derived
89 = cast<CXXRecordDecl>(E->getType()->getAs<RecordType>()->getDecl());
90 Adjustments.push_back(SubobjectAdjustment(CE, Derived));
91 continue;
92 }
93
94 if (CE->getCastKind() == CK_NoOp) {
95 E = CE->getSubExpr();
96 continue;
97 }
98 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
Richard Smith6b6f8aa2013-06-15 00:30:29 +000099 if (!ME->isArrow()) {
Rafael Espindola9c006de2012-10-27 01:03:43 +0000100 assert(ME->getBase()->getType()->isRecordType());
101 if (FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
Richard Smith6b6f8aa2013-06-15 00:30:29 +0000102 if (!Field->isBitField() && !Field->getType()->isReferenceType()) {
Richard Smith2d187902013-06-03 07:13:35 +0000103 E = ME->getBase();
104 Adjustments.push_back(SubobjectAdjustment(Field));
105 continue;
106 }
Rafael Espindola9c006de2012-10-27 01:03:43 +0000107 }
108 }
109 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
Richard Smitha3fd1162018-07-24 21:18:30 +0000110 if (BO->getOpcode() == BO_PtrMemD) {
Rafael Espindola973aa202012-11-01 14:32:20 +0000111 assert(BO->getRHS()->isRValue());
Rafael Espindola9c006de2012-10-27 01:03:43 +0000112 E = BO->getLHS();
113 const MemberPointerType *MPT =
114 BO->getRHS()->getType()->getAs<MemberPointerType>();
115 Adjustments.push_back(SubobjectAdjustment(MPT, BO->getRHS()));
Richard Smithf3fabd22013-06-03 00:17:11 +0000116 continue;
117 } else if (BO->getOpcode() == BO_Comma) {
118 CommaLHSs.push_back(BO->getLHS());
119 E = BO->getRHS();
120 continue;
Rafael Espindola9c006de2012-10-27 01:03:43 +0000121 }
122 }
123
124 // Nothing changed.
125 break;
126 }
127 return E;
128}
129
Chris Lattner4ebae652010-04-16 23:34:13 +0000130/// isKnownToHaveBooleanValue - Return true if this is an integer expression
131/// that is known to return 0 or 1. This happens for _Bool/bool expressions
132/// but also int expressions which are produced by things like comparisons in
133/// C.
134bool Expr::isKnownToHaveBooleanValue() const {
Peter Collingbourne91147592011-04-15 00:35:48 +0000135 const Expr *E = IgnoreParens();
136
Chris Lattner4ebae652010-04-16 23:34:13 +0000137 // If this value has _Bool type, it is obvious 0/1.
Peter Collingbourne91147592011-04-15 00:35:48 +0000138 if (E->getType()->isBooleanType()) return true;
Fangrui Song6907ce22018-07-30 19:24:48 +0000139 // If this is a non-scalar-integer type, we don't care enough to try.
Peter Collingbourne91147592011-04-15 00:35:48 +0000140 if (!E->getType()->isIntegralOrEnumerationType()) return false;
Fangrui Song6907ce22018-07-30 19:24:48 +0000141
Peter Collingbourne91147592011-04-15 00:35:48 +0000142 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
Chris Lattner4ebae652010-04-16 23:34:13 +0000143 switch (UO->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +0000144 case UO_Plus:
Chris Lattner4ebae652010-04-16 23:34:13 +0000145 return UO->getSubExpr()->isKnownToHaveBooleanValue();
Richard Trieu0f097742014-04-04 04:13:47 +0000146 case UO_LNot:
147 return true;
Chris Lattner4ebae652010-04-16 23:34:13 +0000148 default:
149 return false;
150 }
151 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000152
John McCall45d30c32010-06-12 01:56:02 +0000153 // Only look through implicit casts. If the user writes
154 // '(int) (a && b)' treat it as an arbitrary int.
Peter Collingbourne91147592011-04-15 00:35:48 +0000155 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Chris Lattner4ebae652010-04-16 23:34:13 +0000156 return CE->getSubExpr()->isKnownToHaveBooleanValue();
Fangrui Song6907ce22018-07-30 19:24:48 +0000157
Peter Collingbourne91147592011-04-15 00:35:48 +0000158 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
Chris Lattner4ebae652010-04-16 23:34:13 +0000159 switch (BO->getOpcode()) {
160 default: return false;
John McCalle3027922010-08-25 11:45:40 +0000161 case BO_LT: // Relational operators.
162 case BO_GT:
163 case BO_LE:
164 case BO_GE:
165 case BO_EQ: // Equality operators.
166 case BO_NE:
167 case BO_LAnd: // AND operator.
168 case BO_LOr: // Logical OR operator.
Chris Lattner4ebae652010-04-16 23:34:13 +0000169 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +0000170
John McCalle3027922010-08-25 11:45:40 +0000171 case BO_And: // Bitwise AND operator.
172 case BO_Xor: // Bitwise XOR operator.
173 case BO_Or: // Bitwise OR operator.
Chris Lattner4ebae652010-04-16 23:34:13 +0000174 // Handle things like (x==2)|(y==12).
175 return BO->getLHS()->isKnownToHaveBooleanValue() &&
176 BO->getRHS()->isKnownToHaveBooleanValue();
Fangrui Song6907ce22018-07-30 19:24:48 +0000177
John McCalle3027922010-08-25 11:45:40 +0000178 case BO_Comma:
179 case BO_Assign:
Chris Lattner4ebae652010-04-16 23:34:13 +0000180 return BO->getRHS()->isKnownToHaveBooleanValue();
181 }
182 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000183
Peter Collingbourne91147592011-04-15 00:35:48 +0000184 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
Chris Lattner4ebae652010-04-16 23:34:13 +0000185 return CO->getTrueExpr()->isKnownToHaveBooleanValue() &&
186 CO->getFalseExpr()->isKnownToHaveBooleanValue();
Fangrui Song6907ce22018-07-30 19:24:48 +0000187
Chris Lattner4ebae652010-04-16 23:34:13 +0000188 return false;
189}
190
John McCallbd066782011-02-09 08:16:59 +0000191// Amusing macro metaprogramming hack: check whether a class provides
192// a more specific implementation of getExprLoc().
Daniel Dunbarb0ab5e92012-03-09 15:39:19 +0000193//
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000194// See also Stmt.cpp:{getBeginLoc(),getEndLoc()}.
Eugene Zelenkoae304b02017-11-17 18:09:48 +0000195namespace {
196 /// This implementation is used when a class provides a custom
197 /// implementation of getExprLoc.
198 template <class E, class T>
199 SourceLocation getExprLocImpl(const Expr *expr,
200 SourceLocation (T::*v)() const) {
201 return static_cast<const E*>(expr)->getExprLoc();
202 }
John McCallbd066782011-02-09 08:16:59 +0000203
Eugene Zelenkoae304b02017-11-17 18:09:48 +0000204 /// This implementation is used when a class doesn't provide
205 /// a custom implementation of getExprLoc. Overload resolution
206 /// should pick it over the implementation above because it's
207 /// more specialized according to function template partial ordering.
208 template <class E>
209 SourceLocation getExprLocImpl(const Expr *expr,
210 SourceLocation (Expr::*v)() const) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000211 return static_cast<const E *>(expr)->getBeginLoc();
Eugene Zelenkoae304b02017-11-17 18:09:48 +0000212 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000213}
John McCallbd066782011-02-09 08:16:59 +0000214
215SourceLocation Expr::getExprLoc() const {
216 switch (getStmtClass()) {
217 case Stmt::NoStmtClass: llvm_unreachable("statement without class");
218#define ABSTRACT_STMT(type)
219#define STMT(type, base) \
Richard Smitha0cbfc92014-07-26 00:47:13 +0000220 case Stmt::type##Class: break;
John McCallbd066782011-02-09 08:16:59 +0000221#define EXPR(type, base) \
222 case Stmt::type##Class: return getExprLocImpl<type>(this, &type::getExprLoc);
223#include "clang/AST/StmtNodes.inc"
224 }
Richard Smitha0cbfc92014-07-26 00:47:13 +0000225 llvm_unreachable("unknown expression kind");
John McCallbd066782011-02-09 08:16:59 +0000226}
227
Chris Lattner0eedafe2006-08-24 04:56:27 +0000228//===----------------------------------------------------------------------===//
229// Primary Expressions.
230//===----------------------------------------------------------------------===//
231
Fangrui Song6907ce22018-07-30 19:24:48 +0000232/// Compute the type-, value-, and instantiation-dependence of a
Douglas Gregor678d76c2011-07-01 01:22:09 +0000233/// declaration reference
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000234/// based on the declaration being referenced.
Craig Topperce7167c2013-08-22 04:58:56 +0000235static void computeDeclRefDependence(const ASTContext &Ctx, NamedDecl *D,
236 QualType T, bool &TypeDependent,
Douglas Gregor678d76c2011-07-01 01:22:09 +0000237 bool &ValueDependent,
238 bool &InstantiationDependent) {
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000239 TypeDependent = false;
240 ValueDependent = false;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000241 InstantiationDependent = false;
Douglas Gregored6c7442009-11-23 11:41:28 +0000242
243 // (TD) C++ [temp.dep.expr]p3:
244 // An id-expression is type-dependent if it contains:
245 //
Richard Smithcfaa5a32014-10-17 02:46:42 +0000246 // and
Douglas Gregored6c7442009-11-23 11:41:28 +0000247 //
248 // (VD) C++ [temp.dep.constexpr]p2:
249 // An identifier is value-dependent if it is:
Richard Smithcfaa5a32014-10-17 02:46:42 +0000250
Douglas Gregored6c7442009-11-23 11:41:28 +0000251 // (TD) - an identifier that was declared with dependent type
252 // (VD) - a name declared with a dependent type,
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000253 if (T->isDependentType()) {
254 TypeDependent = true;
255 ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000256 InstantiationDependent = true;
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000257 return;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000258 } else if (T->isInstantiationDependentType()) {
259 InstantiationDependent = true;
Douglas Gregored6c7442009-11-23 11:41:28 +0000260 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000261
Douglas Gregored6c7442009-11-23 11:41:28 +0000262 // (TD) - a conversion-function-id that specifies a dependent type
Fangrui Song6907ce22018-07-30 19:24:48 +0000263 if (D->getDeclName().getNameKind()
Douglas Gregor678d76c2011-07-01 01:22:09 +0000264 == DeclarationName::CXXConversionFunctionName) {
265 QualType T = D->getDeclName().getCXXNameType();
266 if (T->isDependentType()) {
267 TypeDependent = true;
268 ValueDependent = true;
269 InstantiationDependent = true;
270 return;
271 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000272
Douglas Gregor678d76c2011-07-01 01:22:09 +0000273 if (T->isInstantiationDependentType())
274 InstantiationDependent = true;
Douglas Gregored6c7442009-11-23 11:41:28 +0000275 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000276
Douglas Gregored6c7442009-11-23 11:41:28 +0000277 // (VD) - the name of a non-type template parameter,
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000278 if (isa<NonTypeTemplateParmDecl>(D)) {
279 ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000280 InstantiationDependent = true;
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000281 return;
282 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000283
Douglas Gregored6c7442009-11-23 11:41:28 +0000284 // (VD) - a constant with integral or enumeration type and is
285 // initialized with an expression that is value-dependent.
Richard Smithec8dcd22011-11-08 01:31:09 +0000286 // (VD) - a constant with literal type and is initialized with an
287 // expression that is value-dependent [C++11].
288 // (VD) - FIXME: Missing from the standard:
289 // - an entity with reference type and is initialized with an
290 // expression that is value-dependent [C++11]
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000291 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000292 if ((Ctx.getLangOpts().CPlusPlus11 ?
Richard Smithd9f663b2013-04-22 15:31:51 +0000293 Var->getType()->isLiteralType(Ctx) :
Richard Smithec8dcd22011-11-08 01:31:09 +0000294 Var->getType()->isIntegralOrEnumerationType()) &&
David Blaikief5697e52012-08-10 00:55:35 +0000295 (Var->getType().isConstQualified() ||
Richard Smithec8dcd22011-11-08 01:31:09 +0000296 Var->getType()->isReferenceType())) {
Sebastian Redl5ca79842010-02-01 20:16:42 +0000297 if (const Expr *Init = Var->getAnyInitializer())
Douglas Gregor678d76c2011-07-01 01:22:09 +0000298 if (Init->isValueDependent()) {
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000299 ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000300 InstantiationDependent = true;
301 }
Richard Smithec8dcd22011-11-08 01:31:09 +0000302 }
303
Fangrui Song6907ce22018-07-30 19:24:48 +0000304 // (VD) - FIXME: Missing from the standard:
305 // - a member function or a static data member of the current
Douglas Gregor0e4de762010-05-11 08:41:30 +0000306 // instantiation
Fangrui Song6907ce22018-07-30 19:24:48 +0000307 if (Var->isStaticDataMember() &&
Richard Smithec8dcd22011-11-08 01:31:09 +0000308 Var->getDeclContext()->isDependentContext()) {
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000309 ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000310 InstantiationDependent = true;
Richard Smith00f5d892013-11-14 22:40:45 +0000311 TypeSourceInfo *TInfo = Var->getFirstDecl()->getTypeSourceInfo();
312 if (TInfo->getType()->isIncompleteArrayType())
313 TypeDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000314 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000315
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000316 return;
317 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000318
319 // (VD) - FIXME: Missing from the standard:
320 // - a member function or a static data member of the current
Douglas Gregor0e4de762010-05-11 08:41:30 +0000321 // instantiation
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000322 if (isa<CXXMethodDecl>(D) && D->getDeclContext()->isDependentContext()) {
323 ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000324 InstantiationDependent = true;
Richard Smithec8dcd22011-11-08 01:31:09 +0000325 }
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000326}
Douglas Gregora6e053e2010-12-15 01:34:56 +0000327
Craig Topperce7167c2013-08-22 04:58:56 +0000328void DeclRefExpr::computeDependence(const ASTContext &Ctx) {
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000329 bool TypeDependent = false;
330 bool ValueDependent = false;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000331 bool InstantiationDependent = false;
Daniel Dunbar9d355812012-03-09 01:51:51 +0000332 computeDeclRefDependence(Ctx, getDecl(), getType(), TypeDependent,
333 ValueDependent, InstantiationDependent);
Richard Smithcfaa5a32014-10-17 02:46:42 +0000334
335 ExprBits.TypeDependent |= TypeDependent;
336 ExprBits.ValueDependent |= ValueDependent;
337 ExprBits.InstantiationDependent |= InstantiationDependent;
338
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000339 // Is the declaration a parameter pack?
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000340 if (getDecl()->isParameterPack())
Douglas Gregor3c6bd2a2011-01-05 21:11:38 +0000341 ExprBits.ContainsUnexpandedParameterPack = true;
Douglas Gregored6c7442009-11-23 11:41:28 +0000342}
343
Bruno Ricci5fc4db72018-12-21 14:10:18 +0000344DeclRefExpr::DeclRefExpr(const ASTContext &Ctx, ValueDecl *D,
345 bool RefersToEnclosingVariableOrCapture, QualType T,
346 ExprValueKind VK, SourceLocation L,
347 const DeclarationNameLoc &LocInfo)
348 : Expr(DeclRefExprClass, T, VK, OK_Ordinary, false, false, false, false),
349 D(D), DNLoc(LocInfo) {
350 DeclRefExprBits.HasQualifier = false;
351 DeclRefExprBits.HasTemplateKWAndArgsInfo = false;
352 DeclRefExprBits.HasFoundDecl = false;
353 DeclRefExprBits.HadMultipleCandidates = false;
354 DeclRefExprBits.RefersToEnclosingVariableOrCapture =
355 RefersToEnclosingVariableOrCapture;
356 DeclRefExprBits.Loc = L;
357 computeDependence(Ctx);
358}
359
Craig Topperce7167c2013-08-22 04:58:56 +0000360DeclRefExpr::DeclRefExpr(const ASTContext &Ctx,
Daniel Dunbar9d355812012-03-09 01:51:51 +0000361 NestedNameSpecifierLoc QualifierLoc,
Bruno Ricci5fc4db72018-12-21 14:10:18 +0000362 SourceLocation TemplateKWLoc, ValueDecl *D,
363 bool RefersToEnclosingVariableOrCapture,
364 const DeclarationNameInfo &NameInfo, NamedDecl *FoundD,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000365 const TemplateArgumentListInfo *TemplateArgs,
John McCall7decc9e2010-11-18 06:31:45 +0000366 QualType T, ExprValueKind VK)
Bruno Ricci5fc4db72018-12-21 14:10:18 +0000367 : Expr(DeclRefExprClass, T, VK, OK_Ordinary, false, false, false, false),
368 D(D), DNLoc(NameInfo.getInfo()) {
Bruno Riccia795e802018-11-13 17:56:44 +0000369 DeclRefExprBits.Loc = NameInfo.getLoc();
Chandler Carruth0e439962011-05-01 21:29:53 +0000370 DeclRefExprBits.HasQualifier = QualifierLoc ? 1 : 0;
Richard Smithcfaa5a32014-10-17 02:46:42 +0000371 if (QualifierLoc) {
James Y Knighte7d82282015-12-29 18:15:14 +0000372 new (getTrailingObjects<NestedNameSpecifierLoc>())
373 NestedNameSpecifierLoc(QualifierLoc);
Richard Smithcfaa5a32014-10-17 02:46:42 +0000374 auto *NNS = QualifierLoc.getNestedNameSpecifier();
375 if (NNS->isInstantiationDependent())
376 ExprBits.InstantiationDependent = true;
377 if (NNS->containsUnexpandedParameterPack())
378 ExprBits.ContainsUnexpandedParameterPack = true;
379 }
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000380 DeclRefExprBits.HasFoundDecl = FoundD ? 1 : 0;
381 if (FoundD)
James Y Knighte7d82282015-12-29 18:15:14 +0000382 *getTrailingObjects<NamedDecl *>() = FoundD;
Abramo Bagnara7945c982012-01-27 09:46:47 +0000383 DeclRefExprBits.HasTemplateKWAndArgsInfo
384 = (TemplateArgs || TemplateKWLoc.isValid()) ? 1 : 0;
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000385 DeclRefExprBits.RefersToEnclosingVariableOrCapture =
386 RefersToEnclosingVariableOrCapture;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000387 if (TemplateArgs) {
388 bool Dependent = false;
389 bool InstantiationDependent = false;
390 bool ContainsUnexpandedParameterPack = false;
James Y Knighte7d82282015-12-29 18:15:14 +0000391 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
392 TemplateKWLoc, *TemplateArgs, getTrailingObjects<TemplateArgumentLoc>(),
393 Dependent, InstantiationDependent, ContainsUnexpandedParameterPack);
Richard Smithcfaa5a32014-10-17 02:46:42 +0000394 assert(!Dependent && "built a DeclRefExpr with dependent template args");
395 ExprBits.InstantiationDependent |= InstantiationDependent;
396 ExprBits.ContainsUnexpandedParameterPack |= ContainsUnexpandedParameterPack;
Abramo Bagnara7945c982012-01-27 09:46:47 +0000397 } else if (TemplateKWLoc.isValid()) {
James Y Knighte7d82282015-12-29 18:15:14 +0000398 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
399 TemplateKWLoc);
Douglas Gregor678d76c2011-07-01 01:22:09 +0000400 }
Benjamin Kramer138ef9c2011-10-10 12:54:05 +0000401 DeclRefExprBits.HadMultipleCandidates = 0;
402
Daniel Dunbar9d355812012-03-09 01:51:51 +0000403 computeDependence(Ctx);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000404}
405
Craig Topperce7167c2013-08-22 04:58:56 +0000406DeclRefExpr *DeclRefExpr::Create(const ASTContext &Context,
Douglas Gregorea972d32011-02-28 21:54:11 +0000407 NestedNameSpecifierLoc QualifierLoc,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000408 SourceLocation TemplateKWLoc,
John McCallce546572009-12-08 09:08:17 +0000409 ValueDecl *D,
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000410 bool RefersToEnclosingVariableOrCapture,
Douglas Gregor4bd90e52009-10-23 18:54:35 +0000411 SourceLocation NameLoc,
Douglas Gregored6c7442009-11-23 11:41:28 +0000412 QualType T,
John McCall7decc9e2010-11-18 06:31:45 +0000413 ExprValueKind VK,
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000414 NamedDecl *FoundD,
Douglas Gregored6c7442009-11-23 11:41:28 +0000415 const TemplateArgumentListInfo *TemplateArgs) {
Abramo Bagnara7945c982012-01-27 09:46:47 +0000416 return Create(Context, QualifierLoc, TemplateKWLoc, D,
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000417 RefersToEnclosingVariableOrCapture,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000418 DeclarationNameInfo(D->getDeclName(), NameLoc),
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000419 T, VK, FoundD, TemplateArgs);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000420}
421
Craig Topperce7167c2013-08-22 04:58:56 +0000422DeclRefExpr *DeclRefExpr::Create(const ASTContext &Context,
Douglas Gregorea972d32011-02-28 21:54:11 +0000423 NestedNameSpecifierLoc QualifierLoc,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000424 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000425 ValueDecl *D,
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000426 bool RefersToEnclosingVariableOrCapture,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000427 const DeclarationNameInfo &NameInfo,
428 QualType T,
John McCall7decc9e2010-11-18 06:31:45 +0000429 ExprValueKind VK,
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000430 NamedDecl *FoundD,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000431 const TemplateArgumentListInfo *TemplateArgs) {
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000432 // Filter out cases where the found Decl is the same as the value refenenced.
433 if (D == FoundD)
Craig Topper36250ad2014-05-12 05:36:57 +0000434 FoundD = nullptr;
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000435
James Y Knighte7d82282015-12-29 18:15:14 +0000436 bool HasTemplateKWAndArgsInfo = TemplateArgs || TemplateKWLoc.isValid();
437 std::size_t Size =
438 totalSizeToAlloc<NestedNameSpecifierLoc, NamedDecl *,
439 ASTTemplateKWAndArgsInfo, TemplateArgumentLoc>(
440 QualifierLoc ? 1 : 0, FoundD ? 1 : 0,
441 HasTemplateKWAndArgsInfo ? 1 : 0,
442 TemplateArgs ? TemplateArgs->size() : 0);
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000443
Benjamin Kramerc3f89252016-10-20 14:27:22 +0000444 void *Mem = Context.Allocate(Size, alignof(DeclRefExpr));
Daniel Dunbar9d355812012-03-09 01:51:51 +0000445 return new (Mem) DeclRefExpr(Context, QualifierLoc, TemplateKWLoc, D,
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000446 RefersToEnclosingVariableOrCapture,
Daniel Dunbar9d355812012-03-09 01:51:51 +0000447 NameInfo, FoundD, TemplateArgs, T, VK);
Douglas Gregor4bd90e52009-10-23 18:54:35 +0000448}
449
Craig Topperce7167c2013-08-22 04:58:56 +0000450DeclRefExpr *DeclRefExpr::CreateEmpty(const ASTContext &Context,
Douglas Gregor87866ce2011-02-04 12:01:24 +0000451 bool HasQualifier,
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000452 bool HasFoundDecl,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000453 bool HasTemplateKWAndArgsInfo,
Argyrios Kyrtzidis1985bb32010-07-08 13:09:47 +0000454 unsigned NumTemplateArgs) {
James Y Knighte7d82282015-12-29 18:15:14 +0000455 assert(NumTemplateArgs == 0 || HasTemplateKWAndArgsInfo);
456 std::size_t Size =
457 totalSizeToAlloc<NestedNameSpecifierLoc, NamedDecl *,
458 ASTTemplateKWAndArgsInfo, TemplateArgumentLoc>(
459 HasQualifier ? 1 : 0, HasFoundDecl ? 1 : 0, HasTemplateKWAndArgsInfo,
460 NumTemplateArgs);
Benjamin Kramerc3f89252016-10-20 14:27:22 +0000461 void *Mem = Context.Allocate(Size, alignof(DeclRefExpr));
Argyrios Kyrtzidis1985bb32010-07-08 13:09:47 +0000462 return new (Mem) DeclRefExpr(EmptyShell());
463}
464
Stephen Kelly724e9e52018-08-09 20:05:03 +0000465SourceLocation DeclRefExpr::getBeginLoc() const {
Daniel Dunbarb507f272012-03-09 15:39:15 +0000466 if (hasQualifier())
467 return getQualifierLoc().getBeginLoc();
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000468 return getNameInfo().getBeginLoc();
Daniel Dunbarb507f272012-03-09 15:39:15 +0000469}
Stephen Kelly02a67ba2018-08-09 20:05:47 +0000470SourceLocation DeclRefExpr::getEndLoc() const {
Daniel Dunbarb507f272012-03-09 15:39:15 +0000471 if (hasExplicitTemplateArgs())
472 return getRAngleLoc();
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000473 return getNameInfo().getEndLoc();
Daniel Dunbarb507f272012-03-09 15:39:15 +0000474}
Douglas Gregor4bd90e52009-10-23 18:54:35 +0000475
Bruno Ricci17ff0262018-10-27 19:21:19 +0000476PredefinedExpr::PredefinedExpr(SourceLocation L, QualType FNTy, IdentKind IK,
Alexey Bataevec474782014-10-09 08:45:04 +0000477 StringLiteral *SL)
478 : Expr(PredefinedExprClass, FNTy, VK_LValue, OK_Ordinary,
479 FNTy->isDependentType(), FNTy->isDependentType(),
480 FNTy->isInstantiationDependentType(),
Bruno Ricci17ff0262018-10-27 19:21:19 +0000481 /*ContainsUnexpandedParameterPack=*/false) {
482 PredefinedExprBits.Kind = IK;
483 assert((getIdentKind() == IK) &&
484 "IdentKind do not fit in PredefinedExprBitfields!");
485 bool HasFunctionName = SL != nullptr;
486 PredefinedExprBits.HasFunctionName = HasFunctionName;
487 PredefinedExprBits.Loc = L;
488 if (HasFunctionName)
489 setFunctionName(SL);
Alexey Bataevec474782014-10-09 08:45:04 +0000490}
491
Bruno Ricci17ff0262018-10-27 19:21:19 +0000492PredefinedExpr::PredefinedExpr(EmptyShell Empty, bool HasFunctionName)
493 : Expr(PredefinedExprClass, Empty) {
494 PredefinedExprBits.HasFunctionName = HasFunctionName;
495}
496
497PredefinedExpr *PredefinedExpr::Create(const ASTContext &Ctx, SourceLocation L,
498 QualType FNTy, IdentKind IK,
499 StringLiteral *SL) {
500 bool HasFunctionName = SL != nullptr;
501 void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *>(HasFunctionName),
502 alignof(PredefinedExpr));
503 return new (Mem) PredefinedExpr(L, FNTy, IK, SL);
504}
505
506PredefinedExpr *PredefinedExpr::CreateEmpty(const ASTContext &Ctx,
507 bool HasFunctionName) {
508 void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *>(HasFunctionName),
509 alignof(PredefinedExpr));
510 return new (Mem) PredefinedExpr(EmptyShell(), HasFunctionName);
511}
512
513StringRef PredefinedExpr::getIdentKindName(PredefinedExpr::IdentKind IK) {
514 switch (IK) {
Alexey Bataevec474782014-10-09 08:45:04 +0000515 case Func:
516 return "__func__";
517 case Function:
518 return "__FUNCTION__";
519 case FuncDName:
520 return "__FUNCDNAME__";
521 case LFunction:
522 return "L__FUNCTION__";
523 case PrettyFunction:
524 return "__PRETTY_FUNCTION__";
525 case FuncSig:
526 return "__FUNCSIG__";
Reid Kleckner4a83f0a2018-07-26 23:18:44 +0000527 case LFuncSig:
528 return "L__FUNCSIG__";
Alexey Bataevec474782014-10-09 08:45:04 +0000529 case PrettyFunctionNoVirtual:
530 break;
531 }
Bruno Ricci17ff0262018-10-27 19:21:19 +0000532 llvm_unreachable("Unknown ident kind for PredefinedExpr");
Alexey Bataevec474782014-10-09 08:45:04 +0000533}
534
Anders Carlsson2fb08242009-09-08 18:24:21 +0000535// FIXME: Maybe this should use DeclPrinter with a special "print predefined
536// expr" policy instead.
Bruno Ricci17ff0262018-10-27 19:21:19 +0000537std::string PredefinedExpr::ComputeName(IdentKind IK, const Decl *CurrentDecl) {
Anders Carlsson5bd8d192010-02-11 18:20:28 +0000538 ASTContext &Context = CurrentDecl->getASTContext();
539
Bruno Ricci17ff0262018-10-27 19:21:19 +0000540 if (IK == PredefinedExpr::FuncDName) {
David Majnemerbed356a2013-11-06 23:31:56 +0000541 if (const NamedDecl *ND = dyn_cast<NamedDecl>(CurrentDecl)) {
Ahmed Charlesb8984322014-03-07 20:03:18 +0000542 std::unique_ptr<MangleContext> MC;
David Majnemerbed356a2013-11-06 23:31:56 +0000543 MC.reset(Context.createMangleContext());
544
545 if (MC->shouldMangleDeclName(ND)) {
546 SmallString<256> Buffer;
547 llvm::raw_svector_ostream Out(Buffer);
548 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(ND))
549 MC->mangleCXXCtor(CD, Ctor_Base, Out);
550 else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(ND))
551 MC->mangleCXXDtor(DD, Dtor_Base, Out);
552 else
553 MC->mangleName(ND, Out);
554
David Majnemerbed356a2013-11-06 23:31:56 +0000555 if (!Buffer.empty() && Buffer.front() == '\01')
556 return Buffer.substr(1);
557 return Buffer.str();
558 } else
559 return ND->getIdentifier()->getName();
560 }
561 return "";
562 }
Mehdi Aminidc9bf8f2016-11-16 07:07:28 +0000563 if (isa<BlockDecl>(CurrentDecl)) {
564 // For blocks we only emit something if it is enclosed in a function
565 // For top-level block we'd like to include the name of variable, but we
566 // don't have it at this point.
Mehdi Aminif5f37ee2016-11-15 22:19:50 +0000567 auto DC = CurrentDecl->getDeclContext();
568 if (DC->isFileContext())
Mehdi Aminidc9bf8f2016-11-16 07:07:28 +0000569 return "";
570
571 SmallString<256> Buffer;
572 llvm::raw_svector_ostream Out(Buffer);
573 if (auto *DCBlock = dyn_cast<BlockDecl>(DC))
574 // For nested blocks, propagate up to the parent.
Bruno Ricci17ff0262018-10-27 19:21:19 +0000575 Out << ComputeName(IK, DCBlock);
Mehdi Aminidc9bf8f2016-11-16 07:07:28 +0000576 else if (auto *DCDecl = dyn_cast<Decl>(DC))
Bruno Ricci17ff0262018-10-27 19:21:19 +0000577 Out << ComputeName(IK, DCDecl) << "_block_invoke";
Alexey Bataevec474782014-10-09 08:45:04 +0000578 return Out.str();
579 }
Anders Carlsson2fb08242009-09-08 18:24:21 +0000580 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CurrentDecl)) {
Bruno Ricci17ff0262018-10-27 19:21:19 +0000581 if (IK != PrettyFunction && IK != PrettyFunctionNoVirtual &&
582 IK != FuncSig && IK != LFuncSig)
Anders Carlsson2fb08242009-09-08 18:24:21 +0000583 return FD->getNameAsString();
584
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000585 SmallString<256> Name;
Anders Carlsson2fb08242009-09-08 18:24:21 +0000586 llvm::raw_svector_ostream Out(Name);
587
588 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
Bruno Ricci17ff0262018-10-27 19:21:19 +0000589 if (MD->isVirtual() && IK != PrettyFunctionNoVirtual)
Anders Carlsson2fb08242009-09-08 18:24:21 +0000590 Out << "virtual ";
Sam Weinig4e83bd22009-12-27 01:38:20 +0000591 if (MD->isStatic())
592 Out << "static ";
Anders Carlsson2fb08242009-09-08 18:24:21 +0000593 }
594
David Blaikiebbafb8a2012-03-11 07:00:24 +0000595 PrintingPolicy Policy(Context.getLangOpts());
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +0000596 std::string Proto;
Douglas Gregor11a434a2012-04-10 20:14:15 +0000597 llvm::raw_string_ostream POut(Proto);
Anders Carlsson2fb08242009-09-08 18:24:21 +0000598
Douglas Gregor11a434a2012-04-10 20:14:15 +0000599 const FunctionDecl *Decl = FD;
600 if (const FunctionDecl* Pattern = FD->getTemplateInstantiationPattern())
601 Decl = Pattern;
602 const FunctionType *AFT = Decl->getType()->getAs<FunctionType>();
Craig Topper36250ad2014-05-12 05:36:57 +0000603 const FunctionProtoType *FT = nullptr;
Anders Carlsson2fb08242009-09-08 18:24:21 +0000604 if (FD->hasWrittenPrototype())
605 FT = dyn_cast<FunctionProtoType>(AFT);
606
Bruno Ricci17ff0262018-10-27 19:21:19 +0000607 if (IK == FuncSig || IK == LFuncSig) {
Richard Smith2f63d462017-01-09 21:40:40 +0000608 switch (AFT->getCallConv()) {
Reid Kleckner52eddda2014-04-08 18:13:24 +0000609 case CC_C: POut << "__cdecl "; break;
610 case CC_X86StdCall: POut << "__stdcall "; break;
611 case CC_X86FastCall: POut << "__fastcall "; break;
612 case CC_X86ThisCall: POut << "__thiscall "; break;
Reid Klecknerd7857f02014-10-24 17:42:17 +0000613 case CC_X86VectorCall: POut << "__vectorcall "; break;
Erich Keane757d3172016-11-02 18:29:35 +0000614 case CC_X86RegCall: POut << "__regcall "; break;
Reid Kleckner52eddda2014-04-08 18:13:24 +0000615 // Only bother printing the conventions that MSVC knows about.
616 default: break;
617 }
618 }
619
620 FD->printQualifiedName(POut, Policy);
621
Douglas Gregor11a434a2012-04-10 20:14:15 +0000622 POut << "(";
Anders Carlsson2fb08242009-09-08 18:24:21 +0000623 if (FT) {
Douglas Gregor11a434a2012-04-10 20:14:15 +0000624 for (unsigned i = 0, e = Decl->getNumParams(); i != e; ++i) {
Anders Carlsson2fb08242009-09-08 18:24:21 +0000625 if (i) POut << ", ";
Argyrios Kyrtzidisa18347e2012-05-05 04:20:37 +0000626 POut << Decl->getParamDecl(i)->getType().stream(Policy);
Anders Carlsson2fb08242009-09-08 18:24:21 +0000627 }
628
629 if (FT->isVariadic()) {
630 if (FD->getNumParams()) POut << ", ";
631 POut << "...";
Bruno Ricci17ff0262018-10-27 19:21:19 +0000632 } else if ((IK == FuncSig || IK == LFuncSig ||
Reid Kleckner4a83f0a2018-07-26 23:18:44 +0000633 !Context.getLangOpts().CPlusPlus) &&
Richard Smithcf63b842017-01-09 22:16:16 +0000634 !Decl->getNumParams()) {
635 POut << "void";
Anders Carlsson2fb08242009-09-08 18:24:21 +0000636 }
637 }
Douglas Gregor11a434a2012-04-10 20:14:15 +0000638 POut << ")";
Anders Carlsson2fb08242009-09-08 18:24:21 +0000639
Sam Weinig4e83bd22009-12-27 01:38:20 +0000640 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
Richard Smith2f63d462017-01-09 21:40:40 +0000641 assert(FT && "We must have a written prototype in this case.");
David Blaikief5697e52012-08-10 00:55:35 +0000642 if (FT->isConst())
Douglas Gregor11a434a2012-04-10 20:14:15 +0000643 POut << " const";
David Blaikief5697e52012-08-10 00:55:35 +0000644 if (FT->isVolatile())
Douglas Gregor11a434a2012-04-10 20:14:15 +0000645 POut << " volatile";
646 RefQualifierKind Ref = MD->getRefQualifier();
647 if (Ref == RQ_LValue)
648 POut << " &";
649 else if (Ref == RQ_RValue)
650 POut << " &&";
Sam Weinig4e83bd22009-12-27 01:38:20 +0000651 }
652
Eugene Zelenkoae304b02017-11-17 18:09:48 +0000653 typedef SmallVector<const ClassTemplateSpecializationDecl *, 8> SpecsTy;
Douglas Gregor11a434a2012-04-10 20:14:15 +0000654 SpecsTy Specs;
655 const DeclContext *Ctx = FD->getDeclContext();
656 while (Ctx && isa<NamedDecl>(Ctx)) {
657 const ClassTemplateSpecializationDecl *Spec
658 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx);
659 if (Spec && !Spec->isExplicitSpecialization())
660 Specs.push_back(Spec);
661 Ctx = Ctx->getParent();
662 }
663
664 std::string TemplateParams;
665 llvm::raw_string_ostream TOut(TemplateParams);
666 for (SpecsTy::reverse_iterator I = Specs.rbegin(), E = Specs.rend();
667 I != E; ++I) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000668 const TemplateParameterList *Params
Douglas Gregor11a434a2012-04-10 20:14:15 +0000669 = (*I)->getSpecializedTemplate()->getTemplateParameters();
670 const TemplateArgumentList &Args = (*I)->getTemplateArgs();
671 assert(Params->size() == Args.size());
672 for (unsigned i = 0, numParams = Params->size(); i != numParams; ++i) {
673 StringRef Param = Params->getParam(i)->getName();
674 if (Param.empty()) continue;
675 TOut << Param << " = ";
676 Args.get(i).print(Policy, TOut);
677 TOut << ", ";
678 }
679 }
680
Fangrui Song6907ce22018-07-30 19:24:48 +0000681 FunctionTemplateSpecializationInfo *FSI
Douglas Gregor11a434a2012-04-10 20:14:15 +0000682 = FD->getTemplateSpecializationInfo();
683 if (FSI && !FSI->isExplicitSpecialization()) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000684 const TemplateParameterList* Params
Douglas Gregor11a434a2012-04-10 20:14:15 +0000685 = FSI->getTemplate()->getTemplateParameters();
686 const TemplateArgumentList* Args = FSI->TemplateArguments;
687 assert(Params->size() == Args->size());
688 for (unsigned i = 0, e = Params->size(); i != e; ++i) {
689 StringRef Param = Params->getParam(i)->getName();
690 if (Param.empty()) continue;
691 TOut << Param << " = ";
692 Args->get(i).print(Policy, TOut);
693 TOut << ", ";
694 }
695 }
696
697 TOut.flush();
698 if (!TemplateParams.empty()) {
699 // remove the trailing comma and space
700 TemplateParams.resize(TemplateParams.size() - 2);
701 POut << " [" << TemplateParams << "]";
702 }
703
704 POut.flush();
705
Benjamin Kramer90f54222013-08-21 11:45:27 +0000706 // Print "auto" for all deduced return types. This includes C++1y return
707 // type deduction and lambdas. For trailing return types resolve the
708 // decltype expression. Otherwise print the real type when this is
709 // not a constructor or destructor.
Alexey Bataevec474782014-10-09 08:45:04 +0000710 if (isa<CXXMethodDecl>(FD) &&
711 cast<CXXMethodDecl>(FD)->getParent()->isLambda())
Benjamin Kramer90f54222013-08-21 11:45:27 +0000712 Proto = "auto " + Proto;
Alp Toker314cc812014-01-25 16:55:45 +0000713 else if (FT && FT->getReturnType()->getAs<DecltypeType>())
714 FT->getReturnType()
715 ->getAs<DecltypeType>()
716 ->getUnderlyingType()
Benjamin Kramer90f54222013-08-21 11:45:27 +0000717 .getAsStringInternal(Proto, Policy);
718 else if (!isa<CXXConstructorDecl>(FD) && !isa<CXXDestructorDecl>(FD))
Alp Toker314cc812014-01-25 16:55:45 +0000719 AFT->getReturnType().getAsStringInternal(Proto, Policy);
Anders Carlsson2fb08242009-09-08 18:24:21 +0000720
721 Out << Proto;
722
Anders Carlsson2fb08242009-09-08 18:24:21 +0000723 return Name.str().str();
724 }
Wei Pan8d6b19a2013-08-26 14:27:34 +0000725 if (const CapturedDecl *CD = dyn_cast<CapturedDecl>(CurrentDecl)) {
726 for (const DeclContext *DC = CD->getParent(); DC; DC = DC->getParent())
727 // Skip to its enclosing function or method, but not its enclosing
728 // CapturedDecl.
729 if (DC->isFunctionOrMethod() && (DC->getDeclKind() != Decl::Captured)) {
730 const Decl *D = Decl::castFromDeclContext(DC);
Bruno Ricci17ff0262018-10-27 19:21:19 +0000731 return ComputeName(IK, D);
Wei Pan8d6b19a2013-08-26 14:27:34 +0000732 }
733 llvm_unreachable("CapturedDecl not inside a function or method");
734 }
Anders Carlsson2fb08242009-09-08 18:24:21 +0000735 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurrentDecl)) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000736 SmallString<256> Name;
Anders Carlsson2fb08242009-09-08 18:24:21 +0000737 llvm::raw_svector_ostream Out(Name);
738 Out << (MD->isInstanceMethod() ? '-' : '+');
739 Out << '[';
Ted Kremenek361ffd92010-03-18 21:23:08 +0000740
741 // For incorrect code, there might not be an ObjCInterfaceDecl. Do
742 // a null check to avoid a crash.
743 if (const ObjCInterfaceDecl *ID = MD->getClassInterface())
Benjamin Kramerb89514a2011-10-14 18:45:37 +0000744 Out << *ID;
Ted Kremenek361ffd92010-03-18 21:23:08 +0000745
Anders Carlsson2fb08242009-09-08 18:24:21 +0000746 if (const ObjCCategoryImplDecl *CID =
Benjamin Kramerb11416d2010-04-17 09:33:03 +0000747 dyn_cast<ObjCCategoryImplDecl>(MD->getDeclContext()))
Benjamin Kramer2f569922012-02-07 11:57:45 +0000748 Out << '(' << *CID << ')';
Benjamin Kramerb11416d2010-04-17 09:33:03 +0000749
Anders Carlsson2fb08242009-09-08 18:24:21 +0000750 Out << ' ';
Aaron Ballmanb190f972014-01-03 17:59:55 +0000751 MD->getSelector().print(Out);
Anders Carlsson2fb08242009-09-08 18:24:21 +0000752 Out << ']';
753
Anders Carlsson2fb08242009-09-08 18:24:21 +0000754 return Name.str().str();
755 }
Bruno Ricci17ff0262018-10-27 19:21:19 +0000756 if (isa<TranslationUnitDecl>(CurrentDecl) && IK == PrettyFunction) {
Anders Carlsson2fb08242009-09-08 18:24:21 +0000757 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
758 return "top level";
759 }
760 return "";
761}
762
Craig Topper37932912013-08-18 10:09:15 +0000763void APNumericStorage::setIntValue(const ASTContext &C,
764 const llvm::APInt &Val) {
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000765 if (hasAllocation())
766 C.Deallocate(pVal);
767
768 BitWidth = Val.getBitWidth();
769 unsigned NumWords = Val.getNumWords();
770 const uint64_t* Words = Val.getRawData();
771 if (NumWords > 1) {
772 pVal = new (C) uint64_t[NumWords];
773 std::copy(Words, Words + NumWords, pVal);
774 } else if (NumWords == 1)
775 VAL = Words[0];
776 else
777 VAL = 0;
778}
779
Craig Topper37932912013-08-18 10:09:15 +0000780IntegerLiteral::IntegerLiteral(const ASTContext &C, const llvm::APInt &V,
Benjamin Kramer1ea8e092012-07-04 17:04:04 +0000781 QualType type, SourceLocation l)
782 : Expr(IntegerLiteralClass, type, VK_RValue, OK_Ordinary, false, false,
783 false, false),
784 Loc(l) {
785 assert(type->isIntegerType() && "Illegal type in IntegerLiteral");
786 assert(V.getBitWidth() == C.getIntWidth(type) &&
787 "Integer type is not the correct size for constant.");
788 setValue(C, V);
789}
790
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000791IntegerLiteral *
Craig Topper37932912013-08-18 10:09:15 +0000792IntegerLiteral::Create(const ASTContext &C, const llvm::APInt &V,
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000793 QualType type, SourceLocation l) {
794 return new (C) IntegerLiteral(C, V, type, l);
795}
796
797IntegerLiteral *
Craig Topper37932912013-08-18 10:09:15 +0000798IntegerLiteral::Create(const ASTContext &C, EmptyShell Empty) {
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000799 return new (C) IntegerLiteral(Empty);
800}
801
Leonard Chandb01c3a2018-06-20 17:19:40 +0000802FixedPointLiteral::FixedPointLiteral(const ASTContext &C, const llvm::APInt &V,
803 QualType type, SourceLocation l,
804 unsigned Scale)
805 : Expr(FixedPointLiteralClass, type, VK_RValue, OK_Ordinary, false, false,
806 false, false),
807 Loc(l), Scale(Scale) {
808 assert(type->isFixedPointType() && "Illegal type in FixedPointLiteral");
809 assert(V.getBitWidth() == C.getTypeInfo(type).Width &&
810 "Fixed point type is not the correct size for constant.");
811 setValue(C, V);
812}
813
814FixedPointLiteral *FixedPointLiteral::CreateFromRawInt(const ASTContext &C,
815 const llvm::APInt &V,
816 QualType type,
817 SourceLocation l,
818 unsigned Scale) {
819 return new (C) FixedPointLiteral(C, V, type, l, Scale);
820}
821
822std::string FixedPointLiteral::getValueAsString(unsigned Radix) const {
823 // Currently the longest decimal number that can be printed is the max for an
824 // unsigned long _Accum: 4294967295.99999999976716935634613037109375
825 // which is 43 characters.
826 SmallString<64> S;
827 FixedPointValueToString(
Leonard Chanc03642e2018-08-06 16:05:08 +0000828 S, llvm::APSInt::getUnsigned(getValue().getZExtValue()), Scale);
Leonard Chandb01c3a2018-06-20 17:19:40 +0000829 return S.str();
830}
831
Craig Topper37932912013-08-18 10:09:15 +0000832FloatingLiteral::FloatingLiteral(const ASTContext &C, const llvm::APFloat &V,
Benjamin Kramer1ea8e092012-07-04 17:04:04 +0000833 bool isexact, QualType Type, SourceLocation L)
834 : Expr(FloatingLiteralClass, Type, VK_RValue, OK_Ordinary, false, false,
835 false, false), Loc(L) {
Tim Northover178723a2013-01-22 09:46:51 +0000836 setSemantics(V.getSemantics());
Benjamin Kramer1ea8e092012-07-04 17:04:04 +0000837 FloatingLiteralBits.IsExact = isexact;
838 setValue(C, V);
839}
840
Craig Topper37932912013-08-18 10:09:15 +0000841FloatingLiteral::FloatingLiteral(const ASTContext &C, EmptyShell Empty)
Eugene Zelenkoae304b02017-11-17 18:09:48 +0000842 : Expr(FloatingLiteralClass, Empty) {
Tim Northover178723a2013-01-22 09:46:51 +0000843 setRawSemantics(IEEEhalf);
Benjamin Kramer1ea8e092012-07-04 17:04:04 +0000844 FloatingLiteralBits.IsExact = false;
845}
846
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000847FloatingLiteral *
Craig Topper37932912013-08-18 10:09:15 +0000848FloatingLiteral::Create(const ASTContext &C, const llvm::APFloat &V,
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000849 bool isexact, QualType Type, SourceLocation L) {
850 return new (C) FloatingLiteral(C, V, isexact, Type, L);
851}
852
853FloatingLiteral *
Craig Topper37932912013-08-18 10:09:15 +0000854FloatingLiteral::Create(const ASTContext &C, EmptyShell Empty) {
Akira Hatanaka428f5b22012-01-10 22:40:09 +0000855 return new (C) FloatingLiteral(C, Empty);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000856}
857
Tim Northover178723a2013-01-22 09:46:51 +0000858const llvm::fltSemantics &FloatingLiteral::getSemantics() const {
859 switch(FloatingLiteralBits.Semantics) {
860 case IEEEhalf:
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000861 return llvm::APFloat::IEEEhalf();
Tim Northover178723a2013-01-22 09:46:51 +0000862 case IEEEsingle:
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000863 return llvm::APFloat::IEEEsingle();
Tim Northover178723a2013-01-22 09:46:51 +0000864 case IEEEdouble:
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000865 return llvm::APFloat::IEEEdouble();
Tim Northover178723a2013-01-22 09:46:51 +0000866 case x87DoubleExtended:
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000867 return llvm::APFloat::x87DoubleExtended();
Tim Northover178723a2013-01-22 09:46:51 +0000868 case IEEEquad:
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000869 return llvm::APFloat::IEEEquad();
Tim Northover178723a2013-01-22 09:46:51 +0000870 case PPCDoubleDouble:
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000871 return llvm::APFloat::PPCDoubleDouble();
Tim Northover178723a2013-01-22 09:46:51 +0000872 }
873 llvm_unreachable("Unrecognised floating semantics");
874}
875
876void FloatingLiteral::setSemantics(const llvm::fltSemantics &Sem) {
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000877 if (&Sem == &llvm::APFloat::IEEEhalf())
Tim Northover178723a2013-01-22 09:46:51 +0000878 FloatingLiteralBits.Semantics = IEEEhalf;
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000879 else if (&Sem == &llvm::APFloat::IEEEsingle())
Tim Northover178723a2013-01-22 09:46:51 +0000880 FloatingLiteralBits.Semantics = IEEEsingle;
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000881 else if (&Sem == &llvm::APFloat::IEEEdouble())
Tim Northover178723a2013-01-22 09:46:51 +0000882 FloatingLiteralBits.Semantics = IEEEdouble;
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000883 else if (&Sem == &llvm::APFloat::x87DoubleExtended())
Tim Northover178723a2013-01-22 09:46:51 +0000884 FloatingLiteralBits.Semantics = x87DoubleExtended;
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000885 else if (&Sem == &llvm::APFloat::IEEEquad())
Tim Northover178723a2013-01-22 09:46:51 +0000886 FloatingLiteralBits.Semantics = IEEEquad;
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000887 else if (&Sem == &llvm::APFloat::PPCDoubleDouble())
Tim Northover178723a2013-01-22 09:46:51 +0000888 FloatingLiteralBits.Semantics = PPCDoubleDouble;
889 else
890 llvm_unreachable("Unknown floating semantics");
891}
892
Chris Lattnera0173132008-06-07 22:13:43 +0000893/// getValueAsApproximateDouble - This returns the value as an inaccurate
894/// double. Note that this may cause loss of precision, but is useful for
895/// debugging dumps, etc.
896double FloatingLiteral::getValueAsApproximateDouble() const {
897 llvm::APFloat V = getValue();
Dale Johannesenc48814b2008-10-09 23:02:32 +0000898 bool ignored;
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000899 V.convert(llvm::APFloat::IEEEdouble(), llvm::APFloat::rmNearestTiesToEven,
Dale Johannesenc48814b2008-10-09 23:02:32 +0000900 &ignored);
Chris Lattnera0173132008-06-07 22:13:43 +0000901 return V.convertToDouble();
902}
903
Bruno Ricciaf214882018-11-15 16:42:14 +0000904unsigned StringLiteral::mapCharByteWidth(TargetInfo const &Target,
905 StringKind SK) {
906 unsigned CharByteWidth = 0;
907 switch (SK) {
908 case Ascii:
909 case UTF8:
910 CharByteWidth = Target.getCharWidth();
911 break;
912 case Wide:
913 CharByteWidth = Target.getWCharWidth();
914 break;
915 case UTF16:
916 CharByteWidth = Target.getChar16Width();
917 break;
918 case UTF32:
919 CharByteWidth = Target.getChar32Width();
920 break;
Eli Friedmanfcec6302011-11-01 02:23:42 +0000921 }
922 assert((CharByteWidth & 7) == 0 && "Assumes character size is byte multiple");
923 CharByteWidth /= 8;
Bruno Ricciaf214882018-11-15 16:42:14 +0000924 assert((CharByteWidth == 1 || CharByteWidth == 2 || CharByteWidth == 4) &&
925 "The only supported character byte widths are 1,2 and 4!");
Eli Friedmanfcec6302011-11-01 02:23:42 +0000926 return CharByteWidth;
927}
928
Bruno Riccib94ad1e2018-11-15 17:31:16 +0000929StringLiteral::StringLiteral(const ASTContext &Ctx, StringRef Str,
930 StringKind Kind, bool Pascal, QualType Ty,
931 const SourceLocation *Loc,
932 unsigned NumConcatenated)
933 : Expr(StringLiteralClass, Ty, VK_LValue, OK_Ordinary, false, false, false,
934 false) {
935 assert(Ctx.getAsConstantArrayType(Ty) &&
Benjamin Kramercdac7612014-02-25 12:26:20 +0000936 "StringLiteral must be of constant array type!");
Bruno Riccib94ad1e2018-11-15 17:31:16 +0000937 unsigned CharByteWidth = mapCharByteWidth(Ctx.getTargetInfo(), Kind);
938 unsigned ByteLength = Str.size();
939 assert((ByteLength % CharByteWidth == 0) &&
940 "The size of the data must be a multiple of CharByteWidth!");
Benjamin Kramercdac7612014-02-25 12:26:20 +0000941
Bruno Riccib94ad1e2018-11-15 17:31:16 +0000942 // Avoid the expensive division. The compiler should be able to figure it
943 // out by itself. However as of clang 7, even with the appropriate
944 // llvm_unreachable added just here, it is not able to do so.
945 unsigned Length;
946 switch (CharByteWidth) {
947 case 1:
948 Length = ByteLength;
949 break;
950 case 2:
951 Length = ByteLength / 2;
952 break;
953 case 4:
954 Length = ByteLength / 4;
955 break;
956 default:
957 llvm_unreachable("Unsupported character width!");
958 }
Mike Stump11289f42009-09-09 15:08:12 +0000959
Bruno Riccib94ad1e2018-11-15 17:31:16 +0000960 StringLiteralBits.Kind = Kind;
961 StringLiteralBits.CharByteWidth = CharByteWidth;
962 StringLiteralBits.IsPascal = Pascal;
963 StringLiteralBits.NumConcatenated = NumConcatenated;
964 *getTrailingObjects<unsigned>() = Length;
Eli Friedmanfcec6302011-11-01 02:23:42 +0000965
Bruno Riccib94ad1e2018-11-15 17:31:16 +0000966 // Initialize the trailing array of SourceLocation.
967 // This is safe since SourceLocation is POD-like.
968 std::memcpy(getTrailingObjects<SourceLocation>(), Loc,
969 NumConcatenated * sizeof(SourceLocation));
Chris Lattnerd3e98952006-10-06 05:22:26 +0000970
Bruno Riccib94ad1e2018-11-15 17:31:16 +0000971 // Initialize the trailing array of char holding the string data.
972 std::memcpy(getTrailingObjects<char>(), Str.data(), ByteLength);
Chris Lattner630970d2009-02-18 05:49:11 +0000973}
974
Bruno Riccib94ad1e2018-11-15 17:31:16 +0000975StringLiteral::StringLiteral(EmptyShell Empty, unsigned NumConcatenated,
976 unsigned Length, unsigned CharByteWidth)
977 : Expr(StringLiteralClass, Empty) {
978 StringLiteralBits.CharByteWidth = CharByteWidth;
979 StringLiteralBits.NumConcatenated = NumConcatenated;
980 *getTrailingObjects<unsigned>() = Length;
981}
982
983StringLiteral *StringLiteral::Create(const ASTContext &Ctx, StringRef Str,
984 StringKind Kind, bool Pascal, QualType Ty,
985 const SourceLocation *Loc,
986 unsigned NumConcatenated) {
987 void *Mem = Ctx.Allocate(totalSizeToAlloc<unsigned, SourceLocation, char>(
988 1, NumConcatenated, Str.size()),
989 alignof(StringLiteral));
990 return new (Mem)
991 StringLiteral(Ctx, Str, Kind, Pascal, Ty, Loc, NumConcatenated);
992}
993
994StringLiteral *StringLiteral::CreateEmpty(const ASTContext &Ctx,
995 unsigned NumConcatenated,
996 unsigned Length,
997 unsigned CharByteWidth) {
998 void *Mem = Ctx.Allocate(totalSizeToAlloc<unsigned, SourceLocation, char>(
999 1, NumConcatenated, Length * CharByteWidth),
1000 alignof(StringLiteral));
1001 return new (Mem)
1002 StringLiteral(EmptyShell(), NumConcatenated, Length, CharByteWidth);
Douglas Gregor958dfc92009-04-15 16:35:07 +00001003}
1004
Alexander Kornienko540bacb2013-02-01 12:35:51 +00001005void StringLiteral::outputString(raw_ostream &OS) const {
Richard Trieudc355912012-06-13 20:25:24 +00001006 switch (getKind()) {
1007 case Ascii: break; // no prefix.
1008 case Wide: OS << 'L'; break;
1009 case UTF8: OS << "u8"; break;
1010 case UTF16: OS << 'u'; break;
1011 case UTF32: OS << 'U'; break;
1012 }
1013 OS << '"';
1014 static const char Hex[] = "0123456789ABCDEF";
1015
1016 unsigned LastSlashX = getLength();
1017 for (unsigned I = 0, N = getLength(); I != N; ++I) {
1018 switch (uint32_t Char = getCodeUnit(I)) {
1019 default:
1020 // FIXME: Convert UTF-8 back to codepoints before rendering.
1021
1022 // Convert UTF-16 surrogate pairs back to codepoints before rendering.
1023 // Leave invalid surrogates alone; we'll use \x for those.
Fangrui Song6907ce22018-07-30 19:24:48 +00001024 if (getKind() == UTF16 && I != N - 1 && Char >= 0xd800 &&
Richard Trieudc355912012-06-13 20:25:24 +00001025 Char <= 0xdbff) {
1026 uint32_t Trail = getCodeUnit(I + 1);
1027 if (Trail >= 0xdc00 && Trail <= 0xdfff) {
1028 Char = 0x10000 + ((Char - 0xd800) << 10) + (Trail - 0xdc00);
1029 ++I;
1030 }
1031 }
1032
1033 if (Char > 0xff) {
1034 // If this is a wide string, output characters over 0xff using \x
1035 // escapes. Otherwise, this is a UTF-16 or UTF-32 string, and Char is a
1036 // codepoint: use \x escapes for invalid codepoints.
1037 if (getKind() == Wide ||
1038 (Char >= 0xd800 && Char <= 0xdfff) || Char >= 0x110000) {
1039 // FIXME: Is this the best way to print wchar_t?
1040 OS << "\\x";
1041 int Shift = 28;
1042 while ((Char >> Shift) == 0)
1043 Shift -= 4;
1044 for (/**/; Shift >= 0; Shift -= 4)
1045 OS << Hex[(Char >> Shift) & 15];
1046 LastSlashX = I;
1047 break;
1048 }
1049
1050 if (Char > 0xffff)
1051 OS << "\\U00"
1052 << Hex[(Char >> 20) & 15]
1053 << Hex[(Char >> 16) & 15];
1054 else
1055 OS << "\\u";
1056 OS << Hex[(Char >> 12) & 15]
1057 << Hex[(Char >> 8) & 15]
1058 << Hex[(Char >> 4) & 15]
1059 << Hex[(Char >> 0) & 15];
1060 break;
1061 }
1062
1063 // If we used \x... for the previous character, and this character is a
1064 // hexadecimal digit, prevent it being slurped as part of the \x.
1065 if (LastSlashX + 1 == I) {
1066 switch (Char) {
1067 case '0': case '1': case '2': case '3': case '4':
1068 case '5': case '6': case '7': case '8': case '9':
1069 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
1070 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
1071 OS << "\"\"";
1072 }
1073 }
1074
1075 assert(Char <= 0xff &&
1076 "Characters above 0xff should already have been handled.");
1077
Jordan Rosea7d03842013-02-08 22:30:41 +00001078 if (isPrintable(Char))
Richard Trieudc355912012-06-13 20:25:24 +00001079 OS << (char)Char;
1080 else // Output anything hard as an octal escape.
1081 OS << '\\'
1082 << (char)('0' + ((Char >> 6) & 7))
1083 << (char)('0' + ((Char >> 3) & 7))
1084 << (char)('0' + ((Char >> 0) & 7));
1085 break;
1086 // Handle some common non-printable cases to make dumps prettier.
1087 case '\\': OS << "\\\\"; break;
1088 case '"': OS << "\\\""; break;
Richard Trieudc355912012-06-13 20:25:24 +00001089 case '\a': OS << "\\a"; break;
1090 case '\b': OS << "\\b"; break;
Benjamin Kramer60a53d52016-11-24 09:41:33 +00001091 case '\f': OS << "\\f"; break;
1092 case '\n': OS << "\\n"; break;
1093 case '\r': OS << "\\r"; break;
1094 case '\t': OS << "\\t"; break;
1095 case '\v': OS << "\\v"; break;
Richard Trieudc355912012-06-13 20:25:24 +00001096 }
1097 }
1098 OS << '"';
1099}
1100
Chris Lattnere925d612010-11-17 07:37:15 +00001101/// getLocationOfByte - Return a source location that points to the specified
1102/// byte of this string literal.
1103///
1104/// Strings are amazingly complex. They can be formed from multiple tokens and
1105/// can have escape sequences in them in addition to the usual trigraph and
1106/// escaped newline business. This routine handles this complexity.
1107///
Richard Smithefb116f2015-12-10 01:11:47 +00001108/// The *StartToken sets the first token to be searched in this function and
1109/// the *StartTokenByteOffset is the byte offset of the first token. Before
1110/// returning, it updates the *StartToken to the TokNo of the token being found
1111/// and sets *StartTokenByteOffset to the byte offset of the token in the
1112/// string.
1113/// Using these two parameters can reduce the time complexity from O(n^2) to
1114/// O(n) if one wants to get the location of byte for all the tokens in a
1115/// string.
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001116///
Richard Smithefb116f2015-12-10 01:11:47 +00001117SourceLocation
1118StringLiteral::getLocationOfByte(unsigned ByteNo, const SourceManager &SM,
1119 const LangOptions &Features,
1120 const TargetInfo &Target, unsigned *StartToken,
1121 unsigned *StartTokenByteOffset) const {
Bruno Ricciaf214882018-11-15 16:42:14 +00001122 assert((getKind() == StringLiteral::Ascii ||
1123 getKind() == StringLiteral::UTF8) &&
Richard Smith4060f772012-06-13 05:37:23 +00001124 "Only narrow string literals are currently supported");
Douglas Gregorfb65e592011-07-27 05:40:30 +00001125
Chris Lattnere925d612010-11-17 07:37:15 +00001126 // Loop over all of the tokens in this string until we find the one that
1127 // contains the byte we're looking for.
1128 unsigned TokNo = 0;
Richard Smithefb116f2015-12-10 01:11:47 +00001129 unsigned StringOffset = 0;
1130 if (StartToken)
1131 TokNo = *StartToken;
1132 if (StartTokenByteOffset) {
1133 StringOffset = *StartTokenByteOffset;
1134 ByteNo -= StringOffset;
1135 }
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001136 while (1) {
Chris Lattnere925d612010-11-17 07:37:15 +00001137 assert(TokNo < getNumConcatenated() && "Invalid byte number!");
1138 SourceLocation StrTokLoc = getStrTokenLoc(TokNo);
Fangrui Song6907ce22018-07-30 19:24:48 +00001139
Chris Lattnere925d612010-11-17 07:37:15 +00001140 // Get the spelling of the string so that we can get the data that makes up
1141 // the string literal, not the identifier for the macro it is potentially
1142 // expanded through.
1143 SourceLocation StrTokSpellingLoc = SM.getSpellingLoc(StrTokLoc);
Richard Smithefb116f2015-12-10 01:11:47 +00001144
Chris Lattnere925d612010-11-17 07:37:15 +00001145 // Re-lex the token to get its length and original spelling.
Richard Smithefb116f2015-12-10 01:11:47 +00001146 std::pair<FileID, unsigned> LocInfo =
1147 SM.getDecomposedLoc(StrTokSpellingLoc);
Chris Lattnere925d612010-11-17 07:37:15 +00001148 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001149 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
Richard Smithefb116f2015-12-10 01:11:47 +00001150 if (Invalid) {
1151 if (StartTokenByteOffset != nullptr)
1152 *StartTokenByteOffset = StringOffset;
1153 if (StartToken != nullptr)
1154 *StartToken = TokNo;
Chris Lattnere925d612010-11-17 07:37:15 +00001155 return StrTokSpellingLoc;
Richard Smithefb116f2015-12-10 01:11:47 +00001156 }
1157
Chris Lattnere925d612010-11-17 07:37:15 +00001158 const char *StrData = Buffer.data()+LocInfo.second;
Fangrui Song6907ce22018-07-30 19:24:48 +00001159
Chris Lattnere925d612010-11-17 07:37:15 +00001160 // Create a lexer starting at the beginning of this token.
Argyrios Kyrtzidis45f51182012-05-11 21:39:18 +00001161 Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), Features,
1162 Buffer.begin(), StrData, Buffer.end());
Chris Lattnere925d612010-11-17 07:37:15 +00001163 Token TheTok;
1164 TheLexer.LexFromRawLexer(TheTok);
Fangrui Song6907ce22018-07-30 19:24:48 +00001165
Chris Lattnere925d612010-11-17 07:37:15 +00001166 // Use the StringLiteralParser to compute the length of the string in bytes.
Craig Topper9d5583e2014-06-26 04:58:39 +00001167 StringLiteralParser SLP(TheTok, SM, Features, Target);
Chris Lattnere925d612010-11-17 07:37:15 +00001168 unsigned TokNumBytes = SLP.GetStringLength();
Fangrui Song6907ce22018-07-30 19:24:48 +00001169
Chris Lattnere925d612010-11-17 07:37:15 +00001170 // If the byte is in this token, return the location of the byte.
1171 if (ByteNo < TokNumBytes ||
Hans Wennborg77d1abe2011-06-30 20:17:41 +00001172 (ByteNo == TokNumBytes && TokNo == getNumConcatenated() - 1)) {
Richard Smithefb116f2015-12-10 01:11:47 +00001173 unsigned Offset = SLP.getOffsetOfStringByte(TheTok, ByteNo);
1174
Chris Lattnere925d612010-11-17 07:37:15 +00001175 // Now that we know the offset of the token in the spelling, use the
1176 // preprocessor to get the offset in the original source.
Richard Smithefb116f2015-12-10 01:11:47 +00001177 if (StartTokenByteOffset != nullptr)
1178 *StartTokenByteOffset = StringOffset;
1179 if (StartToken != nullptr)
1180 *StartToken = TokNo;
Chris Lattnere925d612010-11-17 07:37:15 +00001181 return Lexer::AdvanceToTokenCharacter(StrTokLoc, Offset, SM, Features);
1182 }
Richard Smithefb116f2015-12-10 01:11:47 +00001183
Chris Lattnere925d612010-11-17 07:37:15 +00001184 // Move to the next string token.
Richard Smithefb116f2015-12-10 01:11:47 +00001185 StringOffset += TokNumBytes;
Chris Lattnere925d612010-11-17 07:37:15 +00001186 ++TokNo;
1187 ByteNo -= TokNumBytes;
1188 }
1189}
1190
Chris Lattner1b926492006-08-23 06:42:10 +00001191/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1192/// corresponds to, e.g. "sizeof" or "[pre]++".
Bruno Ricci3dfcb842018-11-13 21:33:22 +00001193StringRef UnaryOperator::getOpcodeStr(Opcode Op) {
1194 switch (Op) {
Etienne Bergeron5356d962016-05-12 20:58:56 +00001195#define UNARY_OPERATION(Name, Spelling) case UO_##Name: return Spelling;
1196#include "clang/AST/OperationKinds.def"
Chris Lattner1b926492006-08-23 06:42:10 +00001197 }
David Blaikief47fa302012-01-17 02:30:50 +00001198 llvm_unreachable("Unknown unary operator");
Chris Lattner1b926492006-08-23 06:42:10 +00001199}
1200
John McCalle3027922010-08-25 11:45:40 +00001201UnaryOperatorKind
Douglas Gregor084d8552009-03-13 23:49:33 +00001202UnaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix) {
1203 switch (OO) {
David Blaikie83d382b2011-09-23 05:06:16 +00001204 default: llvm_unreachable("No unary operator for overloaded function");
John McCalle3027922010-08-25 11:45:40 +00001205 case OO_PlusPlus: return Postfix ? UO_PostInc : UO_PreInc;
1206 case OO_MinusMinus: return Postfix ? UO_PostDec : UO_PreDec;
1207 case OO_Amp: return UO_AddrOf;
1208 case OO_Star: return UO_Deref;
1209 case OO_Plus: return UO_Plus;
1210 case OO_Minus: return UO_Minus;
1211 case OO_Tilde: return UO_Not;
1212 case OO_Exclaim: return UO_LNot;
Richard Smith9f690bd2015-10-27 06:02:45 +00001213 case OO_Coawait: return UO_Coawait;
Douglas Gregor084d8552009-03-13 23:49:33 +00001214 }
1215}
1216
1217OverloadedOperatorKind UnaryOperator::getOverloadedOperator(Opcode Opc) {
1218 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00001219 case UO_PostInc: case UO_PreInc: return OO_PlusPlus;
1220 case UO_PostDec: case UO_PreDec: return OO_MinusMinus;
1221 case UO_AddrOf: return OO_Amp;
1222 case UO_Deref: return OO_Star;
1223 case UO_Plus: return OO_Plus;
1224 case UO_Minus: return OO_Minus;
1225 case UO_Not: return OO_Tilde;
1226 case UO_LNot: return OO_Exclaim;
Richard Smith9f690bd2015-10-27 06:02:45 +00001227 case UO_Coawait: return OO_Coawait;
Douglas Gregor084d8552009-03-13 23:49:33 +00001228 default: return OO_None;
1229 }
1230}
1231
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001232
Chris Lattner0eedafe2006-08-24 04:56:27 +00001233//===----------------------------------------------------------------------===//
1234// Postfix Operators.
1235//===----------------------------------------------------------------------===//
Chris Lattnere165d942006-08-24 04:40:38 +00001236
Justin Lebarf8bdacb2016-01-14 23:31:30 +00001237CallExpr::CallExpr(const ASTContext &C, StmtClass SC, Expr *fn,
1238 ArrayRef<Expr *> preargs, ArrayRef<Expr *> args, QualType t,
Bruno Ricci4c9a0192018-12-03 14:54:03 +00001239 ExprValueKind VK, SourceLocation rparenloc,
Eric Fiselier5cdc2cd2018-12-12 21:50:55 +00001240 unsigned MinNumArgs, ADLCallKind UsesADL)
Justin Lebarf8bdacb2016-01-14 23:31:30 +00001241 : Expr(SC, t, VK, OK_Ordinary, fn->isTypeDependent(),
1242 fn->isValueDependent(), fn->isInstantiationDependent(),
1243 fn->containsUnexpandedParameterPack()),
Bruno Ricci4c9a0192018-12-03 14:54:03 +00001244 RParenLoc(rparenloc) {
Eric Fiselier5cdc2cd2018-12-12 21:50:55 +00001245 CallExprBits.UsesADL = static_cast<bool>(UsesADL);
1246
Bruno Ricci4c9a0192018-12-03 14:54:03 +00001247 NumArgs = std::max<unsigned>(args.size(), MinNumArgs);
Justin Lebarf8bdacb2016-01-14 23:31:30 +00001248 unsigned NumPreArgs = preargs.size();
Bruno Ricci4c9a0192018-12-03 14:54:03 +00001249 CallExprBits.NumPreArgs = NumPreArgs;
1250
1251 SubExprs = new (C) Stmt *[NumArgs + PREARGS_START + NumPreArgs];
Douglas Gregor993603d2008-11-14 16:09:21 +00001252 SubExprs[FN] = fn;
Justin Lebarf8bdacb2016-01-14 23:31:30 +00001253 for (unsigned i = 0; i != NumPreArgs; ++i) {
1254 updateDependenciesFromArg(preargs[i]);
1255 SubExprs[i+PREARGS_START] = preargs[i];
1256 }
Benjamin Kramerc215e762012-08-24 11:54:20 +00001257 for (unsigned i = 0; i != args.size(); ++i) {
Justin Lebarf8bdacb2016-01-14 23:31:30 +00001258 updateDependenciesFromArg(args[i]);
Peter Collingbourne3a347252011-02-08 21:18:02 +00001259 SubExprs[i+PREARGS_START+NumPreArgs] = args[i];
Douglas Gregora6e053e2010-12-15 01:34:56 +00001260 }
Bruno Ricci4c9a0192018-12-03 14:54:03 +00001261 for (unsigned i = args.size(); i != NumArgs; ++i) {
1262 SubExprs[i + PREARGS_START + NumPreArgs] = nullptr;
1263 }
Douglas Gregor993603d2008-11-14 16:09:21 +00001264}
Nate Begeman1e36a852008-01-17 17:46:27 +00001265
Justin Lebarf8bdacb2016-01-14 23:31:30 +00001266CallExpr::CallExpr(const ASTContext &C, StmtClass SC, Expr *fn,
1267 ArrayRef<Expr *> args, QualType t, ExprValueKind VK,
Eric Fiselier5cdc2cd2018-12-12 21:50:55 +00001268 SourceLocation rparenloc, unsigned MinNumArgs,
1269 ADLCallKind UsesADL)
Bruno Ricci4c9a0192018-12-03 14:54:03 +00001270 : CallExpr(C, SC, fn, ArrayRef<Expr *>(), args, t, VK, rparenloc,
Eric Fiselier5cdc2cd2018-12-12 21:50:55 +00001271 MinNumArgs, UsesADL) {}
Justin Lebarf8bdacb2016-01-14 23:31:30 +00001272
Benjamin Kramerf04f98d2015-03-06 14:15:57 +00001273CallExpr::CallExpr(const ASTContext &C, Expr *fn, ArrayRef<Expr *> args,
Bruno Ricci4c9a0192018-12-03 14:54:03 +00001274 QualType t, ExprValueKind VK, SourceLocation rparenloc,
Eric Fiselier5cdc2cd2018-12-12 21:50:55 +00001275 unsigned MinNumArgs, ADLCallKind UsesADL)
1276 : CallExpr(C, CallExprClass, fn, ArrayRef<Expr *>(), args, t, VK, rparenloc,
1277 MinNumArgs, UsesADL) {}
Peter Collingbourne3a347252011-02-08 21:18:02 +00001278
Craig Topper37932912013-08-18 10:09:15 +00001279CallExpr::CallExpr(const ASTContext &C, StmtClass SC, unsigned NumPreArgs,
Bruno Ricci4c9a0192018-12-03 14:54:03 +00001280 unsigned NumArgs, EmptyShell Empty)
1281 : Expr(SC, Empty), NumArgs(NumArgs) {
Peter Collingbourne3a347252011-02-08 21:18:02 +00001282 CallExprBits.NumPreArgs = NumPreArgs;
Bruno Ricci4c9a0192018-12-03 14:54:03 +00001283 SubExprs = new (C) Stmt *[NumArgs + PREARGS_START + NumPreArgs];
Douglas Gregore20a2e52009-04-15 17:43:59 +00001284}
1285
Bruno Ricci4c9a0192018-12-03 14:54:03 +00001286CallExpr::CallExpr(const ASTContext &C, unsigned NumArgs, EmptyShell Empty)
1287 : CallExpr(C, CallExprClass, /*NumPreArgs=*/0, NumArgs, Empty) {}
1288
Justin Lebarf8bdacb2016-01-14 23:31:30 +00001289void CallExpr::updateDependenciesFromArg(Expr *Arg) {
1290 if (Arg->isTypeDependent())
1291 ExprBits.TypeDependent = true;
1292 if (Arg->isValueDependent())
1293 ExprBits.ValueDependent = true;
1294 if (Arg->isInstantiationDependent())
1295 ExprBits.InstantiationDependent = true;
1296 if (Arg->containsUnexpandedParameterPack())
1297 ExprBits.ContainsUnexpandedParameterPack = true;
1298}
1299
John McCallb92ab1a2016-10-26 23:46:34 +00001300FunctionDecl *CallExpr::getDirectCallee() {
1301 return dyn_cast_or_null<FunctionDecl>(getCalleeDecl());
1302}
1303
Nuno Lopes518e3702009-12-20 23:11:08 +00001304Decl *CallExpr::getCalleeDecl() {
John McCallb92ab1a2016-10-26 23:46:34 +00001305 return getCallee()->getReferencedDeclOfCallee();
1306}
1307
1308Decl *Expr::getReferencedDeclOfCallee() {
1309 Expr *CEE = IgnoreParenImpCasts();
Fangrui Song6907ce22018-07-30 19:24:48 +00001310
Douglas Gregore0e96302011-09-06 21:41:04 +00001311 while (SubstNonTypeTemplateParmExpr *NTTP
1312 = dyn_cast<SubstNonTypeTemplateParmExpr>(CEE)) {
1313 CEE = NTTP->getReplacement()->IgnoreParenCasts();
1314 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001315
Sebastian Redl2b1832e2010-09-10 20:55:30 +00001316 // If we're calling a dereference, look at the pointer instead.
1317 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CEE)) {
1318 if (BO->isPtrMemOp())
1319 CEE = BO->getRHS()->IgnoreParenCasts();
1320 } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(CEE)) {
1321 if (UO->getOpcode() == UO_Deref)
1322 CEE = UO->getSubExpr()->IgnoreParenCasts();
1323 }
Chris Lattner52301912009-07-17 15:46:27 +00001324 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CEE))
Nuno Lopes518e3702009-12-20 23:11:08 +00001325 return DRE->getDecl();
Nuno Lopesc095b532009-12-24 00:28:18 +00001326 if (MemberExpr *ME = dyn_cast<MemberExpr>(CEE))
1327 return ME->getMemberDecl();
Zhongxing Xu3c8fa972009-07-17 07:29:51 +00001328
Craig Topper36250ad2014-05-12 05:36:57 +00001329 return nullptr;
Zhongxing Xu3c8fa972009-07-17 07:29:51 +00001330}
1331
Alp Tokera724cff2013-12-28 21:59:02 +00001332/// getBuiltinCallee - If this is a call to a builtin, return the builtin ID. If
Chris Lattner01ff98a2008-10-06 05:00:53 +00001333/// not, return 0.
Alp Tokera724cff2013-12-28 21:59:02 +00001334unsigned CallExpr::getBuiltinCallee() const {
Steve Narofff6e3b3292008-01-31 01:07:12 +00001335 // All simple function calls (e.g. func()) are implicitly cast to pointer to
Mike Stump11289f42009-09-09 15:08:12 +00001336 // function. As a result, we try and obtain the DeclRefExpr from the
Steve Narofff6e3b3292008-01-31 01:07:12 +00001337 // ImplicitCastExpr.
1338 const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(getCallee());
1339 if (!ICE) // FIXME: deal with more complex calls (e.g. (func)(), (*func)()).
Chris Lattner01ff98a2008-10-06 05:00:53 +00001340 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001341
Steve Narofff6e3b3292008-01-31 01:07:12 +00001342 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr());
1343 if (!DRE)
Chris Lattner01ff98a2008-10-06 05:00:53 +00001344 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001345
Anders Carlssonfbcf6762008-01-31 02:13:57 +00001346 const FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
1347 if (!FDecl)
Chris Lattner01ff98a2008-10-06 05:00:53 +00001348 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001349
Douglas Gregor9eb16ea2008-11-21 15:30:19 +00001350 if (!FDecl->getIdentifier())
1351 return 0;
1352
Douglas Gregor15fc9562009-09-12 00:22:50 +00001353 return FDecl->getBuiltinID();
Chris Lattner01ff98a2008-10-06 05:00:53 +00001354}
Anders Carlssonfbcf6762008-01-31 02:13:57 +00001355
Scott Douglass503fc392015-06-10 13:53:15 +00001356bool CallExpr::isUnevaluatedBuiltinCall(const ASTContext &Ctx) const {
Alp Tokera724cff2013-12-28 21:59:02 +00001357 if (unsigned BI = getBuiltinCallee())
Richard Smith5011a002013-01-17 23:46:04 +00001358 return Ctx.BuiltinInfo.isUnevaluated(BI);
1359 return false;
1360}
1361
David Majnemerced8bdf2015-02-25 17:36:15 +00001362QualType CallExpr::getCallReturnType(const ASTContext &Ctx) const {
1363 const Expr *Callee = getCallee();
1364 QualType CalleeType = Callee->getType();
1365 if (const auto *FnTypePtr = CalleeType->getAs<PointerType>()) {
Anders Carlsson00a27592009-05-26 04:57:27 +00001366 CalleeType = FnTypePtr->getPointeeType();
David Majnemerced8bdf2015-02-25 17:36:15 +00001367 } else if (const auto *BPT = CalleeType->getAs<BlockPointerType>()) {
Anders Carlsson00a27592009-05-26 04:57:27 +00001368 CalleeType = BPT->getPointeeType();
David Majnemerced8bdf2015-02-25 17:36:15 +00001369 } else if (CalleeType->isSpecificPlaceholderType(BuiltinType::BoundMember)) {
1370 if (isa<CXXPseudoDestructorExpr>(Callee->IgnoreParens()))
1371 return Ctx.VoidTy;
1372
John McCall0009fcc2011-04-26 20:42:42 +00001373 // This should never be overloaded and so should never return null.
David Majnemerced8bdf2015-02-25 17:36:15 +00001374 CalleeType = Expr::findBoundMemberType(Callee);
1375 }
1376
John McCall0009fcc2011-04-26 20:42:42 +00001377 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00001378 return FnType->getReturnType();
Anders Carlsson00a27592009-05-26 04:57:27 +00001379}
Chris Lattner01ff98a2008-10-06 05:00:53 +00001380
Stephen Kelly724e9e52018-08-09 20:05:03 +00001381SourceLocation CallExpr::getBeginLoc() const {
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001382 if (isa<CXXOperatorCallExpr>(this))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001383 return cast<CXXOperatorCallExpr>(this)->getBeginLoc();
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001384
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001385 SourceLocation begin = getCallee()->getBeginLoc();
Keno Fischer070db172014-08-15 01:39:12 +00001386 if (begin.isInvalid() && getNumArgs() > 0 && getArg(0))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001387 begin = getArg(0)->getBeginLoc();
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001388 return begin;
1389}
Stephen Kelly02a67ba2018-08-09 20:05:47 +00001390SourceLocation CallExpr::getEndLoc() const {
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001391 if (isa<CXXOperatorCallExpr>(this))
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001392 return cast<CXXOperatorCallExpr>(this)->getEndLoc();
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001393
1394 SourceLocation end = getRParenLoc();
Keno Fischer070db172014-08-15 01:39:12 +00001395 if (end.isInvalid() && getNumArgs() > 0 && getArg(getNumArgs() - 1))
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001396 end = getArg(getNumArgs() - 1)->getEndLoc();
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001397 return end;
1398}
John McCall701417a2011-02-21 06:23:05 +00001399
Craig Topper37932912013-08-18 10:09:15 +00001400OffsetOfExpr *OffsetOfExpr::Create(const ASTContext &C, QualType type,
Douglas Gregor882211c2010-04-28 22:16:22 +00001401 SourceLocation OperatorLoc,
Fangrui Song6907ce22018-07-30 19:24:48 +00001402 TypeSourceInfo *tsi,
Benjamin Kramerc215e762012-08-24 11:54:20 +00001403 ArrayRef<OffsetOfNode> comps,
1404 ArrayRef<Expr*> exprs,
Douglas Gregor882211c2010-04-28 22:16:22 +00001405 SourceLocation RParenLoc) {
James Y Knight7281c352015-12-29 22:31:18 +00001406 void *Mem = C.Allocate(
1407 totalSizeToAlloc<OffsetOfNode, Expr *>(comps.size(), exprs.size()));
Douglas Gregor882211c2010-04-28 22:16:22 +00001408
Benjamin Kramerc215e762012-08-24 11:54:20 +00001409 return new (Mem) OffsetOfExpr(C, type, OperatorLoc, tsi, comps, exprs,
1410 RParenLoc);
Douglas Gregor882211c2010-04-28 22:16:22 +00001411}
1412
Craig Topper37932912013-08-18 10:09:15 +00001413OffsetOfExpr *OffsetOfExpr::CreateEmpty(const ASTContext &C,
Douglas Gregor882211c2010-04-28 22:16:22 +00001414 unsigned numComps, unsigned numExprs) {
James Y Knight7281c352015-12-29 22:31:18 +00001415 void *Mem =
1416 C.Allocate(totalSizeToAlloc<OffsetOfNode, Expr *>(numComps, numExprs));
Douglas Gregor882211c2010-04-28 22:16:22 +00001417 return new (Mem) OffsetOfExpr(numComps, numExprs);
1418}
1419
Craig Topper37932912013-08-18 10:09:15 +00001420OffsetOfExpr::OffsetOfExpr(const ASTContext &C, QualType type,
Douglas Gregor882211c2010-04-28 22:16:22 +00001421 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
Benjamin Kramerc215e762012-08-24 11:54:20 +00001422 ArrayRef<OffsetOfNode> comps, ArrayRef<Expr*> exprs,
Douglas Gregor882211c2010-04-28 22:16:22 +00001423 SourceLocation RParenLoc)
John McCall7decc9e2010-11-18 06:31:45 +00001424 : Expr(OffsetOfExprClass, type, VK_RValue, OK_Ordinary,
Fangrui Song6907ce22018-07-30 19:24:48 +00001425 /*TypeDependent=*/false,
Douglas Gregora6e053e2010-12-15 01:34:56 +00001426 /*ValueDependent=*/tsi->getType()->isDependentType(),
Douglas Gregor678d76c2011-07-01 01:22:09 +00001427 tsi->getType()->isInstantiationDependentType(),
Douglas Gregora6e053e2010-12-15 01:34:56 +00001428 tsi->getType()->containsUnexpandedParameterPack()),
Fangrui Song6907ce22018-07-30 19:24:48 +00001429 OperatorLoc(OperatorLoc), RParenLoc(RParenLoc), TSInfo(tsi),
Benjamin Kramerc215e762012-08-24 11:54:20 +00001430 NumComps(comps.size()), NumExprs(exprs.size())
Douglas Gregor882211c2010-04-28 22:16:22 +00001431{
Benjamin Kramerc215e762012-08-24 11:54:20 +00001432 for (unsigned i = 0; i != comps.size(); ++i) {
1433 setComponent(i, comps[i]);
Douglas Gregor882211c2010-04-28 22:16:22 +00001434 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001435
Benjamin Kramerc215e762012-08-24 11:54:20 +00001436 for (unsigned i = 0; i != exprs.size(); ++i) {
1437 if (exprs[i]->isTypeDependent() || exprs[i]->isValueDependent())
Douglas Gregora6e053e2010-12-15 01:34:56 +00001438 ExprBits.ValueDependent = true;
Benjamin Kramerc215e762012-08-24 11:54:20 +00001439 if (exprs[i]->containsUnexpandedParameterPack())
Douglas Gregora6e053e2010-12-15 01:34:56 +00001440 ExprBits.ContainsUnexpandedParameterPack = true;
1441
Benjamin Kramerc215e762012-08-24 11:54:20 +00001442 setIndexExpr(i, exprs[i]);
Douglas Gregor882211c2010-04-28 22:16:22 +00001443 }
1444}
1445
James Y Knight7281c352015-12-29 22:31:18 +00001446IdentifierInfo *OffsetOfNode::getFieldName() const {
Douglas Gregor882211c2010-04-28 22:16:22 +00001447 assert(getKind() == Field || getKind() == Identifier);
1448 if (getKind() == Field)
1449 return getField()->getIdentifier();
Fangrui Song6907ce22018-07-30 19:24:48 +00001450
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001451 return reinterpret_cast<IdentifierInfo *> (Data & ~(uintptr_t)Mask);
Douglas Gregor882211c2010-04-28 22:16:22 +00001452}
1453
David Majnemer10fd83d2015-01-15 10:04:14 +00001454UnaryExprOrTypeTraitExpr::UnaryExprOrTypeTraitExpr(
1455 UnaryExprOrTypeTrait ExprKind, Expr *E, QualType resultType,
1456 SourceLocation op, SourceLocation rp)
1457 : Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_RValue, OK_Ordinary,
1458 false, // Never type-dependent (C++ [temp.dep.expr]p3).
1459 // Value-dependent if the argument is type-dependent.
1460 E->isTypeDependent(), E->isInstantiationDependent(),
1461 E->containsUnexpandedParameterPack()),
1462 OpLoc(op), RParenLoc(rp) {
1463 UnaryExprOrTypeTraitExprBits.Kind = ExprKind;
1464 UnaryExprOrTypeTraitExprBits.IsType = false;
1465 Argument.Ex = E;
1466
1467 // Check to see if we are in the situation where alignof(decl) should be
1468 // dependent because decl's alignment is dependent.
Richard Smith6822bd72018-10-26 19:26:45 +00001469 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
David Majnemer10fd83d2015-01-15 10:04:14 +00001470 if (!isValueDependent() || !isInstantiationDependent()) {
1471 E = E->IgnoreParens();
1472
1473 const ValueDecl *D = nullptr;
1474 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
1475 D = DRE->getDecl();
1476 else if (const auto *ME = dyn_cast<MemberExpr>(E))
1477 D = ME->getMemberDecl();
1478
1479 if (D) {
1480 for (const auto *I : D->specific_attrs<AlignedAttr>()) {
1481 if (I->isAlignmentDependent()) {
1482 setValueDependent(true);
1483 setInstantiationDependent(true);
1484 break;
1485 }
1486 }
1487 }
1488 }
1489 }
1490}
1491
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00001492MemberExpr *MemberExpr::Create(
1493 const ASTContext &C, Expr *base, bool isarrow, SourceLocation OperatorLoc,
1494 NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,
1495 ValueDecl *memberdecl, DeclAccessPair founddecl,
1496 DeclarationNameInfo nameinfo, const TemplateArgumentListInfo *targs,
1497 QualType ty, ExprValueKind vk, ExprObjectKind ok) {
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001498
Douglas Gregorea972d32011-02-28 21:54:11 +00001499 bool hasQualOrFound = (QualifierLoc ||
John McCalla8ae2222010-04-06 21:38:20 +00001500 founddecl.getDecl() != memberdecl ||
1501 founddecl.getAccess() != memberdecl->getAccess());
Mike Stump11289f42009-09-09 15:08:12 +00001502
James Y Knighte7d82282015-12-29 18:15:14 +00001503 bool HasTemplateKWAndArgsInfo = targs || TemplateKWLoc.isValid();
1504 std::size_t Size =
1505 totalSizeToAlloc<MemberExprNameQualifier, ASTTemplateKWAndArgsInfo,
1506 TemplateArgumentLoc>(hasQualOrFound ? 1 : 0,
1507 HasTemplateKWAndArgsInfo ? 1 : 0,
1508 targs ? targs->size() : 0);
Mike Stump11289f42009-09-09 15:08:12 +00001509
Benjamin Kramerc3f89252016-10-20 14:27:22 +00001510 void *Mem = C.Allocate(Size, alignof(MemberExpr));
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00001511 MemberExpr *E = new (Mem)
1512 MemberExpr(base, isarrow, OperatorLoc, memberdecl, nameinfo, ty, vk, ok);
John McCall16df1e52010-03-30 21:47:33 +00001513
1514 if (hasQualOrFound) {
Douglas Gregorea972d32011-02-28 21:54:11 +00001515 // FIXME: Wrong. We should be looking at the member declaration we found.
1516 if (QualifierLoc && QualifierLoc.getNestedNameSpecifier()->isDependent()) {
John McCall16df1e52010-03-30 21:47:33 +00001517 E->setValueDependent(true);
1518 E->setTypeDependent(true);
Douglas Gregor678d76c2011-07-01 01:22:09 +00001519 E->setInstantiationDependent(true);
Fangrui Song6907ce22018-07-30 19:24:48 +00001520 }
1521 else if (QualifierLoc &&
1522 QualifierLoc.getNestedNameSpecifier()->isInstantiationDependent())
Douglas Gregor678d76c2011-07-01 01:22:09 +00001523 E->setInstantiationDependent(true);
Fangrui Song6907ce22018-07-30 19:24:48 +00001524
Bruno Ricci4c742532018-11-15 13:56:22 +00001525 E->MemberExprBits.HasQualifierOrFoundDecl = true;
John McCall16df1e52010-03-30 21:47:33 +00001526
James Y Knighte7d82282015-12-29 18:15:14 +00001527 MemberExprNameQualifier *NQ =
1528 E->getTrailingObjects<MemberExprNameQualifier>();
Douglas Gregorea972d32011-02-28 21:54:11 +00001529 NQ->QualifierLoc = QualifierLoc;
John McCall16df1e52010-03-30 21:47:33 +00001530 NQ->FoundDecl = founddecl;
1531 }
1532
Bruno Ricci4c742532018-11-15 13:56:22 +00001533 E->MemberExprBits.HasTemplateKWAndArgsInfo =
1534 (targs || TemplateKWLoc.isValid());
Abramo Bagnara7945c982012-01-27 09:46:47 +00001535
John McCall16df1e52010-03-30 21:47:33 +00001536 if (targs) {
Douglas Gregor678d76c2011-07-01 01:22:09 +00001537 bool Dependent = false;
1538 bool InstantiationDependent = false;
1539 bool ContainsUnexpandedParameterPack = false;
James Y Knighte7d82282015-12-29 18:15:14 +00001540 E->getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
1541 TemplateKWLoc, *targs, E->getTrailingObjects<TemplateArgumentLoc>(),
1542 Dependent, InstantiationDependent, ContainsUnexpandedParameterPack);
Douglas Gregor678d76c2011-07-01 01:22:09 +00001543 if (InstantiationDependent)
1544 E->setInstantiationDependent(true);
Abramo Bagnara7945c982012-01-27 09:46:47 +00001545 } else if (TemplateKWLoc.isValid()) {
James Y Knighte7d82282015-12-29 18:15:14 +00001546 E->getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
1547 TemplateKWLoc);
John McCall16df1e52010-03-30 21:47:33 +00001548 }
1549
1550 return E;
Douglas Gregorf405d7e2009-08-31 23:41:50 +00001551}
1552
Stephen Kelly724e9e52018-08-09 20:05:03 +00001553SourceLocation MemberExpr::getBeginLoc() const {
Douglas Gregor25b7e052011-03-02 21:06:53 +00001554 if (isImplicitAccess()) {
1555 if (hasQualifier())
Daniel Dunbarb507f272012-03-09 15:39:15 +00001556 return getQualifierLoc().getBeginLoc();
1557 return MemberLoc;
Douglas Gregor25b7e052011-03-02 21:06:53 +00001558 }
Abramo Bagnara7945c982012-01-27 09:46:47 +00001559
Daniel Dunbarb507f272012-03-09 15:39:15 +00001560 // FIXME: We don't want this to happen. Rather, we should be able to
1561 // detect all kinds of implicit accesses more cleanly.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001562 SourceLocation BaseStartLoc = getBase()->getBeginLoc();
Daniel Dunbarb507f272012-03-09 15:39:15 +00001563 if (BaseStartLoc.isValid())
1564 return BaseStartLoc;
1565 return MemberLoc;
1566}
Stephen Kelly02a67ba2018-08-09 20:05:47 +00001567SourceLocation MemberExpr::getEndLoc() const {
Abramo Bagnara9b836fb2012-11-08 13:52:58 +00001568 SourceLocation EndLoc = getMemberNameInfo().getEndLoc();
Daniel Dunbarb507f272012-03-09 15:39:15 +00001569 if (hasExplicitTemplateArgs())
Abramo Bagnara9b836fb2012-11-08 13:52:58 +00001570 EndLoc = getRAngleLoc();
1571 else if (EndLoc.isInvalid())
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001572 EndLoc = getBase()->getEndLoc();
Abramo Bagnara9b836fb2012-11-08 13:52:58 +00001573 return EndLoc;
Douglas Gregor25b7e052011-03-02 21:06:53 +00001574}
1575
Alp Tokerc1086762013-12-07 13:51:35 +00001576bool CastExpr::CastConsistency() const {
John McCall9320b872011-09-09 05:25:32 +00001577 switch (getCastKind()) {
1578 case CK_DerivedToBase:
1579 case CK_UncheckedDerivedToBase:
1580 case CK_DerivedToBaseMemberPointer:
1581 case CK_BaseToDerived:
1582 case CK_BaseToDerivedMemberPointer:
1583 assert(!path_empty() && "Cast kind should have a base path!");
1584 break;
1585
1586 case CK_CPointerToObjCPointerCast:
1587 assert(getType()->isObjCObjectPointerType());
1588 assert(getSubExpr()->getType()->isPointerType());
1589 goto CheckNoBasePath;
1590
1591 case CK_BlockPointerToObjCPointerCast:
1592 assert(getType()->isObjCObjectPointerType());
1593 assert(getSubExpr()->getType()->isBlockPointerType());
1594 goto CheckNoBasePath;
1595
John McCallc62bb392012-02-15 01:22:51 +00001596 case CK_ReinterpretMemberPointer:
1597 assert(getType()->isMemberPointerType());
1598 assert(getSubExpr()->getType()->isMemberPointerType());
1599 goto CheckNoBasePath;
1600
John McCall9320b872011-09-09 05:25:32 +00001601 case CK_BitCast:
1602 // Arbitrary casts to C pointer types count as bitcasts.
1603 // Otherwise, we should only have block and ObjC pointer casts
1604 // here if they stay within the type kind.
1605 if (!getType()->isPointerType()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001606 assert(getType()->isObjCObjectPointerType() ==
John McCall9320b872011-09-09 05:25:32 +00001607 getSubExpr()->getType()->isObjCObjectPointerType());
Fangrui Song6907ce22018-07-30 19:24:48 +00001608 assert(getType()->isBlockPointerType() ==
John McCall9320b872011-09-09 05:25:32 +00001609 getSubExpr()->getType()->isBlockPointerType());
1610 }
1611 goto CheckNoBasePath;
1612
1613 case CK_AnyPointerToBlockPointerCast:
1614 assert(getType()->isBlockPointerType());
1615 assert(getSubExpr()->getType()->isAnyPointerType() &&
1616 !getSubExpr()->getType()->isBlockPointerType());
1617 goto CheckNoBasePath;
1618
Douglas Gregored90df32012-02-22 05:02:47 +00001619 case CK_CopyAndAutoreleaseBlockObject:
1620 assert(getType()->isBlockPointerType());
1621 assert(getSubExpr()->getType()->isBlockPointerType());
1622 goto CheckNoBasePath;
Eli Friedman34866c72012-08-31 00:14:07 +00001623
1624 case CK_FunctionToPointerDecay:
1625 assert(getType()->isPointerType());
1626 assert(getSubExpr()->getType()->isFunctionType());
1627 goto CheckNoBasePath;
1628
Anastasia Stulova04307942018-11-16 16:22:56 +00001629 case CK_AddressSpaceConversion: {
1630 auto Ty = getType();
1631 auto SETy = getSubExpr()->getType();
1632 assert(getValueKindForType(Ty) == Expr::getValueKindForType(SETy));
1633 if (!isGLValue())
1634 Ty = Ty->getPointeeType();
1635 if (!isGLValue())
1636 SETy = SETy->getPointeeType();
1637 assert(!Ty.isNull() && !SETy.isNull() &&
1638 Ty.getAddressSpace() != SETy.getAddressSpace());
1639 goto CheckNoBasePath;
1640 }
John McCall9320b872011-09-09 05:25:32 +00001641 // These should not have an inheritance path.
1642 case CK_Dynamic:
1643 case CK_ToUnion:
1644 case CK_ArrayToPointerDecay:
John McCall9320b872011-09-09 05:25:32 +00001645 case CK_NullToMemberPointer:
1646 case CK_NullToPointer:
1647 case CK_ConstructorConversion:
1648 case CK_IntegralToPointer:
1649 case CK_PointerToIntegral:
1650 case CK_ToVoid:
1651 case CK_VectorSplat:
1652 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +00001653 case CK_BooleanToSignedIntegral:
John McCall9320b872011-09-09 05:25:32 +00001654 case CK_IntegralToFloating:
1655 case CK_FloatingToIntegral:
1656 case CK_FloatingCast:
1657 case CK_ObjCObjectLValueCast:
1658 case CK_FloatingRealToComplex:
1659 case CK_FloatingComplexToReal:
1660 case CK_FloatingComplexCast:
1661 case CK_FloatingComplexToIntegralComplex:
1662 case CK_IntegralRealToComplex:
1663 case CK_IntegralComplexToReal:
1664 case CK_IntegralComplexCast:
1665 case CK_IntegralComplexToFloatingComplex:
John McCall2d637d22011-09-10 06:18:15 +00001666 case CK_ARCProduceObject:
1667 case CK_ARCConsumeObject:
1668 case CK_ARCReclaimReturnedObject:
1669 case CK_ARCExtendBlockObject:
Andrew Savonichevb555b762018-10-23 15:19:20 +00001670 case CK_ZeroToOCLOpaqueType:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00001671 case CK_IntToOCLSampler:
Leonard Chan99bda372018-10-15 16:07:02 +00001672 case CK_FixedPointCast:
John McCall9320b872011-09-09 05:25:32 +00001673 assert(!getType()->isBooleanType() && "unheralded conversion to bool");
1674 goto CheckNoBasePath;
1675
1676 case CK_Dependent:
1677 case CK_LValueToRValue:
John McCall9320b872011-09-09 05:25:32 +00001678 case CK_NoOp:
David Chisnallfa35df62012-01-16 17:27:18 +00001679 case CK_AtomicToNonAtomic:
1680 case CK_NonAtomicToAtomic:
John McCall9320b872011-09-09 05:25:32 +00001681 case CK_PointerToBoolean:
1682 case CK_IntegralToBoolean:
1683 case CK_FloatingToBoolean:
1684 case CK_MemberPointerToBoolean:
1685 case CK_FloatingComplexToBoolean:
1686 case CK_IntegralComplexToBoolean:
1687 case CK_LValueBitCast: // -> bool&
1688 case CK_UserDefinedConversion: // operator bool()
Eli Friedman34866c72012-08-31 00:14:07 +00001689 case CK_BuiltinFnToFnPtr:
Leonard Chanb4ba4672018-10-23 17:55:35 +00001690 case CK_FixedPointToBoolean:
John McCall9320b872011-09-09 05:25:32 +00001691 CheckNoBasePath:
1692 assert(path_empty() && "Cast kind should not have a base path!");
1693 break;
1694 }
Alp Tokerc1086762013-12-07 13:51:35 +00001695 return true;
John McCall9320b872011-09-09 05:25:32 +00001696}
1697
Eric Fiselier0683c0e2018-05-07 21:07:10 +00001698const char *CastExpr::getCastKindName(CastKind CK) {
1699 switch (CK) {
Etienne Bergeron5356d962016-05-12 20:58:56 +00001700#define CAST_OPERATION(Name) case CK_##Name: return #Name;
1701#include "clang/AST/OperationKinds.def"
Anders Carlsson496335e2009-09-03 00:59:21 +00001702 }
John McCallc5e62b42010-11-13 09:02:35 +00001703 llvm_unreachable("Unhandled cast kind!");
Anders Carlsson496335e2009-09-03 00:59:21 +00001704}
1705
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001706namespace {
Richard Smith1ef75542018-06-27 20:30:34 +00001707 const Expr *skipImplicitTemporary(const Expr *E) {
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001708 // Skip through reference binding to temporary.
Richard Smith1ef75542018-06-27 20:30:34 +00001709 if (auto *Materialize = dyn_cast<MaterializeTemporaryExpr>(E))
1710 E = Materialize->GetTemporaryExpr();
Stephan Bergmannf31b0dc2017-06-27 08:19:09 +00001711
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001712 // Skip any temporary bindings; they're implicit.
Richard Smith1ef75542018-06-27 20:30:34 +00001713 if (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
1714 E = Binder->getSubExpr();
Stephan Bergmannf31b0dc2017-06-27 08:19:09 +00001715
Richard Smith1ef75542018-06-27 20:30:34 +00001716 return E;
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001717 }
Stephan Bergmannf31b0dc2017-06-27 08:19:09 +00001718}
1719
Douglas Gregord196a582009-12-14 19:27:10 +00001720Expr *CastExpr::getSubExprAsWritten() {
Richard Smith1ef75542018-06-27 20:30:34 +00001721 const Expr *SubExpr = nullptr;
1722 const CastExpr *E = this;
Douglas Gregord196a582009-12-14 19:27:10 +00001723 do {
Stephan Bergmannf31b0dc2017-06-27 08:19:09 +00001724 SubExpr = skipImplicitTemporary(E->getSubExpr());
Douglas Gregorfe314812011-06-21 17:03:29 +00001725
Douglas Gregord196a582009-12-14 19:27:10 +00001726 // Conversions by constructor and conversion functions have a
1727 // subexpression describing the call; strip it off.
John McCalle3027922010-08-25 11:45:40 +00001728 if (E->getCastKind() == CK_ConstructorConversion)
Stephan Bergmannf31b0dc2017-06-27 08:19:09 +00001729 SubExpr =
1730 skipImplicitTemporary(cast<CXXConstructExpr>(SubExpr)->getArg(0));
Manman Ren8abc2e52016-02-02 22:23:03 +00001731 else if (E->getCastKind() == CK_UserDefinedConversion) {
1732 assert((isa<CXXMemberCallExpr>(SubExpr) ||
1733 isa<BlockExpr>(SubExpr)) &&
1734 "Unexpected SubExpr for CK_UserDefinedConversion.");
Richard Smith1ef75542018-06-27 20:30:34 +00001735 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SubExpr))
1736 SubExpr = MCE->getImplicitObjectArgument();
Manman Ren8abc2e52016-02-02 22:23:03 +00001737 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001738
Douglas Gregord196a582009-12-14 19:27:10 +00001739 // If the subexpression we're left with is an implicit cast, look
1740 // through that, too.
Fangrui Song6907ce22018-07-30 19:24:48 +00001741 } while ((E = dyn_cast<ImplicitCastExpr>(SubExpr)));
1742
Richard Smith1ef75542018-06-27 20:30:34 +00001743 return const_cast<Expr*>(SubExpr);
1744}
1745
1746NamedDecl *CastExpr::getConversionFunction() const {
1747 const Expr *SubExpr = nullptr;
1748
1749 for (const CastExpr *E = this; E; E = dyn_cast<ImplicitCastExpr>(SubExpr)) {
1750 SubExpr = skipImplicitTemporary(E->getSubExpr());
1751
1752 if (E->getCastKind() == CK_ConstructorConversion)
1753 return cast<CXXConstructExpr>(SubExpr)->getConstructor();
1754
1755 if (E->getCastKind() == CK_UserDefinedConversion) {
1756 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SubExpr))
1757 return MCE->getMethodDecl();
1758 }
1759 }
1760
1761 return nullptr;
Douglas Gregord196a582009-12-14 19:27:10 +00001762}
1763
Roman Lebedev4aaf1dc2018-08-01 06:06:16 +00001764CastExpr::BasePathSizeTy *CastExpr::BasePathSize() {
1765 assert(!path_empty());
1766 switch (getStmtClass()) {
1767#define ABSTRACT_STMT(x)
1768#define CASTEXPR(Type, Base) \
1769 case Stmt::Type##Class: \
1770 return static_cast<Type *>(this) \
1771 ->getTrailingObjects<CastExpr::BasePathSizeTy>();
1772#define STMT(Type, Base)
1773#include "clang/AST/StmtNodes.inc"
1774 default:
1775 llvm_unreachable("non-cast expressions not possible here");
1776 }
1777}
1778
John McCallcf142162010-08-07 06:22:56 +00001779CXXBaseSpecifier **CastExpr::path_buffer() {
1780 switch (getStmtClass()) {
1781#define ABSTRACT_STMT(x)
James Y Knight1d75c5e2015-12-30 02:27:28 +00001782#define CASTEXPR(Type, Base) \
1783 case Stmt::Type##Class: \
1784 return static_cast<Type *>(this)->getTrailingObjects<CXXBaseSpecifier *>();
John McCallcf142162010-08-07 06:22:56 +00001785#define STMT(Type, Base)
1786#include "clang/AST/StmtNodes.inc"
1787 default:
1788 llvm_unreachable("non-cast expressions not possible here");
John McCallcf142162010-08-07 06:22:56 +00001789 }
1790}
1791
John McCallf1ef7962017-08-15 21:42:47 +00001792const FieldDecl *CastExpr::getTargetFieldForToUnionCast(QualType unionType,
1793 QualType opType) {
1794 auto RD = unionType->castAs<RecordType>()->getDecl();
1795 return getTargetFieldForToUnionCast(RD, opType);
1796}
1797
1798const FieldDecl *CastExpr::getTargetFieldForToUnionCast(const RecordDecl *RD,
1799 QualType OpType) {
1800 auto &Ctx = RD->getASTContext();
1801 RecordDecl::field_iterator Field, FieldEnd;
1802 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
1803 Field != FieldEnd; ++Field) {
1804 if (Ctx.hasSameUnqualifiedType(Field->getType(), OpType) &&
1805 !Field->isUnnamedBitfield()) {
1806 return *Field;
1807 }
1808 }
1809 return nullptr;
1810}
1811
Craig Topper37932912013-08-18 10:09:15 +00001812ImplicitCastExpr *ImplicitCastExpr::Create(const ASTContext &C, QualType T,
John McCallcf142162010-08-07 06:22:56 +00001813 CastKind Kind, Expr *Operand,
1814 const CXXCastPath *BasePath,
John McCall2536c6d2010-08-25 10:28:54 +00001815 ExprValueKind VK) {
John McCallcf142162010-08-07 06:22:56 +00001816 unsigned PathSize = (BasePath ? BasePath->size() : 0);
Roman Lebedev4aaf1dc2018-08-01 06:06:16 +00001817 void *Buffer =
1818 C.Allocate(totalSizeToAlloc<CastExpr::BasePathSizeTy, CXXBaseSpecifier *>(
1819 PathSize ? 1 : 0, PathSize));
John McCallcf142162010-08-07 06:22:56 +00001820 ImplicitCastExpr *E =
John McCall2536c6d2010-08-25 10:28:54 +00001821 new (Buffer) ImplicitCastExpr(T, Kind, Operand, PathSize, VK);
James Y Knight1d75c5e2015-12-30 02:27:28 +00001822 if (PathSize)
1823 std::uninitialized_copy_n(BasePath->data(), BasePath->size(),
1824 E->getTrailingObjects<CXXBaseSpecifier *>());
John McCallcf142162010-08-07 06:22:56 +00001825 return E;
1826}
1827
Craig Topper37932912013-08-18 10:09:15 +00001828ImplicitCastExpr *ImplicitCastExpr::CreateEmpty(const ASTContext &C,
John McCallcf142162010-08-07 06:22:56 +00001829 unsigned PathSize) {
Roman Lebedev4aaf1dc2018-08-01 06:06:16 +00001830 void *Buffer =
1831 C.Allocate(totalSizeToAlloc<CastExpr::BasePathSizeTy, CXXBaseSpecifier *>(
1832 PathSize ? 1 : 0, PathSize));
John McCallcf142162010-08-07 06:22:56 +00001833 return new (Buffer) ImplicitCastExpr(EmptyShell(), PathSize);
1834}
1835
1836
Craig Topper37932912013-08-18 10:09:15 +00001837CStyleCastExpr *CStyleCastExpr::Create(const ASTContext &C, QualType T,
John McCall7decc9e2010-11-18 06:31:45 +00001838 ExprValueKind VK, CastKind K, Expr *Op,
John McCallcf142162010-08-07 06:22:56 +00001839 const CXXCastPath *BasePath,
1840 TypeSourceInfo *WrittenTy,
1841 SourceLocation L, SourceLocation R) {
1842 unsigned PathSize = (BasePath ? BasePath->size() : 0);
Roman Lebedev4aaf1dc2018-08-01 06:06:16 +00001843 void *Buffer =
1844 C.Allocate(totalSizeToAlloc<CastExpr::BasePathSizeTy, CXXBaseSpecifier *>(
1845 PathSize ? 1 : 0, PathSize));
John McCallcf142162010-08-07 06:22:56 +00001846 CStyleCastExpr *E =
John McCall7decc9e2010-11-18 06:31:45 +00001847 new (Buffer) CStyleCastExpr(T, VK, K, Op, PathSize, WrittenTy, L, R);
James Y Knight1d75c5e2015-12-30 02:27:28 +00001848 if (PathSize)
1849 std::uninitialized_copy_n(BasePath->data(), BasePath->size(),
1850 E->getTrailingObjects<CXXBaseSpecifier *>());
John McCallcf142162010-08-07 06:22:56 +00001851 return E;
1852}
1853
Craig Topper37932912013-08-18 10:09:15 +00001854CStyleCastExpr *CStyleCastExpr::CreateEmpty(const ASTContext &C,
1855 unsigned PathSize) {
Roman Lebedev4aaf1dc2018-08-01 06:06:16 +00001856 void *Buffer =
1857 C.Allocate(totalSizeToAlloc<CastExpr::BasePathSizeTy, CXXBaseSpecifier *>(
1858 PathSize ? 1 : 0, PathSize));
John McCallcf142162010-08-07 06:22:56 +00001859 return new (Buffer) CStyleCastExpr(EmptyShell(), PathSize);
1860}
1861
Chris Lattner1b926492006-08-23 06:42:10 +00001862/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1863/// corresponds to, e.g. "<<=".
David Blaikie1d202a62012-10-08 01:11:04 +00001864StringRef BinaryOperator::getOpcodeStr(Opcode Op) {
Chris Lattner1b926492006-08-23 06:42:10 +00001865 switch (Op) {
Etienne Bergeron5356d962016-05-12 20:58:56 +00001866#define BINARY_OPERATION(Name, Spelling) case BO_##Name: return Spelling;
1867#include "clang/AST/OperationKinds.def"
Chris Lattner1b926492006-08-23 06:42:10 +00001868 }
David Blaikiee4d798f2012-01-20 21:50:17 +00001869 llvm_unreachable("Invalid OpCode!");
Chris Lattner1b926492006-08-23 06:42:10 +00001870}
Steve Naroff47500512007-04-19 23:00:49 +00001871
John McCalle3027922010-08-25 11:45:40 +00001872BinaryOperatorKind
Douglas Gregor1baf54e2009-03-13 18:40:31 +00001873BinaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO) {
1874 switch (OO) {
David Blaikie83d382b2011-09-23 05:06:16 +00001875 default: llvm_unreachable("Not an overloadable binary operator");
John McCalle3027922010-08-25 11:45:40 +00001876 case OO_Plus: return BO_Add;
1877 case OO_Minus: return BO_Sub;
1878 case OO_Star: return BO_Mul;
1879 case OO_Slash: return BO_Div;
1880 case OO_Percent: return BO_Rem;
1881 case OO_Caret: return BO_Xor;
1882 case OO_Amp: return BO_And;
1883 case OO_Pipe: return BO_Or;
1884 case OO_Equal: return BO_Assign;
Richard Smithc70f1d62017-12-14 15:16:18 +00001885 case OO_Spaceship: return BO_Cmp;
John McCalle3027922010-08-25 11:45:40 +00001886 case OO_Less: return BO_LT;
1887 case OO_Greater: return BO_GT;
1888 case OO_PlusEqual: return BO_AddAssign;
1889 case OO_MinusEqual: return BO_SubAssign;
1890 case OO_StarEqual: return BO_MulAssign;
1891 case OO_SlashEqual: return BO_DivAssign;
1892 case OO_PercentEqual: return BO_RemAssign;
1893 case OO_CaretEqual: return BO_XorAssign;
1894 case OO_AmpEqual: return BO_AndAssign;
1895 case OO_PipeEqual: return BO_OrAssign;
1896 case OO_LessLess: return BO_Shl;
1897 case OO_GreaterGreater: return BO_Shr;
1898 case OO_LessLessEqual: return BO_ShlAssign;
1899 case OO_GreaterGreaterEqual: return BO_ShrAssign;
1900 case OO_EqualEqual: return BO_EQ;
1901 case OO_ExclaimEqual: return BO_NE;
1902 case OO_LessEqual: return BO_LE;
1903 case OO_GreaterEqual: return BO_GE;
1904 case OO_AmpAmp: return BO_LAnd;
1905 case OO_PipePipe: return BO_LOr;
1906 case OO_Comma: return BO_Comma;
1907 case OO_ArrowStar: return BO_PtrMemI;
Douglas Gregor1baf54e2009-03-13 18:40:31 +00001908 }
1909}
1910
1911OverloadedOperatorKind BinaryOperator::getOverloadedOperator(Opcode Opc) {
1912 static const OverloadedOperatorKind OverOps[] = {
1913 /* .* Cannot be overloaded */OO_None, OO_ArrowStar,
1914 OO_Star, OO_Slash, OO_Percent,
1915 OO_Plus, OO_Minus,
1916 OO_LessLess, OO_GreaterGreater,
Richard Smithc70f1d62017-12-14 15:16:18 +00001917 OO_Spaceship,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00001918 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
1919 OO_EqualEqual, OO_ExclaimEqual,
1920 OO_Amp,
1921 OO_Caret,
1922 OO_Pipe,
1923 OO_AmpAmp,
1924 OO_PipePipe,
1925 OO_Equal, OO_StarEqual,
1926 OO_SlashEqual, OO_PercentEqual,
1927 OO_PlusEqual, OO_MinusEqual,
1928 OO_LessLessEqual, OO_GreaterGreaterEqual,
1929 OO_AmpEqual, OO_CaretEqual,
1930 OO_PipeEqual,
1931 OO_Comma
1932 };
1933 return OverOps[Opc];
1934}
1935
Andrew Kaylor3d0a5402017-09-19 20:26:40 +00001936bool BinaryOperator::isNullPointerArithmeticExtension(ASTContext &Ctx,
1937 Opcode Opc,
1938 Expr *LHS, Expr *RHS) {
1939 if (Opc != BO_Add)
1940 return false;
1941
1942 // Check that we have one pointer and one integer operand.
1943 Expr *PExp;
Andrew Kaylor3d0a5402017-09-19 20:26:40 +00001944 if (LHS->getType()->isPointerType()) {
1945 if (!RHS->getType()->isIntegerType())
1946 return false;
1947 PExp = LHS;
Andrew Kaylor3d0a5402017-09-19 20:26:40 +00001948 } else if (RHS->getType()->isPointerType()) {
1949 if (!LHS->getType()->isIntegerType())
1950 return false;
1951 PExp = RHS;
Andrew Kaylor3d0a5402017-09-19 20:26:40 +00001952 } else {
1953 return false;
1954 }
1955
1956 // Check that the pointer is a nullptr.
1957 if (!PExp->IgnoreParenCasts()
1958 ->isNullPointerConstant(Ctx, Expr::NPC_ValueDependentIsNotNull))
1959 return false;
1960
1961 // Check that the pointee type is char-sized.
1962 const PointerType *PTy = PExp->getType()->getAs<PointerType>();
1963 if (!PTy || !PTy->getPointeeType()->isCharType())
1964 return false;
1965
Andrew Kaylor3d0a5402017-09-19 20:26:40 +00001966 return true;
1967}
Craig Topper37932912013-08-18 10:09:15 +00001968InitListExpr::InitListExpr(const ASTContext &C, SourceLocation lbraceloc,
Benjamin Kramerc215e762012-08-24 11:54:20 +00001969 ArrayRef<Expr*> initExprs, SourceLocation rbraceloc)
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001970 : Expr(InitListExprClass, QualType(), VK_RValue, OK_Ordinary, false, false,
1971 false, false),
1972 InitExprs(C, initExprs.size()),
1973 LBraceLoc(lbraceloc), RBraceLoc(rbraceloc), AltForm(nullptr, true)
1974{
Sebastian Redlc83ed822012-02-17 08:42:25 +00001975 sawArrayRangeDesignator(false);
Benjamin Kramerc215e762012-08-24 11:54:20 +00001976 for (unsigned I = 0; I != initExprs.size(); ++I) {
Ted Kremenek013041e2010-02-19 01:50:18 +00001977 if (initExprs[I]->isTypeDependent())
John McCall925b16622010-10-26 08:39:16 +00001978 ExprBits.TypeDependent = true;
Ted Kremenek013041e2010-02-19 01:50:18 +00001979 if (initExprs[I]->isValueDependent())
John McCall925b16622010-10-26 08:39:16 +00001980 ExprBits.ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +00001981 if (initExprs[I]->isInstantiationDependent())
1982 ExprBits.InstantiationDependent = true;
Douglas Gregora6e053e2010-12-15 01:34:56 +00001983 if (initExprs[I]->containsUnexpandedParameterPack())
1984 ExprBits.ContainsUnexpandedParameterPack = true;
Douglas Gregordeebf6e2009-11-19 23:25:22 +00001985 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001986
Benjamin Kramerc215e762012-08-24 11:54:20 +00001987 InitExprs.insert(C, InitExprs.end(), initExprs.begin(), initExprs.end());
Anders Carlsson4692db02007-08-31 04:56:16 +00001988}
Chris Lattner1ec5f562007-06-27 05:38:08 +00001989
Craig Topper37932912013-08-18 10:09:15 +00001990void InitListExpr::reserveInits(const ASTContext &C, unsigned NumInits) {
Ted Kremenek013041e2010-02-19 01:50:18 +00001991 if (NumInits > InitExprs.size())
Ted Kremenekac034612010-04-13 23:39:13 +00001992 InitExprs.reserve(C, NumInits);
Douglas Gregor6d00c992009-03-20 23:58:33 +00001993}
1994
Craig Topper37932912013-08-18 10:09:15 +00001995void InitListExpr::resizeInits(const ASTContext &C, unsigned NumInits) {
Craig Topper36250ad2014-05-12 05:36:57 +00001996 InitExprs.resize(C, NumInits, nullptr);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001997}
1998
Craig Topper37932912013-08-18 10:09:15 +00001999Expr *InitListExpr::updateInit(const ASTContext &C, unsigned Init, Expr *expr) {
Ted Kremenek013041e2010-02-19 01:50:18 +00002000 if (Init >= InitExprs.size()) {
Craig Topper36250ad2014-05-12 05:36:57 +00002001 InitExprs.insert(C, InitExprs.end(), Init - InitExprs.size() + 1, nullptr);
Richard Smithc275da62013-12-06 01:27:24 +00002002 setInit(Init, expr);
Craig Topper36250ad2014-05-12 05:36:57 +00002003 return nullptr;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002004 }
Mike Stump11289f42009-09-09 15:08:12 +00002005
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002006 Expr *Result = cast_or_null<Expr>(InitExprs[Init]);
Richard Smithc275da62013-12-06 01:27:24 +00002007 setInit(Init, expr);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002008 return Result;
2009}
2010
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +00002011void InitListExpr::setArrayFiller(Expr *filler) {
Argyrios Kyrtzidisd4590a5d2011-10-21 23:02:22 +00002012 assert(!hasArrayFiller() && "Filler already set!");
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +00002013 ArrayFillerOrUnionFieldInit = filler;
2014 // Fill out any "holes" in the array due to designated initializers.
2015 Expr **inits = getInits();
2016 for (unsigned i = 0, e = getNumInits(); i != e; ++i)
Craig Topper36250ad2014-05-12 05:36:57 +00002017 if (inits[i] == nullptr)
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +00002018 inits[i] = filler;
2019}
2020
Richard Smith9ec1e482012-04-15 02:50:59 +00002021bool InitListExpr::isStringLiteralInit() const {
2022 if (getNumInits() != 1)
2023 return false;
Eli Friedmancf4ab082012-08-20 20:55:45 +00002024 const ArrayType *AT = getType()->getAsArrayTypeUnsafe();
2025 if (!AT || !AT->getElementType()->isIntegerType())
Richard Smith9ec1e482012-04-15 02:50:59 +00002026 return false;
Ted Kremenek256bd962014-01-19 06:31:34 +00002027 // It is possible for getInit() to return null.
2028 const Expr *Init = getInit(0);
2029 if (!Init)
2030 return false;
2031 Init = Init->IgnoreParens();
Richard Smith9ec1e482012-04-15 02:50:59 +00002032 return isa<StringLiteral>(Init) || isa<ObjCEncodeExpr>(Init);
2033}
2034
Richard Smith122f88d2016-12-06 23:52:28 +00002035bool InitListExpr::isTransparent() const {
2036 assert(isSemanticForm() && "syntactic form never semantically transparent");
2037
2038 // A glvalue InitListExpr is always just sugar.
2039 if (isGLValue()) {
2040 assert(getNumInits() == 1 && "multiple inits in glvalue init list");
2041 return true;
2042 }
2043
2044 // Otherwise, we're sugar if and only if we have exactly one initializer that
2045 // is of the same type.
2046 if (getNumInits() != 1 || !getInit(0))
2047 return false;
2048
Richard Smith382bc512017-02-23 22:41:47 +00002049 // Don't confuse aggregate initialization of a struct X { X &x; }; with a
2050 // transparent struct copy.
2051 if (!getInit(0)->isRValue() && getType()->isRecordType())
2052 return false;
2053
Richard Smith122f88d2016-12-06 23:52:28 +00002054 return getType().getCanonicalType() ==
2055 getInit(0)->getType().getCanonicalType();
2056}
2057
Daniel Marjamaki817a3bf2017-09-29 09:44:41 +00002058bool InitListExpr::isIdiomaticZeroInitializer(const LangOptions &LangOpts) const {
2059 assert(isSyntacticForm() && "only test syntactic form as zero initializer");
2060
2061 if (LangOpts.CPlusPlus || getNumInits() != 1) {
2062 return false;
2063 }
2064
2065 const IntegerLiteral *Lit = dyn_cast<IntegerLiteral>(getInit(0));
2066 return Lit && Lit->getValue() == 0;
2067}
2068
Stephen Kelly724e9e52018-08-09 20:05:03 +00002069SourceLocation InitListExpr::getBeginLoc() const {
Abramo Bagnara8d16bd42012-11-08 18:41:43 +00002070 if (InitListExpr *SyntacticForm = getSyntacticForm())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002071 return SyntacticForm->getBeginLoc();
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002072 SourceLocation Beg = LBraceLoc;
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002073 if (Beg.isInvalid()) {
2074 // Find the first non-null initializer.
2075 for (InitExprsTy::const_iterator I = InitExprs.begin(),
Fangrui Song6907ce22018-07-30 19:24:48 +00002076 E = InitExprs.end();
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002077 I != E; ++I) {
2078 if (Stmt *S = *I) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002079 Beg = S->getBeginLoc();
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002080 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00002081 }
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002082 }
2083 }
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002084 return Beg;
2085}
2086
Stephen Kelly02a67ba2018-08-09 20:05:47 +00002087SourceLocation InitListExpr::getEndLoc() const {
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002088 if (InitListExpr *SyntacticForm = getSyntacticForm())
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002089 return SyntacticForm->getEndLoc();
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002090 SourceLocation End = RBraceLoc;
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002091 if (End.isInvalid()) {
2092 // Find the first non-null initializer from the end.
2093 for (InitExprsTy::const_reverse_iterator I = InitExprs.rbegin(),
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002094 E = InitExprs.rend();
2095 I != E; ++I) {
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002096 if (Stmt *S = *I) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002097 End = S->getEndLoc();
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002098 break;
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002099 }
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002100 }
2101 }
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002102 return End;
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002103}
2104
Steve Naroff991e99d2008-09-04 15:31:07 +00002105/// getFunctionType - Return the underlying function type for this block.
Eugene Zelenkoae304b02017-11-17 18:09:48 +00002106///
John McCallc833dea2012-02-17 03:32:35 +00002107const FunctionProtoType *BlockExpr::getFunctionType() const {
2108 // The block pointer is never sugared, but the function type might be.
2109 return cast<BlockPointerType>(getType())
2110 ->getPointeeType()->castAs<FunctionProtoType>();
Steve Naroffc540d662008-09-03 18:15:37 +00002111}
2112
Mike Stump11289f42009-09-09 15:08:12 +00002113SourceLocation BlockExpr::getCaretLocation() const {
2114 return TheBlock->getCaretLocation();
Steve Naroff415d3d52008-10-08 17:01:13 +00002115}
Mike Stump11289f42009-09-09 15:08:12 +00002116const Stmt *BlockExpr::getBody() const {
Douglas Gregore3dcb2d2009-04-18 00:02:19 +00002117 return TheBlock->getBody();
2118}
Mike Stump11289f42009-09-09 15:08:12 +00002119Stmt *BlockExpr::getBody() {
2120 return TheBlock->getBody();
Douglas Gregore3dcb2d2009-04-18 00:02:19 +00002121}
Steve Naroff415d3d52008-10-08 17:01:13 +00002122
Eugene Zelenkoae304b02017-11-17 18:09:48 +00002123
Chris Lattner1ec5f562007-06-27 05:38:08 +00002124//===----------------------------------------------------------------------===//
2125// Generic Expression Routines
2126//===----------------------------------------------------------------------===//
2127
Chris Lattner237f2752009-02-14 07:37:35 +00002128/// isUnusedResultAWarning - Return true if this immediate expression should
2129/// be warned about if the result is unused. If so, fill in Loc and Ranges
2130/// with location to warn on and the source range[s] to report with the
2131/// warning.
Fangrui Song6907ce22018-07-30 19:24:48 +00002132bool Expr::isUnusedResultAWarning(const Expr *&WarnE, SourceLocation &Loc,
Eli Friedmanc11535c2012-05-24 00:47:05 +00002133 SourceRange &R1, SourceRange &R2,
2134 ASTContext &Ctx) const {
Anders Carlsson789e2cc2009-05-15 23:10:19 +00002135 // Don't warn if the expr is type dependent. The type could end up
2136 // instantiating to void.
2137 if (isTypeDependent())
2138 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002139
Chris Lattner1ec5f562007-06-27 05:38:08 +00002140 switch (getStmtClass()) {
2141 default:
John McCallc493a732010-03-12 07:11:26 +00002142 if (getType()->isVoidType())
2143 return false;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002144 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002145 Loc = getExprLoc();
2146 R1 = getSourceRange();
2147 return true;
Chris Lattner1ec5f562007-06-27 05:38:08 +00002148 case ParenExprClass:
Chris Lattner237f2752009-02-14 07:37:35 +00002149 return cast<ParenExpr>(this)->getSubExpr()->
Eli Friedmanc11535c2012-05-24 00:47:05 +00002150 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00002151 case GenericSelectionExprClass:
2152 return cast<GenericSelectionExpr>(this)->getResultExpr()->
Eli Friedmanc11535c2012-05-24 00:47:05 +00002153 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Eric Fiselier16269a82018-03-27 00:58:16 +00002154 case CoawaitExprClass:
Eric Fiselier855c0922018-03-27 03:33:06 +00002155 case CoyieldExprClass:
2156 return cast<CoroutineSuspendExpr>(this)->getResumeExpr()->
Eric Fiselier16269a82018-03-27 00:58:16 +00002157 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Eli Friedman75807f22013-07-20 00:40:58 +00002158 case ChooseExprClass:
2159 return cast<ChooseExpr>(this)->getChosenSubExpr()->
2160 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Chris Lattner1ec5f562007-06-27 05:38:08 +00002161 case UnaryOperatorClass: {
2162 const UnaryOperator *UO = cast<UnaryOperator>(this);
Mike Stump11289f42009-09-09 15:08:12 +00002163
Chris Lattner1ec5f562007-06-27 05:38:08 +00002164 switch (UO->getOpcode()) {
Eli Friedmanc11535c2012-05-24 00:47:05 +00002165 case UO_Plus:
2166 case UO_Minus:
2167 case UO_AddrOf:
2168 case UO_Not:
2169 case UO_LNot:
2170 case UO_Deref:
2171 break;
Richard Smith9f690bd2015-10-27 06:02:45 +00002172 case UO_Coawait:
2173 // This is just the 'operator co_await' call inside the guts of a
2174 // dependent co_await call.
John McCalle3027922010-08-25 11:45:40 +00002175 case UO_PostInc:
2176 case UO_PostDec:
2177 case UO_PreInc:
2178 case UO_PreDec: // ++/--
Chris Lattner237f2752009-02-14 07:37:35 +00002179 return false; // Not a warning.
John McCalle3027922010-08-25 11:45:40 +00002180 case UO_Real:
2181 case UO_Imag:
Chris Lattnera44d1162007-06-27 05:58:59 +00002182 // accessing a piece of a volatile complex is a side-effect.
Mike Stump53f9ded2009-11-03 23:25:48 +00002183 if (Ctx.getCanonicalType(UO->getSubExpr()->getType())
2184 .isVolatileQualified())
Chris Lattner237f2752009-02-14 07:37:35 +00002185 return false;
2186 break;
John McCalle3027922010-08-25 11:45:40 +00002187 case UO_Extension:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002188 return UO->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Chris Lattner1ec5f562007-06-27 05:38:08 +00002189 }
Eli Friedmanc11535c2012-05-24 00:47:05 +00002190 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002191 Loc = UO->getOperatorLoc();
2192 R1 = UO->getSubExpr()->getSourceRange();
2193 return true;
Chris Lattner1ec5f562007-06-27 05:38:08 +00002194 }
Chris Lattnerae7a8342007-12-01 06:07:34 +00002195 case BinaryOperatorClass: {
Chris Lattner237f2752009-02-14 07:37:35 +00002196 const BinaryOperator *BO = cast<BinaryOperator>(this);
Ted Kremenek43a9c962010-04-07 18:49:21 +00002197 switch (BO->getOpcode()) {
2198 default:
2199 break;
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00002200 // Consider the RHS of comma for side effects. LHS was checked by
2201 // Sema::CheckCommaOperands.
John McCalle3027922010-08-25 11:45:40 +00002202 case BO_Comma:
Ted Kremenek43a9c962010-04-07 18:49:21 +00002203 // ((foo = <blah>), 0) is an idiom for hiding the result (and
2204 // lvalue-ness) of an assignment written in a macro.
2205 if (IntegerLiteral *IE =
2206 dyn_cast<IntegerLiteral>(BO->getRHS()->IgnoreParens()))
2207 if (IE->getValue() == 0)
2208 return false;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002209 return BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00002210 // Consider '||', '&&' to have side effects if the LHS or RHS does.
John McCalle3027922010-08-25 11:45:40 +00002211 case BO_LAnd:
2212 case BO_LOr:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002213 if (!BO->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx) ||
2214 !BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx))
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00002215 return false;
2216 break;
John McCall1e3715a2010-02-16 04:10:53 +00002217 }
Chris Lattner237f2752009-02-14 07:37:35 +00002218 if (BO->isAssignmentOp())
2219 return false;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002220 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002221 Loc = BO->getOperatorLoc();
2222 R1 = BO->getLHS()->getSourceRange();
2223 R2 = BO->getRHS()->getSourceRange();
2224 return true;
Chris Lattnerae7a8342007-12-01 06:07:34 +00002225 }
Chris Lattner86928112007-08-25 02:00:02 +00002226 case CompoundAssignOperatorClass:
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00002227 case VAArgExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002228 case AtomicExprClass:
Chris Lattner237f2752009-02-14 07:37:35 +00002229 return false;
Chris Lattner1ec5f562007-06-27 05:38:08 +00002230
Fariborz Jahanian9fac54d2007-12-01 19:58:28 +00002231 case ConditionalOperatorClass: {
Ted Kremeneke96dad92011-03-01 20:34:48 +00002232 // If only one of the LHS or RHS is a warning, the operator might
2233 // be being used for control flow. Only warn if both the LHS and
2234 // RHS are warnings.
Fariborz Jahanian9fac54d2007-12-01 19:58:28 +00002235 const ConditionalOperator *Exp = cast<ConditionalOperator>(this);
Eli Friedmanc11535c2012-05-24 00:47:05 +00002236 if (!Exp->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx))
Ted Kremeneke96dad92011-03-01 20:34:48 +00002237 return false;
2238 if (!Exp->getLHS())
Chris Lattner237f2752009-02-14 07:37:35 +00002239 return true;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002240 return Exp->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Fariborz Jahanian9fac54d2007-12-01 19:58:28 +00002241 }
2242
Chris Lattnera44d1162007-06-27 05:58:59 +00002243 case MemberExprClass:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002244 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002245 Loc = cast<MemberExpr>(this)->getMemberLoc();
2246 R1 = SourceRange(Loc, Loc);
2247 R2 = cast<MemberExpr>(this)->getBase()->getSourceRange();
2248 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002249
Chris Lattner1ec5f562007-06-27 05:38:08 +00002250 case ArraySubscriptExprClass:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002251 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002252 Loc = cast<ArraySubscriptExpr>(this)->getRBracketLoc();
2253 R1 = cast<ArraySubscriptExpr>(this)->getLHS()->getSourceRange();
2254 R2 = cast<ArraySubscriptExpr>(this)->getRHS()->getSourceRange();
2255 return true;
Eli Friedman824f8c12008-05-27 15:24:04 +00002256
Chandler Carruth46339472011-08-17 09:49:44 +00002257 case CXXOperatorCallExprClass: {
Richard Trieu99e1c952014-03-11 03:11:08 +00002258 // Warn about operator ==,!=,<,>,<=, and >= even when user-defined operator
Chandler Carruth46339472011-08-17 09:49:44 +00002259 // overloads as there is no reasonable way to define these such that they
2260 // have non-trivial, desirable side-effects. See the -Wunused-comparison
Richard Trieu99e1c952014-03-11 03:11:08 +00002261 // warning: operators == and != are commonly typo'ed, and so warning on them
Chandler Carruth46339472011-08-17 09:49:44 +00002262 // provides additional value as well. If this list is updated,
2263 // DiagnoseUnusedComparison should be as well.
2264 const CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(this);
Richard Trieu99e1c952014-03-11 03:11:08 +00002265 switch (Op->getOperator()) {
2266 default:
2267 break;
2268 case OO_EqualEqual:
2269 case OO_ExclaimEqual:
2270 case OO_Less:
2271 case OO_Greater:
2272 case OO_GreaterEqual:
2273 case OO_LessEqual:
David Majnemerced8bdf2015-02-25 17:36:15 +00002274 if (Op->getCallReturnType(Ctx)->isReferenceType() ||
2275 Op->getCallReturnType(Ctx)->isVoidType())
Richard Trieu161132b2014-05-14 23:22:10 +00002276 break;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002277 WarnE = this;
Matt Beaumont-Gaydcaacaa2011-09-19 18:51:20 +00002278 Loc = Op->getOperatorLoc();
2279 R1 = Op->getSourceRange();
Chandler Carruth46339472011-08-17 09:49:44 +00002280 return true;
Matt Beaumont-Gaydcaacaa2011-09-19 18:51:20 +00002281 }
Chandler Carruth46339472011-08-17 09:49:44 +00002282
2283 // Fallthrough for generic call handling.
Galina Kistanovaf87496d2017-06-03 06:31:42 +00002284 LLVM_FALLTHROUGH;
Chandler Carruth46339472011-08-17 09:49:44 +00002285 }
Chris Lattner1ec5f562007-06-27 05:38:08 +00002286 case CallExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00002287 case CXXMemberCallExprClass:
2288 case UserDefinedLiteralClass: {
Chris Lattner237f2752009-02-14 07:37:35 +00002289 // If this is a direct call, get the callee.
2290 const CallExpr *CE = cast<CallExpr>(this);
Nuno Lopes518e3702009-12-20 23:11:08 +00002291 if (const Decl *FD = CE->getCalleeDecl()) {
Kaelyn Takata0a2e84c2015-04-09 19:43:04 +00002292 const FunctionDecl *Func = dyn_cast<FunctionDecl>(FD);
2293 bool HasWarnUnusedResultAttr = Func ? Func->hasUnusedResultAttr()
2294 : FD->hasAttr<WarnUnusedResultAttr>();
2295
Chris Lattner237f2752009-02-14 07:37:35 +00002296 // If the callee has attribute pure, const, or warn_unused_result, warn
2297 // about it. void foo() { strlen("bar"); } should warn.
Chris Lattner1a6babf2009-10-13 04:53:48 +00002298 //
2299 // Note: If new cases are added here, DiagnoseUnusedExprResult should be
2300 // updated to match for QoI.
Kaelyn Takata0a2e84c2015-04-09 19:43:04 +00002301 if (HasWarnUnusedResultAttr ||
Aaron Ballman9ead1242013-12-19 02:39:40 +00002302 FD->hasAttr<PureAttr>() || FD->hasAttr<ConstAttr>()) {
Eli Friedmanc11535c2012-05-24 00:47:05 +00002303 WarnE = this;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002304 Loc = CE->getCallee()->getBeginLoc();
Chris Lattner1a6babf2009-10-13 04:53:48 +00002305 R1 = CE->getCallee()->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002306
Chris Lattner1a6babf2009-10-13 04:53:48 +00002307 if (unsigned NumArgs = CE->getNumArgs())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002308 R2 = SourceRange(CE->getArg(0)->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002309 CE->getArg(NumArgs - 1)->getEndLoc());
Chris Lattner1a6babf2009-10-13 04:53:48 +00002310 return true;
2311 }
Chris Lattner237f2752009-02-14 07:37:35 +00002312 }
2313 return false;
2314 }
Anders Carlsson6aa50392009-11-17 17:11:23 +00002315
Matt Beaumont-Gayabf836c2012-10-23 06:15:26 +00002316 // If we don't know precisely what we're looking at, let's not warn.
2317 case UnresolvedLookupExprClass:
2318 case CXXUnresolvedConstructExprClass:
2319 return false;
2320
Anders Carlsson6aa50392009-11-17 17:11:23 +00002321 case CXXTemporaryObjectExprClass:
Eugene Zelenkoae304b02017-11-17 18:09:48 +00002322 case CXXConstructExprClass: {
Lubos Lunak1f490f32013-07-21 13:15:58 +00002323 if (const CXXRecordDecl *Type = getType()->getAsCXXRecordDecl()) {
2324 if (Type->hasAttr<WarnUnusedAttr>()) {
2325 WarnE = this;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002326 Loc = getBeginLoc();
Lubos Lunak1f490f32013-07-21 13:15:58 +00002327 R1 = getSourceRange();
2328 return true;
2329 }
2330 }
Anders Carlsson6aa50392009-11-17 17:11:23 +00002331 return false;
Eugene Zelenkoae304b02017-11-17 18:09:48 +00002332 }
Anders Carlsson6aa50392009-11-17 17:11:23 +00002333
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +00002334 case ObjCMessageExprClass: {
2335 const ObjCMessageExpr *ME = cast<ObjCMessageExpr>(this);
David Blaikiebbafb8a2012-03-11 07:00:24 +00002336 if (Ctx.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00002337 ME->isInstanceMessage() &&
2338 !ME->getType()->isVoidType() &&
Jean-Daniel Dupas06028a52013-07-19 20:25:56 +00002339 ME->getMethodFamily() == OMF_init) {
Eli Friedmanc11535c2012-05-24 00:47:05 +00002340 WarnE = this;
John McCall31168b02011-06-15 23:02:42 +00002341 Loc = getExprLoc();
2342 R1 = ME->getSourceRange();
2343 return true;
2344 }
2345
Fariborz Jahanianac6b4ef2014-07-18 22:59:10 +00002346 if (const ObjCMethodDecl *MD = ME->getMethodDecl())
Fariborz Jahanianb0553e22015-02-16 23:49:44 +00002347 if (MD->hasAttr<WarnUnusedResultAttr>()) {
Fariborz Jahanianac6b4ef2014-07-18 22:59:10 +00002348 WarnE = this;
2349 Loc = getExprLoc();
2350 return true;
2351 }
2352
Chris Lattner237f2752009-02-14 07:37:35 +00002353 return false;
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +00002354 }
Mike Stump11289f42009-09-09 15:08:12 +00002355
John McCallb7bd14f2010-12-02 01:19:52 +00002356 case ObjCPropertyRefExprClass:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002357 WarnE = this;
Chris Lattnerd37f61c2009-08-16 16:51:50 +00002358 Loc = getExprLoc();
2359 R1 = getSourceRange();
Chris Lattnerd8b800a2009-08-16 16:45:18 +00002360 return true;
John McCallb7bd14f2010-12-02 01:19:52 +00002361
John McCallfe96e0b2011-11-06 09:01:30 +00002362 case PseudoObjectExprClass: {
2363 const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this);
2364
2365 // Only complain about things that have the form of a getter.
2366 if (isa<UnaryOperator>(PO->getSyntacticForm()) ||
2367 isa<BinaryOperator>(PO->getSyntacticForm()))
2368 return false;
2369
Eli Friedmanc11535c2012-05-24 00:47:05 +00002370 WarnE = this;
John McCallfe96e0b2011-11-06 09:01:30 +00002371 Loc = getExprLoc();
2372 R1 = getSourceRange();
2373 return true;
2374 }
2375
Chris Lattner944d3062008-07-26 19:51:01 +00002376 case StmtExprClass: {
2377 // Statement exprs don't logically have side effects themselves, but are
2378 // sometimes used in macros in ways that give them a type that is unused.
2379 // For example ({ blah; foo(); }) will end up with a type if foo has a type.
2380 // however, if the result of the stmt expr is dead, we don't want to emit a
2381 // warning.
2382 const CompoundStmt *CS = cast<StmtExpr>(this)->getSubStmt();
Argyrios Kyrtzidis90963412010-09-19 21:21:10 +00002383 if (!CS->body_empty()) {
Chris Lattner944d3062008-07-26 19:51:01 +00002384 if (const Expr *E = dyn_cast<Expr>(CS->body_back()))
Eli Friedmanc11535c2012-05-24 00:47:05 +00002385 return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Argyrios Kyrtzidis90963412010-09-19 21:21:10 +00002386 if (const LabelStmt *Label = dyn_cast<LabelStmt>(CS->body_back()))
2387 if (const Expr *E = dyn_cast<Expr>(Label->getSubStmt()))
Eli Friedmanc11535c2012-05-24 00:47:05 +00002388 return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Argyrios Kyrtzidis90963412010-09-19 21:21:10 +00002389 }
Mike Stump11289f42009-09-09 15:08:12 +00002390
John McCallc493a732010-03-12 07:11:26 +00002391 if (getType()->isVoidType())
2392 return false;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002393 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002394 Loc = cast<StmtExpr>(this)->getLParenLoc();
2395 R1 = getSourceRange();
2396 return true;
Chris Lattner944d3062008-07-26 19:51:01 +00002397 }
Eli Friedmanbdd57532012-09-24 23:02:26 +00002398 case CXXFunctionalCastExprClass:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002399 case CStyleCastExprClass: {
Eli Friedmanf92f6452012-05-24 21:05:41 +00002400 // Ignore an explicit cast to void unless the operand is a non-trivial
Eli Friedmanc11535c2012-05-24 00:47:05 +00002401 // volatile lvalue.
Eli Friedmanf92f6452012-05-24 21:05:41 +00002402 const CastExpr *CE = cast<CastExpr>(this);
Eli Friedmanc11535c2012-05-24 00:47:05 +00002403 if (CE->getCastKind() == CK_ToVoid) {
2404 if (CE->getSubExpr()->isGLValue() &&
Eli Friedmanf92f6452012-05-24 21:05:41 +00002405 CE->getSubExpr()->getType().isVolatileQualified()) {
2406 const DeclRefExpr *DRE =
2407 dyn_cast<DeclRefExpr>(CE->getSubExpr()->IgnoreParens());
2408 if (!(DRE && isa<VarDecl>(DRE->getDecl()) &&
Erich Keane80b0fb02017-10-19 15:58:58 +00002409 cast<VarDecl>(DRE->getDecl())->hasLocalStorage()) &&
2410 !isa<CallExpr>(CE->getSubExpr()->IgnoreParens())) {
Eli Friedmanf92f6452012-05-24 21:05:41 +00002411 return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc,
2412 R1, R2, Ctx);
2413 }
2414 }
Chris Lattner2706a552009-07-28 18:25:28 +00002415 return false;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002416 }
Eli Friedmanf92f6452012-05-24 21:05:41 +00002417
Eli Friedmanc11535c2012-05-24 00:47:05 +00002418 // If this is a cast to a constructor conversion, check the operand.
Anders Carlsson6aa50392009-11-17 17:11:23 +00002419 // Otherwise, the result of the cast is unused.
Eli Friedmanc11535c2012-05-24 00:47:05 +00002420 if (CE->getCastKind() == CK_ConstructorConversion)
2421 return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Eli Friedmanf92f6452012-05-24 21:05:41 +00002422
Eli Friedmanc11535c2012-05-24 00:47:05 +00002423 WarnE = this;
Eli Friedmanf92f6452012-05-24 21:05:41 +00002424 if (const CXXFunctionalCastExpr *CXXCE =
2425 dyn_cast<CXXFunctionalCastExpr>(this)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002426 Loc = CXXCE->getBeginLoc();
Eli Friedmanf92f6452012-05-24 21:05:41 +00002427 R1 = CXXCE->getSubExpr()->getSourceRange();
2428 } else {
2429 const CStyleCastExpr *CStyleCE = cast<CStyleCastExpr>(this);
2430 Loc = CStyleCE->getLParenLoc();
2431 R1 = CStyleCE->getSubExpr()->getSourceRange();
2432 }
Chris Lattner237f2752009-02-14 07:37:35 +00002433 return true;
Anders Carlsson6aa50392009-11-17 17:11:23 +00002434 }
Eli Friedmanc11535c2012-05-24 00:47:05 +00002435 case ImplicitCastExprClass: {
2436 const CastExpr *ICE = cast<ImplicitCastExpr>(this);
Eli Friedmanca8da1d2008-05-19 21:24:43 +00002437
Eli Friedmanc11535c2012-05-24 00:47:05 +00002438 // lvalue-to-rvalue conversion on a volatile lvalue is a side-effect.
2439 if (ICE->getCastKind() == CK_LValueToRValue &&
2440 ICE->getSubExpr()->getType().isVolatileQualified())
2441 return false;
2442
2443 return ICE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2444 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002445 case CXXDefaultArgExprClass:
Mike Stump53f9ded2009-11-03 23:25:48 +00002446 return (cast<CXXDefaultArgExpr>(this)
Eli Friedmanc11535c2012-05-24 00:47:05 +00002447 ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
Richard Smith852c9db2013-04-20 22:23:05 +00002448 case CXXDefaultInitExprClass:
2449 return (cast<CXXDefaultInitExpr>(this)
2450 ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
Sebastian Redlbd150f42008-11-21 19:14:01 +00002451
2452 case CXXNewExprClass:
2453 // FIXME: In theory, there might be new expressions that don't have side
2454 // effects (e.g. a placement new with an uninitialized POD).
2455 case CXXDeleteExprClass:
Chris Lattner237f2752009-02-14 07:37:35 +00002456 return false;
Richard Smith122f88d2016-12-06 23:52:28 +00002457 case MaterializeTemporaryExprClass:
2458 return cast<MaterializeTemporaryExpr>(this)->GetTemporaryExpr()
2459 ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Anders Carlssone80ccac2009-08-16 04:11:06 +00002460 case CXXBindTemporaryExprClass:
Richard Smith122f88d2016-12-06 23:52:28 +00002461 return cast<CXXBindTemporaryExpr>(this)->getSubExpr()
2462 ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
John McCall5d413782010-12-06 08:20:24 +00002463 case ExprWithCleanupsClass:
Richard Smith122f88d2016-12-06 23:52:28 +00002464 return cast<ExprWithCleanups>(this)->getSubExpr()
2465 ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Sebastian Redlbd150f42008-11-21 19:14:01 +00002466 }
Chris Lattner1ec5f562007-06-27 05:38:08 +00002467}
2468
Fariborz Jahanian07735332009-02-22 18:40:18 +00002469/// isOBJCGCCandidate - Check if an expression is objc gc'able.
Fariborz Jahanian063c7722009-09-08 23:38:54 +00002470/// returns true, if it is; false otherwise.
Fariborz Jahanianc6d98002009-06-01 21:29:32 +00002471bool Expr::isOBJCGCCandidate(ASTContext &Ctx) const {
Peter Collingbourne91147592011-04-15 00:35:48 +00002472 const Expr *E = IgnoreParens();
2473 switch (E->getStmtClass()) {
Fariborz Jahanian07735332009-02-22 18:40:18 +00002474 default:
2475 return false;
2476 case ObjCIvarRefExprClass:
2477 return true;
Fariborz Jahanian392124c2009-02-23 18:59:50 +00002478 case Expr::UnaryOperatorClass:
Peter Collingbourne91147592011-04-15 00:35:48 +00002479 return cast<UnaryOperator>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
Fariborz Jahanian07735332009-02-22 18:40:18 +00002480 case ImplicitCastExprClass:
Peter Collingbourne91147592011-04-15 00:35:48 +00002481 return cast<ImplicitCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
Douglas Gregorfe314812011-06-21 17:03:29 +00002482 case MaterializeTemporaryExprClass:
2483 return cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr()
2484 ->isOBJCGCCandidate(Ctx);
Fariborz Jahaniana16904b2009-05-05 23:28:21 +00002485 case CStyleCastExprClass:
Peter Collingbourne91147592011-04-15 00:35:48 +00002486 return cast<CStyleCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002487 case DeclRefExprClass: {
John McCall113bee02012-03-10 09:33:50 +00002488 const Decl *D = cast<DeclRefExpr>(E)->getDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +00002489
Fariborz Jahanianc6d98002009-06-01 21:29:32 +00002490 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2491 if (VD->hasGlobalStorage())
2492 return true;
2493 QualType T = VD->getType();
Fariborz Jahaniancceedbf2009-09-16 18:09:18 +00002494 // dereferencing to a pointer is always a gc'able candidate,
2495 // unless it is __weak.
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00002496 return T->isPointerType() &&
John McCall8ccfcb52009-09-24 19:53:00 +00002497 (Ctx.getObjCGCAttrKind(T) != Qualifiers::Weak);
Fariborz Jahanianc6d98002009-06-01 21:29:32 +00002498 }
Fariborz Jahanian07735332009-02-22 18:40:18 +00002499 return false;
2500 }
Douglas Gregorf405d7e2009-08-31 23:41:50 +00002501 case MemberExprClass: {
Peter Collingbourne91147592011-04-15 00:35:48 +00002502 const MemberExpr *M = cast<MemberExpr>(E);
Fariborz Jahanianc6d98002009-06-01 21:29:32 +00002503 return M->getBase()->isOBJCGCCandidate(Ctx);
Fariborz Jahanian07735332009-02-22 18:40:18 +00002504 }
2505 case ArraySubscriptExprClass:
Peter Collingbourne91147592011-04-15 00:35:48 +00002506 return cast<ArraySubscriptExpr>(E)->getBase()->isOBJCGCCandidate(Ctx);
Fariborz Jahanian07735332009-02-22 18:40:18 +00002507 }
2508}
Sebastian Redlce354af2010-09-10 20:55:33 +00002509
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +00002510bool Expr::isBoundMemberFunction(ASTContext &Ctx) const {
2511 if (isTypeDependent())
2512 return false;
John McCall086a4642010-11-24 05:12:34 +00002513 return ClassifyLValue(Ctx) == Expr::LV_MemberFunction;
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +00002514}
2515
John McCall0009fcc2011-04-26 20:42:42 +00002516QualType Expr::findBoundMemberType(const Expr *expr) {
John McCalle314e272011-10-18 21:02:43 +00002517 assert(expr->hasPlaceholderType(BuiltinType::BoundMember));
John McCall0009fcc2011-04-26 20:42:42 +00002518
2519 // Bound member expressions are always one of these possibilities:
2520 // x->m x.m x->*y x.*y
2521 // (possibly parenthesized)
2522
2523 expr = expr->IgnoreParens();
2524 if (const MemberExpr *mem = dyn_cast<MemberExpr>(expr)) {
2525 assert(isa<CXXMethodDecl>(mem->getMemberDecl()));
2526 return mem->getMemberDecl()->getType();
2527 }
2528
2529 if (const BinaryOperator *op = dyn_cast<BinaryOperator>(expr)) {
2530 QualType type = op->getRHS()->getType()->castAs<MemberPointerType>()
2531 ->getPointeeType();
2532 assert(type->isFunctionType());
2533 return type;
2534 }
2535
David Majnemerced8bdf2015-02-25 17:36:15 +00002536 assert(isa<UnresolvedMemberExpr>(expr) || isa<CXXPseudoDestructorExpr>(expr));
John McCall0009fcc2011-04-26 20:42:42 +00002537 return QualType();
2538}
2539
Ted Kremenekfff70962008-01-17 16:57:34 +00002540Expr* Expr::IgnoreParens() {
2541 Expr* E = this;
Abramo Bagnara932e3932010-10-15 07:51:18 +00002542 while (true) {
2543 if (ParenExpr* P = dyn_cast<ParenExpr>(E)) {
2544 E = P->getSubExpr();
2545 continue;
2546 }
2547 if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) {
2548 if (P->getOpcode() == UO_Extension) {
2549 E = P->getSubExpr();
2550 continue;
2551 }
2552 }
Peter Collingbourne91147592011-04-15 00:35:48 +00002553 if (GenericSelectionExpr* P = dyn_cast<GenericSelectionExpr>(E)) {
2554 if (!P->isResultDependent()) {
2555 E = P->getResultExpr();
2556 continue;
2557 }
2558 }
Eli Friedman75807f22013-07-20 00:40:58 +00002559 if (ChooseExpr* P = dyn_cast<ChooseExpr>(E)) {
2560 if (!P->isConditionDependent()) {
2561 E = P->getChosenSubExpr();
2562 continue;
2563 }
2564 }
Abramo Bagnara932e3932010-10-15 07:51:18 +00002565 return E;
2566 }
Ted Kremenekfff70962008-01-17 16:57:34 +00002567}
2568
Chris Lattnerf2660962008-02-13 01:02:39 +00002569/// IgnoreParenCasts - Ignore parentheses and casts. Strip off any ParenExpr
2570/// or CastExprs or ImplicitCastExprs, returning their operand.
2571Expr *Expr::IgnoreParenCasts() {
2572 Expr *E = this;
2573 while (true) {
Eli Friedman75807f22013-07-20 00:40:58 +00002574 E = E->IgnoreParens();
Abramo Bagnara932e3932010-10-15 07:51:18 +00002575 if (CastExpr *P = dyn_cast<CastExpr>(E)) {
Chris Lattnerf2660962008-02-13 01:02:39 +00002576 E = P->getSubExpr();
Abramo Bagnara932e3932010-10-15 07:51:18 +00002577 continue;
2578 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002579 if (MaterializeTemporaryExpr *Materialize
Douglas Gregorfe314812011-06-21 17:03:29 +00002580 = dyn_cast<MaterializeTemporaryExpr>(E)) {
2581 E = Materialize->GetTemporaryExpr();
2582 continue;
2583 }
Douglas Gregor6a40b082011-09-08 17:56:33 +00002584 if (SubstNonTypeTemplateParmExpr *NTTP
2585 = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2586 E = NTTP->getReplacement();
2587 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +00002588 }
Fangrui Song407659a2018-11-30 23:41:18 +00002589 if (FullExpr *FE = dyn_cast<FullExpr>(E)) {
2590 E = FE->getSubExpr();
Bill Wendling8003edc2018-11-09 00:41:36 +00002591 continue;
2592 }
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 }
Fangrui Song407659a2018-11-30 23:41:18 +00002614 if (FullExpr *FE = dyn_cast<FullExpr>(E)) {
2615 E = FE->getSubExpr();
Bill Wendling8003edc2018-11-09 00:41:36 +00002616 continue;
2617 }
Ted Kremenek6f375e52014-04-16 07:26:09 +00002618 return E;
2619 }
2620}
2621
John McCall5a4ce8b2010-12-04 08:24:19 +00002622/// IgnoreParenLValueCasts - Ignore parentheses and lvalue-to-rvalue
2623/// casts. This is intended purely as a temporary workaround for code
2624/// that hasn't yet been rewritten to do the right thing about those
2625/// casts, and may disappear along with the last internal use.
John McCall34376a62010-12-04 03:47:34 +00002626Expr *Expr::IgnoreParenLValueCasts() {
2627 Expr *E = this;
John McCall5a4ce8b2010-12-04 08:24:19 +00002628 while (true) {
Eli Friedman75807f22013-07-20 00:40:58 +00002629 E = E->IgnoreParens();
2630 if (CastExpr *P = dyn_cast<CastExpr>(E)) {
John McCall34376a62010-12-04 03:47:34 +00002631 if (P->getCastKind() == CK_LValueToRValue) {
2632 E = P->getSubExpr();
2633 continue;
2634 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002635 } else if (MaterializeTemporaryExpr *Materialize
Douglas Gregorfe314812011-06-21 17:03:29 +00002636 = dyn_cast<MaterializeTemporaryExpr>(E)) {
2637 E = Materialize->GetTemporaryExpr();
2638 continue;
Douglas Gregor6a40b082011-09-08 17:56:33 +00002639 } else if (SubstNonTypeTemplateParmExpr *NTTP
2640 = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2641 E = NTTP->getReplacement();
2642 continue;
Fangrui Song407659a2018-11-30 23:41:18 +00002643 } else if (FullExpr *FE = dyn_cast<FullExpr>(E)) {
2644 E = FE->getSubExpr();
Bill Wendling8003edc2018-11-09 00:41:36 +00002645 continue;
John McCall34376a62010-12-04 03:47:34 +00002646 }
2647 break;
2648 }
2649 return E;
2650}
Rafael Espindolaecbe2e92012-06-28 01:56:38 +00002651
2652Expr *Expr::ignoreParenBaseCasts() {
2653 Expr *E = this;
2654 while (true) {
Eli Friedman75807f22013-07-20 00:40:58 +00002655 E = E->IgnoreParens();
Rafael Espindolaecbe2e92012-06-28 01:56:38 +00002656 if (CastExpr *CE = dyn_cast<CastExpr>(E)) {
2657 if (CE->getCastKind() == CK_DerivedToBase ||
2658 CE->getCastKind() == CK_UncheckedDerivedToBase ||
2659 CE->getCastKind() == CK_NoOp) {
2660 E = CE->getSubExpr();
2661 continue;
2662 }
2663 }
2664
2665 return E;
2666 }
2667}
2668
John McCalleebc8322010-05-05 22:59:52 +00002669Expr *Expr::IgnoreParenImpCasts() {
2670 Expr *E = this;
2671 while (true) {
Eli Friedman75807f22013-07-20 00:40:58 +00002672 E = E->IgnoreParens();
Abramo Bagnara932e3932010-10-15 07:51:18 +00002673 if (ImplicitCastExpr *P = dyn_cast<ImplicitCastExpr>(E)) {
John McCalleebc8322010-05-05 22:59:52 +00002674 E = P->getSubExpr();
Abramo Bagnara932e3932010-10-15 07:51:18 +00002675 continue;
2676 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002677 if (MaterializeTemporaryExpr *Materialize
Douglas Gregorfe314812011-06-21 17:03:29 +00002678 = dyn_cast<MaterializeTemporaryExpr>(E)) {
2679 E = Materialize->GetTemporaryExpr();
2680 continue;
2681 }
Douglas Gregor6a40b082011-09-08 17:56:33 +00002682 if (SubstNonTypeTemplateParmExpr *NTTP
2683 = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2684 E = NTTP->getReplacement();
2685 continue;
2686 }
Bill Wendling8003edc2018-11-09 00:41:36 +00002687 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(E)) {
2688 E = CE->getSubExpr();
2689 continue;
2690 }
Abramo Bagnara932e3932010-10-15 07:51:18 +00002691 return E;
John McCalleebc8322010-05-05 22:59:52 +00002692 }
2693}
2694
Hans Wennborgde2e67e2011-06-09 17:06:51 +00002695Expr *Expr::IgnoreConversionOperator() {
2696 if (CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(this)) {
Chandler Carruth4352b0b2011-06-21 17:22:09 +00002697 if (MCE->getMethodDecl() && isa<CXXConversionDecl>(MCE->getMethodDecl()))
Hans Wennborgde2e67e2011-06-09 17:06:51 +00002698 return MCE->getImplicitObjectArgument();
2699 }
2700 return this;
2701}
2702
Chris Lattneref26c772009-03-13 17:28:01 +00002703/// IgnoreParenNoopCasts - Ignore parentheses and casts that do not change the
2704/// value (including ptr->int casts of the same size). Strip off any
2705/// ParenExpr or CastExprs, returning their operand.
2706Expr *Expr::IgnoreParenNoopCasts(ASTContext &Ctx) {
2707 Expr *E = this;
2708 while (true) {
Eli Friedman75807f22013-07-20 00:40:58 +00002709 E = E->IgnoreParens();
Mike Stump11289f42009-09-09 15:08:12 +00002710
Chris Lattneref26c772009-03-13 17:28:01 +00002711 if (CastExpr *P = dyn_cast<CastExpr>(E)) {
2712 // We ignore integer <-> casts that are of the same width, ptr<->ptr and
Douglas Gregorb90df602010-06-16 00:17:44 +00002713 // ptr<->int casts of the same width. We also ignore all identity casts.
Chris Lattneref26c772009-03-13 17:28:01 +00002714 Expr *SE = P->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002715
Chris Lattneref26c772009-03-13 17:28:01 +00002716 if (Ctx.hasSameUnqualifiedType(E->getType(), SE->getType())) {
2717 E = SE;
2718 continue;
2719 }
Mike Stump11289f42009-09-09 15:08:12 +00002720
Abramo Bagnara932e3932010-10-15 07:51:18 +00002721 if ((E->getType()->isPointerType() ||
Douglas Gregor6972a622010-06-16 00:35:25 +00002722 E->getType()->isIntegralType(Ctx)) &&
Abramo Bagnara932e3932010-10-15 07:51:18 +00002723 (SE->getType()->isPointerType() ||
Douglas Gregor6972a622010-06-16 00:35:25 +00002724 SE->getType()->isIntegralType(Ctx)) &&
Chris Lattneref26c772009-03-13 17:28:01 +00002725 Ctx.getTypeSize(E->getType()) == Ctx.getTypeSize(SE->getType())) {
2726 E = SE;
2727 continue;
2728 }
2729 }
Mike Stump11289f42009-09-09 15:08:12 +00002730
Douglas Gregor6a40b082011-09-08 17:56:33 +00002731 if (SubstNonTypeTemplateParmExpr *NTTP
2732 = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2733 E = NTTP->getReplacement();
2734 continue;
2735 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002736
Chris Lattneref26c772009-03-13 17:28:01 +00002737 return E;
2738 }
2739}
2740
Douglas Gregord196a582009-12-14 19:27:10 +00002741bool Expr::isDefaultArgument() const {
2742 const Expr *E = this;
Douglas Gregorfe314812011-06-21 17:03:29 +00002743 if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
2744 E = M->GetTemporaryExpr();
2745
Douglas Gregord196a582009-12-14 19:27:10 +00002746 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
2747 E = ICE->getSubExprAsWritten();
Fangrui Song6907ce22018-07-30 19:24:48 +00002748
Douglas Gregord196a582009-12-14 19:27:10 +00002749 return isa<CXXDefaultArgExpr>(E);
2750}
Chris Lattneref26c772009-03-13 17:28:01 +00002751
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002752/// Skip over any no-op casts and any temporary-binding
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002753/// expressions.
Anders Carlsson66bbf502010-11-28 16:40:49 +00002754static const Expr *skipTemporaryBindingsNoOpCastsAndParens(const Expr *E) {
Douglas Gregorfe314812011-06-21 17:03:29 +00002755 if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
2756 E = M->GetTemporaryExpr();
2757
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002758 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCalle3027922010-08-25 11:45:40 +00002759 if (ICE->getCastKind() == CK_NoOp)
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002760 E = ICE->getSubExpr();
2761 else
2762 break;
2763 }
2764
2765 while (const CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
2766 E = BE->getSubExpr();
2767
2768 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCalle3027922010-08-25 11:45:40 +00002769 if (ICE->getCastKind() == CK_NoOp)
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002770 E = ICE->getSubExpr();
2771 else
2772 break;
2773 }
Anders Carlsson66bbf502010-11-28 16:40:49 +00002774
2775 return E->IgnoreParens();
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002776}
2777
John McCall7a626f62010-09-15 10:14:12 +00002778/// isTemporaryObject - Determines if this expression produces a
2779/// temporary of the given class type.
2780bool Expr::isTemporaryObject(ASTContext &C, const CXXRecordDecl *TempTy) const {
2781 if (!C.hasSameUnqualifiedType(getType(), C.getTypeDeclType(TempTy)))
2782 return false;
2783
Anders Carlsson66bbf502010-11-28 16:40:49 +00002784 const Expr *E = skipTemporaryBindingsNoOpCastsAndParens(this);
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002785
John McCall02dc8c72010-09-15 20:59:13 +00002786 // Temporaries are by definition pr-values of class type.
Fariborz Jahanian30e8d582010-09-27 17:30:38 +00002787 if (!E->Classify(C).isPRValue()) {
2788 // In this context, property reference is a message call and is pr-value.
John McCallb7bd14f2010-12-02 01:19:52 +00002789 if (!isa<ObjCPropertyRefExpr>(E))
Fariborz Jahanian30e8d582010-09-27 17:30:38 +00002790 return false;
2791 }
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002792
John McCallf4ee1dd2010-09-16 06:57:56 +00002793 // Black-list a few cases which yield pr-values of class type that don't
2794 // refer to temporaries of that type:
2795
2796 // - implicit derived-to-base conversions
John McCall7a626f62010-09-15 10:14:12 +00002797 if (isa<ImplicitCastExpr>(E)) {
2798 switch (cast<ImplicitCastExpr>(E)->getCastKind()) {
2799 case CK_DerivedToBase:
2800 case CK_UncheckedDerivedToBase:
2801 return false;
2802 default:
2803 break;
2804 }
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002805 }
2806
John McCallf4ee1dd2010-09-16 06:57:56 +00002807 // - member expressions (all)
2808 if (isa<MemberExpr>(E))
2809 return false;
2810
Eli Friedman13ffdd82012-06-15 23:51:06 +00002811 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E))
2812 if (BO->isPtrMemOp())
2813 return false;
2814
John McCallc07a0c72011-02-17 10:25:35 +00002815 // - opaque values (all)
2816 if (isa<OpaqueValueExpr>(E))
2817 return false;
2818
John McCall7a626f62010-09-15 10:14:12 +00002819 return true;
Douglas Gregor45cf7e32010-04-02 18:24:57 +00002820}
2821
Douglas Gregor25b7e052011-03-02 21:06:53 +00002822bool Expr::isImplicitCXXThis() const {
2823 const Expr *E = this;
Fangrui Song6907ce22018-07-30 19:24:48 +00002824
Douglas Gregor25b7e052011-03-02 21:06:53 +00002825 // Strip away parentheses and casts we don't care about.
2826 while (true) {
2827 if (const ParenExpr *Paren = dyn_cast<ParenExpr>(E)) {
2828 E = Paren->getSubExpr();
2829 continue;
2830 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002831
Douglas Gregor25b7e052011-03-02 21:06:53 +00002832 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2833 if (ICE->getCastKind() == CK_NoOp ||
2834 ICE->getCastKind() == CK_LValueToRValue ||
Fangrui Song6907ce22018-07-30 19:24:48 +00002835 ICE->getCastKind() == CK_DerivedToBase ||
Douglas Gregor25b7e052011-03-02 21:06:53 +00002836 ICE->getCastKind() == CK_UncheckedDerivedToBase) {
2837 E = ICE->getSubExpr();
2838 continue;
2839 }
2840 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002841
Douglas Gregor25b7e052011-03-02 21:06:53 +00002842 if (const UnaryOperator* UnOp = dyn_cast<UnaryOperator>(E)) {
2843 if (UnOp->getOpcode() == UO_Extension) {
2844 E = UnOp->getSubExpr();
2845 continue;
2846 }
2847 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002848
Douglas Gregorfe314812011-06-21 17:03:29 +00002849 if (const MaterializeTemporaryExpr *M
2850 = dyn_cast<MaterializeTemporaryExpr>(E)) {
2851 E = M->GetTemporaryExpr();
2852 continue;
2853 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002854
Douglas Gregor25b7e052011-03-02 21:06:53 +00002855 break;
2856 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002857
Douglas Gregor25b7e052011-03-02 21:06:53 +00002858 if (const CXXThisExpr *This = dyn_cast<CXXThisExpr>(E))
2859 return This->isImplicit();
Fangrui Song6907ce22018-07-30 19:24:48 +00002860
Douglas Gregor25b7e052011-03-02 21:06:53 +00002861 return false;
2862}
2863
Douglas Gregor4619e432008-12-05 23:32:09 +00002864/// hasAnyTypeDependentArguments - Determines if any of the expressions
2865/// in Exprs is type-dependent.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002866bool Expr::hasAnyTypeDependentArguments(ArrayRef<Expr *> Exprs) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002867 for (unsigned I = 0; I < Exprs.size(); ++I)
Douglas Gregor4619e432008-12-05 23:32:09 +00002868 if (Exprs[I]->isTypeDependent())
2869 return true;
2870
2871 return false;
2872}
2873
Abramo Bagnara847c6602014-05-22 19:20:46 +00002874bool Expr::isConstantInitializer(ASTContext &Ctx, bool IsForRef,
2875 const Expr **Culprit) const {
Eli Friedman384da272009-01-25 03:12:18 +00002876 // This function is attempting whether an expression is an initializer
Eli Friedman4c27ac22013-07-16 22:40:53 +00002877 // which can be evaluated at compile-time. It very closely parallels
2878 // ConstExprEmitter in CGExprConstant.cpp; if they don't match, it
2879 // will lead to unexpected results. Like ConstExprEmitter, it falls back
2880 // to isEvaluatable most of the time.
2881 //
John McCall8b0f4ff2010-08-02 21:13:48 +00002882 // If we ever capture reference-binding directly in the AST, we can
2883 // kill the second parameter.
2884
2885 if (IsForRef) {
2886 EvalResult Result;
Abramo Bagnara847c6602014-05-22 19:20:46 +00002887 if (EvaluateAsLValue(Result, Ctx) && !Result.HasSideEffects)
2888 return true;
2889 if (Culprit)
2890 *Culprit = this;
2891 return false;
John McCall8b0f4ff2010-08-02 21:13:48 +00002892 }
Eli Friedmancf7cbe72009-02-20 02:36:22 +00002893
Anders Carlssona7c5eb72008-11-24 05:23:59 +00002894 switch (getStmtClass()) {
Eli Friedman384da272009-01-25 03:12:18 +00002895 default: break;
Anders Carlssona7c5eb72008-11-24 05:23:59 +00002896 case StringLiteralClass:
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00002897 case ObjCEncodeExprClass:
Anders Carlssona7c5eb72008-11-24 05:23:59 +00002898 return true;
John McCall81c9cea2010-08-01 21:51:45 +00002899 case CXXTemporaryObjectExprClass:
2900 case CXXConstructExprClass: {
2901 const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
John McCall8b0f4ff2010-08-02 21:13:48 +00002902
Eli Friedman4c27ac22013-07-16 22:40:53 +00002903 if (CE->getConstructor()->isTrivial() &&
2904 CE->getConstructor()->getParent()->hasTrivialDestructor()) {
2905 // Trivial default constructor
Richard Smithd62306a2011-11-10 06:34:14 +00002906 if (!CE->getNumArgs()) return true;
John McCall8b0f4ff2010-08-02 21:13:48 +00002907
Eli Friedman4c27ac22013-07-16 22:40:53 +00002908 // Trivial copy constructor
2909 assert(CE->getNumArgs() == 1 && "trivial ctor with > 1 argument");
Abramo Bagnara847c6602014-05-22 19:20:46 +00002910 return CE->getArg(0)->isConstantInitializer(Ctx, false, Culprit);
Richard Smithd62306a2011-11-10 06:34:14 +00002911 }
2912
Richard Smithd62306a2011-11-10 06:34:14 +00002913 break;
John McCall81c9cea2010-08-01 21:51:45 +00002914 }
Fangrui Song407659a2018-11-30 23:41:18 +00002915 case ConstantExprClass: {
2916 // FIXME: We should be able to return "true" here, but it can lead to extra
2917 // error messages. E.g. in Sema/array-init.c.
2918 const Expr *Exp = cast<ConstantExpr>(this)->getSubExpr();
2919 return Exp->isConstantInitializer(Ctx, false, Culprit);
2920 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002921 case CompoundLiteralExprClass: {
Eli Friedmancf7cbe72009-02-20 02:36:22 +00002922 // This handles gcc's extension that allows global initializers like
2923 // "struct x {int x;} x = (struct x) {};".
2924 // FIXME: This accepts other cases it shouldn't!
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002925 const Expr *Exp = cast<CompoundLiteralExpr>(this)->getInitializer();
Abramo Bagnara847c6602014-05-22 19:20:46 +00002926 return Exp->isConstantInitializer(Ctx, false, Culprit);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002927 }
Yunzhong Gaocb779302015-06-10 00:27:52 +00002928 case DesignatedInitUpdateExprClass: {
2929 const DesignatedInitUpdateExpr *DIUE = cast<DesignatedInitUpdateExpr>(this);
2930 return DIUE->getBase()->isConstantInitializer(Ctx, false, Culprit) &&
2931 DIUE->getUpdater()->isConstantInitializer(Ctx, false, Culprit);
2932 }
Anders Carlssona7c5eb72008-11-24 05:23:59 +00002933 case InitListExprClass: {
Eli Friedman4c27ac22013-07-16 22:40:53 +00002934 const InitListExpr *ILE = cast<InitListExpr>(this);
2935 if (ILE->getType()->isArrayType()) {
2936 unsigned numInits = ILE->getNumInits();
2937 for (unsigned i = 0; i < numInits; i++) {
Abramo Bagnara847c6602014-05-22 19:20:46 +00002938 if (!ILE->getInit(i)->isConstantInitializer(Ctx, false, Culprit))
Eli Friedman4c27ac22013-07-16 22:40:53 +00002939 return false;
2940 }
2941 return true;
Anders Carlssona7c5eb72008-11-24 05:23:59 +00002942 }
Eli Friedman4c27ac22013-07-16 22:40:53 +00002943
2944 if (ILE->getType()->isRecordType()) {
2945 unsigned ElementNo = 0;
2946 RecordDecl *RD = ILE->getType()->getAs<RecordType>()->getDecl();
Hans Wennborga302cd92014-08-21 16:06:57 +00002947 for (const auto *Field : RD->fields()) {
Eli Friedman4c27ac22013-07-16 22:40:53 +00002948 // If this is a union, skip all the fields that aren't being initialized.
Hans Wennborga302cd92014-08-21 16:06:57 +00002949 if (RD->isUnion() && ILE->getInitializedFieldInUnion() != Field)
Eli Friedman4c27ac22013-07-16 22:40:53 +00002950 continue;
2951
2952 // Don't emit anonymous bitfields, they just affect layout.
2953 if (Field->isUnnamedBitfield())
2954 continue;
2955
2956 if (ElementNo < ILE->getNumInits()) {
2957 const Expr *Elt = ILE->getInit(ElementNo++);
2958 if (Field->isBitField()) {
2959 // Bitfields have to evaluate to an integer.
Fangrui Song407659a2018-11-30 23:41:18 +00002960 EvalResult Result;
2961 if (!Elt->EvaluateAsInt(Result, Ctx)) {
Abramo Bagnara847c6602014-05-22 19:20:46 +00002962 if (Culprit)
2963 *Culprit = Elt;
Eli Friedman4c27ac22013-07-16 22:40:53 +00002964 return false;
Abramo Bagnara847c6602014-05-22 19:20:46 +00002965 }
Eli Friedman4c27ac22013-07-16 22:40:53 +00002966 } else {
2967 bool RefType = Field->getType()->isReferenceType();
Abramo Bagnara847c6602014-05-22 19:20:46 +00002968 if (!Elt->isConstantInitializer(Ctx, RefType, Culprit))
Eli Friedman4c27ac22013-07-16 22:40:53 +00002969 return false;
2970 }
2971 }
2972 }
2973 return true;
2974 }
2975
2976 break;
Anders Carlssona7c5eb72008-11-24 05:23:59 +00002977 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00002978 case ImplicitValueInitExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00002979 case NoInitExprClass:
Douglas Gregor0202cb42009-01-29 17:44:32 +00002980 return true;
Chris Lattner3eb172a2009-10-13 07:14:16 +00002981 case ParenExprClass:
John McCall8b0f4ff2010-08-02 21:13:48 +00002982 return cast<ParenExpr>(this)->getSubExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00002983 ->isConstantInitializer(Ctx, IsForRef, Culprit);
Peter Collingbourne91147592011-04-15 00:35:48 +00002984 case GenericSelectionExprClass:
Peter Collingbourne91147592011-04-15 00:35:48 +00002985 return cast<GenericSelectionExpr>(this)->getResultExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00002986 ->isConstantInitializer(Ctx, IsForRef, Culprit);
Abramo Bagnarab59a5b62010-09-27 07:13:32 +00002987 case ChooseExprClass:
Abramo Bagnara847c6602014-05-22 19:20:46 +00002988 if (cast<ChooseExpr>(this)->isConditionDependent()) {
2989 if (Culprit)
2990 *Culprit = this;
Eli Friedman75807f22013-07-20 00:40:58 +00002991 return false;
Abramo Bagnara847c6602014-05-22 19:20:46 +00002992 }
Eli Friedman75807f22013-07-20 00:40:58 +00002993 return cast<ChooseExpr>(this)->getChosenSubExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00002994 ->isConstantInitializer(Ctx, IsForRef, Culprit);
Eli Friedman384da272009-01-25 03:12:18 +00002995 case UnaryOperatorClass: {
2996 const UnaryOperator* Exp = cast<UnaryOperator>(this);
John McCalle3027922010-08-25 11:45:40 +00002997 if (Exp->getOpcode() == UO_Extension)
Abramo Bagnara847c6602014-05-22 19:20:46 +00002998 return Exp->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
Eli Friedman384da272009-01-25 03:12:18 +00002999 break;
3000 }
John McCall8b0f4ff2010-08-02 21:13:48 +00003001 case CXXFunctionalCastExprClass:
John McCall81c9cea2010-08-01 21:51:45 +00003002 case CXXStaticCastExprClass:
Chris Lattner1f02e052009-04-21 05:19:11 +00003003 case ImplicitCastExprClass:
Eli Friedman4c27ac22013-07-16 22:40:53 +00003004 case CStyleCastExprClass:
3005 case ObjCBridgedCastExprClass:
3006 case CXXDynamicCastExprClass:
3007 case CXXReinterpretCastExprClass:
3008 case CXXConstCastExprClass: {
Richard Smith161f09a2011-12-06 22:44:34 +00003009 const CastExpr *CE = cast<CastExpr>(this);
3010
Eli Friedman13ec75b2011-12-21 00:43:02 +00003011 // Handle misc casts we want to ignore.
Eli Friedman13ec75b2011-12-21 00:43:02 +00003012 if (CE->getCastKind() == CK_NoOp ||
3013 CE->getCastKind() == CK_LValueToRValue ||
3014 CE->getCastKind() == CK_ToUnion ||
Eli Friedman4c27ac22013-07-16 22:40:53 +00003015 CE->getCastKind() == CK_ConstructorConversion ||
3016 CE->getCastKind() == CK_NonAtomicToAtomic ||
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00003017 CE->getCastKind() == CK_AtomicToNonAtomic ||
3018 CE->getCastKind() == CK_IntToOCLSampler)
Abramo Bagnara847c6602014-05-22 19:20:46 +00003019 return CE->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
Richard Smith161f09a2011-12-06 22:44:34 +00003020
Eli Friedman384da272009-01-25 03:12:18 +00003021 break;
Richard Smith161f09a2011-12-06 22:44:34 +00003022 }
Douglas Gregorfe314812011-06-21 17:03:29 +00003023 case MaterializeTemporaryExprClass:
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003024 return cast<MaterializeTemporaryExpr>(this)->GetTemporaryExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00003025 ->isConstantInitializer(Ctx, false, Culprit);
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003026
Eli Friedman4c27ac22013-07-16 22:40:53 +00003027 case SubstNonTypeTemplateParmExprClass:
3028 return cast<SubstNonTypeTemplateParmExpr>(this)->getReplacement()
Abramo Bagnara847c6602014-05-22 19:20:46 +00003029 ->isConstantInitializer(Ctx, false, Culprit);
Eli Friedman4c27ac22013-07-16 22:40:53 +00003030 case CXXDefaultArgExprClass:
3031 return cast<CXXDefaultArgExpr>(this)->getExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00003032 ->isConstantInitializer(Ctx, false, Culprit);
Eli Friedman4c27ac22013-07-16 22:40:53 +00003033 case CXXDefaultInitExprClass:
3034 return cast<CXXDefaultInitExpr>(this)->getExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00003035 ->isConstantInitializer(Ctx, false, Culprit);
Anders Carlssona7c5eb72008-11-24 05:23:59 +00003036 }
Richard Smithce8eca52015-12-08 03:21:47 +00003037 // Allow certain forms of UB in constant initializers: signed integer
3038 // overflow and floating-point division by zero. We'll give a warning on
3039 // these, but they're common enough that we have to accept them.
3040 if (isEvaluatable(Ctx, SE_AllowUndefinedBehavior))
Abramo Bagnara847c6602014-05-22 19:20:46 +00003041 return true;
3042 if (Culprit)
3043 *Culprit = this;
3044 return false;
Steve Naroffb03f5942007-09-02 20:30:18 +00003045}
3046
Nico Weber758fbac2018-02-13 21:31:47 +00003047bool CallExpr::isBuiltinAssumeFalse(const ASTContext &Ctx) const {
3048 const FunctionDecl* FD = getDirectCallee();
3049 if (!FD || (FD->getBuiltinID() != Builtin::BI__assume &&
3050 FD->getBuiltinID() != Builtin::BI__builtin_assume))
3051 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00003052
Nico Weber758fbac2018-02-13 21:31:47 +00003053 const Expr* Arg = getArg(0);
3054 bool ArgVal;
3055 return !Arg->isValueDependent() &&
3056 Arg->EvaluateAsBooleanCondition(ArgVal, Ctx) && !ArgVal;
3057}
3058
Scott Douglasscc013592015-06-10 15:18:23 +00003059namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003060 /// Look for any side effects within a Stmt.
Scott Douglasscc013592015-06-10 15:18:23 +00003061 class SideEffectFinder : public ConstEvaluatedExprVisitor<SideEffectFinder> {
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003062 typedef ConstEvaluatedExprVisitor<SideEffectFinder> Inherited;
Scott Douglasscc013592015-06-10 15:18:23 +00003063 const bool IncludePossibleEffects;
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003064 bool HasSideEffects;
Scott Douglasscc013592015-06-10 15:18:23 +00003065
3066 public:
3067 explicit SideEffectFinder(const ASTContext &Context, bool IncludePossible)
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003068 : Inherited(Context),
3069 IncludePossibleEffects(IncludePossible), HasSideEffects(false) { }
Scott Douglasscc013592015-06-10 15:18:23 +00003070
3071 bool hasSideEffects() const { return HasSideEffects; }
3072
3073 void VisitExpr(const Expr *E) {
3074 if (!HasSideEffects &&
3075 E->HasSideEffects(Context, IncludePossibleEffects))
3076 HasSideEffects = true;
3077 }
3078 };
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003079}
Scott Douglasscc013592015-06-10 15:18:23 +00003080
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003081bool Expr::HasSideEffects(const ASTContext &Ctx,
3082 bool IncludePossibleEffects) const {
3083 // In circumstances where we care about definite side effects instead of
3084 // potential side effects, we want to ignore expressions that are part of a
3085 // macro expansion as a potential side effect.
3086 if (!IncludePossibleEffects && getExprLoc().isMacroID())
3087 return false;
3088
Richard Smith0421ce72012-08-07 04:16:51 +00003089 if (isInstantiationDependent())
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003090 return IncludePossibleEffects;
Richard Smith0421ce72012-08-07 04:16:51 +00003091
3092 switch (getStmtClass()) {
3093 case NoStmtClass:
3094 #define ABSTRACT_STMT(Type)
3095 #define STMT(Type, Base) case Type##Class:
3096 #define EXPR(Type, Base)
3097 #include "clang/AST/StmtNodes.inc"
3098 llvm_unreachable("unexpected Expr kind");
3099
3100 case DependentScopeDeclRefExprClass:
3101 case CXXUnresolvedConstructExprClass:
3102 case CXXDependentScopeMemberExprClass:
3103 case UnresolvedLookupExprClass:
3104 case UnresolvedMemberExprClass:
3105 case PackExpansionExprClass:
3106 case SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +00003107 case FunctionParmPackExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +00003108 case TypoExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +00003109 case CXXFoldExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003110 llvm_unreachable("shouldn't see dependent / unresolved nodes here");
3111
Richard Smitha33e4fe2012-08-07 05:18:29 +00003112 case DeclRefExprClass:
3113 case ObjCIvarRefExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003114 case PredefinedExprClass:
3115 case IntegerLiteralClass:
Leonard Chandb01c3a2018-06-20 17:19:40 +00003116 case FixedPointLiteralClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003117 case FloatingLiteralClass:
3118 case ImaginaryLiteralClass:
3119 case StringLiteralClass:
3120 case CharacterLiteralClass:
3121 case OffsetOfExprClass:
3122 case ImplicitValueInitExprClass:
3123 case UnaryExprOrTypeTraitExprClass:
3124 case AddrLabelExprClass:
3125 case GNUNullExprClass:
Richard Smith410306b2016-12-12 02:53:20 +00003126 case ArrayInitIndexExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00003127 case NoInitExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003128 case CXXBoolLiteralExprClass:
3129 case CXXNullPtrLiteralExprClass:
3130 case CXXThisExprClass:
3131 case CXXScalarValueInitExprClass:
3132 case TypeTraitExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003133 case ArrayTypeTraitExprClass:
3134 case ExpressionTraitExprClass:
3135 case CXXNoexceptExprClass:
3136 case SizeOfPackExprClass:
3137 case ObjCStringLiteralClass:
3138 case ObjCEncodeExprClass:
3139 case ObjCBoolLiteralExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +00003140 case ObjCAvailabilityCheckExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003141 case CXXUuidofExprClass:
3142 case OpaqueValueExprClass:
3143 // These never have a side-effect.
3144 return false;
3145
Bill Wendling7c44da22018-10-31 03:48:47 +00003146 case ConstantExprClass:
3147 // FIXME: Move this into the "return false;" block above.
3148 return cast<ConstantExpr>(this)->getSubExpr()->HasSideEffects(
3149 Ctx, IncludePossibleEffects);
3150
Richard Smith0421ce72012-08-07 04:16:51 +00003151 case CallExprClass:
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003152 case CXXOperatorCallExprClass:
3153 case CXXMemberCallExprClass:
3154 case CUDAKernelCallExprClass:
Michael Kupersteinaed5ccd2015-04-06 13:22:01 +00003155 case UserDefinedLiteralClass: {
3156 // We don't know a call definitely has side effects, except for calls
3157 // to pure/const functions that definitely don't.
3158 // If the call itself is considered side-effect free, check the operands.
3159 const Decl *FD = cast<CallExpr>(this)->getCalleeDecl();
3160 bool IsPure = FD && (FD->hasAttr<ConstAttr>() || FD->hasAttr<PureAttr>());
3161 if (IsPure || !IncludePossibleEffects)
3162 break;
3163 return true;
3164 }
3165
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003166 case BlockExprClass:
3167 case CXXBindTemporaryExprClass:
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003168 if (!IncludePossibleEffects)
3169 break;
3170 return true;
3171
John McCall5e77d762013-04-16 07:28:30 +00003172 case MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +00003173 case MSPropertySubscriptExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003174 case CompoundAssignOperatorClass:
3175 case VAArgExprClass:
3176 case AtomicExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003177 case CXXThrowExprClass:
3178 case CXXNewExprClass:
3179 case CXXDeleteExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +00003180 case CoawaitExprClass:
Eric Fiselier20f25cb2017-03-06 23:38:15 +00003181 case DependentCoawaitExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +00003182 case CoyieldExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003183 // These always have a side-effect.
3184 return true;
3185
Scott Douglasscc013592015-06-10 15:18:23 +00003186 case StmtExprClass: {
3187 // StmtExprs have a side-effect if any substatement does.
3188 SideEffectFinder Finder(Ctx, IncludePossibleEffects);
3189 Finder.Visit(cast<StmtExpr>(this)->getSubStmt());
3190 return Finder.hasSideEffects();
3191 }
3192
Tim Shen4a05bb82016-06-21 20:29:17 +00003193 case ExprWithCleanupsClass:
3194 if (IncludePossibleEffects)
3195 if (cast<ExprWithCleanups>(this)->cleanupsHaveSideEffects())
3196 return true;
3197 break;
3198
Richard Smith0421ce72012-08-07 04:16:51 +00003199 case ParenExprClass:
3200 case ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +00003201 case OMPArraySectionExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003202 case MemberExprClass:
3203 case ConditionalOperatorClass:
3204 case BinaryConditionalOperatorClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003205 case CompoundLiteralExprClass:
3206 case ExtVectorElementExprClass:
3207 case DesignatedInitExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00003208 case DesignatedInitUpdateExprClass:
Richard Smith410306b2016-12-12 02:53:20 +00003209 case ArrayInitLoopExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003210 case ParenListExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003211 case CXXPseudoDestructorExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +00003212 case CXXStdInitializerListExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003213 case SubstNonTypeTemplateParmExprClass:
3214 case MaterializeTemporaryExprClass:
3215 case ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +00003216 case ConvertVectorExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003217 case AsTypeExprClass:
3218 // These have a side-effect if any subexpression does.
3219 break;
3220
Richard Smitha33e4fe2012-08-07 05:18:29 +00003221 case UnaryOperatorClass:
3222 if (cast<UnaryOperator>(this)->isIncrementDecrementOp())
Richard Smith0421ce72012-08-07 04:16:51 +00003223 return true;
3224 break;
Richard Smith0421ce72012-08-07 04:16:51 +00003225
3226 case BinaryOperatorClass:
3227 if (cast<BinaryOperator>(this)->isAssignmentOp())
3228 return true;
3229 break;
3230
Richard Smith0421ce72012-08-07 04:16:51 +00003231 case InitListExprClass:
3232 // FIXME: The children for an InitListExpr doesn't include the array filler.
3233 if (const Expr *E = cast<InitListExpr>(this)->getArrayFiller())
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003234 if (E->HasSideEffects(Ctx, IncludePossibleEffects))
Richard Smith0421ce72012-08-07 04:16:51 +00003235 return true;
3236 break;
3237
3238 case GenericSelectionExprClass:
3239 return cast<GenericSelectionExpr>(this)->getResultExpr()->
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003240 HasSideEffects(Ctx, IncludePossibleEffects);
Richard Smith0421ce72012-08-07 04:16:51 +00003241
3242 case ChooseExprClass:
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003243 return cast<ChooseExpr>(this)->getChosenSubExpr()->HasSideEffects(
3244 Ctx, IncludePossibleEffects);
Richard Smith0421ce72012-08-07 04:16:51 +00003245
3246 case CXXDefaultArgExprClass:
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003247 return cast<CXXDefaultArgExpr>(this)->getExpr()->HasSideEffects(
3248 Ctx, IncludePossibleEffects);
Richard Smith0421ce72012-08-07 04:16:51 +00003249
Reid Klecknerd60b82f2014-11-17 23:36:45 +00003250 case CXXDefaultInitExprClass: {
3251 const FieldDecl *FD = cast<CXXDefaultInitExpr>(this)->getField();
3252 if (const Expr *E = FD->getInClassInitializer())
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003253 return E->HasSideEffects(Ctx, IncludePossibleEffects);
Richard Smith852c9db2013-04-20 22:23:05 +00003254 // If we've not yet parsed the initializer, assume it has side-effects.
3255 return true;
Reid Klecknerd60b82f2014-11-17 23:36:45 +00003256 }
Richard Smith852c9db2013-04-20 22:23:05 +00003257
Richard Smith0421ce72012-08-07 04:16:51 +00003258 case CXXDynamicCastExprClass: {
3259 // A dynamic_cast expression has side-effects if it can throw.
3260 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(this);
3261 if (DCE->getTypeAsWritten()->isReferenceType() &&
3262 DCE->getCastKind() == CK_Dynamic)
3263 return true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00003264 }
3265 LLVM_FALLTHROUGH;
Richard Smitha33e4fe2012-08-07 05:18:29 +00003266 case ImplicitCastExprClass:
3267 case CStyleCastExprClass:
3268 case CXXStaticCastExprClass:
3269 case CXXReinterpretCastExprClass:
3270 case CXXConstCastExprClass:
3271 case CXXFunctionalCastExprClass: {
Aaron Ballman409af502015-01-03 17:00:12 +00003272 // While volatile reads are side-effecting in both C and C++, we treat them
3273 // as having possible (not definite) side-effects. This allows idiomatic
3274 // code to behave without warning, such as sizeof(*v) for a volatile-
3275 // qualified pointer.
3276 if (!IncludePossibleEffects)
3277 break;
3278
Richard Smitha33e4fe2012-08-07 05:18:29 +00003279 const CastExpr *CE = cast<CastExpr>(this);
3280 if (CE->getCastKind() == CK_LValueToRValue &&
3281 CE->getSubExpr()->getType().isVolatileQualified())
3282 return true;
Richard Smith0421ce72012-08-07 04:16:51 +00003283 break;
3284 }
3285
Richard Smithef8bf432012-08-13 20:08:14 +00003286 case CXXTypeidExprClass:
3287 // typeid might throw if its subexpression is potentially-evaluated, so has
3288 // side-effects in that case whether or not its subexpression does.
3289 return cast<CXXTypeidExpr>(this)->isPotentiallyEvaluated();
Richard Smith0421ce72012-08-07 04:16:51 +00003290
3291 case CXXConstructExprClass:
3292 case CXXTemporaryObjectExprClass: {
3293 const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003294 if (!CE->getConstructor()->isTrivial() && IncludePossibleEffects)
Richard Smith0421ce72012-08-07 04:16:51 +00003295 return true;
Richard Smitha33e4fe2012-08-07 05:18:29 +00003296 // A trivial constructor does not add any side-effects of its own. Just look
3297 // at its arguments.
Richard Smith0421ce72012-08-07 04:16:51 +00003298 break;
3299 }
3300
Richard Smith5179eb72016-06-28 19:03:57 +00003301 case CXXInheritedCtorInitExprClass: {
3302 const auto *ICIE = cast<CXXInheritedCtorInitExpr>(this);
3303 if (!ICIE->getConstructor()->isTrivial() && IncludePossibleEffects)
3304 return true;
3305 break;
3306 }
3307
Richard Smith0421ce72012-08-07 04:16:51 +00003308 case LambdaExprClass: {
3309 const LambdaExpr *LE = cast<LambdaExpr>(this);
Richard Smithb3d203f2018-10-19 19:01:34 +00003310 for (Expr *E : LE->capture_inits())
3311 if (E->HasSideEffects(Ctx, IncludePossibleEffects))
Richard Smith0421ce72012-08-07 04:16:51 +00003312 return true;
3313 return false;
3314 }
3315
3316 case PseudoObjectExprClass: {
3317 // Only look for side-effects in the semantic form, and look past
3318 // OpaqueValueExpr bindings in that form.
3319 const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this);
3320 for (PseudoObjectExpr::const_semantics_iterator I = PO->semantics_begin(),
3321 E = PO->semantics_end();
3322 I != E; ++I) {
3323 const Expr *Subexpr = *I;
3324 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Subexpr))
3325 Subexpr = OVE->getSourceExpr();
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003326 if (Subexpr->HasSideEffects(Ctx, IncludePossibleEffects))
Richard Smith0421ce72012-08-07 04:16:51 +00003327 return true;
3328 }
3329 return false;
3330 }
3331
3332 case ObjCBoxedExprClass:
3333 case ObjCArrayLiteralClass:
3334 case ObjCDictionaryLiteralClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003335 case ObjCSelectorExprClass:
3336 case ObjCProtocolExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003337 case ObjCIsaExprClass:
3338 case ObjCIndirectCopyRestoreExprClass:
3339 case ObjCSubscriptRefExprClass:
3340 case ObjCBridgedCastExprClass:
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003341 case ObjCMessageExprClass:
3342 case ObjCPropertyRefExprClass:
3343 // FIXME: Classify these cases better.
3344 if (IncludePossibleEffects)
3345 return true;
3346 break;
Richard Smith0421ce72012-08-07 04:16:51 +00003347 }
3348
3349 // Recurse to children.
Benjamin Kramer642f1732015-07-02 21:03:14 +00003350 for (const Stmt *SubStmt : children())
3351 if (SubStmt &&
3352 cast<Expr>(SubStmt)->HasSideEffects(Ctx, IncludePossibleEffects))
3353 return true;
Richard Smith0421ce72012-08-07 04:16:51 +00003354
3355 return false;
3356}
3357
Douglas Gregor1be329d2012-02-23 07:33:15 +00003358namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003359 /// Look for a call to a non-trivial function within an expression.
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003360 class NonTrivialCallFinder : public ConstEvaluatedExprVisitor<NonTrivialCallFinder>
3361 {
3362 typedef ConstEvaluatedExprVisitor<NonTrivialCallFinder> Inherited;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003363
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003364 bool NonTrivial;
Fangrui Song6907ce22018-07-30 19:24:48 +00003365
Douglas Gregor1be329d2012-02-23 07:33:15 +00003366 public:
Scott Douglass503fc392015-06-10 13:53:15 +00003367 explicit NonTrivialCallFinder(const ASTContext &Context)
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003368 : Inherited(Context), NonTrivial(false) { }
Fangrui Song6907ce22018-07-30 19:24:48 +00003369
Douglas Gregor1be329d2012-02-23 07:33:15 +00003370 bool hasNonTrivialCall() const { return NonTrivial; }
Scott Douglass503fc392015-06-10 13:53:15 +00003371
3372 void VisitCallExpr(const CallExpr *E) {
3373 if (const CXXMethodDecl *Method
3374 = dyn_cast_or_null<const CXXMethodDecl>(E->getCalleeDecl())) {
Douglas Gregor1be329d2012-02-23 07:33:15 +00003375 if (Method->isTrivial()) {
3376 // Recurse to children of the call.
3377 Inherited::VisitStmt(E);
3378 return;
3379 }
3380 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003381
Douglas Gregor1be329d2012-02-23 07:33:15 +00003382 NonTrivial = true;
3383 }
Scott Douglass503fc392015-06-10 13:53:15 +00003384
3385 void VisitCXXConstructExpr(const CXXConstructExpr *E) {
Douglas Gregor1be329d2012-02-23 07:33:15 +00003386 if (E->getConstructor()->isTrivial()) {
3387 // Recurse to children of the call.
3388 Inherited::VisitStmt(E);
3389 return;
3390 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003391
Douglas Gregor1be329d2012-02-23 07:33:15 +00003392 NonTrivial = true;
3393 }
Scott Douglass503fc392015-06-10 13:53:15 +00003394
3395 void VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
Douglas Gregor1be329d2012-02-23 07:33:15 +00003396 if (E->getTemporary()->getDestructor()->isTrivial()) {
3397 Inherited::VisitStmt(E);
3398 return;
3399 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003400
Douglas Gregor1be329d2012-02-23 07:33:15 +00003401 NonTrivial = true;
3402 }
3403 };
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003404}
Douglas Gregor1be329d2012-02-23 07:33:15 +00003405
Scott Douglass503fc392015-06-10 13:53:15 +00003406bool Expr::hasNonTrivialCall(const ASTContext &Ctx) const {
Douglas Gregor1be329d2012-02-23 07:33:15 +00003407 NonTrivialCallFinder Finder(Ctx);
3408 Finder.Visit(this);
Fangrui Song6907ce22018-07-30 19:24:48 +00003409 return Finder.hasNonTrivialCall();
Douglas Gregor1be329d2012-02-23 07:33:15 +00003410}
3411
Fangrui Song6907ce22018-07-30 19:24:48 +00003412/// isNullPointerConstant - C99 6.3.2.3p3 - Return whether this is a null
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003413/// pointer constant or not, as well as the specific kind of constant detected.
3414/// Null pointer constants can be integer constant expressions with the
3415/// value zero, casts of zero to void*, nullptr (C++0X), or __null
3416/// (a GNU extension).
3417Expr::NullPointerConstantKind
3418Expr::isNullPointerConstant(ASTContext &Ctx,
3419 NullPointerConstantValueDependence NPC) const {
Reid Klecknera5eef142013-11-12 02:22:34 +00003420 if (isValueDependent() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00003421 (!Ctx.getLangOpts().CPlusPlus11 || Ctx.getLangOpts().MSVCCompat)) {
Douglas Gregor56751b52009-09-25 04:25:58 +00003422 switch (NPC) {
3423 case NPC_NeverValueDependent:
David Blaikie83d382b2011-09-23 05:06:16 +00003424 llvm_unreachable("Unexpected value dependent expression!");
Douglas Gregor56751b52009-09-25 04:25:58 +00003425 case NPC_ValueDependentIsNull:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003426 if (isTypeDependent() || getType()->isIntegralType(Ctx))
David Blaikie1c7c8f72012-08-08 17:33:31 +00003427 return NPCK_ZeroExpression;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003428 else
3429 return NPCK_NotNull;
Fangrui Song6907ce22018-07-30 19:24:48 +00003430
Douglas Gregor56751b52009-09-25 04:25:58 +00003431 case NPC_ValueDependentIsNotNull:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003432 return NPCK_NotNull;
Douglas Gregor56751b52009-09-25 04:25:58 +00003433 }
3434 }
Daniel Dunbarebc51402009-09-18 08:46:16 +00003435
Sebastian Redl72b8aef2008-10-31 14:43:28 +00003436 // Strip off a cast to void*, if it exists. Except in C++.
Argyrios Kyrtzidis3bab3d22008-08-18 23:01:59 +00003437 if (const ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(this)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003438 if (!Ctx.getLangOpts().CPlusPlus) {
Sebastian Redl72b8aef2008-10-31 14:43:28 +00003439 // Check that it is a cast to void*.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003440 if (const PointerType *PT = CE->getType()->getAs<PointerType>()) {
Sebastian Redl72b8aef2008-10-31 14:43:28 +00003441 QualType Pointee = PT->getPointeeType();
Richard Smithdab73ce2018-11-28 06:25:06 +00003442 Qualifiers Qs = Pointee.getQualifiers();
Yaxun Liub7318e02017-10-13 03:37:48 +00003443 // Only (void*)0 or equivalent are treated as nullptr. If pointee type
3444 // has non-default address space it is not treated as nullptr.
3445 // (__generic void*)0 in OpenCL 2.0 should not be treated as nullptr
3446 // since it cannot be assigned to a pointer to constant address space.
Richard Smithdab73ce2018-11-28 06:25:06 +00003447 if ((Ctx.getLangOpts().OpenCLVersion >= 200 &&
Yaxun Liub7318e02017-10-13 03:37:48 +00003448 Pointee.getAddressSpace() == LangAS::opencl_generic) ||
3449 (Ctx.getLangOpts().OpenCL &&
3450 Ctx.getLangOpts().OpenCLVersion < 200 &&
Richard Smithdab73ce2018-11-28 06:25:06 +00003451 Pointee.getAddressSpace() == LangAS::opencl_private))
3452 Qs.removeAddressSpace();
Anastasia Stulova2446b8b2015-12-11 17:41:19 +00003453
Richard Smithdab73ce2018-11-28 06:25:06 +00003454 if (Pointee->isVoidType() && Qs.empty() && // to void*
3455 CE->getSubExpr()->getType()->isIntegerType()) // from int
Douglas Gregor56751b52009-09-25 04:25:58 +00003456 return CE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
Sebastian Redl72b8aef2008-10-31 14:43:28 +00003457 }
Steve Naroffada7d422007-05-20 17:54:12 +00003458 }
Steve Naroff4871fe02008-01-14 16:10:57 +00003459 } else if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(this)) {
3460 // Ignore the ImplicitCastExpr type entirely.
Douglas Gregor56751b52009-09-25 04:25:58 +00003461 return ICE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
Steve Naroff4871fe02008-01-14 16:10:57 +00003462 } else if (const ParenExpr *PE = dyn_cast<ParenExpr>(this)) {
3463 // Accept ((void*)0) as a null pointer constant, as many other
3464 // implementations do.
Douglas Gregor56751b52009-09-25 04:25:58 +00003465 return PE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
Peter Collingbourne91147592011-04-15 00:35:48 +00003466 } else if (const GenericSelectionExpr *GE =
3467 dyn_cast<GenericSelectionExpr>(this)) {
Eli Friedman75807f22013-07-20 00:40:58 +00003468 if (GE->isResultDependent())
3469 return NPCK_NotNull;
Peter Collingbourne91147592011-04-15 00:35:48 +00003470 return GE->getResultExpr()->isNullPointerConstant(Ctx, NPC);
Eli Friedman75807f22013-07-20 00:40:58 +00003471 } else if (const ChooseExpr *CE = dyn_cast<ChooseExpr>(this)) {
3472 if (CE->isConditionDependent())
3473 return NPCK_NotNull;
3474 return CE->getChosenSubExpr()->isNullPointerConstant(Ctx, NPC);
Mike Stump11289f42009-09-09 15:08:12 +00003475 } else if (const CXXDefaultArgExpr *DefaultArg
Chris Lattner58258242008-04-10 02:22:51 +00003476 = dyn_cast<CXXDefaultArgExpr>(this)) {
Richard Smith852c9db2013-04-20 22:23:05 +00003477 // See through default argument expressions.
Douglas Gregor56751b52009-09-25 04:25:58 +00003478 return DefaultArg->getExpr()->isNullPointerConstant(Ctx, NPC);
Richard Smith852c9db2013-04-20 22:23:05 +00003479 } else if (const CXXDefaultInitExpr *DefaultInit
3480 = dyn_cast<CXXDefaultInitExpr>(this)) {
3481 // See through default initializer expressions.
3482 return DefaultInit->getExpr()->isNullPointerConstant(Ctx, NPC);
Douglas Gregor3be4b122008-11-29 04:51:27 +00003483 } else if (isa<GNUNullExpr>(this)) {
3484 // The GNU __null extension is always a null pointer constant.
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003485 return NPCK_GNUNull;
Fangrui Song6907ce22018-07-30 19:24:48 +00003486 } else if (const MaterializeTemporaryExpr *M
Douglas Gregorfe314812011-06-21 17:03:29 +00003487 = dyn_cast<MaterializeTemporaryExpr>(this)) {
3488 return M->GetTemporaryExpr()->isNullPointerConstant(Ctx, NPC);
John McCallfe96e0b2011-11-06 09:01:30 +00003489 } else if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(this)) {
3490 if (const Expr *Source = OVE->getSourceExpr())
3491 return Source->isNullPointerConstant(Ctx, NPC);
Steve Naroff09035312008-01-14 02:53:34 +00003492 }
Douglas Gregor3be4b122008-11-29 04:51:27 +00003493
Richard Smith89645bc2013-01-02 12:01:23 +00003494 // C++11 nullptr_t is always a null pointer constant.
Sebastian Redl576fd422009-05-10 18:38:11 +00003495 if (getType()->isNullPtrType())
Richard Smith89645bc2013-01-02 12:01:23 +00003496 return NPCK_CXX11_nullptr;
Sebastian Redl576fd422009-05-10 18:38:11 +00003497
Fariborz Jahanian3567c422010-09-27 22:42:37 +00003498 if (const RecordType *UT = getType()->getAsUnionType())
Richard Smith4055de42013-06-13 02:46:14 +00003499 if (!Ctx.getLangOpts().CPlusPlus11 &&
3500 UT && UT->getDecl()->hasAttr<TransparentUnionAttr>())
Fariborz Jahanian3567c422010-09-27 22:42:37 +00003501 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(this)){
3502 const Expr *InitExpr = CLE->getInitializer();
3503 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(InitExpr))
3504 return ILE->getInit(0)->isNullPointerConstant(Ctx, NPC);
3505 }
Steve Naroff4871fe02008-01-14 16:10:57 +00003506 // This expression must be an integer type.
Fangrui Song6907ce22018-07-30 19:24:48 +00003507 if (!getType()->isIntegerType() ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00003508 (Ctx.getLangOpts().CPlusPlus && getType()->isEnumeralType()))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003509 return NPCK_NotNull;
Mike Stump11289f42009-09-09 15:08:12 +00003510
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003511 if (Ctx.getLangOpts().CPlusPlus11) {
Richard Smith4055de42013-06-13 02:46:14 +00003512 // C++11 [conv.ptr]p1: A null pointer constant is an integer literal with
3513 // value zero or a prvalue of type std::nullptr_t.
Reid Klecknera5eef142013-11-12 02:22:34 +00003514 // Microsoft mode permits C++98 rules reflecting MSVC behavior.
Richard Smith4055de42013-06-13 02:46:14 +00003515 const IntegerLiteral *Lit = dyn_cast<IntegerLiteral>(this);
Reid Klecknera5eef142013-11-12 02:22:34 +00003516 if (Lit && !Lit->getValue())
3517 return NPCK_ZeroLiteral;
Alp Tokerbfa39342014-01-14 12:51:41 +00003518 else if (!Ctx.getLangOpts().MSVCCompat || !isCXX98IntegralConstantExpr(Ctx))
Reid Klecknera5eef142013-11-12 02:22:34 +00003519 return NPCK_NotNull;
Richard Smith98a0a492012-02-14 21:38:30 +00003520 } else {
Richard Smith4055de42013-06-13 02:46:14 +00003521 // If we have an integer constant expression, we need to *evaluate* it and
3522 // test for the value 0.
Richard Smith98a0a492012-02-14 21:38:30 +00003523 if (!isIntegerConstantExpr(Ctx))
3524 return NPCK_NotNull;
3525 }
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003526
David Blaikie1c7c8f72012-08-08 17:33:31 +00003527 if (EvaluateKnownConstInt(Ctx) != 0)
3528 return NPCK_NotNull;
3529
3530 if (isa<IntegerLiteral>(this))
3531 return NPCK_ZeroLiteral;
3532 return NPCK_ZeroExpression;
Steve Naroff218bc2b2007-05-04 21:54:46 +00003533}
Steve Narofff7a5da12007-07-28 23:10:27 +00003534
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003535/// If this expression is an l-value for an Objective C
John McCall34376a62010-12-04 03:47:34 +00003536/// property, find the underlying property reference expression.
3537const ObjCPropertyRefExpr *Expr::getObjCProperty() const {
3538 const Expr *E = this;
3539 while (true) {
3540 assert((E->getValueKind() == VK_LValue &&
3541 E->getObjectKind() == OK_ObjCProperty) &&
3542 "expression is not a property reference");
3543 E = E->IgnoreParenCasts();
3544 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3545 if (BO->getOpcode() == BO_Comma) {
3546 E = BO->getRHS();
3547 continue;
3548 }
3549 }
3550
3551 break;
3552 }
3553
3554 return cast<ObjCPropertyRefExpr>(E);
3555}
3556
Anna Zaks97c7ce32012-10-01 20:34:04 +00003557bool Expr::isObjCSelfExpr() const {
3558 const Expr *E = IgnoreParenImpCasts();
3559
3560 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
3561 if (!DRE)
3562 return false;
3563
3564 const ImplicitParamDecl *Param = dyn_cast<ImplicitParamDecl>(DRE->getDecl());
3565 if (!Param)
3566 return false;
3567
3568 const ObjCMethodDecl *M = dyn_cast<ObjCMethodDecl>(Param->getDeclContext());
3569 if (!M)
3570 return false;
3571
3572 return M->getSelfDecl() == Param;
3573}
3574
John McCalld25db7e2013-05-06 21:39:12 +00003575FieldDecl *Expr::getSourceBitField() {
Douglas Gregor19623dc2009-07-06 15:38:40 +00003576 Expr *E = this->IgnoreParens();
Douglas Gregor71235ec2009-05-02 02:18:30 +00003577
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003578 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall34376a62010-12-04 03:47:34 +00003579 if (ICE->getCastKind() == CK_LValueToRValue ||
3580 (ICE->getValueKind() != VK_RValue && ICE->getCastKind() == CK_NoOp))
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003581 E = ICE->getSubExpr()->IgnoreParens();
3582 else
3583 break;
3584 }
3585
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003586 if (MemberExpr *MemRef = dyn_cast<MemberExpr>(E))
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00003587 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemRef->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00003588 if (Field->isBitField())
3589 return Field;
3590
George Burgess IV00f70bd2018-03-01 05:43:23 +00003591 if (ObjCIvarRefExpr *IvarRef = dyn_cast<ObjCIvarRefExpr>(E)) {
3592 FieldDecl *Ivar = IvarRef->getDecl();
3593 if (Ivar->isBitField())
3594 return Ivar;
3595 }
John McCalld25db7e2013-05-06 21:39:12 +00003596
Richard Smith7873de02016-08-11 22:25:46 +00003597 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E)) {
Argyrios Kyrtzidisd3f00542010-10-30 19:52:22 +00003598 if (FieldDecl *Field = dyn_cast<FieldDecl>(DeclRef->getDecl()))
3599 if (Field->isBitField())
3600 return Field;
3601
Richard Smith7873de02016-08-11 22:25:46 +00003602 if (BindingDecl *BD = dyn_cast<BindingDecl>(DeclRef->getDecl()))
3603 if (Expr *E = BD->getBinding())
3604 return E->getSourceBitField();
3605 }
3606
Eli Friedman609ada22011-07-13 02:05:57 +00003607 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(E)) {
Douglas Gregor71235ec2009-05-02 02:18:30 +00003608 if (BinOp->isAssignmentOp() && BinOp->getLHS())
John McCalld25db7e2013-05-06 21:39:12 +00003609 return BinOp->getLHS()->getSourceBitField();
Douglas Gregor71235ec2009-05-02 02:18:30 +00003610
Eli Friedman609ada22011-07-13 02:05:57 +00003611 if (BinOp->getOpcode() == BO_Comma && BinOp->getRHS())
John McCalld25db7e2013-05-06 21:39:12 +00003612 return BinOp->getRHS()->getSourceBitField();
Eli Friedman609ada22011-07-13 02:05:57 +00003613 }
3614
Richard Smith5b571672014-09-24 23:55:00 +00003615 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E))
3616 if (UnOp->isPrefix() && UnOp->isIncrementDecrementOp())
3617 return UnOp->getSubExpr()->getSourceBitField();
3618
Craig Topper36250ad2014-05-12 05:36:57 +00003619 return nullptr;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003620}
3621
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003622bool Expr::refersToVectorElement() const {
Richard Smith7873de02016-08-11 22:25:46 +00003623 // FIXME: Why do we not just look at the ObjectKind here?
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003624 const Expr *E = this->IgnoreParens();
Fangrui Song6907ce22018-07-30 19:24:48 +00003625
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003626 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall2536c6d2010-08-25 10:28:54 +00003627 if (ICE->getValueKind() != VK_RValue &&
John McCalle3027922010-08-25 11:45:40 +00003628 ICE->getCastKind() == CK_NoOp)
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003629 E = ICE->getSubExpr()->IgnoreParens();
3630 else
3631 break;
3632 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003633
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003634 if (const ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(E))
3635 return ASE->getBase()->getType()->isVectorType();
3636
3637 if (isa<ExtVectorElementExpr>(E))
3638 return true;
3639
Richard Smith7873de02016-08-11 22:25:46 +00003640 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3641 if (auto *BD = dyn_cast<BindingDecl>(DRE->getDecl()))
3642 if (auto *E = BD->getBinding())
3643 return E->refersToVectorElement();
3644
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003645 return false;
3646}
3647
Andrey Bokhankod9eab9c2015-08-03 10:38:10 +00003648bool Expr::refersToGlobalRegisterVar() const {
3649 const Expr *E = this->IgnoreParenImpCasts();
3650
3651 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
3652 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
3653 if (VD->getStorageClass() == SC_Register &&
3654 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
3655 return true;
3656
3657 return false;
3658}
3659
Chris Lattnerb8211f62009-02-16 22:14:05 +00003660/// isArrow - Return true if the base expression is a pointer to vector,
3661/// return false if the base expression is a vector.
3662bool ExtVectorElementExpr::isArrow() const {
3663 return getBase()->getType()->isPointerType();
3664}
3665
Nate Begemance4d7fc2008-04-18 23:10:10 +00003666unsigned ExtVectorElementExpr::getNumElements() const {
John McCall9dd450b2009-09-21 23:43:11 +00003667 if (const VectorType *VT = getType()->getAs<VectorType>())
Nate Begemanf322eab2008-05-09 06:41:27 +00003668 return VT->getNumElements();
3669 return 1;
Chris Lattner177bd452007-08-03 16:00:20 +00003670}
3671
Nate Begemanf322eab2008-05-09 06:41:27 +00003672/// containsDuplicateElements - Return true if any element access is repeated.
Nate Begemance4d7fc2008-04-18 23:10:10 +00003673bool ExtVectorElementExpr::containsDuplicateElements() const {
Daniel Dunbarcb2a0562009-10-18 02:09:09 +00003674 // FIXME: Refactor this code to an accessor on the AST node which returns the
3675 // "type" of component access, and share with code below and in Sema.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003676 StringRef Comp = Accessor->getName();
Nate Begeman7e5185b2009-01-18 02:01:21 +00003677
3678 // Halving swizzles do not contain duplicate elements.
Daniel Dunbar125c9c92009-10-17 23:53:04 +00003679 if (Comp == "hi" || Comp == "lo" || Comp == "even" || Comp == "odd")
Nate Begeman7e5185b2009-01-18 02:01:21 +00003680 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003681
Nate Begeman7e5185b2009-01-18 02:01:21 +00003682 // Advance past s-char prefix on hex swizzles.
Daniel Dunbar125c9c92009-10-17 23:53:04 +00003683 if (Comp[0] == 's' || Comp[0] == 'S')
3684 Comp = Comp.substr(1);
Mike Stump11289f42009-09-09 15:08:12 +00003685
Daniel Dunbar125c9c92009-10-17 23:53:04 +00003686 for (unsigned i = 0, e = Comp.size(); i != e; ++i)
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003687 if (Comp.substr(i + 1).find(Comp[i]) != StringRef::npos)
Steve Naroff0d595ca2007-07-30 03:29:09 +00003688 return true;
Daniel Dunbar125c9c92009-10-17 23:53:04 +00003689
Steve Naroff0d595ca2007-07-30 03:29:09 +00003690 return false;
3691}
Chris Lattner885b4952007-08-02 23:36:59 +00003692
Nate Begemanf322eab2008-05-09 06:41:27 +00003693/// getEncodedElementAccess - We encode the fields as a llvm ConstantArray.
Nate Begemand3862152008-05-13 21:03:02 +00003694void ExtVectorElementExpr::getEncodedElementAccess(
Benjamin Kramer99383102015-07-28 16:25:32 +00003695 SmallVectorImpl<uint32_t> &Elts) const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003696 StringRef Comp = Accessor->getName();
Pirama Arumuga Nainar98eaa622016-07-22 18:49:43 +00003697 bool isNumericAccessor = false;
3698 if (Comp[0] == 's' || Comp[0] == 'S') {
Daniel Dunbarce5a0b32009-10-18 02:09:31 +00003699 Comp = Comp.substr(1);
Pirama Arumuga Nainar98eaa622016-07-22 18:49:43 +00003700 isNumericAccessor = true;
3701 }
Mike Stump11289f42009-09-09 15:08:12 +00003702
Daniel Dunbarce5a0b32009-10-18 02:09:31 +00003703 bool isHi = Comp == "hi";
3704 bool isLo = Comp == "lo";
3705 bool isEven = Comp == "even";
3706 bool isOdd = Comp == "odd";
Mike Stump11289f42009-09-09 15:08:12 +00003707
Nate Begemanf322eab2008-05-09 06:41:27 +00003708 for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
3709 uint64_t Index;
Mike Stump11289f42009-09-09 15:08:12 +00003710
Nate Begemanf322eab2008-05-09 06:41:27 +00003711 if (isHi)
3712 Index = e + i;
3713 else if (isLo)
3714 Index = i;
3715 else if (isEven)
3716 Index = 2 * i;
3717 else if (isOdd)
3718 Index = 2 * i + 1;
3719 else
Pirama Arumuga Nainar98eaa622016-07-22 18:49:43 +00003720 Index = ExtVectorType::getAccessorIdx(Comp[i], isNumericAccessor);
Chris Lattner885b4952007-08-02 23:36:59 +00003721
Nate Begemand3862152008-05-13 21:03:02 +00003722 Elts.push_back(Index);
Chris Lattner885b4952007-08-02 23:36:59 +00003723 }
Nate Begemanf322eab2008-05-09 06:41:27 +00003724}
3725
Craig Topper37932912013-08-18 10:09:15 +00003726ShuffleVectorExpr::ShuffleVectorExpr(const ASTContext &C, ArrayRef<Expr*> args,
Douglas Gregora6e053e2010-12-15 01:34:56 +00003727 QualType Type, SourceLocation BLoc,
Fangrui Song6907ce22018-07-30 19:24:48 +00003728 SourceLocation RP)
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003729 : Expr(ShuffleVectorExprClass, Type, VK_RValue, OK_Ordinary,
3730 Type->isDependentType(), Type->isDependentType(),
3731 Type->isInstantiationDependentType(),
3732 Type->containsUnexpandedParameterPack()),
3733 BuiltinLoc(BLoc), RParenLoc(RP), NumExprs(args.size())
3734{
Benjamin Kramerc215e762012-08-24 11:54:20 +00003735 SubExprs = new (C) Stmt*[args.size()];
3736 for (unsigned i = 0; i != args.size(); i++) {
Douglas Gregora6e053e2010-12-15 01:34:56 +00003737 if (args[i]->isTypeDependent())
3738 ExprBits.TypeDependent = true;
3739 if (args[i]->isValueDependent())
3740 ExprBits.ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003741 if (args[i]->isInstantiationDependent())
3742 ExprBits.InstantiationDependent = true;
Douglas Gregora6e053e2010-12-15 01:34:56 +00003743 if (args[i]->containsUnexpandedParameterPack())
3744 ExprBits.ContainsUnexpandedParameterPack = true;
3745
3746 SubExprs[i] = args[i];
3747 }
3748}
3749
Craig Topper37932912013-08-18 10:09:15 +00003750void ShuffleVectorExpr::setExprs(const ASTContext &C, ArrayRef<Expr *> Exprs) {
Nate Begeman48745922009-08-12 02:28:50 +00003751 if (SubExprs) C.Deallocate(SubExprs);
3752
Dmitri Gribenko674eaa22013-05-10 00:43:44 +00003753 this->NumExprs = Exprs.size();
Dmitri Gribenko48d6daf2013-05-10 17:30:13 +00003754 SubExprs = new (C) Stmt*[NumExprs];
Dmitri Gribenko674eaa22013-05-10 00:43:44 +00003755 memcpy(SubExprs, Exprs.data(), sizeof(Expr *) * Exprs.size());
Mike Stump11289f42009-09-09 15:08:12 +00003756}
Nate Begeman48745922009-08-12 02:28:50 +00003757
Craig Topper37932912013-08-18 10:09:15 +00003758GenericSelectionExpr::GenericSelectionExpr(const ASTContext &Context,
Peter Collingbourne91147592011-04-15 00:35:48 +00003759 SourceLocation GenericLoc, Expr *ControllingExpr,
Benjamin Kramerc215e762012-08-24 11:54:20 +00003760 ArrayRef<TypeSourceInfo*> AssocTypes,
3761 ArrayRef<Expr*> AssocExprs,
3762 SourceLocation DefaultLoc,
Peter Collingbourne91147592011-04-15 00:35:48 +00003763 SourceLocation RParenLoc,
3764 bool ContainsUnexpandedParameterPack,
3765 unsigned ResultIndex)
3766 : Expr(GenericSelectionExprClass,
3767 AssocExprs[ResultIndex]->getType(),
3768 AssocExprs[ResultIndex]->getValueKind(),
3769 AssocExprs[ResultIndex]->getObjectKind(),
3770 AssocExprs[ResultIndex]->isTypeDependent(),
3771 AssocExprs[ResultIndex]->isValueDependent(),
Douglas Gregor678d76c2011-07-01 01:22:09 +00003772 AssocExprs[ResultIndex]->isInstantiationDependent(),
Peter Collingbourne91147592011-04-15 00:35:48 +00003773 ContainsUnexpandedParameterPack),
Benjamin Kramerc215e762012-08-24 11:54:20 +00003774 AssocTypes(new (Context) TypeSourceInfo*[AssocTypes.size()]),
3775 SubExprs(new (Context) Stmt*[END_EXPR+AssocExprs.size()]),
3776 NumAssocs(AssocExprs.size()), ResultIndex(ResultIndex),
3777 GenericLoc(GenericLoc), DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
Peter Collingbourne91147592011-04-15 00:35:48 +00003778 SubExprs[CONTROLLING] = ControllingExpr;
Benjamin Kramerc215e762012-08-24 11:54:20 +00003779 assert(AssocTypes.size() == AssocExprs.size());
3780 std::copy(AssocTypes.begin(), AssocTypes.end(), this->AssocTypes);
3781 std::copy(AssocExprs.begin(), AssocExprs.end(), SubExprs+END_EXPR);
Peter Collingbourne91147592011-04-15 00:35:48 +00003782}
3783
Craig Topper37932912013-08-18 10:09:15 +00003784GenericSelectionExpr::GenericSelectionExpr(const ASTContext &Context,
Peter Collingbourne91147592011-04-15 00:35:48 +00003785 SourceLocation GenericLoc, Expr *ControllingExpr,
Benjamin Kramerc215e762012-08-24 11:54:20 +00003786 ArrayRef<TypeSourceInfo*> AssocTypes,
3787 ArrayRef<Expr*> AssocExprs,
3788 SourceLocation DefaultLoc,
Peter Collingbourne91147592011-04-15 00:35:48 +00003789 SourceLocation RParenLoc,
3790 bool ContainsUnexpandedParameterPack)
3791 : Expr(GenericSelectionExprClass,
3792 Context.DependentTy,
3793 VK_RValue,
3794 OK_Ordinary,
Douglas Gregor678d76c2011-07-01 01:22:09 +00003795 /*isTypeDependent=*/true,
3796 /*isValueDependent=*/true,
3797 /*isInstantiationDependent=*/true,
Peter Collingbourne91147592011-04-15 00:35:48 +00003798 ContainsUnexpandedParameterPack),
Benjamin Kramerc215e762012-08-24 11:54:20 +00003799 AssocTypes(new (Context) TypeSourceInfo*[AssocTypes.size()]),
3800 SubExprs(new (Context) Stmt*[END_EXPR+AssocExprs.size()]),
3801 NumAssocs(AssocExprs.size()), ResultIndex(-1U), GenericLoc(GenericLoc),
3802 DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
Peter Collingbourne91147592011-04-15 00:35:48 +00003803 SubExprs[CONTROLLING] = ControllingExpr;
Benjamin Kramerc215e762012-08-24 11:54:20 +00003804 assert(AssocTypes.size() == AssocExprs.size());
3805 std::copy(AssocTypes.begin(), AssocTypes.end(), this->AssocTypes);
3806 std::copy(AssocExprs.begin(), AssocExprs.end(), SubExprs+END_EXPR);
Peter Collingbourne91147592011-04-15 00:35:48 +00003807}
3808
Ted Kremenek85e92ec2007-08-24 18:13:47 +00003809//===----------------------------------------------------------------------===//
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003810// DesignatedInitExpr
3811//===----------------------------------------------------------------------===//
3812
Chandler Carruth631abd92011-06-16 06:47:06 +00003813IdentifierInfo *DesignatedInitExpr::Designator::getFieldName() const {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003814 assert(Kind == FieldDesignator && "Only valid on a field designator");
3815 if (Field.NameOrField & 0x01)
3816 return reinterpret_cast<IdentifierInfo *>(Field.NameOrField&~0x01);
3817 else
3818 return getField()->getIdentifier();
3819}
3820
Craig Topper37932912013-08-18 10:09:15 +00003821DesignatedInitExpr::DesignatedInitExpr(const ASTContext &C, QualType Ty,
David Majnemerf7e36092016-06-23 00:15:04 +00003822 llvm::ArrayRef<Designator> Designators,
Mike Stump11289f42009-09-09 15:08:12 +00003823 SourceLocation EqualOrColonLoc,
Douglas Gregord5846a12009-04-15 06:41:24 +00003824 bool GNUSyntax,
Benjamin Kramerc215e762012-08-24 11:54:20 +00003825 ArrayRef<Expr*> IndexExprs,
Douglas Gregorca1aeec2009-05-21 23:17:49 +00003826 Expr *Init)
Mike Stump11289f42009-09-09 15:08:12 +00003827 : Expr(DesignatedInitExprClass, Ty,
John McCall7decc9e2010-11-18 06:31:45 +00003828 Init->getValueKind(), Init->getObjectKind(),
Douglas Gregora6e053e2010-12-15 01:34:56 +00003829 Init->isTypeDependent(), Init->isValueDependent(),
Douglas Gregor678d76c2011-07-01 01:22:09 +00003830 Init->isInstantiationDependent(),
Douglas Gregora6e053e2010-12-15 01:34:56 +00003831 Init->containsUnexpandedParameterPack()),
Mike Stump11289f42009-09-09 15:08:12 +00003832 EqualOrColonLoc(EqualOrColonLoc), GNUSyntax(GNUSyntax),
David Majnemerf7e36092016-06-23 00:15:04 +00003833 NumDesignators(Designators.size()), NumSubExprs(IndexExprs.size() + 1) {
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00003834 this->Designators = new (C) Designator[NumDesignators];
Douglas Gregorca1aeec2009-05-21 23:17:49 +00003835
3836 // Record the initializer itself.
Benjamin Kramer5733e352015-07-18 17:09:36 +00003837 child_iterator Child = child_begin();
Douglas Gregorca1aeec2009-05-21 23:17:49 +00003838 *Child++ = Init;
3839
3840 // Copy the designators and their subexpressions, computing
3841 // value-dependence along the way.
3842 unsigned IndexIdx = 0;
3843 for (unsigned I = 0; I != NumDesignators; ++I) {
Douglas Gregord5846a12009-04-15 06:41:24 +00003844 this->Designators[I] = Designators[I];
Douglas Gregorca1aeec2009-05-21 23:17:49 +00003845
3846 if (this->Designators[I].isArrayDesignator()) {
3847 // Compute type- and value-dependence.
3848 Expr *Index = IndexExprs[IndexIdx];
Douglas Gregora6e053e2010-12-15 01:34:56 +00003849 if (Index->isTypeDependent() || Index->isValueDependent())
David Majnemer4f217682015-01-09 01:39:09 +00003850 ExprBits.TypeDependent = ExprBits.ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003851 if (Index->isInstantiationDependent())
3852 ExprBits.InstantiationDependent = true;
Douglas Gregora6e053e2010-12-15 01:34:56 +00003853 // Propagate unexpanded parameter packs.
3854 if (Index->containsUnexpandedParameterPack())
3855 ExprBits.ContainsUnexpandedParameterPack = true;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00003856
3857 // Copy the index expressions into permanent storage.
3858 *Child++ = IndexExprs[IndexIdx++];
3859 } else if (this->Designators[I].isArrayRangeDesignator()) {
3860 // Compute type- and value-dependence.
3861 Expr *Start = IndexExprs[IndexIdx];
3862 Expr *End = IndexExprs[IndexIdx + 1];
Douglas Gregora6e053e2010-12-15 01:34:56 +00003863 if (Start->isTypeDependent() || Start->isValueDependent() ||
Douglas Gregor678d76c2011-07-01 01:22:09 +00003864 End->isTypeDependent() || End->isValueDependent()) {
David Majnemer4f217682015-01-09 01:39:09 +00003865 ExprBits.TypeDependent = ExprBits.ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003866 ExprBits.InstantiationDependent = true;
Fangrui Song6907ce22018-07-30 19:24:48 +00003867 } else if (Start->isInstantiationDependent() ||
Douglas Gregor678d76c2011-07-01 01:22:09 +00003868 End->isInstantiationDependent()) {
3869 ExprBits.InstantiationDependent = true;
3870 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003871
Douglas Gregora6e053e2010-12-15 01:34:56 +00003872 // Propagate unexpanded parameter packs.
3873 if (Start->containsUnexpandedParameterPack() ||
3874 End->containsUnexpandedParameterPack())
3875 ExprBits.ContainsUnexpandedParameterPack = true;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00003876
3877 // Copy the start/end expressions into permanent storage.
3878 *Child++ = IndexExprs[IndexIdx++];
3879 *Child++ = IndexExprs[IndexIdx++];
3880 }
3881 }
3882
Benjamin Kramerc215e762012-08-24 11:54:20 +00003883 assert(IndexIdx == IndexExprs.size() && "Wrong number of index expressions");
Douglas Gregord5846a12009-04-15 06:41:24 +00003884}
3885
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003886DesignatedInitExpr *
David Majnemerf7e36092016-06-23 00:15:04 +00003887DesignatedInitExpr::Create(const ASTContext &C,
3888 llvm::ArrayRef<Designator> Designators,
Benjamin Kramerc215e762012-08-24 11:54:20 +00003889 ArrayRef<Expr*> IndexExprs,
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003890 SourceLocation ColonOrEqualLoc,
3891 bool UsesColonSyntax, Expr *Init) {
James Y Knighte00a67e2015-12-31 04:18:25 +00003892 void *Mem = C.Allocate(totalSizeToAlloc<Stmt *>(IndexExprs.size() + 1),
Benjamin Kramerc3f89252016-10-20 14:27:22 +00003893 alignof(DesignatedInitExpr));
David Majnemerf7e36092016-06-23 00:15:04 +00003894 return new (Mem) DesignatedInitExpr(C, C.VoidTy, Designators,
Douglas Gregorca1aeec2009-05-21 23:17:49 +00003895 ColonOrEqualLoc, UsesColonSyntax,
Benjamin Kramerc215e762012-08-24 11:54:20 +00003896 IndexExprs, Init);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003897}
3898
Craig Topper37932912013-08-18 10:09:15 +00003899DesignatedInitExpr *DesignatedInitExpr::CreateEmpty(const ASTContext &C,
Douglas Gregor38676d52009-04-16 00:55:48 +00003900 unsigned NumIndexExprs) {
James Y Knighte00a67e2015-12-31 04:18:25 +00003901 void *Mem = C.Allocate(totalSizeToAlloc<Stmt *>(NumIndexExprs + 1),
Benjamin Kramerc3f89252016-10-20 14:27:22 +00003902 alignof(DesignatedInitExpr));
Douglas Gregor38676d52009-04-16 00:55:48 +00003903 return new (Mem) DesignatedInitExpr(NumIndexExprs + 1);
3904}
3905
Craig Topper37932912013-08-18 10:09:15 +00003906void DesignatedInitExpr::setDesignators(const ASTContext &C,
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00003907 const Designator *Desigs,
Douglas Gregor38676d52009-04-16 00:55:48 +00003908 unsigned NumDesigs) {
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00003909 Designators = new (C) Designator[NumDesigs];
Douglas Gregor38676d52009-04-16 00:55:48 +00003910 NumDesignators = NumDesigs;
3911 for (unsigned I = 0; I != NumDesigs; ++I)
3912 Designators[I] = Desigs[I];
3913}
3914
Abramo Bagnara22f8cd72011-03-16 15:08:46 +00003915SourceRange DesignatedInitExpr::getDesignatorsSourceRange() const {
3916 DesignatedInitExpr *DIE = const_cast<DesignatedInitExpr*>(this);
3917 if (size() == 1)
3918 return DIE->getDesignator(0)->getSourceRange();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003919 return SourceRange(DIE->getDesignator(0)->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00003920 DIE->getDesignator(size() - 1)->getEndLoc());
Abramo Bagnara22f8cd72011-03-16 15:08:46 +00003921}
3922
Stephen Kelly724e9e52018-08-09 20:05:03 +00003923SourceLocation DesignatedInitExpr::getBeginLoc() const {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003924 SourceLocation StartLoc;
David Majnemerf7e36092016-06-23 00:15:04 +00003925 auto *DIE = const_cast<DesignatedInitExpr *>(this);
3926 Designator &First = *DIE->getDesignator(0);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003927 if (First.isFieldDesignator()) {
Douglas Gregor5c7c9cb2009-03-28 00:41:23 +00003928 if (GNUSyntax)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003929 StartLoc = SourceLocation::getFromRawEncoding(First.Field.FieldLoc);
3930 else
3931 StartLoc = SourceLocation::getFromRawEncoding(First.Field.DotLoc);
3932 } else
Chris Lattner8ba22472009-02-16 22:33:34 +00003933 StartLoc =
3934 SourceLocation::getFromRawEncoding(First.ArrayOrRange.LBracketLoc);
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00003935 return StartLoc;
3936}
3937
Stephen Kelly02a67ba2018-08-09 20:05:47 +00003938SourceLocation DesignatedInitExpr::getEndLoc() const {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00003939 return getInit()->getEndLoc();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003940}
3941
Dmitri Gribenkod06f7ff2013-01-26 15:15:52 +00003942Expr *DesignatedInitExpr::getArrayIndex(const Designator& D) const {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003943 assert(D.Kind == Designator::ArrayDesignator && "Requires array designator");
James Y Knighte00a67e2015-12-31 04:18:25 +00003944 return getSubExpr(D.ArrayOrRange.Index + 1);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003945}
3946
Dmitri Gribenkod06f7ff2013-01-26 15:15:52 +00003947Expr *DesignatedInitExpr::getArrayRangeStart(const Designator &D) const {
Mike Stump11289f42009-09-09 15:08:12 +00003948 assert(D.Kind == Designator::ArrayRangeDesignator &&
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003949 "Requires array range designator");
James Y Knighte00a67e2015-12-31 04:18:25 +00003950 return getSubExpr(D.ArrayOrRange.Index + 1);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003951}
3952
Dmitri Gribenkod06f7ff2013-01-26 15:15:52 +00003953Expr *DesignatedInitExpr::getArrayRangeEnd(const Designator &D) const {
Mike Stump11289f42009-09-09 15:08:12 +00003954 assert(D.Kind == Designator::ArrayRangeDesignator &&
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003955 "Requires array range designator");
James Y Knighte00a67e2015-12-31 04:18:25 +00003956 return getSubExpr(D.ArrayOrRange.Index + 2);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00003957}
3958
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003959/// Replaces the designator at index @p Idx with the series
Douglas Gregord5846a12009-04-15 06:41:24 +00003960/// of designators in [First, Last).
Craig Topper37932912013-08-18 10:09:15 +00003961void DesignatedInitExpr::ExpandDesignator(const ASTContext &C, unsigned Idx,
Mike Stump11289f42009-09-09 15:08:12 +00003962 const Designator *First,
Douglas Gregord5846a12009-04-15 06:41:24 +00003963 const Designator *Last) {
3964 unsigned NumNewDesignators = Last - First;
3965 if (NumNewDesignators == 0) {
3966 std::copy_backward(Designators + Idx + 1,
3967 Designators + NumDesignators,
3968 Designators + Idx);
3969 --NumNewDesignators;
3970 return;
3971 } else if (NumNewDesignators == 1) {
3972 Designators[Idx] = *First;
3973 return;
3974 }
3975
Mike Stump11289f42009-09-09 15:08:12 +00003976 Designator *NewDesignators
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00003977 = new (C) Designator[NumDesignators - 1 + NumNewDesignators];
Douglas Gregord5846a12009-04-15 06:41:24 +00003978 std::copy(Designators, Designators + Idx, NewDesignators);
3979 std::copy(First, Last, NewDesignators + Idx);
3980 std::copy(Designators + Idx + 1, Designators + NumDesignators,
3981 NewDesignators + Idx + NumNewDesignators);
Douglas Gregord5846a12009-04-15 06:41:24 +00003982 Designators = NewDesignators;
3983 NumDesignators = NumDesignators - 1 + NumNewDesignators;
3984}
3985
Yunzhong Gaocb779302015-06-10 00:27:52 +00003986DesignatedInitUpdateExpr::DesignatedInitUpdateExpr(const ASTContext &C,
3987 SourceLocation lBraceLoc, Expr *baseExpr, SourceLocation rBraceLoc)
3988 : Expr(DesignatedInitUpdateExprClass, baseExpr->getType(), VK_RValue,
3989 OK_Ordinary, false, false, false, false) {
3990 BaseAndUpdaterExprs[0] = baseExpr;
3991
3992 InitListExpr *ILE = new (C) InitListExpr(C, lBraceLoc, None, rBraceLoc);
3993 ILE->setType(baseExpr->getType());
3994 BaseAndUpdaterExprs[1] = ILE;
3995}
3996
Stephen Kelly724e9e52018-08-09 20:05:03 +00003997SourceLocation DesignatedInitUpdateExpr::getBeginLoc() const {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003998 return getBase()->getBeginLoc();
Yunzhong Gaocb779302015-06-10 00:27:52 +00003999}
4000
Stephen Kelly02a67ba2018-08-09 20:05:47 +00004001SourceLocation DesignatedInitUpdateExpr::getEndLoc() const {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00004002 return getBase()->getEndLoc();
Yunzhong Gaocb779302015-06-10 00:27:52 +00004003}
4004
Bruno Riccif49e1ca2018-11-20 16:20:40 +00004005ParenListExpr::ParenListExpr(SourceLocation LParenLoc, ArrayRef<Expr *> Exprs,
4006 SourceLocation RParenLoc)
4007 : Expr(ParenListExprClass, QualType(), VK_RValue, OK_Ordinary, false, false,
4008 false, false),
4009 LParenLoc(LParenLoc), RParenLoc(RParenLoc) {
4010 ParenListExprBits.NumExprs = Exprs.size();
4011
4012 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
4013 if (Exprs[I]->isTypeDependent())
Douglas Gregora6e053e2010-12-15 01:34:56 +00004014 ExprBits.TypeDependent = true;
Bruno Riccif49e1ca2018-11-20 16:20:40 +00004015 if (Exprs[I]->isValueDependent())
Douglas Gregora6e053e2010-12-15 01:34:56 +00004016 ExprBits.ValueDependent = true;
Bruno Riccif49e1ca2018-11-20 16:20:40 +00004017 if (Exprs[I]->isInstantiationDependent())
Douglas Gregor678d76c2011-07-01 01:22:09 +00004018 ExprBits.InstantiationDependent = true;
Bruno Riccif49e1ca2018-11-20 16:20:40 +00004019 if (Exprs[I]->containsUnexpandedParameterPack())
Douglas Gregora6e053e2010-12-15 01:34:56 +00004020 ExprBits.ContainsUnexpandedParameterPack = true;
4021
Bruno Riccif49e1ca2018-11-20 16:20:40 +00004022 getTrailingObjects<Stmt *>()[I] = Exprs[I];
Douglas Gregora6e053e2010-12-15 01:34:56 +00004023 }
Nate Begeman5ec4b312009-08-10 23:49:36 +00004024}
4025
Bruno Riccif49e1ca2018-11-20 16:20:40 +00004026ParenListExpr::ParenListExpr(EmptyShell Empty, unsigned NumExprs)
4027 : Expr(ParenListExprClass, Empty) {
4028 ParenListExprBits.NumExprs = NumExprs;
4029}
4030
4031ParenListExpr *ParenListExpr::Create(const ASTContext &Ctx,
4032 SourceLocation LParenLoc,
4033 ArrayRef<Expr *> Exprs,
4034 SourceLocation RParenLoc) {
4035 void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *>(Exprs.size()),
4036 alignof(ParenListExpr));
4037 return new (Mem) ParenListExpr(LParenLoc, Exprs, RParenLoc);
4038}
4039
4040ParenListExpr *ParenListExpr::CreateEmpty(const ASTContext &Ctx,
4041 unsigned NumExprs) {
4042 void *Mem =
4043 Ctx.Allocate(totalSizeToAlloc<Stmt *>(NumExprs), alignof(ParenListExpr));
4044 return new (Mem) ParenListExpr(EmptyShell(), NumExprs);
4045}
4046
John McCall1bf58462011-02-16 08:02:54 +00004047const OpaqueValueExpr *OpaqueValueExpr::findInCopyConstruct(const Expr *e) {
4048 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(e))
4049 e = ewc->getSubExpr();
Douglas Gregorfe314812011-06-21 17:03:29 +00004050 if (const MaterializeTemporaryExpr *m = dyn_cast<MaterializeTemporaryExpr>(e))
4051 e = m->GetTemporaryExpr();
John McCall1bf58462011-02-16 08:02:54 +00004052 e = cast<CXXConstructExpr>(e)->getArg(0);
4053 while (const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
4054 e = ice->getSubExpr();
4055 return cast<OpaqueValueExpr>(e);
4056}
4057
Craig Topper37932912013-08-18 10:09:15 +00004058PseudoObjectExpr *PseudoObjectExpr::Create(const ASTContext &Context,
4059 EmptyShell sh,
John McCallfe96e0b2011-11-06 09:01:30 +00004060 unsigned numSemanticExprs) {
James Y Knighte00a67e2015-12-31 04:18:25 +00004061 void *buffer =
4062 Context.Allocate(totalSizeToAlloc<Expr *>(1 + numSemanticExprs),
Benjamin Kramerc3f89252016-10-20 14:27:22 +00004063 alignof(PseudoObjectExpr));
John McCallfe96e0b2011-11-06 09:01:30 +00004064 return new(buffer) PseudoObjectExpr(sh, numSemanticExprs);
4065}
4066
4067PseudoObjectExpr::PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs)
4068 : Expr(PseudoObjectExprClass, shell) {
4069 PseudoObjectExprBits.NumSubExprs = numSemanticExprs + 1;
4070}
4071
Craig Topper37932912013-08-18 10:09:15 +00004072PseudoObjectExpr *PseudoObjectExpr::Create(const ASTContext &C, Expr *syntax,
John McCallfe96e0b2011-11-06 09:01:30 +00004073 ArrayRef<Expr*> semantics,
4074 unsigned resultIndex) {
4075 assert(syntax && "no syntactic expression!");
Eugene Zelenkoae304b02017-11-17 18:09:48 +00004076 assert(semantics.size() && "no semantic expressions!");
John McCallfe96e0b2011-11-06 09:01:30 +00004077
4078 QualType type;
4079 ExprValueKind VK;
4080 if (resultIndex == NoResult) {
4081 type = C.VoidTy;
4082 VK = VK_RValue;
4083 } else {
4084 assert(resultIndex < semantics.size());
4085 type = semantics[resultIndex]->getType();
4086 VK = semantics[resultIndex]->getValueKind();
4087 assert(semantics[resultIndex]->getObjectKind() == OK_Ordinary);
4088 }
4089
James Y Knighte00a67e2015-12-31 04:18:25 +00004090 void *buffer = C.Allocate(totalSizeToAlloc<Expr *>(semantics.size() + 1),
Benjamin Kramerc3f89252016-10-20 14:27:22 +00004091 alignof(PseudoObjectExpr));
John McCallfe96e0b2011-11-06 09:01:30 +00004092 return new(buffer) PseudoObjectExpr(type, VK, syntax, semantics,
4093 resultIndex);
4094}
4095
4096PseudoObjectExpr::PseudoObjectExpr(QualType type, ExprValueKind VK,
4097 Expr *syntax, ArrayRef<Expr*> semantics,
4098 unsigned resultIndex)
4099 : Expr(PseudoObjectExprClass, type, VK, OK_Ordinary,
4100 /*filled in at end of ctor*/ false, false, false, false) {
4101 PseudoObjectExprBits.NumSubExprs = semantics.size() + 1;
4102 PseudoObjectExprBits.ResultIndex = resultIndex + 1;
4103
4104 for (unsigned i = 0, e = semantics.size() + 1; i != e; ++i) {
4105 Expr *E = (i == 0 ? syntax : semantics[i-1]);
4106 getSubExprsBuffer()[i] = E;
4107
4108 if (E->isTypeDependent())
4109 ExprBits.TypeDependent = true;
4110 if (E->isValueDependent())
4111 ExprBits.ValueDependent = true;
4112 if (E->isInstantiationDependent())
4113 ExprBits.InstantiationDependent = true;
4114 if (E->containsUnexpandedParameterPack())
4115 ExprBits.ContainsUnexpandedParameterPack = true;
4116
4117 if (isa<OpaqueValueExpr>(E))
Craig Topper36250ad2014-05-12 05:36:57 +00004118 assert(cast<OpaqueValueExpr>(E)->getSourceExpr() != nullptr &&
John McCallfe96e0b2011-11-06 09:01:30 +00004119 "opaque-value semantic expressions for pseudo-object "
4120 "operations must have sources");
4121 }
4122}
4123
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004124//===----------------------------------------------------------------------===//
Ted Kremenek85e92ec2007-08-24 18:13:47 +00004125// Child Iterators for iterating over subexpressions/substatements
4126//===----------------------------------------------------------------------===//
4127
Peter Collingbournee190dee2011-03-11 19:24:49 +00004128// UnaryExprOrTypeTraitExpr
4129Stmt::child_range UnaryExprOrTypeTraitExpr::children() {
Aaron Ballman4c54fe02017-04-11 20:21:30 +00004130 const_child_range CCR =
4131 const_cast<const UnaryExprOrTypeTraitExpr *>(this)->children();
4132 return child_range(cast_away_const(CCR.begin()), cast_away_const(CCR.end()));
4133}
4134
4135Stmt::const_child_range UnaryExprOrTypeTraitExpr::children() const {
Sebastian Redl6f282892008-11-11 17:56:53 +00004136 // If this is of a type and the type is a VLA type (and not a typedef), the
4137 // size expression of the VLA needs to be treated as an executable expression.
4138 // Why isn't this weirdness documented better in StmtIterator?
4139 if (isArgumentType()) {
Aaron Ballman4c54fe02017-04-11 20:21:30 +00004140 if (const VariableArrayType *T =
4141 dyn_cast<VariableArrayType>(getArgumentType().getTypePtr()))
4142 return const_child_range(const_child_iterator(T), const_child_iterator());
4143 return const_child_range(const_child_iterator(), const_child_iterator());
Sebastian Redl6f282892008-11-11 17:56:53 +00004144 }
Aaron Ballman4c54fe02017-04-11 20:21:30 +00004145 return const_child_range(&Argument.Ex, &Argument.Ex + 1);
Ted Kremenek04746ce2007-10-18 23:28:49 +00004146}
Fariborz Jahaniana32aaef2007-10-17 16:58:11 +00004147
Benjamin Kramerc215e762012-08-24 11:54:20 +00004148AtomicExpr::AtomicExpr(SourceLocation BLoc, ArrayRef<Expr*> args,
Eli Friedman8d3e43f2011-10-14 22:48:56 +00004149 QualType t, AtomicOp op, SourceLocation RP)
Eugene Zelenkoae304b02017-11-17 18:09:48 +00004150 : Expr(AtomicExprClass, t, VK_RValue, OK_Ordinary,
4151 false, false, false, false),
4152 NumSubExprs(args.size()), BuiltinLoc(BLoc), RParenLoc(RP), Op(op)
4153{
Benjamin Kramerc215e762012-08-24 11:54:20 +00004154 assert(args.size() == getNumSubExprs(op) && "wrong number of subexpressions");
4155 for (unsigned i = 0; i != args.size(); i++) {
Eli Friedman8d3e43f2011-10-14 22:48:56 +00004156 if (args[i]->isTypeDependent())
4157 ExprBits.TypeDependent = true;
4158 if (args[i]->isValueDependent())
4159 ExprBits.ValueDependent = true;
4160 if (args[i]->isInstantiationDependent())
4161 ExprBits.InstantiationDependent = true;
4162 if (args[i]->containsUnexpandedParameterPack())
4163 ExprBits.ContainsUnexpandedParameterPack = true;
4164
4165 SubExprs[i] = args[i];
4166 }
4167}
Richard Smithaa22a8c2012-04-10 22:49:28 +00004168
4169unsigned AtomicExpr::getNumSubExprs(AtomicOp Op) {
4170 switch (Op) {
Richard Smithfeea8832012-04-12 05:08:17 +00004171 case AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +00004172 case AO__opencl_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +00004173 case AO__c11_atomic_load:
Yaxun Liu39195062017-08-04 18:16:31 +00004174 case AO__atomic_load_n:
Yaxun Liu30d652a2017-08-15 16:02:49 +00004175 return 2;
Richard Smithfeea8832012-04-12 05:08:17 +00004176
Yaxun Liu30d652a2017-08-15 16:02:49 +00004177 case AO__opencl_atomic_load:
Richard Smithfeea8832012-04-12 05:08:17 +00004178 case AO__c11_atomic_store:
4179 case AO__c11_atomic_exchange:
4180 case AO__atomic_load:
4181 case AO__atomic_store:
4182 case AO__atomic_store_n:
4183 case AO__atomic_exchange_n:
4184 case AO__c11_atomic_fetch_add:
4185 case AO__c11_atomic_fetch_sub:
4186 case AO__c11_atomic_fetch_and:
4187 case AO__c11_atomic_fetch_or:
4188 case AO__c11_atomic_fetch_xor:
4189 case AO__atomic_fetch_add:
4190 case AO__atomic_fetch_sub:
4191 case AO__atomic_fetch_and:
4192 case AO__atomic_fetch_or:
4193 case AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00004194 case AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00004195 case AO__atomic_add_fetch:
4196 case AO__atomic_sub_fetch:
4197 case AO__atomic_and_fetch:
4198 case AO__atomic_or_fetch:
4199 case AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00004200 case AO__atomic_nand_fetch:
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00004201 case AO__atomic_fetch_min:
4202 case AO__atomic_fetch_max:
Yaxun Liu30d652a2017-08-15 16:02:49 +00004203 return 3;
Richard Smithfeea8832012-04-12 05:08:17 +00004204
Yaxun Liu30d652a2017-08-15 16:02:49 +00004205 case AO__opencl_atomic_store:
4206 case AO__opencl_atomic_exchange:
4207 case AO__opencl_atomic_fetch_add:
4208 case AO__opencl_atomic_fetch_sub:
4209 case AO__opencl_atomic_fetch_and:
4210 case AO__opencl_atomic_fetch_or:
4211 case AO__opencl_atomic_fetch_xor:
4212 case AO__opencl_atomic_fetch_min:
4213 case AO__opencl_atomic_fetch_max:
Richard Smithfeea8832012-04-12 05:08:17 +00004214 case AO__atomic_exchange:
Yaxun Liu30d652a2017-08-15 16:02:49 +00004215 return 4;
Richard Smithfeea8832012-04-12 05:08:17 +00004216
4217 case AO__c11_atomic_compare_exchange_strong:
4218 case AO__c11_atomic_compare_exchange_weak:
Yaxun Liu30d652a2017-08-15 16:02:49 +00004219 return 5;
4220
Yaxun Liu39195062017-08-04 18:16:31 +00004221 case AO__opencl_atomic_compare_exchange_strong:
4222 case AO__opencl_atomic_compare_exchange_weak:
Richard Smithfeea8832012-04-12 05:08:17 +00004223 case AO__atomic_compare_exchange:
4224 case AO__atomic_compare_exchange_n:
Yaxun Liu30d652a2017-08-15 16:02:49 +00004225 return 6;
Richard Smithaa22a8c2012-04-10 22:49:28 +00004226 }
4227 llvm_unreachable("unknown atomic op");
4228}
Alexey Bataeva1764212015-09-30 09:22:36 +00004229
Yaxun Liu39195062017-08-04 18:16:31 +00004230QualType AtomicExpr::getValueType() const {
4231 auto T = getPtr()->getType()->castAs<PointerType>()->getPointeeType();
4232 if (auto AT = T->getAs<AtomicType>())
4233 return AT->getValueType();
4234 return T;
4235}
4236
Alexey Bataev31300ed2016-02-04 11:27:03 +00004237QualType OMPArraySectionExpr::getBaseOriginalType(const Expr *Base) {
Alexey Bataeva1764212015-09-30 09:22:36 +00004238 unsigned ArraySectionCount = 0;
4239 while (auto *OASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParens())) {
4240 Base = OASE->getBase();
4241 ++ArraySectionCount;
4242 }
Alexey Bataev31300ed2016-02-04 11:27:03 +00004243 while (auto *ASE =
4244 dyn_cast<ArraySubscriptExpr>(Base->IgnoreParenImpCasts())) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004245 Base = ASE->getBase();
4246 ++ArraySectionCount;
4247 }
Alexey Bataev31300ed2016-02-04 11:27:03 +00004248 Base = Base->IgnoreParenImpCasts();
Alexey Bataeva1764212015-09-30 09:22:36 +00004249 auto OriginalTy = Base->getType();
4250 if (auto *DRE = dyn_cast<DeclRefExpr>(Base))
4251 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
4252 OriginalTy = PVD->getOriginalType().getNonReferenceType();
4253
4254 for (unsigned Cnt = 0; Cnt < ArraySectionCount; ++Cnt) {
4255 if (OriginalTy->isAnyPointerType())
4256 OriginalTy = OriginalTy->getPointeeType();
4257 else {
Eugene Zelenkoae304b02017-11-17 18:09:48 +00004258 assert (OriginalTy->isArrayType());
Alexey Bataeva1764212015-09-30 09:22:36 +00004259 OriginalTy = OriginalTy->castAsArrayTypeUnsafe()->getElementType();
4260 }
4261 }
4262 return OriginalTy;
4263}