blob: 5c9ceac854cfc446b4a423d37fcb06e88e2d521f [file] [log] [blame]
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001//===--- Expr.cpp - Expression AST Node Implementation --------------------===//
Chris Lattner1b926492006-08-23 06:42:10 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chris Lattner1b926492006-08-23 06:42:10 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the Expr class and subclasses.
10//
11//===----------------------------------------------------------------------===//
12
Eric Fiselier708afb52019-05-16 21:04:15 +000013#include "clang/AST/Expr.h"
14#include "clang/AST/APValue.h"
Chris Lattner5c4664e2007-07-15 23:32:58 +000015#include "clang/AST/ASTContext.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000016#include "clang/AST/Attr.h"
Douglas Gregor9a657932008-10-21 23:43:52 +000017#include "clang/AST/DeclCXX.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000018#include "clang/AST/DeclObjC.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000019#include "clang/AST/DeclTemplate.h"
Douglas Gregor1be329d2012-02-23 07:33:15 +000020#include "clang/AST/EvaluatedExprVisitor.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000021#include "clang/AST/ExprCXX.h"
David Majnemerbed356a2013-11-06 23:31:56 +000022#include "clang/AST/Mangle.h"
Eugene Zelenkoae304b02017-11-17 18:09:48 +000023#include "clang/AST/RecordLayout.h"
24#include "clang/AST/StmtVisitor.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000025#include "clang/Basic/Builtins.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000026#include "clang/Basic/CharInfo.h"
Chris Lattnere925d612010-11-17 07:37:15 +000027#include "clang/Basic/SourceManager.h"
Chris Lattnera7944d82007-11-27 18:22:04 +000028#include "clang/Basic/TargetInfo.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000029#include "clang/Lex/Lexer.h"
30#include "clang/Lex/LiteralSupport.h"
Douglas Gregor0840cc02009-11-01 20:32:48 +000031#include "llvm/Support/ErrorHandling.h"
Anders Carlsson2fb08242009-09-08 18:24:21 +000032#include "llvm/Support/raw_ostream.h"
Douglas Gregord5846a12009-04-15 06:41:24 +000033#include <algorithm>
Eli Friedmanfcec6302011-11-01 02:23:42 +000034#include <cstring>
Chris Lattner1b926492006-08-23 06:42:10 +000035using namespace clang;
36
Richard Smith018ac392016-11-03 18:55:18 +000037const Expr *Expr::getBestDynamicClassTypeExpr() const {
38 const Expr *E = this;
39 while (true) {
40 E = E->ignoreParenBaseCasts();
Rafael Espindola49e860b2012-06-26 17:45:31 +000041
Richard Smith018ac392016-11-03 18:55:18 +000042 // Follow the RHS of a comma operator.
43 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
44 if (BO->getOpcode() == BO_Comma) {
45 E = BO->getRHS();
46 continue;
47 }
48 }
49
50 // Step into initializer for materialized temporaries.
51 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
Tykerb0561b32019-11-17 11:41:55 +010052 E = MTE->getSubExpr();
Richard Smith018ac392016-11-03 18:55:18 +000053 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();
Simon Pilgrim1cd399c2019-10-03 11:22:48 +000088 auto *Derived =
89 cast<CXXRecordDecl>(E->getType()->castAs<RecordType>()->getDecl());
Rafael Espindola9c006de2012-10-27 01:03:43 +000090 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
Erik Pilkingtond9957c72019-11-20 15:39:22 -0800130bool Expr::isKnownToHaveBooleanValue(bool Semantic) const {
Peter Collingbourne91147592011-04-15 00:35:48 +0000131 const Expr *E = IgnoreParens();
132
Chris Lattner4ebae652010-04-16 23:34:13 +0000133 // If this value has _Bool type, it is obvious 0/1.
Peter Collingbourne91147592011-04-15 00:35:48 +0000134 if (E->getType()->isBooleanType()) return true;
Fangrui Song6907ce22018-07-30 19:24:48 +0000135 // If this is a non-scalar-integer type, we don't care enough to try.
Peter Collingbourne91147592011-04-15 00:35:48 +0000136 if (!E->getType()->isIntegralOrEnumerationType()) return false;
Fangrui Song6907ce22018-07-30 19:24:48 +0000137
Peter Collingbourne91147592011-04-15 00:35:48 +0000138 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
Chris Lattner4ebae652010-04-16 23:34:13 +0000139 switch (UO->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +0000140 case UO_Plus:
Erik Pilkingtond9957c72019-11-20 15:39:22 -0800141 return UO->getSubExpr()->isKnownToHaveBooleanValue(Semantic);
Richard Trieu0f097742014-04-04 04:13:47 +0000142 case UO_LNot:
143 return true;
Chris Lattner4ebae652010-04-16 23:34:13 +0000144 default:
145 return false;
146 }
147 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000148
John McCall45d30c32010-06-12 01:56:02 +0000149 // Only look through implicit casts. If the user writes
150 // '(int) (a && b)' treat it as an arbitrary int.
Erik Pilkingtond9957c72019-11-20 15:39:22 -0800151 // FIXME: Should we look through any cast expression in !Semantic mode?
Peter Collingbourne91147592011-04-15 00:35:48 +0000152 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
Erik Pilkingtond9957c72019-11-20 15:39:22 -0800153 return CE->getSubExpr()->isKnownToHaveBooleanValue(Semantic);
Fangrui Song6907ce22018-07-30 19:24:48 +0000154
Peter Collingbourne91147592011-04-15 00:35:48 +0000155 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
Chris Lattner4ebae652010-04-16 23:34:13 +0000156 switch (BO->getOpcode()) {
157 default: return false;
John McCalle3027922010-08-25 11:45:40 +0000158 case BO_LT: // Relational operators.
159 case BO_GT:
160 case BO_LE:
161 case BO_GE:
162 case BO_EQ: // Equality operators.
163 case BO_NE:
164 case BO_LAnd: // AND operator.
165 case BO_LOr: // Logical OR operator.
Chris Lattner4ebae652010-04-16 23:34:13 +0000166 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +0000167
John McCalle3027922010-08-25 11:45:40 +0000168 case BO_And: // Bitwise AND operator.
169 case BO_Xor: // Bitwise XOR operator.
170 case BO_Or: // Bitwise OR operator.
Chris Lattner4ebae652010-04-16 23:34:13 +0000171 // Handle things like (x==2)|(y==12).
Erik Pilkingtond9957c72019-11-20 15:39:22 -0800172 return BO->getLHS()->isKnownToHaveBooleanValue(Semantic) &&
173 BO->getRHS()->isKnownToHaveBooleanValue(Semantic);
Fangrui Song6907ce22018-07-30 19:24:48 +0000174
John McCalle3027922010-08-25 11:45:40 +0000175 case BO_Comma:
176 case BO_Assign:
Erik Pilkingtond9957c72019-11-20 15:39:22 -0800177 return BO->getRHS()->isKnownToHaveBooleanValue(Semantic);
Chris Lattner4ebae652010-04-16 23:34:13 +0000178 }
179 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000180
Peter Collingbourne91147592011-04-15 00:35:48 +0000181 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
Erik Pilkingtond9957c72019-11-20 15:39:22 -0800182 return CO->getTrueExpr()->isKnownToHaveBooleanValue(Semantic) &&
183 CO->getFalseExpr()->isKnownToHaveBooleanValue(Semantic);
Fangrui Song6907ce22018-07-30 19:24:48 +0000184
Erik Pilkington5c621522019-09-17 21:11:51 +0000185 if (isa<ObjCBoolLiteralExpr>(E))
186 return true;
187
188 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
Erik Pilkingtond9957c72019-11-20 15:39:22 -0800189 return OVE->getSourceExpr()->isKnownToHaveBooleanValue(Semantic);
Erik Pilkington5c621522019-09-17 21:11:51 +0000190
Erik Pilkington8bfb3532019-11-18 10:56:05 -0800191 if (const FieldDecl *FD = E->getSourceBitField())
Erik Pilkingtond9957c72019-11-20 15:39:22 -0800192 if (!Semantic && FD->getType()->isUnsignedIntegerType() &&
Erik Pilkington8bfb3532019-11-18 10:56:05 -0800193 !FD->getBitWidth()->isValueDependent() &&
194 FD->getBitWidthValue(FD->getASTContext()) == 1)
195 return true;
196
Chris Lattner4ebae652010-04-16 23:34:13 +0000197 return false;
198}
199
John McCallbd066782011-02-09 08:16:59 +0000200// Amusing macro metaprogramming hack: check whether a class provides
201// a more specific implementation of getExprLoc().
Daniel Dunbarb0ab5e92012-03-09 15:39:19 +0000202//
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000203// See also Stmt.cpp:{getBeginLoc(),getEndLoc()}.
Eugene Zelenkoae304b02017-11-17 18:09:48 +0000204namespace {
205 /// This implementation is used when a class provides a custom
206 /// implementation of getExprLoc.
207 template <class E, class T>
208 SourceLocation getExprLocImpl(const Expr *expr,
209 SourceLocation (T::*v)() const) {
210 return static_cast<const E*>(expr)->getExprLoc();
211 }
John McCallbd066782011-02-09 08:16:59 +0000212
Eugene Zelenkoae304b02017-11-17 18:09:48 +0000213 /// This implementation is used when a class doesn't provide
214 /// a custom implementation of getExprLoc. Overload resolution
215 /// should pick it over the implementation above because it's
216 /// more specialized according to function template partial ordering.
217 template <class E>
218 SourceLocation getExprLocImpl(const Expr *expr,
219 SourceLocation (Expr::*v)() const) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000220 return static_cast<const E *>(expr)->getBeginLoc();
Eugene Zelenkoae304b02017-11-17 18:09:48 +0000221 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000222}
John McCallbd066782011-02-09 08:16:59 +0000223
224SourceLocation Expr::getExprLoc() const {
225 switch (getStmtClass()) {
226 case Stmt::NoStmtClass: llvm_unreachable("statement without class");
227#define ABSTRACT_STMT(type)
228#define STMT(type, base) \
Richard Smitha0cbfc92014-07-26 00:47:13 +0000229 case Stmt::type##Class: break;
John McCallbd066782011-02-09 08:16:59 +0000230#define EXPR(type, base) \
231 case Stmt::type##Class: return getExprLocImpl<type>(this, &type::getExprLoc);
232#include "clang/AST/StmtNodes.inc"
233 }
Richard Smitha0cbfc92014-07-26 00:47:13 +0000234 llvm_unreachable("unknown expression kind");
John McCallbd066782011-02-09 08:16:59 +0000235}
236
Chris Lattner0eedafe2006-08-24 04:56:27 +0000237//===----------------------------------------------------------------------===//
238// Primary Expressions.
239//===----------------------------------------------------------------------===//
240
Gauthier Harnisch83c7b612019-06-15 10:24:47 +0000241static void AssertResultStorageKind(ConstantExpr::ResultStorageKind Kind) {
242 assert((Kind == ConstantExpr::RSK_APValue ||
243 Kind == ConstantExpr::RSK_Int64 || Kind == ConstantExpr::RSK_None) &&
244 "Invalid StorageKind Value");
245}
246
247ConstantExpr::ResultStorageKind
248ConstantExpr::getStorageKind(const APValue &Value) {
249 switch (Value.getKind()) {
250 case APValue::None:
Gauthier Harnischdea9d572019-06-21 08:26:21 +0000251 case APValue::Indeterminate:
Gauthier Harnisch83c7b612019-06-15 10:24:47 +0000252 return ConstantExpr::RSK_None;
253 case APValue::Int:
254 if (!Value.getInt().needsCleanup())
255 return ConstantExpr::RSK_Int64;
256 LLVM_FALLTHROUGH;
257 default:
258 return ConstantExpr::RSK_APValue;
259 }
260}
261
Gauthier Harnischdea9d572019-06-21 08:26:21 +0000262ConstantExpr::ResultStorageKind
263ConstantExpr::getStorageKind(const Type *T, const ASTContext &Context) {
264 if (T->isIntegralOrEnumerationType() && Context.getTypeInfo(T).Width <= 64)
265 return ConstantExpr::RSK_Int64;
266 return ConstantExpr::RSK_APValue;
267}
268
Gauthier Harnisch83c7b612019-06-15 10:24:47 +0000269void ConstantExpr::DefaultInit(ResultStorageKind StorageKind) {
270 ConstantExprBits.ResultKind = StorageKind;
Gauthier Harnischdea9d572019-06-21 08:26:21 +0000271 ConstantExprBits.APValueKind = APValue::None;
272 ConstantExprBits.HasCleanup = false;
273 if (StorageKind == ConstantExpr::RSK_APValue)
Gauthier Harnisch83c7b612019-06-15 10:24:47 +0000274 ::new (getTrailingObjects<APValue>()) APValue();
275}
276
277ConstantExpr::ConstantExpr(Expr *subexpr, ResultStorageKind StorageKind)
278 : FullExpr(ConstantExprClass, subexpr) {
279 DefaultInit(StorageKind);
280}
281
282ConstantExpr *ConstantExpr::Create(const ASTContext &Context, Expr *E,
283 ResultStorageKind StorageKind) {
284 assert(!isa<ConstantExpr>(E));
285 AssertResultStorageKind(StorageKind);
286 unsigned Size = totalSizeToAlloc<APValue, uint64_t>(
287 StorageKind == ConstantExpr::RSK_APValue,
288 StorageKind == ConstantExpr::RSK_Int64);
289 void *Mem = Context.Allocate(Size, alignof(ConstantExpr));
290 ConstantExpr *Self = new (Mem) ConstantExpr(E, StorageKind);
Gauthier Harnisch83c7b612019-06-15 10:24:47 +0000291 return Self;
292}
293
294ConstantExpr *ConstantExpr::Create(const ASTContext &Context, Expr *E,
295 const APValue &Result) {
296 ResultStorageKind StorageKind = getStorageKind(Result);
297 ConstantExpr *Self = Create(Context, E, StorageKind);
Gauthier Harnischdea9d572019-06-21 08:26:21 +0000298 Self->SetResult(Result, Context);
Gauthier Harnisch83c7b612019-06-15 10:24:47 +0000299 return Self;
300}
301
302ConstantExpr::ConstantExpr(ResultStorageKind StorageKind, EmptyShell Empty)
303 : FullExpr(ConstantExprClass, Empty) {
304 DefaultInit(StorageKind);
305}
306
307ConstantExpr *ConstantExpr::CreateEmpty(const ASTContext &Context,
308 ResultStorageKind StorageKind,
309 EmptyShell Empty) {
310 AssertResultStorageKind(StorageKind);
311 unsigned Size = totalSizeToAlloc<APValue, uint64_t>(
312 StorageKind == ConstantExpr::RSK_APValue,
313 StorageKind == ConstantExpr::RSK_Int64);
314 void *Mem = Context.Allocate(Size, alignof(ConstantExpr));
315 ConstantExpr *Self = new (Mem) ConstantExpr(StorageKind, Empty);
Gauthier Harnisch83c7b612019-06-15 10:24:47 +0000316 return Self;
317}
318
Gauthier Harnischdea9d572019-06-21 08:26:21 +0000319void ConstantExpr::MoveIntoResult(APValue &Value, const ASTContext &Context) {
Gauthier Harnisch83c7b612019-06-15 10:24:47 +0000320 assert(getStorageKind(Value) == ConstantExprBits.ResultKind &&
321 "Invalid storage for this value kind");
Gauthier Harnischdea9d572019-06-21 08:26:21 +0000322 ConstantExprBits.APValueKind = Value.getKind();
Gauthier Harnisch83c7b612019-06-15 10:24:47 +0000323 switch (ConstantExprBits.ResultKind) {
324 case RSK_None:
325 return;
326 case RSK_Int64:
327 Int64Result() = *Value.getInt().getRawData();
328 ConstantExprBits.BitWidth = Value.getInt().getBitWidth();
329 ConstantExprBits.IsUnsigned = Value.getInt().isUnsigned();
330 return;
331 case RSK_APValue:
Gauthier Harnischdea9d572019-06-21 08:26:21 +0000332 if (!ConstantExprBits.HasCleanup && Value.needsCleanup()) {
333 ConstantExprBits.HasCleanup = true;
334 Context.addDestruction(&APValueResult());
335 }
Gauthier Harnisch83c7b612019-06-15 10:24:47 +0000336 APValueResult() = std::move(Value);
337 return;
338 }
339 llvm_unreachable("Invalid ResultKind Bits");
340}
341
Gauthier Harnischdea9d572019-06-21 08:26:21 +0000342llvm::APSInt ConstantExpr::getResultAsAPSInt() const {
343 switch (ConstantExprBits.ResultKind) {
344 case ConstantExpr::RSK_APValue:
345 return APValueResult().getInt();
346 case ConstantExpr::RSK_Int64:
347 return llvm::APSInt(llvm::APInt(ConstantExprBits.BitWidth, Int64Result()),
348 ConstantExprBits.IsUnsigned);
349 default:
350 llvm_unreachable("invalid Accessor");
351 }
352}
353
Gauthier Harnisch83c7b612019-06-15 10:24:47 +0000354APValue ConstantExpr::getAPValueResult() const {
355 switch (ConstantExprBits.ResultKind) {
356 case ConstantExpr::RSK_APValue:
357 return APValueResult();
358 case ConstantExpr::RSK_Int64:
359 return APValue(
360 llvm::APSInt(llvm::APInt(ConstantExprBits.BitWidth, Int64Result()),
361 ConstantExprBits.IsUnsigned));
362 case ConstantExpr::RSK_None:
363 return APValue();
364 }
365 llvm_unreachable("invalid ResultKind");
366}
367
Fangrui Song6907ce22018-07-30 19:24:48 +0000368/// Compute the type-, value-, and instantiation-dependence of a
Douglas Gregor678d76c2011-07-01 01:22:09 +0000369/// declaration reference
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000370/// based on the declaration being referenced.
Craig Topperce7167c2013-08-22 04:58:56 +0000371static void computeDeclRefDependence(const ASTContext &Ctx, NamedDecl *D,
372 QualType T, bool &TypeDependent,
Douglas Gregor678d76c2011-07-01 01:22:09 +0000373 bool &ValueDependent,
374 bool &InstantiationDependent) {
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000375 TypeDependent = false;
376 ValueDependent = false;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000377 InstantiationDependent = false;
Douglas Gregored6c7442009-11-23 11:41:28 +0000378
379 // (TD) C++ [temp.dep.expr]p3:
380 // An id-expression is type-dependent if it contains:
381 //
Richard Smithcfaa5a32014-10-17 02:46:42 +0000382 // and
Douglas Gregored6c7442009-11-23 11:41:28 +0000383 //
384 // (VD) C++ [temp.dep.constexpr]p2:
385 // An identifier is value-dependent if it is:
Richard Smithcfaa5a32014-10-17 02:46:42 +0000386
Douglas Gregored6c7442009-11-23 11:41:28 +0000387 // (TD) - an identifier that was declared with dependent type
388 // (VD) - a name declared with a dependent type,
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000389 if (T->isDependentType()) {
390 TypeDependent = true;
391 ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000392 InstantiationDependent = true;
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000393 return;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000394 } else if (T->isInstantiationDependentType()) {
395 InstantiationDependent = true;
Douglas Gregored6c7442009-11-23 11:41:28 +0000396 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000397
Douglas Gregored6c7442009-11-23 11:41:28 +0000398 // (TD) - a conversion-function-id that specifies a dependent type
Fangrui Song6907ce22018-07-30 19:24:48 +0000399 if (D->getDeclName().getNameKind()
Douglas Gregor678d76c2011-07-01 01:22:09 +0000400 == DeclarationName::CXXConversionFunctionName) {
401 QualType T = D->getDeclName().getCXXNameType();
402 if (T->isDependentType()) {
403 TypeDependent = true;
404 ValueDependent = true;
405 InstantiationDependent = true;
406 return;
407 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000408
Douglas Gregor678d76c2011-07-01 01:22:09 +0000409 if (T->isInstantiationDependentType())
410 InstantiationDependent = true;
Douglas Gregored6c7442009-11-23 11:41:28 +0000411 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000412
Douglas Gregored6c7442009-11-23 11:41:28 +0000413 // (VD) - the name of a non-type template parameter,
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000414 if (isa<NonTypeTemplateParmDecl>(D)) {
415 ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000416 InstantiationDependent = true;
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000417 return;
418 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000419
Douglas Gregored6c7442009-11-23 11:41:28 +0000420 // (VD) - a constant with integral or enumeration type and is
421 // initialized with an expression that is value-dependent.
Richard Smithec8dcd22011-11-08 01:31:09 +0000422 // (VD) - a constant with literal type and is initialized with an
423 // expression that is value-dependent [C++11].
424 // (VD) - FIXME: Missing from the standard:
425 // - an entity with reference type and is initialized with an
426 // expression that is value-dependent [C++11]
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000427 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000428 if ((Ctx.getLangOpts().CPlusPlus11 ?
Richard Smithd9f663b2013-04-22 15:31:51 +0000429 Var->getType()->isLiteralType(Ctx) :
Richard Smithec8dcd22011-11-08 01:31:09 +0000430 Var->getType()->isIntegralOrEnumerationType()) &&
David Blaikief5697e52012-08-10 00:55:35 +0000431 (Var->getType().isConstQualified() ||
Richard Smithec8dcd22011-11-08 01:31:09 +0000432 Var->getType()->isReferenceType())) {
Sebastian Redl5ca79842010-02-01 20:16:42 +0000433 if (const Expr *Init = Var->getAnyInitializer())
Douglas Gregor678d76c2011-07-01 01:22:09 +0000434 if (Init->isValueDependent()) {
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000435 ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000436 InstantiationDependent = true;
437 }
Richard Smithec8dcd22011-11-08 01:31:09 +0000438 }
439
Fangrui Song6907ce22018-07-30 19:24:48 +0000440 // (VD) - FIXME: Missing from the standard:
441 // - a member function or a static data member of the current
Douglas Gregor0e4de762010-05-11 08:41:30 +0000442 // instantiation
Fangrui Song6907ce22018-07-30 19:24:48 +0000443 if (Var->isStaticDataMember() &&
Richard Smithec8dcd22011-11-08 01:31:09 +0000444 Var->getDeclContext()->isDependentContext()) {
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000445 ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000446 InstantiationDependent = true;
Richard Smith00f5d892013-11-14 22:40:45 +0000447 TypeSourceInfo *TInfo = Var->getFirstDecl()->getTypeSourceInfo();
448 if (TInfo->getType()->isIncompleteArrayType())
449 TypeDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000450 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000451
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000452 return;
453 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000454
455 // (VD) - FIXME: Missing from the standard:
456 // - a member function or a static data member of the current
Douglas Gregor0e4de762010-05-11 08:41:30 +0000457 // instantiation
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000458 if (isa<CXXMethodDecl>(D) && D->getDeclContext()->isDependentContext()) {
459 ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000460 InstantiationDependent = true;
Richard Smithec8dcd22011-11-08 01:31:09 +0000461 }
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000462}
Douglas Gregora6e053e2010-12-15 01:34:56 +0000463
Craig Topperce7167c2013-08-22 04:58:56 +0000464void DeclRefExpr::computeDependence(const ASTContext &Ctx) {
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000465 bool TypeDependent = false;
466 bool ValueDependent = false;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000467 bool InstantiationDependent = false;
Daniel Dunbar9d355812012-03-09 01:51:51 +0000468 computeDeclRefDependence(Ctx, getDecl(), getType(), TypeDependent,
469 ValueDependent, InstantiationDependent);
Richard Smithcfaa5a32014-10-17 02:46:42 +0000470
471 ExprBits.TypeDependent |= TypeDependent;
472 ExprBits.ValueDependent |= ValueDependent;
473 ExprBits.InstantiationDependent |= InstantiationDependent;
474
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000475 // Is the declaration a parameter pack?
Douglas Gregorf144f4f2011-01-19 21:52:31 +0000476 if (getDecl()->isParameterPack())
Douglas Gregor3c6bd2a2011-01-05 21:11:38 +0000477 ExprBits.ContainsUnexpandedParameterPack = true;
Douglas Gregored6c7442009-11-23 11:41:28 +0000478}
479
Bruno Ricci5fc4db72018-12-21 14:10:18 +0000480DeclRefExpr::DeclRefExpr(const ASTContext &Ctx, ValueDecl *D,
481 bool RefersToEnclosingVariableOrCapture, QualType T,
482 ExprValueKind VK, SourceLocation L,
Richard Smith715f7a12019-06-11 17:50:32 +0000483 const DeclarationNameLoc &LocInfo,
484 NonOdrUseReason NOUR)
Bruno Ricci5fc4db72018-12-21 14:10:18 +0000485 : Expr(DeclRefExprClass, T, VK, OK_Ordinary, false, false, false, false),
486 D(D), DNLoc(LocInfo) {
487 DeclRefExprBits.HasQualifier = false;
488 DeclRefExprBits.HasTemplateKWAndArgsInfo = false;
489 DeclRefExprBits.HasFoundDecl = false;
490 DeclRefExprBits.HadMultipleCandidates = false;
491 DeclRefExprBits.RefersToEnclosingVariableOrCapture =
492 RefersToEnclosingVariableOrCapture;
Richard Smith715f7a12019-06-11 17:50:32 +0000493 DeclRefExprBits.NonOdrUseReason = NOUR;
Bruno Ricci5fc4db72018-12-21 14:10:18 +0000494 DeclRefExprBits.Loc = L;
495 computeDependence(Ctx);
496}
497
Craig Topperce7167c2013-08-22 04:58:56 +0000498DeclRefExpr::DeclRefExpr(const ASTContext &Ctx,
Daniel Dunbar9d355812012-03-09 01:51:51 +0000499 NestedNameSpecifierLoc QualifierLoc,
Bruno Ricci5fc4db72018-12-21 14:10:18 +0000500 SourceLocation TemplateKWLoc, ValueDecl *D,
501 bool RefersToEnclosingVariableOrCapture,
502 const DeclarationNameInfo &NameInfo, NamedDecl *FoundD,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000503 const TemplateArgumentListInfo *TemplateArgs,
Richard Smith715f7a12019-06-11 17:50:32 +0000504 QualType T, ExprValueKind VK, NonOdrUseReason NOUR)
Bruno Ricci5fc4db72018-12-21 14:10:18 +0000505 : Expr(DeclRefExprClass, T, VK, OK_Ordinary, false, false, false, false),
506 D(D), DNLoc(NameInfo.getInfo()) {
Bruno Riccia795e802018-11-13 17:56:44 +0000507 DeclRefExprBits.Loc = NameInfo.getLoc();
Chandler Carruth0e439962011-05-01 21:29:53 +0000508 DeclRefExprBits.HasQualifier = QualifierLoc ? 1 : 0;
Richard Smithcfaa5a32014-10-17 02:46:42 +0000509 if (QualifierLoc) {
James Y Knighte7d82282015-12-29 18:15:14 +0000510 new (getTrailingObjects<NestedNameSpecifierLoc>())
511 NestedNameSpecifierLoc(QualifierLoc);
Richard Smithcfaa5a32014-10-17 02:46:42 +0000512 auto *NNS = QualifierLoc.getNestedNameSpecifier();
513 if (NNS->isInstantiationDependent())
514 ExprBits.InstantiationDependent = true;
515 if (NNS->containsUnexpandedParameterPack())
516 ExprBits.ContainsUnexpandedParameterPack = true;
517 }
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000518 DeclRefExprBits.HasFoundDecl = FoundD ? 1 : 0;
519 if (FoundD)
James Y Knighte7d82282015-12-29 18:15:14 +0000520 *getTrailingObjects<NamedDecl *>() = FoundD;
Abramo Bagnara7945c982012-01-27 09:46:47 +0000521 DeclRefExprBits.HasTemplateKWAndArgsInfo
522 = (TemplateArgs || TemplateKWLoc.isValid()) ? 1 : 0;
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000523 DeclRefExprBits.RefersToEnclosingVariableOrCapture =
524 RefersToEnclosingVariableOrCapture;
Richard Smith715f7a12019-06-11 17:50:32 +0000525 DeclRefExprBits.NonOdrUseReason = NOUR;
Douglas Gregor678d76c2011-07-01 01:22:09 +0000526 if (TemplateArgs) {
527 bool Dependent = false;
528 bool InstantiationDependent = false;
529 bool ContainsUnexpandedParameterPack = false;
James Y Knighte7d82282015-12-29 18:15:14 +0000530 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
531 TemplateKWLoc, *TemplateArgs, getTrailingObjects<TemplateArgumentLoc>(),
532 Dependent, InstantiationDependent, ContainsUnexpandedParameterPack);
Richard Smithcfaa5a32014-10-17 02:46:42 +0000533 assert(!Dependent && "built a DeclRefExpr with dependent template args");
534 ExprBits.InstantiationDependent |= InstantiationDependent;
535 ExprBits.ContainsUnexpandedParameterPack |= ContainsUnexpandedParameterPack;
Abramo Bagnara7945c982012-01-27 09:46:47 +0000536 } else if (TemplateKWLoc.isValid()) {
James Y Knighte7d82282015-12-29 18:15:14 +0000537 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
538 TemplateKWLoc);
Douglas Gregor678d76c2011-07-01 01:22:09 +0000539 }
Benjamin Kramer138ef9c2011-10-10 12:54:05 +0000540 DeclRefExprBits.HadMultipleCandidates = 0;
541
Daniel Dunbar9d355812012-03-09 01:51:51 +0000542 computeDependence(Ctx);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000543}
544
Craig Topperce7167c2013-08-22 04:58:56 +0000545DeclRefExpr *DeclRefExpr::Create(const ASTContext &Context,
Douglas Gregorea972d32011-02-28 21:54:11 +0000546 NestedNameSpecifierLoc QualifierLoc,
Richard Smith715f7a12019-06-11 17:50:32 +0000547 SourceLocation TemplateKWLoc, ValueDecl *D,
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000548 bool RefersToEnclosingVariableOrCapture,
Richard Smith715f7a12019-06-11 17:50:32 +0000549 SourceLocation NameLoc, QualType T,
550 ExprValueKind VK, NamedDecl *FoundD,
551 const TemplateArgumentListInfo *TemplateArgs,
552 NonOdrUseReason NOUR) {
Abramo Bagnara7945c982012-01-27 09:46:47 +0000553 return Create(Context, QualifierLoc, TemplateKWLoc, D,
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000554 RefersToEnclosingVariableOrCapture,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000555 DeclarationNameInfo(D->getDeclName(), NameLoc),
Richard Smith715f7a12019-06-11 17:50:32 +0000556 T, VK, FoundD, TemplateArgs, NOUR);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000557}
558
Craig Topperce7167c2013-08-22 04:58:56 +0000559DeclRefExpr *DeclRefExpr::Create(const ASTContext &Context,
Douglas Gregorea972d32011-02-28 21:54:11 +0000560 NestedNameSpecifierLoc QualifierLoc,
Richard Smith715f7a12019-06-11 17:50:32 +0000561 SourceLocation TemplateKWLoc, ValueDecl *D,
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000562 bool RefersToEnclosingVariableOrCapture,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000563 const DeclarationNameInfo &NameInfo,
Richard Smith715f7a12019-06-11 17:50:32 +0000564 QualType T, ExprValueKind VK,
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000565 NamedDecl *FoundD,
Richard Smith715f7a12019-06-11 17:50:32 +0000566 const TemplateArgumentListInfo *TemplateArgs,
567 NonOdrUseReason NOUR) {
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000568 // Filter out cases where the found Decl is the same as the value refenenced.
569 if (D == FoundD)
Craig Topper36250ad2014-05-12 05:36:57 +0000570 FoundD = nullptr;
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000571
James Y Knighte7d82282015-12-29 18:15:14 +0000572 bool HasTemplateKWAndArgsInfo = TemplateArgs || TemplateKWLoc.isValid();
573 std::size_t Size =
574 totalSizeToAlloc<NestedNameSpecifierLoc, NamedDecl *,
575 ASTTemplateKWAndArgsInfo, TemplateArgumentLoc>(
576 QualifierLoc ? 1 : 0, FoundD ? 1 : 0,
577 HasTemplateKWAndArgsInfo ? 1 : 0,
578 TemplateArgs ? TemplateArgs->size() : 0);
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000579
Benjamin Kramerc3f89252016-10-20 14:27:22 +0000580 void *Mem = Context.Allocate(Size, alignof(DeclRefExpr));
Daniel Dunbar9d355812012-03-09 01:51:51 +0000581 return new (Mem) DeclRefExpr(Context, QualifierLoc, TemplateKWLoc, D,
Richard Smith715f7a12019-06-11 17:50:32 +0000582 RefersToEnclosingVariableOrCapture, NameInfo,
583 FoundD, TemplateArgs, T, VK, NOUR);
Douglas Gregor4bd90e52009-10-23 18:54:35 +0000584}
585
Craig Topperce7167c2013-08-22 04:58:56 +0000586DeclRefExpr *DeclRefExpr::CreateEmpty(const ASTContext &Context,
Douglas Gregor87866ce2011-02-04 12:01:24 +0000587 bool HasQualifier,
Chandler Carruth8d26bb02011-05-01 23:48:14 +0000588 bool HasFoundDecl,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000589 bool HasTemplateKWAndArgsInfo,
Argyrios Kyrtzidis1985bb32010-07-08 13:09:47 +0000590 unsigned NumTemplateArgs) {
James Y Knighte7d82282015-12-29 18:15:14 +0000591 assert(NumTemplateArgs == 0 || HasTemplateKWAndArgsInfo);
592 std::size_t Size =
593 totalSizeToAlloc<NestedNameSpecifierLoc, NamedDecl *,
594 ASTTemplateKWAndArgsInfo, TemplateArgumentLoc>(
595 HasQualifier ? 1 : 0, HasFoundDecl ? 1 : 0, HasTemplateKWAndArgsInfo,
596 NumTemplateArgs);
Benjamin Kramerc3f89252016-10-20 14:27:22 +0000597 void *Mem = Context.Allocate(Size, alignof(DeclRefExpr));
Argyrios Kyrtzidis1985bb32010-07-08 13:09:47 +0000598 return new (Mem) DeclRefExpr(EmptyShell());
599}
600
Stephen Kelly724e9e52018-08-09 20:05:03 +0000601SourceLocation DeclRefExpr::getBeginLoc() const {
Daniel Dunbarb507f272012-03-09 15:39:15 +0000602 if (hasQualifier())
603 return getQualifierLoc().getBeginLoc();
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000604 return getNameInfo().getBeginLoc();
Daniel Dunbarb507f272012-03-09 15:39:15 +0000605}
Stephen Kelly02a67ba2018-08-09 20:05:47 +0000606SourceLocation DeclRefExpr::getEndLoc() const {
Daniel Dunbarb507f272012-03-09 15:39:15 +0000607 if (hasExplicitTemplateArgs())
608 return getRAngleLoc();
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000609 return getNameInfo().getEndLoc();
Daniel Dunbarb507f272012-03-09 15:39:15 +0000610}
Douglas Gregor4bd90e52009-10-23 18:54:35 +0000611
Bruno Ricci17ff0262018-10-27 19:21:19 +0000612PredefinedExpr::PredefinedExpr(SourceLocation L, QualType FNTy, IdentKind IK,
Alexey Bataevec474782014-10-09 08:45:04 +0000613 StringLiteral *SL)
614 : Expr(PredefinedExprClass, FNTy, VK_LValue, OK_Ordinary,
615 FNTy->isDependentType(), FNTy->isDependentType(),
616 FNTy->isInstantiationDependentType(),
Bruno Ricci17ff0262018-10-27 19:21:19 +0000617 /*ContainsUnexpandedParameterPack=*/false) {
618 PredefinedExprBits.Kind = IK;
619 assert((getIdentKind() == IK) &&
620 "IdentKind do not fit in PredefinedExprBitfields!");
621 bool HasFunctionName = SL != nullptr;
622 PredefinedExprBits.HasFunctionName = HasFunctionName;
623 PredefinedExprBits.Loc = L;
624 if (HasFunctionName)
625 setFunctionName(SL);
Alexey Bataevec474782014-10-09 08:45:04 +0000626}
627
Bruno Ricci17ff0262018-10-27 19:21:19 +0000628PredefinedExpr::PredefinedExpr(EmptyShell Empty, bool HasFunctionName)
629 : Expr(PredefinedExprClass, Empty) {
630 PredefinedExprBits.HasFunctionName = HasFunctionName;
631}
632
633PredefinedExpr *PredefinedExpr::Create(const ASTContext &Ctx, SourceLocation L,
634 QualType FNTy, IdentKind IK,
635 StringLiteral *SL) {
636 bool HasFunctionName = SL != nullptr;
637 void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *>(HasFunctionName),
638 alignof(PredefinedExpr));
639 return new (Mem) PredefinedExpr(L, FNTy, IK, SL);
640}
641
642PredefinedExpr *PredefinedExpr::CreateEmpty(const ASTContext &Ctx,
643 bool HasFunctionName) {
644 void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *>(HasFunctionName),
645 alignof(PredefinedExpr));
646 return new (Mem) PredefinedExpr(EmptyShell(), HasFunctionName);
647}
648
649StringRef PredefinedExpr::getIdentKindName(PredefinedExpr::IdentKind IK) {
650 switch (IK) {
Alexey Bataevec474782014-10-09 08:45:04 +0000651 case Func:
652 return "__func__";
653 case Function:
654 return "__FUNCTION__";
655 case FuncDName:
656 return "__FUNCDNAME__";
657 case LFunction:
658 return "L__FUNCTION__";
659 case PrettyFunction:
660 return "__PRETTY_FUNCTION__";
661 case FuncSig:
662 return "__FUNCSIG__";
Reid Kleckner4a83f0a2018-07-26 23:18:44 +0000663 case LFuncSig:
664 return "L__FUNCSIG__";
Alexey Bataevec474782014-10-09 08:45:04 +0000665 case PrettyFunctionNoVirtual:
666 break;
667 }
Bruno Ricci17ff0262018-10-27 19:21:19 +0000668 llvm_unreachable("Unknown ident kind for PredefinedExpr");
Alexey Bataevec474782014-10-09 08:45:04 +0000669}
670
Anders Carlsson2fb08242009-09-08 18:24:21 +0000671// FIXME: Maybe this should use DeclPrinter with a special "print predefined
672// expr" policy instead.
Bruno Ricci17ff0262018-10-27 19:21:19 +0000673std::string PredefinedExpr::ComputeName(IdentKind IK, const Decl *CurrentDecl) {
Anders Carlsson5bd8d192010-02-11 18:20:28 +0000674 ASTContext &Context = CurrentDecl->getASTContext();
675
Bruno Ricci17ff0262018-10-27 19:21:19 +0000676 if (IK == PredefinedExpr::FuncDName) {
David Majnemerbed356a2013-11-06 23:31:56 +0000677 if (const NamedDecl *ND = dyn_cast<NamedDecl>(CurrentDecl)) {
Ahmed Charlesb8984322014-03-07 20:03:18 +0000678 std::unique_ptr<MangleContext> MC;
David Majnemerbed356a2013-11-06 23:31:56 +0000679 MC.reset(Context.createMangleContext());
680
681 if (MC->shouldMangleDeclName(ND)) {
682 SmallString<256> Buffer;
683 llvm::raw_svector_ostream Out(Buffer);
684 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(ND))
685 MC->mangleCXXCtor(CD, Ctor_Base, Out);
686 else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(ND))
687 MC->mangleCXXDtor(DD, Dtor_Base, Out);
688 else
689 MC->mangleName(ND, Out);
690
David Majnemerbed356a2013-11-06 23:31:56 +0000691 if (!Buffer.empty() && Buffer.front() == '\01')
692 return Buffer.substr(1);
693 return Buffer.str();
694 } else
695 return ND->getIdentifier()->getName();
696 }
697 return "";
698 }
Mehdi Aminidc9bf8f2016-11-16 07:07:28 +0000699 if (isa<BlockDecl>(CurrentDecl)) {
700 // For blocks we only emit something if it is enclosed in a function
701 // For top-level block we'd like to include the name of variable, but we
702 // don't have it at this point.
Mehdi Aminif5f37ee2016-11-15 22:19:50 +0000703 auto DC = CurrentDecl->getDeclContext();
704 if (DC->isFileContext())
Mehdi Aminidc9bf8f2016-11-16 07:07:28 +0000705 return "";
706
707 SmallString<256> Buffer;
708 llvm::raw_svector_ostream Out(Buffer);
709 if (auto *DCBlock = dyn_cast<BlockDecl>(DC))
710 // For nested blocks, propagate up to the parent.
Bruno Ricci17ff0262018-10-27 19:21:19 +0000711 Out << ComputeName(IK, DCBlock);
Mehdi Aminidc9bf8f2016-11-16 07:07:28 +0000712 else if (auto *DCDecl = dyn_cast<Decl>(DC))
Bruno Ricci17ff0262018-10-27 19:21:19 +0000713 Out << ComputeName(IK, DCDecl) << "_block_invoke";
Alexey Bataevec474782014-10-09 08:45:04 +0000714 return Out.str();
715 }
Anders Carlsson2fb08242009-09-08 18:24:21 +0000716 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CurrentDecl)) {
Bruno Ricci17ff0262018-10-27 19:21:19 +0000717 if (IK != PrettyFunction && IK != PrettyFunctionNoVirtual &&
718 IK != FuncSig && IK != LFuncSig)
Anders Carlsson2fb08242009-09-08 18:24:21 +0000719 return FD->getNameAsString();
720
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000721 SmallString<256> Name;
Anders Carlsson2fb08242009-09-08 18:24:21 +0000722 llvm::raw_svector_ostream Out(Name);
723
724 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
Bruno Ricci17ff0262018-10-27 19:21:19 +0000725 if (MD->isVirtual() && IK != PrettyFunctionNoVirtual)
Anders Carlsson2fb08242009-09-08 18:24:21 +0000726 Out << "virtual ";
Sam Weinig4e83bd22009-12-27 01:38:20 +0000727 if (MD->isStatic())
728 Out << "static ";
Anders Carlsson2fb08242009-09-08 18:24:21 +0000729 }
730
David Blaikiebbafb8a2012-03-11 07:00:24 +0000731 PrintingPolicy Policy(Context.getLangOpts());
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +0000732 std::string Proto;
Douglas Gregor11a434a2012-04-10 20:14:15 +0000733 llvm::raw_string_ostream POut(Proto);
Anders Carlsson2fb08242009-09-08 18:24:21 +0000734
Douglas Gregor11a434a2012-04-10 20:14:15 +0000735 const FunctionDecl *Decl = FD;
736 if (const FunctionDecl* Pattern = FD->getTemplateInstantiationPattern())
737 Decl = Pattern;
738 const FunctionType *AFT = Decl->getType()->getAs<FunctionType>();
Craig Topper36250ad2014-05-12 05:36:57 +0000739 const FunctionProtoType *FT = nullptr;
Anders Carlsson2fb08242009-09-08 18:24:21 +0000740 if (FD->hasWrittenPrototype())
741 FT = dyn_cast<FunctionProtoType>(AFT);
742
Bruno Ricci17ff0262018-10-27 19:21:19 +0000743 if (IK == FuncSig || IK == LFuncSig) {
Richard Smith2f63d462017-01-09 21:40:40 +0000744 switch (AFT->getCallConv()) {
Reid Kleckner52eddda2014-04-08 18:13:24 +0000745 case CC_C: POut << "__cdecl "; break;
746 case CC_X86StdCall: POut << "__stdcall "; break;
747 case CC_X86FastCall: POut << "__fastcall "; break;
748 case CC_X86ThisCall: POut << "__thiscall "; break;
Reid Klecknerd7857f02014-10-24 17:42:17 +0000749 case CC_X86VectorCall: POut << "__vectorcall "; break;
Erich Keane757d3172016-11-02 18:29:35 +0000750 case CC_X86RegCall: POut << "__regcall "; break;
Reid Kleckner52eddda2014-04-08 18:13:24 +0000751 // Only bother printing the conventions that MSVC knows about.
752 default: break;
753 }
754 }
755
756 FD->printQualifiedName(POut, Policy);
757
Douglas Gregor11a434a2012-04-10 20:14:15 +0000758 POut << "(";
Anders Carlsson2fb08242009-09-08 18:24:21 +0000759 if (FT) {
Douglas Gregor11a434a2012-04-10 20:14:15 +0000760 for (unsigned i = 0, e = Decl->getNumParams(); i != e; ++i) {
Anders Carlsson2fb08242009-09-08 18:24:21 +0000761 if (i) POut << ", ";
Argyrios Kyrtzidisa18347e2012-05-05 04:20:37 +0000762 POut << Decl->getParamDecl(i)->getType().stream(Policy);
Anders Carlsson2fb08242009-09-08 18:24:21 +0000763 }
764
765 if (FT->isVariadic()) {
766 if (FD->getNumParams()) POut << ", ";
767 POut << "...";
Bruno Ricci17ff0262018-10-27 19:21:19 +0000768 } else if ((IK == FuncSig || IK == LFuncSig ||
Reid Kleckner4a83f0a2018-07-26 23:18:44 +0000769 !Context.getLangOpts().CPlusPlus) &&
Richard Smithcf63b842017-01-09 22:16:16 +0000770 !Decl->getNumParams()) {
771 POut << "void";
Anders Carlsson2fb08242009-09-08 18:24:21 +0000772 }
773 }
Douglas Gregor11a434a2012-04-10 20:14:15 +0000774 POut << ")";
Anders Carlsson2fb08242009-09-08 18:24:21 +0000775
Sam Weinig4e83bd22009-12-27 01:38:20 +0000776 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
Richard Smith2f63d462017-01-09 21:40:40 +0000777 assert(FT && "We must have a written prototype in this case.");
David Blaikief5697e52012-08-10 00:55:35 +0000778 if (FT->isConst())
Douglas Gregor11a434a2012-04-10 20:14:15 +0000779 POut << " const";
David Blaikief5697e52012-08-10 00:55:35 +0000780 if (FT->isVolatile())
Douglas Gregor11a434a2012-04-10 20:14:15 +0000781 POut << " volatile";
782 RefQualifierKind Ref = MD->getRefQualifier();
783 if (Ref == RQ_LValue)
784 POut << " &";
785 else if (Ref == RQ_RValue)
786 POut << " &&";
Sam Weinig4e83bd22009-12-27 01:38:20 +0000787 }
788
Eugene Zelenkoae304b02017-11-17 18:09:48 +0000789 typedef SmallVector<const ClassTemplateSpecializationDecl *, 8> SpecsTy;
Douglas Gregor11a434a2012-04-10 20:14:15 +0000790 SpecsTy Specs;
791 const DeclContext *Ctx = FD->getDeclContext();
792 while (Ctx && isa<NamedDecl>(Ctx)) {
793 const ClassTemplateSpecializationDecl *Spec
794 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx);
795 if (Spec && !Spec->isExplicitSpecialization())
796 Specs.push_back(Spec);
797 Ctx = Ctx->getParent();
798 }
799
800 std::string TemplateParams;
801 llvm::raw_string_ostream TOut(TemplateParams);
802 for (SpecsTy::reverse_iterator I = Specs.rbegin(), E = Specs.rend();
803 I != E; ++I) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000804 const TemplateParameterList *Params
Douglas Gregor11a434a2012-04-10 20:14:15 +0000805 = (*I)->getSpecializedTemplate()->getTemplateParameters();
806 const TemplateArgumentList &Args = (*I)->getTemplateArgs();
807 assert(Params->size() == Args.size());
808 for (unsigned i = 0, numParams = Params->size(); i != numParams; ++i) {
809 StringRef Param = Params->getParam(i)->getName();
810 if (Param.empty()) continue;
811 TOut << Param << " = ";
812 Args.get(i).print(Policy, TOut);
813 TOut << ", ";
814 }
815 }
816
Fangrui Song6907ce22018-07-30 19:24:48 +0000817 FunctionTemplateSpecializationInfo *FSI
Douglas Gregor11a434a2012-04-10 20:14:15 +0000818 = FD->getTemplateSpecializationInfo();
819 if (FSI && !FSI->isExplicitSpecialization()) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000820 const TemplateParameterList* Params
Douglas Gregor11a434a2012-04-10 20:14:15 +0000821 = FSI->getTemplate()->getTemplateParameters();
822 const TemplateArgumentList* Args = FSI->TemplateArguments;
823 assert(Params->size() == Args->size());
824 for (unsigned i = 0, e = Params->size(); i != e; ++i) {
825 StringRef Param = Params->getParam(i)->getName();
826 if (Param.empty()) continue;
827 TOut << Param << " = ";
828 Args->get(i).print(Policy, TOut);
829 TOut << ", ";
830 }
831 }
832
833 TOut.flush();
834 if (!TemplateParams.empty()) {
835 // remove the trailing comma and space
836 TemplateParams.resize(TemplateParams.size() - 2);
837 POut << " [" << TemplateParams << "]";
838 }
839
840 POut.flush();
841
Benjamin Kramer90f54222013-08-21 11:45:27 +0000842 // Print "auto" for all deduced return types. This includes C++1y return
843 // type deduction and lambdas. For trailing return types resolve the
844 // decltype expression. Otherwise print the real type when this is
845 // not a constructor or destructor.
Alexey Bataevec474782014-10-09 08:45:04 +0000846 if (isa<CXXMethodDecl>(FD) &&
847 cast<CXXMethodDecl>(FD)->getParent()->isLambda())
Benjamin Kramer90f54222013-08-21 11:45:27 +0000848 Proto = "auto " + Proto;
Alp Toker314cc812014-01-25 16:55:45 +0000849 else if (FT && FT->getReturnType()->getAs<DecltypeType>())
850 FT->getReturnType()
851 ->getAs<DecltypeType>()
852 ->getUnderlyingType()
Benjamin Kramer90f54222013-08-21 11:45:27 +0000853 .getAsStringInternal(Proto, Policy);
854 else if (!isa<CXXConstructorDecl>(FD) && !isa<CXXDestructorDecl>(FD))
Alp Toker314cc812014-01-25 16:55:45 +0000855 AFT->getReturnType().getAsStringInternal(Proto, Policy);
Anders Carlsson2fb08242009-09-08 18:24:21 +0000856
857 Out << Proto;
858
Anders Carlsson2fb08242009-09-08 18:24:21 +0000859 return Name.str().str();
860 }
Wei Pan8d6b19a2013-08-26 14:27:34 +0000861 if (const CapturedDecl *CD = dyn_cast<CapturedDecl>(CurrentDecl)) {
862 for (const DeclContext *DC = CD->getParent(); DC; DC = DC->getParent())
863 // Skip to its enclosing function or method, but not its enclosing
864 // CapturedDecl.
865 if (DC->isFunctionOrMethod() && (DC->getDeclKind() != Decl::Captured)) {
866 const Decl *D = Decl::castFromDeclContext(DC);
Bruno Ricci17ff0262018-10-27 19:21:19 +0000867 return ComputeName(IK, D);
Wei Pan8d6b19a2013-08-26 14:27:34 +0000868 }
869 llvm_unreachable("CapturedDecl not inside a function or method");
870 }
Anders Carlsson2fb08242009-09-08 18:24:21 +0000871 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurrentDecl)) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000872 SmallString<256> Name;
Anders Carlsson2fb08242009-09-08 18:24:21 +0000873 llvm::raw_svector_ostream Out(Name);
874 Out << (MD->isInstanceMethod() ? '-' : '+');
875 Out << '[';
Ted Kremenek361ffd92010-03-18 21:23:08 +0000876
877 // For incorrect code, there might not be an ObjCInterfaceDecl. Do
878 // a null check to avoid a crash.
879 if (const ObjCInterfaceDecl *ID = MD->getClassInterface())
Benjamin Kramerb89514a2011-10-14 18:45:37 +0000880 Out << *ID;
Ted Kremenek361ffd92010-03-18 21:23:08 +0000881
Anders Carlsson2fb08242009-09-08 18:24:21 +0000882 if (const ObjCCategoryImplDecl *CID =
Benjamin Kramerb11416d2010-04-17 09:33:03 +0000883 dyn_cast<ObjCCategoryImplDecl>(MD->getDeclContext()))
Benjamin Kramer2f569922012-02-07 11:57:45 +0000884 Out << '(' << *CID << ')';
Benjamin Kramerb11416d2010-04-17 09:33:03 +0000885
Anders Carlsson2fb08242009-09-08 18:24:21 +0000886 Out << ' ';
Aaron Ballmanb190f972014-01-03 17:59:55 +0000887 MD->getSelector().print(Out);
Anders Carlsson2fb08242009-09-08 18:24:21 +0000888 Out << ']';
889
Anders Carlsson2fb08242009-09-08 18:24:21 +0000890 return Name.str().str();
891 }
Bruno Ricci17ff0262018-10-27 19:21:19 +0000892 if (isa<TranslationUnitDecl>(CurrentDecl) && IK == PrettyFunction) {
Anders Carlsson2fb08242009-09-08 18:24:21 +0000893 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
894 return "top level";
895 }
896 return "";
897}
898
Craig Topper37932912013-08-18 10:09:15 +0000899void APNumericStorage::setIntValue(const ASTContext &C,
900 const llvm::APInt &Val) {
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000901 if (hasAllocation())
902 C.Deallocate(pVal);
903
904 BitWidth = Val.getBitWidth();
905 unsigned NumWords = Val.getNumWords();
906 const uint64_t* Words = Val.getRawData();
907 if (NumWords > 1) {
908 pVal = new (C) uint64_t[NumWords];
909 std::copy(Words, Words + NumWords, pVal);
910 } else if (NumWords == 1)
911 VAL = Words[0];
912 else
913 VAL = 0;
914}
915
Craig Topper37932912013-08-18 10:09:15 +0000916IntegerLiteral::IntegerLiteral(const ASTContext &C, const llvm::APInt &V,
Benjamin Kramer1ea8e092012-07-04 17:04:04 +0000917 QualType type, SourceLocation l)
918 : Expr(IntegerLiteralClass, type, VK_RValue, OK_Ordinary, false, false,
919 false, false),
920 Loc(l) {
921 assert(type->isIntegerType() && "Illegal type in IntegerLiteral");
922 assert(V.getBitWidth() == C.getIntWidth(type) &&
923 "Integer type is not the correct size for constant.");
924 setValue(C, V);
925}
926
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000927IntegerLiteral *
Craig Topper37932912013-08-18 10:09:15 +0000928IntegerLiteral::Create(const ASTContext &C, const llvm::APInt &V,
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000929 QualType type, SourceLocation l) {
930 return new (C) IntegerLiteral(C, V, type, l);
931}
932
933IntegerLiteral *
Craig Topper37932912013-08-18 10:09:15 +0000934IntegerLiteral::Create(const ASTContext &C, EmptyShell Empty) {
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000935 return new (C) IntegerLiteral(Empty);
936}
937
Leonard Chandb01c3a2018-06-20 17:19:40 +0000938FixedPointLiteral::FixedPointLiteral(const ASTContext &C, const llvm::APInt &V,
939 QualType type, SourceLocation l,
940 unsigned Scale)
941 : Expr(FixedPointLiteralClass, type, VK_RValue, OK_Ordinary, false, false,
942 false, false),
943 Loc(l), Scale(Scale) {
944 assert(type->isFixedPointType() && "Illegal type in FixedPointLiteral");
945 assert(V.getBitWidth() == C.getTypeInfo(type).Width &&
946 "Fixed point type is not the correct size for constant.");
947 setValue(C, V);
948}
949
950FixedPointLiteral *FixedPointLiteral::CreateFromRawInt(const ASTContext &C,
951 const llvm::APInt &V,
952 QualType type,
953 SourceLocation l,
954 unsigned Scale) {
955 return new (C) FixedPointLiteral(C, V, type, l, Scale);
956}
957
958std::string FixedPointLiteral::getValueAsString(unsigned Radix) const {
959 // Currently the longest decimal number that can be printed is the max for an
960 // unsigned long _Accum: 4294967295.99999999976716935634613037109375
961 // which is 43 characters.
962 SmallString<64> S;
963 FixedPointValueToString(
Leonard Chanc03642e2018-08-06 16:05:08 +0000964 S, llvm::APSInt::getUnsigned(getValue().getZExtValue()), Scale);
Leonard Chandb01c3a2018-06-20 17:19:40 +0000965 return S.str();
966}
967
Craig Topper37932912013-08-18 10:09:15 +0000968FloatingLiteral::FloatingLiteral(const ASTContext &C, const llvm::APFloat &V,
Benjamin Kramer1ea8e092012-07-04 17:04:04 +0000969 bool isexact, QualType Type, SourceLocation L)
970 : Expr(FloatingLiteralClass, Type, VK_RValue, OK_Ordinary, false, false,
971 false, false), Loc(L) {
Tim Northover178723a2013-01-22 09:46:51 +0000972 setSemantics(V.getSemantics());
Benjamin Kramer1ea8e092012-07-04 17:04:04 +0000973 FloatingLiteralBits.IsExact = isexact;
974 setValue(C, V);
975}
976
Craig Topper37932912013-08-18 10:09:15 +0000977FloatingLiteral::FloatingLiteral(const ASTContext &C, EmptyShell Empty)
Eugene Zelenkoae304b02017-11-17 18:09:48 +0000978 : Expr(FloatingLiteralClass, Empty) {
Gauthier Harnisch83c7b612019-06-15 10:24:47 +0000979 setRawSemantics(llvm::APFloatBase::S_IEEEhalf);
Benjamin Kramer1ea8e092012-07-04 17:04:04 +0000980 FloatingLiteralBits.IsExact = false;
981}
982
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000983FloatingLiteral *
Craig Topper37932912013-08-18 10:09:15 +0000984FloatingLiteral::Create(const ASTContext &C, const llvm::APFloat &V,
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000985 bool isexact, QualType Type, SourceLocation L) {
986 return new (C) FloatingLiteral(C, V, isexact, Type, L);
987}
988
989FloatingLiteral *
Craig Topper37932912013-08-18 10:09:15 +0000990FloatingLiteral::Create(const ASTContext &C, EmptyShell Empty) {
Akira Hatanaka428f5b22012-01-10 22:40:09 +0000991 return new (C) FloatingLiteral(C, Empty);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +0000992}
993
Chris Lattnera0173132008-06-07 22:13:43 +0000994/// getValueAsApproximateDouble - This returns the value as an inaccurate
995/// double. Note that this may cause loss of precision, but is useful for
996/// debugging dumps, etc.
997double FloatingLiteral::getValueAsApproximateDouble() const {
998 llvm::APFloat V = getValue();
Dale Johannesenc48814b2008-10-09 23:02:32 +0000999 bool ignored;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001000 V.convert(llvm::APFloat::IEEEdouble(), llvm::APFloat::rmNearestTiesToEven,
Dale Johannesenc48814b2008-10-09 23:02:32 +00001001 &ignored);
Chris Lattnera0173132008-06-07 22:13:43 +00001002 return V.convertToDouble();
1003}
1004
Bruno Ricciaf214882018-11-15 16:42:14 +00001005unsigned StringLiteral::mapCharByteWidth(TargetInfo const &Target,
1006 StringKind SK) {
1007 unsigned CharByteWidth = 0;
1008 switch (SK) {
1009 case Ascii:
1010 case UTF8:
1011 CharByteWidth = Target.getCharWidth();
1012 break;
1013 case Wide:
1014 CharByteWidth = Target.getWCharWidth();
1015 break;
1016 case UTF16:
1017 CharByteWidth = Target.getChar16Width();
1018 break;
1019 case UTF32:
1020 CharByteWidth = Target.getChar32Width();
1021 break;
Eli Friedmanfcec6302011-11-01 02:23:42 +00001022 }
1023 assert((CharByteWidth & 7) == 0 && "Assumes character size is byte multiple");
1024 CharByteWidth /= 8;
Bruno Ricciaf214882018-11-15 16:42:14 +00001025 assert((CharByteWidth == 1 || CharByteWidth == 2 || CharByteWidth == 4) &&
1026 "The only supported character byte widths are 1,2 and 4!");
Eli Friedmanfcec6302011-11-01 02:23:42 +00001027 return CharByteWidth;
1028}
1029
Bruno Riccib94ad1e2018-11-15 17:31:16 +00001030StringLiteral::StringLiteral(const ASTContext &Ctx, StringRef Str,
1031 StringKind Kind, bool Pascal, QualType Ty,
1032 const SourceLocation *Loc,
1033 unsigned NumConcatenated)
1034 : Expr(StringLiteralClass, Ty, VK_LValue, OK_Ordinary, false, false, false,
1035 false) {
1036 assert(Ctx.getAsConstantArrayType(Ty) &&
Benjamin Kramercdac7612014-02-25 12:26:20 +00001037 "StringLiteral must be of constant array type!");
Bruno Riccib94ad1e2018-11-15 17:31:16 +00001038 unsigned CharByteWidth = mapCharByteWidth(Ctx.getTargetInfo(), Kind);
1039 unsigned ByteLength = Str.size();
1040 assert((ByteLength % CharByteWidth == 0) &&
1041 "The size of the data must be a multiple of CharByteWidth!");
Benjamin Kramercdac7612014-02-25 12:26:20 +00001042
Bruno Riccib94ad1e2018-11-15 17:31:16 +00001043 // Avoid the expensive division. The compiler should be able to figure it
1044 // out by itself. However as of clang 7, even with the appropriate
1045 // llvm_unreachable added just here, it is not able to do so.
1046 unsigned Length;
1047 switch (CharByteWidth) {
1048 case 1:
1049 Length = ByteLength;
1050 break;
1051 case 2:
1052 Length = ByteLength / 2;
1053 break;
1054 case 4:
1055 Length = ByteLength / 4;
1056 break;
1057 default:
1058 llvm_unreachable("Unsupported character width!");
1059 }
Mike Stump11289f42009-09-09 15:08:12 +00001060
Bruno Riccib94ad1e2018-11-15 17:31:16 +00001061 StringLiteralBits.Kind = Kind;
1062 StringLiteralBits.CharByteWidth = CharByteWidth;
1063 StringLiteralBits.IsPascal = Pascal;
1064 StringLiteralBits.NumConcatenated = NumConcatenated;
1065 *getTrailingObjects<unsigned>() = Length;
Eli Friedmanfcec6302011-11-01 02:23:42 +00001066
Bruno Riccib94ad1e2018-11-15 17:31:16 +00001067 // Initialize the trailing array of SourceLocation.
1068 // This is safe since SourceLocation is POD-like.
1069 std::memcpy(getTrailingObjects<SourceLocation>(), Loc,
1070 NumConcatenated * sizeof(SourceLocation));
Chris Lattnerd3e98952006-10-06 05:22:26 +00001071
Bruno Riccib94ad1e2018-11-15 17:31:16 +00001072 // Initialize the trailing array of char holding the string data.
1073 std::memcpy(getTrailingObjects<char>(), Str.data(), ByteLength);
Chris Lattner630970d2009-02-18 05:49:11 +00001074}
1075
Bruno Riccib94ad1e2018-11-15 17:31:16 +00001076StringLiteral::StringLiteral(EmptyShell Empty, unsigned NumConcatenated,
1077 unsigned Length, unsigned CharByteWidth)
1078 : Expr(StringLiteralClass, Empty) {
1079 StringLiteralBits.CharByteWidth = CharByteWidth;
1080 StringLiteralBits.NumConcatenated = NumConcatenated;
1081 *getTrailingObjects<unsigned>() = Length;
1082}
1083
1084StringLiteral *StringLiteral::Create(const ASTContext &Ctx, StringRef Str,
1085 StringKind Kind, bool Pascal, QualType Ty,
1086 const SourceLocation *Loc,
1087 unsigned NumConcatenated) {
1088 void *Mem = Ctx.Allocate(totalSizeToAlloc<unsigned, SourceLocation, char>(
1089 1, NumConcatenated, Str.size()),
1090 alignof(StringLiteral));
1091 return new (Mem)
1092 StringLiteral(Ctx, Str, Kind, Pascal, Ty, Loc, NumConcatenated);
1093}
1094
1095StringLiteral *StringLiteral::CreateEmpty(const ASTContext &Ctx,
1096 unsigned NumConcatenated,
1097 unsigned Length,
1098 unsigned CharByteWidth) {
1099 void *Mem = Ctx.Allocate(totalSizeToAlloc<unsigned, SourceLocation, char>(
1100 1, NumConcatenated, Length * CharByteWidth),
1101 alignof(StringLiteral));
1102 return new (Mem)
1103 StringLiteral(EmptyShell(), NumConcatenated, Length, CharByteWidth);
Douglas Gregor958dfc92009-04-15 16:35:07 +00001104}
1105
Alexander Kornienko540bacb2013-02-01 12:35:51 +00001106void StringLiteral::outputString(raw_ostream &OS) const {
Richard Trieudc355912012-06-13 20:25:24 +00001107 switch (getKind()) {
1108 case Ascii: break; // no prefix.
1109 case Wide: OS << 'L'; break;
1110 case UTF8: OS << "u8"; break;
1111 case UTF16: OS << 'u'; break;
1112 case UTF32: OS << 'U'; break;
1113 }
1114 OS << '"';
1115 static const char Hex[] = "0123456789ABCDEF";
1116
1117 unsigned LastSlashX = getLength();
1118 for (unsigned I = 0, N = getLength(); I != N; ++I) {
1119 switch (uint32_t Char = getCodeUnit(I)) {
1120 default:
1121 // FIXME: Convert UTF-8 back to codepoints before rendering.
1122
1123 // Convert UTF-16 surrogate pairs back to codepoints before rendering.
1124 // Leave invalid surrogates alone; we'll use \x for those.
Fangrui Song6907ce22018-07-30 19:24:48 +00001125 if (getKind() == UTF16 && I != N - 1 && Char >= 0xd800 &&
Richard Trieudc355912012-06-13 20:25:24 +00001126 Char <= 0xdbff) {
1127 uint32_t Trail = getCodeUnit(I + 1);
1128 if (Trail >= 0xdc00 && Trail <= 0xdfff) {
1129 Char = 0x10000 + ((Char - 0xd800) << 10) + (Trail - 0xdc00);
1130 ++I;
1131 }
1132 }
1133
1134 if (Char > 0xff) {
1135 // If this is a wide string, output characters over 0xff using \x
1136 // escapes. Otherwise, this is a UTF-16 or UTF-32 string, and Char is a
1137 // codepoint: use \x escapes for invalid codepoints.
1138 if (getKind() == Wide ||
1139 (Char >= 0xd800 && Char <= 0xdfff) || Char >= 0x110000) {
1140 // FIXME: Is this the best way to print wchar_t?
1141 OS << "\\x";
1142 int Shift = 28;
1143 while ((Char >> Shift) == 0)
1144 Shift -= 4;
1145 for (/**/; Shift >= 0; Shift -= 4)
1146 OS << Hex[(Char >> Shift) & 15];
1147 LastSlashX = I;
1148 break;
1149 }
1150
1151 if (Char > 0xffff)
1152 OS << "\\U00"
1153 << Hex[(Char >> 20) & 15]
1154 << Hex[(Char >> 16) & 15];
1155 else
1156 OS << "\\u";
1157 OS << Hex[(Char >> 12) & 15]
1158 << Hex[(Char >> 8) & 15]
1159 << Hex[(Char >> 4) & 15]
1160 << Hex[(Char >> 0) & 15];
1161 break;
1162 }
1163
1164 // If we used \x... for the previous character, and this character is a
1165 // hexadecimal digit, prevent it being slurped as part of the \x.
1166 if (LastSlashX + 1 == I) {
1167 switch (Char) {
1168 case '0': case '1': case '2': case '3': case '4':
1169 case '5': case '6': case '7': case '8': case '9':
1170 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
1171 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
1172 OS << "\"\"";
1173 }
1174 }
1175
1176 assert(Char <= 0xff &&
1177 "Characters above 0xff should already have been handled.");
1178
Jordan Rosea7d03842013-02-08 22:30:41 +00001179 if (isPrintable(Char))
Richard Trieudc355912012-06-13 20:25:24 +00001180 OS << (char)Char;
1181 else // Output anything hard as an octal escape.
1182 OS << '\\'
1183 << (char)('0' + ((Char >> 6) & 7))
1184 << (char)('0' + ((Char >> 3) & 7))
1185 << (char)('0' + ((Char >> 0) & 7));
1186 break;
1187 // Handle some common non-printable cases to make dumps prettier.
1188 case '\\': OS << "\\\\"; break;
1189 case '"': OS << "\\\""; break;
Richard Trieudc355912012-06-13 20:25:24 +00001190 case '\a': OS << "\\a"; break;
1191 case '\b': OS << "\\b"; break;
Benjamin Kramer60a53d52016-11-24 09:41:33 +00001192 case '\f': OS << "\\f"; break;
1193 case '\n': OS << "\\n"; break;
1194 case '\r': OS << "\\r"; break;
1195 case '\t': OS << "\\t"; break;
1196 case '\v': OS << "\\v"; break;
Richard Trieudc355912012-06-13 20:25:24 +00001197 }
1198 }
1199 OS << '"';
1200}
1201
Chris Lattnere925d612010-11-17 07:37:15 +00001202/// getLocationOfByte - Return a source location that points to the specified
1203/// byte of this string literal.
1204///
1205/// Strings are amazingly complex. They can be formed from multiple tokens and
1206/// can have escape sequences in them in addition to the usual trigraph and
1207/// escaped newline business. This routine handles this complexity.
1208///
Richard Smithefb116f2015-12-10 01:11:47 +00001209/// The *StartToken sets the first token to be searched in this function and
1210/// the *StartTokenByteOffset is the byte offset of the first token. Before
1211/// returning, it updates the *StartToken to the TokNo of the token being found
1212/// and sets *StartTokenByteOffset to the byte offset of the token in the
1213/// string.
1214/// Using these two parameters can reduce the time complexity from O(n^2) to
1215/// O(n) if one wants to get the location of byte for all the tokens in a
1216/// string.
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001217///
Richard Smithefb116f2015-12-10 01:11:47 +00001218SourceLocation
1219StringLiteral::getLocationOfByte(unsigned ByteNo, const SourceManager &SM,
1220 const LangOptions &Features,
1221 const TargetInfo &Target, unsigned *StartToken,
1222 unsigned *StartTokenByteOffset) const {
Bruno Ricciaf214882018-11-15 16:42:14 +00001223 assert((getKind() == StringLiteral::Ascii ||
1224 getKind() == StringLiteral::UTF8) &&
Richard Smith4060f772012-06-13 05:37:23 +00001225 "Only narrow string literals are currently supported");
Douglas Gregorfb65e592011-07-27 05:40:30 +00001226
Chris Lattnere925d612010-11-17 07:37:15 +00001227 // Loop over all of the tokens in this string until we find the one that
1228 // contains the byte we're looking for.
1229 unsigned TokNo = 0;
Richard Smithefb116f2015-12-10 01:11:47 +00001230 unsigned StringOffset = 0;
1231 if (StartToken)
1232 TokNo = *StartToken;
1233 if (StartTokenByteOffset) {
1234 StringOffset = *StartTokenByteOffset;
1235 ByteNo -= StringOffset;
1236 }
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001237 while (1) {
Chris Lattnere925d612010-11-17 07:37:15 +00001238 assert(TokNo < getNumConcatenated() && "Invalid byte number!");
1239 SourceLocation StrTokLoc = getStrTokenLoc(TokNo);
Fangrui Song6907ce22018-07-30 19:24:48 +00001240
Chris Lattnere925d612010-11-17 07:37:15 +00001241 // Get the spelling of the string so that we can get the data that makes up
1242 // the string literal, not the identifier for the macro it is potentially
1243 // expanded through.
1244 SourceLocation StrTokSpellingLoc = SM.getSpellingLoc(StrTokLoc);
Richard Smithefb116f2015-12-10 01:11:47 +00001245
Chris Lattnere925d612010-11-17 07:37:15 +00001246 // Re-lex the token to get its length and original spelling.
Richard Smithefb116f2015-12-10 01:11:47 +00001247 std::pair<FileID, unsigned> LocInfo =
1248 SM.getDecomposedLoc(StrTokSpellingLoc);
Chris Lattnere925d612010-11-17 07:37:15 +00001249 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001250 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
Richard Smithefb116f2015-12-10 01:11:47 +00001251 if (Invalid) {
1252 if (StartTokenByteOffset != nullptr)
1253 *StartTokenByteOffset = StringOffset;
1254 if (StartToken != nullptr)
1255 *StartToken = TokNo;
Chris Lattnere925d612010-11-17 07:37:15 +00001256 return StrTokSpellingLoc;
Richard Smithefb116f2015-12-10 01:11:47 +00001257 }
1258
Chris Lattnere925d612010-11-17 07:37:15 +00001259 const char *StrData = Buffer.data()+LocInfo.second;
Fangrui Song6907ce22018-07-30 19:24:48 +00001260
Chris Lattnere925d612010-11-17 07:37:15 +00001261 // Create a lexer starting at the beginning of this token.
Argyrios Kyrtzidis45f51182012-05-11 21:39:18 +00001262 Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), Features,
1263 Buffer.begin(), StrData, Buffer.end());
Chris Lattnere925d612010-11-17 07:37:15 +00001264 Token TheTok;
1265 TheLexer.LexFromRawLexer(TheTok);
Fangrui Song6907ce22018-07-30 19:24:48 +00001266
Chris Lattnere925d612010-11-17 07:37:15 +00001267 // Use the StringLiteralParser to compute the length of the string in bytes.
Craig Topper9d5583e2014-06-26 04:58:39 +00001268 StringLiteralParser SLP(TheTok, SM, Features, Target);
Chris Lattnere925d612010-11-17 07:37:15 +00001269 unsigned TokNumBytes = SLP.GetStringLength();
Fangrui Song6907ce22018-07-30 19:24:48 +00001270
Chris Lattnere925d612010-11-17 07:37:15 +00001271 // If the byte is in this token, return the location of the byte.
1272 if (ByteNo < TokNumBytes ||
Hans Wennborg77d1abe2011-06-30 20:17:41 +00001273 (ByteNo == TokNumBytes && TokNo == getNumConcatenated() - 1)) {
Richard Smithefb116f2015-12-10 01:11:47 +00001274 unsigned Offset = SLP.getOffsetOfStringByte(TheTok, ByteNo);
1275
Chris Lattnere925d612010-11-17 07:37:15 +00001276 // Now that we know the offset of the token in the spelling, use the
1277 // preprocessor to get the offset in the original source.
Richard Smithefb116f2015-12-10 01:11:47 +00001278 if (StartTokenByteOffset != nullptr)
1279 *StartTokenByteOffset = StringOffset;
1280 if (StartToken != nullptr)
1281 *StartToken = TokNo;
Chris Lattnere925d612010-11-17 07:37:15 +00001282 return Lexer::AdvanceToTokenCharacter(StrTokLoc, Offset, SM, Features);
1283 }
Richard Smithefb116f2015-12-10 01:11:47 +00001284
Chris Lattnere925d612010-11-17 07:37:15 +00001285 // Move to the next string token.
Richard Smithefb116f2015-12-10 01:11:47 +00001286 StringOffset += TokNumBytes;
Chris Lattnere925d612010-11-17 07:37:15 +00001287 ++TokNo;
1288 ByteNo -= TokNumBytes;
1289 }
1290}
1291
Chris Lattner1b926492006-08-23 06:42:10 +00001292/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1293/// corresponds to, e.g. "sizeof" or "[pre]++".
Bruno Ricci3dfcb842018-11-13 21:33:22 +00001294StringRef UnaryOperator::getOpcodeStr(Opcode Op) {
1295 switch (Op) {
Etienne Bergeron5356d962016-05-12 20:58:56 +00001296#define UNARY_OPERATION(Name, Spelling) case UO_##Name: return Spelling;
1297#include "clang/AST/OperationKinds.def"
Chris Lattner1b926492006-08-23 06:42:10 +00001298 }
David Blaikief47fa302012-01-17 02:30:50 +00001299 llvm_unreachable("Unknown unary operator");
Chris Lattner1b926492006-08-23 06:42:10 +00001300}
1301
John McCalle3027922010-08-25 11:45:40 +00001302UnaryOperatorKind
Douglas Gregor084d8552009-03-13 23:49:33 +00001303UnaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix) {
1304 switch (OO) {
David Blaikie83d382b2011-09-23 05:06:16 +00001305 default: llvm_unreachable("No unary operator for overloaded function");
John McCalle3027922010-08-25 11:45:40 +00001306 case OO_PlusPlus: return Postfix ? UO_PostInc : UO_PreInc;
1307 case OO_MinusMinus: return Postfix ? UO_PostDec : UO_PreDec;
1308 case OO_Amp: return UO_AddrOf;
1309 case OO_Star: return UO_Deref;
1310 case OO_Plus: return UO_Plus;
1311 case OO_Minus: return UO_Minus;
1312 case OO_Tilde: return UO_Not;
1313 case OO_Exclaim: return UO_LNot;
Richard Smith9f690bd2015-10-27 06:02:45 +00001314 case OO_Coawait: return UO_Coawait;
Douglas Gregor084d8552009-03-13 23:49:33 +00001315 }
1316}
1317
1318OverloadedOperatorKind UnaryOperator::getOverloadedOperator(Opcode Opc) {
1319 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00001320 case UO_PostInc: case UO_PreInc: return OO_PlusPlus;
1321 case UO_PostDec: case UO_PreDec: return OO_MinusMinus;
1322 case UO_AddrOf: return OO_Amp;
1323 case UO_Deref: return OO_Star;
1324 case UO_Plus: return OO_Plus;
1325 case UO_Minus: return OO_Minus;
1326 case UO_Not: return OO_Tilde;
1327 case UO_LNot: return OO_Exclaim;
Richard Smith9f690bd2015-10-27 06:02:45 +00001328 case UO_Coawait: return OO_Coawait;
Douglas Gregor084d8552009-03-13 23:49:33 +00001329 default: return OO_None;
1330 }
1331}
1332
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001333
Chris Lattner0eedafe2006-08-24 04:56:27 +00001334//===----------------------------------------------------------------------===//
1335// Postfix Operators.
1336//===----------------------------------------------------------------------===//
Chris Lattnere165d942006-08-24 04:40:38 +00001337
Bruno Riccic5885cf2018-12-21 15:20:32 +00001338CallExpr::CallExpr(StmtClass SC, Expr *Fn, ArrayRef<Expr *> PreArgs,
1339 ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,
1340 SourceLocation RParenLoc, unsigned MinNumArgs,
1341 ADLCallKind UsesADL)
1342 : Expr(SC, Ty, VK, OK_Ordinary, Fn->isTypeDependent(),
1343 Fn->isValueDependent(), Fn->isInstantiationDependent(),
1344 Fn->containsUnexpandedParameterPack()),
1345 RParenLoc(RParenLoc) {
1346 NumArgs = std::max<unsigned>(Args.size(), MinNumArgs);
1347 unsigned NumPreArgs = PreArgs.size();
1348 CallExprBits.NumPreArgs = NumPreArgs;
1349 assert((NumPreArgs == getNumPreArgs()) && "NumPreArgs overflow!");
1350
1351 unsigned OffsetToTrailingObjects = offsetToTrailingObjects(SC);
1352 CallExprBits.OffsetToTrailingObjects = OffsetToTrailingObjects;
1353 assert((CallExprBits.OffsetToTrailingObjects == OffsetToTrailingObjects) &&
1354 "OffsetToTrailingObjects overflow!");
1355
Eric Fiselier5cdc2cd2018-12-12 21:50:55 +00001356 CallExprBits.UsesADL = static_cast<bool>(UsesADL);
1357
Bruno Riccic5885cf2018-12-21 15:20:32 +00001358 setCallee(Fn);
1359 for (unsigned I = 0; I != NumPreArgs; ++I) {
1360 updateDependenciesFromArg(PreArgs[I]);
1361 setPreArg(I, PreArgs[I]);
Justin Lebarf8bdacb2016-01-14 23:31:30 +00001362 }
Bruno Riccic5885cf2018-12-21 15:20:32 +00001363 for (unsigned I = 0; I != Args.size(); ++I) {
1364 updateDependenciesFromArg(Args[I]);
1365 setArg(I, Args[I]);
Douglas Gregora6e053e2010-12-15 01:34:56 +00001366 }
Bruno Riccic5885cf2018-12-21 15:20:32 +00001367 for (unsigned I = Args.size(); I != NumArgs; ++I) {
1368 setArg(I, nullptr);
Bruno Ricci4c9a0192018-12-03 14:54:03 +00001369 }
Douglas Gregor993603d2008-11-14 16:09:21 +00001370}
Nate Begeman1e36a852008-01-17 17:46:27 +00001371
Bruno Riccic5885cf2018-12-21 15:20:32 +00001372CallExpr::CallExpr(StmtClass SC, unsigned NumPreArgs, unsigned NumArgs,
1373 EmptyShell Empty)
Bruno Ricci4c9a0192018-12-03 14:54:03 +00001374 : Expr(SC, Empty), NumArgs(NumArgs) {
Peter Collingbourne3a347252011-02-08 21:18:02 +00001375 CallExprBits.NumPreArgs = NumPreArgs;
Bruno Riccic5885cf2018-12-21 15:20:32 +00001376 assert((NumPreArgs == getNumPreArgs()) && "NumPreArgs overflow!");
1377
1378 unsigned OffsetToTrailingObjects = offsetToTrailingObjects(SC);
1379 CallExprBits.OffsetToTrailingObjects = OffsetToTrailingObjects;
1380 assert((CallExprBits.OffsetToTrailingObjects == OffsetToTrailingObjects) &&
1381 "OffsetToTrailingObjects overflow!");
Douglas Gregore20a2e52009-04-15 17:43:59 +00001382}
1383
Bruno Riccic5885cf2018-12-21 15:20:32 +00001384CallExpr *CallExpr::Create(const ASTContext &Ctx, Expr *Fn,
1385 ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,
1386 SourceLocation RParenLoc, unsigned MinNumArgs,
1387 ADLCallKind UsesADL) {
1388 unsigned NumArgs = std::max<unsigned>(Args.size(), MinNumArgs);
1389 unsigned SizeOfTrailingObjects =
1390 CallExpr::sizeOfTrailingObjects(/*NumPreArgs=*/0, NumArgs);
1391 void *Mem =
1392 Ctx.Allocate(sizeof(CallExpr) + SizeOfTrailingObjects, alignof(CallExpr));
1393 return new (Mem) CallExpr(CallExprClass, Fn, /*PreArgs=*/{}, Args, Ty, VK,
1394 RParenLoc, MinNumArgs, UsesADL);
1395}
1396
1397CallExpr *CallExpr::CreateTemporary(void *Mem, Expr *Fn, QualType Ty,
1398 ExprValueKind VK, SourceLocation RParenLoc,
1399 ADLCallKind UsesADL) {
1400 assert(!(reinterpret_cast<uintptr_t>(Mem) % alignof(CallExpr)) &&
1401 "Misaligned memory in CallExpr::CreateTemporary!");
1402 return new (Mem) CallExpr(CallExprClass, Fn, /*PreArgs=*/{}, /*Args=*/{}, Ty,
1403 VK, RParenLoc, /*MinNumArgs=*/0, UsesADL);
1404}
1405
1406CallExpr *CallExpr::CreateEmpty(const ASTContext &Ctx, unsigned NumArgs,
1407 EmptyShell Empty) {
1408 unsigned SizeOfTrailingObjects =
1409 CallExpr::sizeOfTrailingObjects(/*NumPreArgs=*/0, NumArgs);
1410 void *Mem =
1411 Ctx.Allocate(sizeof(CallExpr) + SizeOfTrailingObjects, alignof(CallExpr));
1412 return new (Mem) CallExpr(CallExprClass, /*NumPreArgs=*/0, NumArgs, Empty);
1413}
1414
1415unsigned CallExpr::offsetToTrailingObjects(StmtClass SC) {
1416 switch (SC) {
1417 case CallExprClass:
1418 return sizeof(CallExpr);
1419 case CXXOperatorCallExprClass:
1420 return sizeof(CXXOperatorCallExpr);
1421 case CXXMemberCallExprClass:
1422 return sizeof(CXXMemberCallExpr);
1423 case UserDefinedLiteralClass:
1424 return sizeof(UserDefinedLiteral);
1425 case CUDAKernelCallExprClass:
1426 return sizeof(CUDAKernelCallExpr);
1427 default:
1428 llvm_unreachable("unexpected class deriving from CallExpr!");
1429 }
1430}
Bruno Ricci4c9a0192018-12-03 14:54:03 +00001431
Justin Lebarf8bdacb2016-01-14 23:31:30 +00001432void CallExpr::updateDependenciesFromArg(Expr *Arg) {
1433 if (Arg->isTypeDependent())
1434 ExprBits.TypeDependent = true;
1435 if (Arg->isValueDependent())
1436 ExprBits.ValueDependent = true;
1437 if (Arg->isInstantiationDependent())
1438 ExprBits.InstantiationDependent = true;
1439 if (Arg->containsUnexpandedParameterPack())
1440 ExprBits.ContainsUnexpandedParameterPack = true;
1441}
1442
John McCallb92ab1a2016-10-26 23:46:34 +00001443Decl *Expr::getReferencedDeclOfCallee() {
1444 Expr *CEE = IgnoreParenImpCasts();
Fangrui Song6907ce22018-07-30 19:24:48 +00001445
Douglas Gregore0e96302011-09-06 21:41:04 +00001446 while (SubstNonTypeTemplateParmExpr *NTTP
1447 = dyn_cast<SubstNonTypeTemplateParmExpr>(CEE)) {
1448 CEE = NTTP->getReplacement()->IgnoreParenCasts();
1449 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001450
Sebastian Redl2b1832e2010-09-10 20:55:30 +00001451 // If we're calling a dereference, look at the pointer instead.
1452 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CEE)) {
1453 if (BO->isPtrMemOp())
1454 CEE = BO->getRHS()->IgnoreParenCasts();
1455 } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(CEE)) {
1456 if (UO->getOpcode() == UO_Deref)
1457 CEE = UO->getSubExpr()->IgnoreParenCasts();
1458 }
Chris Lattner52301912009-07-17 15:46:27 +00001459 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CEE))
Nuno Lopes518e3702009-12-20 23:11:08 +00001460 return DRE->getDecl();
Nuno Lopesc095b532009-12-24 00:28:18 +00001461 if (MemberExpr *ME = dyn_cast<MemberExpr>(CEE))
1462 return ME->getMemberDecl();
Yaxun Liud83c7402019-02-26 16:20:41 +00001463 if (auto *BE = dyn_cast<BlockExpr>(CEE))
1464 return BE->getBlockDecl();
Zhongxing Xu3c8fa972009-07-17 07:29:51 +00001465
Craig Topper36250ad2014-05-12 05:36:57 +00001466 return nullptr;
Zhongxing Xu3c8fa972009-07-17 07:29:51 +00001467}
1468
Alp Tokera724cff2013-12-28 21:59:02 +00001469/// getBuiltinCallee - If this is a call to a builtin, return the builtin ID. If
Chris Lattner01ff98a2008-10-06 05:00:53 +00001470/// not, return 0.
Alp Tokera724cff2013-12-28 21:59:02 +00001471unsigned CallExpr::getBuiltinCallee() const {
Steve Narofff6e3b3292008-01-31 01:07:12 +00001472 // All simple function calls (e.g. func()) are implicitly cast to pointer to
Mike Stump11289f42009-09-09 15:08:12 +00001473 // function. As a result, we try and obtain the DeclRefExpr from the
Steve Narofff6e3b3292008-01-31 01:07:12 +00001474 // ImplicitCastExpr.
1475 const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(getCallee());
1476 if (!ICE) // FIXME: deal with more complex calls (e.g. (func)(), (*func)()).
Chris Lattner01ff98a2008-10-06 05:00:53 +00001477 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001478
Steve Narofff6e3b3292008-01-31 01:07:12 +00001479 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr());
1480 if (!DRE)
Chris Lattner01ff98a2008-10-06 05:00:53 +00001481 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001482
Anders Carlssonfbcf6762008-01-31 02:13:57 +00001483 const FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
1484 if (!FDecl)
Chris Lattner01ff98a2008-10-06 05:00:53 +00001485 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001486
Douglas Gregor9eb16ea2008-11-21 15:30:19 +00001487 if (!FDecl->getIdentifier())
1488 return 0;
1489
Douglas Gregor15fc9562009-09-12 00:22:50 +00001490 return FDecl->getBuiltinID();
Chris Lattner01ff98a2008-10-06 05:00:53 +00001491}
Anders Carlssonfbcf6762008-01-31 02:13:57 +00001492
Scott Douglass503fc392015-06-10 13:53:15 +00001493bool CallExpr::isUnevaluatedBuiltinCall(const ASTContext &Ctx) const {
Alp Tokera724cff2013-12-28 21:59:02 +00001494 if (unsigned BI = getBuiltinCallee())
Richard Smith5011a002013-01-17 23:46:04 +00001495 return Ctx.BuiltinInfo.isUnevaluated(BI);
1496 return false;
1497}
1498
David Majnemerced8bdf2015-02-25 17:36:15 +00001499QualType CallExpr::getCallReturnType(const ASTContext &Ctx) const {
1500 const Expr *Callee = getCallee();
1501 QualType CalleeType = Callee->getType();
1502 if (const auto *FnTypePtr = CalleeType->getAs<PointerType>()) {
Anders Carlsson00a27592009-05-26 04:57:27 +00001503 CalleeType = FnTypePtr->getPointeeType();
David Majnemerced8bdf2015-02-25 17:36:15 +00001504 } else if (const auto *BPT = CalleeType->getAs<BlockPointerType>()) {
Anders Carlsson00a27592009-05-26 04:57:27 +00001505 CalleeType = BPT->getPointeeType();
David Majnemerced8bdf2015-02-25 17:36:15 +00001506 } else if (CalleeType->isSpecificPlaceholderType(BuiltinType::BoundMember)) {
1507 if (isa<CXXPseudoDestructorExpr>(Callee->IgnoreParens()))
1508 return Ctx.VoidTy;
1509
John McCall0009fcc2011-04-26 20:42:42 +00001510 // This should never be overloaded and so should never return null.
David Majnemerced8bdf2015-02-25 17:36:15 +00001511 CalleeType = Expr::findBoundMemberType(Callee);
1512 }
1513
John McCall0009fcc2011-04-26 20:42:42 +00001514 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00001515 return FnType->getReturnType();
Anders Carlsson00a27592009-05-26 04:57:27 +00001516}
Chris Lattner01ff98a2008-10-06 05:00:53 +00001517
Aaron Ballmand23e9bc2019-01-03 14:24:31 +00001518const Attr *CallExpr::getUnusedResultAttr(const ASTContext &Ctx) const {
1519 // If the return type is a struct, union, or enum that is marked nodiscard,
1520 // then return the return type attribute.
1521 if (const TagDecl *TD = getCallReturnType(Ctx)->getAsTagDecl())
1522 if (const auto *A = TD->getAttr<WarnUnusedResultAttr>())
1523 return A;
1524
1525 // Otherwise, see if the callee is marked nodiscard and return that attribute
1526 // instead.
1527 const Decl *D = getCalleeDecl();
1528 return D ? D->getAttr<WarnUnusedResultAttr>() : nullptr;
1529}
1530
Stephen Kelly724e9e52018-08-09 20:05:03 +00001531SourceLocation CallExpr::getBeginLoc() const {
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001532 if (isa<CXXOperatorCallExpr>(this))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001533 return cast<CXXOperatorCallExpr>(this)->getBeginLoc();
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001534
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001535 SourceLocation begin = getCallee()->getBeginLoc();
Keno Fischer070db172014-08-15 01:39:12 +00001536 if (begin.isInvalid() && getNumArgs() > 0 && getArg(0))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001537 begin = getArg(0)->getBeginLoc();
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001538 return begin;
1539}
Stephen Kelly02a67ba2018-08-09 20:05:47 +00001540SourceLocation CallExpr::getEndLoc() const {
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001541 if (isa<CXXOperatorCallExpr>(this))
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001542 return cast<CXXOperatorCallExpr>(this)->getEndLoc();
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001543
1544 SourceLocation end = getRParenLoc();
Keno Fischer070db172014-08-15 01:39:12 +00001545 if (end.isInvalid() && getNumArgs() > 0 && getArg(getNumArgs() - 1))
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001546 end = getArg(getNumArgs() - 1)->getEndLoc();
Daniel Dunbarcdf295c2012-03-09 15:39:24 +00001547 return end;
1548}
John McCall701417a2011-02-21 06:23:05 +00001549
Craig Topper37932912013-08-18 10:09:15 +00001550OffsetOfExpr *OffsetOfExpr::Create(const ASTContext &C, QualType type,
Douglas Gregor882211c2010-04-28 22:16:22 +00001551 SourceLocation OperatorLoc,
Fangrui Song6907ce22018-07-30 19:24:48 +00001552 TypeSourceInfo *tsi,
Benjamin Kramerc215e762012-08-24 11:54:20 +00001553 ArrayRef<OffsetOfNode> comps,
1554 ArrayRef<Expr*> exprs,
Douglas Gregor882211c2010-04-28 22:16:22 +00001555 SourceLocation RParenLoc) {
James Y Knight7281c352015-12-29 22:31:18 +00001556 void *Mem = C.Allocate(
1557 totalSizeToAlloc<OffsetOfNode, Expr *>(comps.size(), exprs.size()));
Douglas Gregor882211c2010-04-28 22:16:22 +00001558
Benjamin Kramerc215e762012-08-24 11:54:20 +00001559 return new (Mem) OffsetOfExpr(C, type, OperatorLoc, tsi, comps, exprs,
1560 RParenLoc);
Douglas Gregor882211c2010-04-28 22:16:22 +00001561}
1562
Craig Topper37932912013-08-18 10:09:15 +00001563OffsetOfExpr *OffsetOfExpr::CreateEmpty(const ASTContext &C,
Douglas Gregor882211c2010-04-28 22:16:22 +00001564 unsigned numComps, unsigned numExprs) {
James Y Knight7281c352015-12-29 22:31:18 +00001565 void *Mem =
1566 C.Allocate(totalSizeToAlloc<OffsetOfNode, Expr *>(numComps, numExprs));
Douglas Gregor882211c2010-04-28 22:16:22 +00001567 return new (Mem) OffsetOfExpr(numComps, numExprs);
1568}
1569
Craig Topper37932912013-08-18 10:09:15 +00001570OffsetOfExpr::OffsetOfExpr(const ASTContext &C, QualType type,
Douglas Gregor882211c2010-04-28 22:16:22 +00001571 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
Benjamin Kramerc215e762012-08-24 11:54:20 +00001572 ArrayRef<OffsetOfNode> comps, ArrayRef<Expr*> exprs,
Douglas Gregor882211c2010-04-28 22:16:22 +00001573 SourceLocation RParenLoc)
John McCall7decc9e2010-11-18 06:31:45 +00001574 : Expr(OffsetOfExprClass, type, VK_RValue, OK_Ordinary,
Fangrui Song6907ce22018-07-30 19:24:48 +00001575 /*TypeDependent=*/false,
Douglas Gregora6e053e2010-12-15 01:34:56 +00001576 /*ValueDependent=*/tsi->getType()->isDependentType(),
Douglas Gregor678d76c2011-07-01 01:22:09 +00001577 tsi->getType()->isInstantiationDependentType(),
Douglas Gregora6e053e2010-12-15 01:34:56 +00001578 tsi->getType()->containsUnexpandedParameterPack()),
Fangrui Song6907ce22018-07-30 19:24:48 +00001579 OperatorLoc(OperatorLoc), RParenLoc(RParenLoc), TSInfo(tsi),
Benjamin Kramerc215e762012-08-24 11:54:20 +00001580 NumComps(comps.size()), NumExprs(exprs.size())
Douglas Gregor882211c2010-04-28 22:16:22 +00001581{
Benjamin Kramerc215e762012-08-24 11:54:20 +00001582 for (unsigned i = 0; i != comps.size(); ++i) {
1583 setComponent(i, comps[i]);
Douglas Gregor882211c2010-04-28 22:16:22 +00001584 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001585
Benjamin Kramerc215e762012-08-24 11:54:20 +00001586 for (unsigned i = 0; i != exprs.size(); ++i) {
1587 if (exprs[i]->isTypeDependent() || exprs[i]->isValueDependent())
Douglas Gregora6e053e2010-12-15 01:34:56 +00001588 ExprBits.ValueDependent = true;
Benjamin Kramerc215e762012-08-24 11:54:20 +00001589 if (exprs[i]->containsUnexpandedParameterPack())
Douglas Gregora6e053e2010-12-15 01:34:56 +00001590 ExprBits.ContainsUnexpandedParameterPack = true;
1591
Benjamin Kramerc215e762012-08-24 11:54:20 +00001592 setIndexExpr(i, exprs[i]);
Douglas Gregor882211c2010-04-28 22:16:22 +00001593 }
1594}
1595
James Y Knight7281c352015-12-29 22:31:18 +00001596IdentifierInfo *OffsetOfNode::getFieldName() const {
Douglas Gregor882211c2010-04-28 22:16:22 +00001597 assert(getKind() == Field || getKind() == Identifier);
1598 if (getKind() == Field)
1599 return getField()->getIdentifier();
Fangrui Song6907ce22018-07-30 19:24:48 +00001600
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001601 return reinterpret_cast<IdentifierInfo *> (Data & ~(uintptr_t)Mask);
Douglas Gregor882211c2010-04-28 22:16:22 +00001602}
1603
David Majnemer10fd83d2015-01-15 10:04:14 +00001604UnaryExprOrTypeTraitExpr::UnaryExprOrTypeTraitExpr(
1605 UnaryExprOrTypeTrait ExprKind, Expr *E, QualType resultType,
1606 SourceLocation op, SourceLocation rp)
1607 : Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_RValue, OK_Ordinary,
1608 false, // Never type-dependent (C++ [temp.dep.expr]p3).
1609 // Value-dependent if the argument is type-dependent.
1610 E->isTypeDependent(), E->isInstantiationDependent(),
1611 E->containsUnexpandedParameterPack()),
1612 OpLoc(op), RParenLoc(rp) {
1613 UnaryExprOrTypeTraitExprBits.Kind = ExprKind;
1614 UnaryExprOrTypeTraitExprBits.IsType = false;
1615 Argument.Ex = E;
1616
1617 // Check to see if we are in the situation where alignof(decl) should be
1618 // dependent because decl's alignment is dependent.
Richard Smith6822bd72018-10-26 19:26:45 +00001619 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
David Majnemer10fd83d2015-01-15 10:04:14 +00001620 if (!isValueDependent() || !isInstantiationDependent()) {
1621 E = E->IgnoreParens();
1622
1623 const ValueDecl *D = nullptr;
1624 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
1625 D = DRE->getDecl();
1626 else if (const auto *ME = dyn_cast<MemberExpr>(E))
1627 D = ME->getMemberDecl();
1628
1629 if (D) {
1630 for (const auto *I : D->specific_attrs<AlignedAttr>()) {
1631 if (I->isAlignmentDependent()) {
1632 setValueDependent(true);
1633 setInstantiationDependent(true);
1634 break;
1635 }
1636 }
1637 }
1638 }
1639 }
1640}
1641
Richard Smithdcf17de2019-06-06 23:24:15 +00001642MemberExpr::MemberExpr(Expr *Base, bool IsArrow, SourceLocation OperatorLoc,
1643 ValueDecl *MemberDecl,
1644 const DeclarationNameInfo &NameInfo, QualType T,
Richard Smith1bbad592019-06-11 17:50:36 +00001645 ExprValueKind VK, ExprObjectKind OK,
1646 NonOdrUseReason NOUR)
Richard Smithdcf17de2019-06-06 23:24:15 +00001647 : Expr(MemberExprClass, T, VK, OK, Base->isTypeDependent(),
1648 Base->isValueDependent(), Base->isInstantiationDependent(),
1649 Base->containsUnexpandedParameterPack()),
1650 Base(Base), MemberDecl(MemberDecl), MemberDNLoc(NameInfo.getInfo()),
1651 MemberLoc(NameInfo.getLoc()) {
1652 assert(!NameInfo.getName() ||
1653 MemberDecl->getDeclName() == NameInfo.getName());
1654 MemberExprBits.IsArrow = IsArrow;
1655 MemberExprBits.HasQualifierOrFoundDecl = false;
1656 MemberExprBits.HasTemplateKWAndArgsInfo = false;
1657 MemberExprBits.HadMultipleCandidates = false;
Richard Smith1bbad592019-06-11 17:50:36 +00001658 MemberExprBits.NonOdrUseReason = NOUR;
Richard Smithdcf17de2019-06-06 23:24:15 +00001659 MemberExprBits.OperatorLoc = OperatorLoc;
1660}
1661
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00001662MemberExpr *MemberExpr::Create(
Richard Smithdcf17de2019-06-06 23:24:15 +00001663 const ASTContext &C, Expr *Base, bool IsArrow, SourceLocation OperatorLoc,
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00001664 NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,
Richard Smithdcf17de2019-06-06 23:24:15 +00001665 ValueDecl *MemberDecl, DeclAccessPair FoundDecl,
1666 DeclarationNameInfo NameInfo, const TemplateArgumentListInfo *TemplateArgs,
Richard Smith1bbad592019-06-11 17:50:36 +00001667 QualType T, ExprValueKind VK, ExprObjectKind OK, NonOdrUseReason NOUR) {
Richard Smithdcf17de2019-06-06 23:24:15 +00001668 bool HasQualOrFound = QualifierLoc || FoundDecl.getDecl() != MemberDecl ||
1669 FoundDecl.getAccess() != MemberDecl->getAccess();
1670 bool HasTemplateKWAndArgsInfo = TemplateArgs || TemplateKWLoc.isValid();
James Y Knighte7d82282015-12-29 18:15:14 +00001671 std::size_t Size =
1672 totalSizeToAlloc<MemberExprNameQualifier, ASTTemplateKWAndArgsInfo,
Richard Smithdcf17de2019-06-06 23:24:15 +00001673 TemplateArgumentLoc>(
1674 HasQualOrFound ? 1 : 0, HasTemplateKWAndArgsInfo ? 1 : 0,
1675 TemplateArgs ? TemplateArgs->size() : 0);
Mike Stump11289f42009-09-09 15:08:12 +00001676
Benjamin Kramerc3f89252016-10-20 14:27:22 +00001677 void *Mem = C.Allocate(Size, alignof(MemberExpr));
Richard Smith1bbad592019-06-11 17:50:36 +00001678 MemberExpr *E = new (Mem) MemberExpr(Base, IsArrow, OperatorLoc, MemberDecl,
1679 NameInfo, T, VK, OK, NOUR);
John McCall16df1e52010-03-30 21:47:33 +00001680
Michael Liao59312cb2019-12-03 21:15:17 -05001681 if (isa<FieldDecl>(MemberDecl)) {
Elizabeth Andrews878a24e2019-12-03 14:20:52 -08001682 DeclContext *DC = MemberDecl->getDeclContext();
1683 // dyn_cast_or_null is used to handle objC variables which do not
1684 // have a declaration context.
1685 CXXRecordDecl *RD = dyn_cast_or_null<CXXRecordDecl>(DC);
1686 if (RD && RD->isDependentContext() && RD->isCurrentInstantiation(DC))
1687 E->setTypeDependent(T->isDependentType());
1688 }
1689
Richard Smithdcf17de2019-06-06 23:24:15 +00001690 if (HasQualOrFound) {
Douglas Gregorea972d32011-02-28 21:54:11 +00001691 // FIXME: Wrong. We should be looking at the member declaration we found.
1692 if (QualifierLoc && QualifierLoc.getNestedNameSpecifier()->isDependent()) {
John McCall16df1e52010-03-30 21:47:33 +00001693 E->setValueDependent(true);
1694 E->setTypeDependent(true);
Douglas Gregor678d76c2011-07-01 01:22:09 +00001695 E->setInstantiationDependent(true);
Fangrui Song6907ce22018-07-30 19:24:48 +00001696 }
1697 else if (QualifierLoc &&
1698 QualifierLoc.getNestedNameSpecifier()->isInstantiationDependent())
Douglas Gregor678d76c2011-07-01 01:22:09 +00001699 E->setInstantiationDependent(true);
Fangrui Song6907ce22018-07-30 19:24:48 +00001700
Bruno Ricci4c742532018-11-15 13:56:22 +00001701 E->MemberExprBits.HasQualifierOrFoundDecl = true;
John McCall16df1e52010-03-30 21:47:33 +00001702
James Y Knighte7d82282015-12-29 18:15:14 +00001703 MemberExprNameQualifier *NQ =
1704 E->getTrailingObjects<MemberExprNameQualifier>();
Douglas Gregorea972d32011-02-28 21:54:11 +00001705 NQ->QualifierLoc = QualifierLoc;
Richard Smithdcf17de2019-06-06 23:24:15 +00001706 NQ->FoundDecl = FoundDecl;
John McCall16df1e52010-03-30 21:47:33 +00001707 }
1708
Bruno Ricci4c742532018-11-15 13:56:22 +00001709 E->MemberExprBits.HasTemplateKWAndArgsInfo =
Richard Smithdcf17de2019-06-06 23:24:15 +00001710 TemplateArgs || TemplateKWLoc.isValid();
Abramo Bagnara7945c982012-01-27 09:46:47 +00001711
Richard Smithdcf17de2019-06-06 23:24:15 +00001712 if (TemplateArgs) {
Douglas Gregor678d76c2011-07-01 01:22:09 +00001713 bool Dependent = false;
1714 bool InstantiationDependent = false;
1715 bool ContainsUnexpandedParameterPack = false;
James Y Knighte7d82282015-12-29 18:15:14 +00001716 E->getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
Richard Smithdcf17de2019-06-06 23:24:15 +00001717 TemplateKWLoc, *TemplateArgs,
1718 E->getTrailingObjects<TemplateArgumentLoc>(), Dependent,
1719 InstantiationDependent, ContainsUnexpandedParameterPack);
Douglas Gregor678d76c2011-07-01 01:22:09 +00001720 if (InstantiationDependent)
1721 E->setInstantiationDependent(true);
Abramo Bagnara7945c982012-01-27 09:46:47 +00001722 } else if (TemplateKWLoc.isValid()) {
James Y Knighte7d82282015-12-29 18:15:14 +00001723 E->getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
1724 TemplateKWLoc);
John McCall16df1e52010-03-30 21:47:33 +00001725 }
1726
1727 return E;
Douglas Gregorf405d7e2009-08-31 23:41:50 +00001728}
1729
Richard Smithdcf17de2019-06-06 23:24:15 +00001730MemberExpr *MemberExpr::CreateEmpty(const ASTContext &Context,
1731 bool HasQualifier, bool HasFoundDecl,
1732 bool HasTemplateKWAndArgsInfo,
1733 unsigned NumTemplateArgs) {
1734 assert((!NumTemplateArgs || HasTemplateKWAndArgsInfo) &&
1735 "template args but no template arg info?");
1736 bool HasQualOrFound = HasQualifier || HasFoundDecl;
1737 std::size_t Size =
1738 totalSizeToAlloc<MemberExprNameQualifier, ASTTemplateKWAndArgsInfo,
1739 TemplateArgumentLoc>(HasQualOrFound ? 1 : 0,
1740 HasTemplateKWAndArgsInfo ? 1 : 0,
1741 NumTemplateArgs);
1742 void *Mem = Context.Allocate(Size, alignof(MemberExpr));
1743 return new (Mem) MemberExpr(EmptyShell());
1744}
1745
Stephen Kelly724e9e52018-08-09 20:05:03 +00001746SourceLocation MemberExpr::getBeginLoc() const {
Douglas Gregor25b7e052011-03-02 21:06:53 +00001747 if (isImplicitAccess()) {
1748 if (hasQualifier())
Daniel Dunbarb507f272012-03-09 15:39:15 +00001749 return getQualifierLoc().getBeginLoc();
1750 return MemberLoc;
Douglas Gregor25b7e052011-03-02 21:06:53 +00001751 }
Abramo Bagnara7945c982012-01-27 09:46:47 +00001752
Daniel Dunbarb507f272012-03-09 15:39:15 +00001753 // FIXME: We don't want this to happen. Rather, we should be able to
1754 // detect all kinds of implicit accesses more cleanly.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001755 SourceLocation BaseStartLoc = getBase()->getBeginLoc();
Daniel Dunbarb507f272012-03-09 15:39:15 +00001756 if (BaseStartLoc.isValid())
1757 return BaseStartLoc;
1758 return MemberLoc;
1759}
Stephen Kelly02a67ba2018-08-09 20:05:47 +00001760SourceLocation MemberExpr::getEndLoc() const {
Abramo Bagnara9b836fb2012-11-08 13:52:58 +00001761 SourceLocation EndLoc = getMemberNameInfo().getEndLoc();
Daniel Dunbarb507f272012-03-09 15:39:15 +00001762 if (hasExplicitTemplateArgs())
Abramo Bagnara9b836fb2012-11-08 13:52:58 +00001763 EndLoc = getRAngleLoc();
1764 else if (EndLoc.isInvalid())
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001765 EndLoc = getBase()->getEndLoc();
Abramo Bagnara9b836fb2012-11-08 13:52:58 +00001766 return EndLoc;
Douglas Gregor25b7e052011-03-02 21:06:53 +00001767}
1768
Alp Tokerc1086762013-12-07 13:51:35 +00001769bool CastExpr::CastConsistency() const {
John McCall9320b872011-09-09 05:25:32 +00001770 switch (getCastKind()) {
1771 case CK_DerivedToBase:
1772 case CK_UncheckedDerivedToBase:
1773 case CK_DerivedToBaseMemberPointer:
1774 case CK_BaseToDerived:
1775 case CK_BaseToDerivedMemberPointer:
1776 assert(!path_empty() && "Cast kind should have a base path!");
1777 break;
1778
1779 case CK_CPointerToObjCPointerCast:
1780 assert(getType()->isObjCObjectPointerType());
1781 assert(getSubExpr()->getType()->isPointerType());
1782 goto CheckNoBasePath;
1783
1784 case CK_BlockPointerToObjCPointerCast:
1785 assert(getType()->isObjCObjectPointerType());
1786 assert(getSubExpr()->getType()->isBlockPointerType());
1787 goto CheckNoBasePath;
1788
John McCallc62bb392012-02-15 01:22:51 +00001789 case CK_ReinterpretMemberPointer:
1790 assert(getType()->isMemberPointerType());
1791 assert(getSubExpr()->getType()->isMemberPointerType());
1792 goto CheckNoBasePath;
1793
John McCall9320b872011-09-09 05:25:32 +00001794 case CK_BitCast:
1795 // Arbitrary casts to C pointer types count as bitcasts.
1796 // Otherwise, we should only have block and ObjC pointer casts
1797 // here if they stay within the type kind.
1798 if (!getType()->isPointerType()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001799 assert(getType()->isObjCObjectPointerType() ==
John McCall9320b872011-09-09 05:25:32 +00001800 getSubExpr()->getType()->isObjCObjectPointerType());
Fangrui Song6907ce22018-07-30 19:24:48 +00001801 assert(getType()->isBlockPointerType() ==
John McCall9320b872011-09-09 05:25:32 +00001802 getSubExpr()->getType()->isBlockPointerType());
1803 }
1804 goto CheckNoBasePath;
1805
1806 case CK_AnyPointerToBlockPointerCast:
1807 assert(getType()->isBlockPointerType());
1808 assert(getSubExpr()->getType()->isAnyPointerType() &&
1809 !getSubExpr()->getType()->isBlockPointerType());
1810 goto CheckNoBasePath;
1811
Douglas Gregored90df32012-02-22 05:02:47 +00001812 case CK_CopyAndAutoreleaseBlockObject:
1813 assert(getType()->isBlockPointerType());
1814 assert(getSubExpr()->getType()->isBlockPointerType());
1815 goto CheckNoBasePath;
Eli Friedman34866c72012-08-31 00:14:07 +00001816
1817 case CK_FunctionToPointerDecay:
1818 assert(getType()->isPointerType());
1819 assert(getSubExpr()->getType()->isFunctionType());
1820 goto CheckNoBasePath;
1821
Anastasia Stulova04307942018-11-16 16:22:56 +00001822 case CK_AddressSpaceConversion: {
1823 auto Ty = getType();
1824 auto SETy = getSubExpr()->getType();
1825 assert(getValueKindForType(Ty) == Expr::getValueKindForType(SETy));
Anastasia Stulovaa29aa472019-11-27 11:03:11 +00001826 if (isRValue()) {
Anastasia Stulova04307942018-11-16 16:22:56 +00001827 Ty = Ty->getPointeeType();
Anastasia Stulova04307942018-11-16 16:22:56 +00001828 SETy = SETy->getPointeeType();
Anastasia Stulovad1986d12019-01-14 11:44:22 +00001829 }
Anastasia Stulova04307942018-11-16 16:22:56 +00001830 assert(!Ty.isNull() && !SETy.isNull() &&
1831 Ty.getAddressSpace() != SETy.getAddressSpace());
1832 goto CheckNoBasePath;
1833 }
John McCall9320b872011-09-09 05:25:32 +00001834 // These should not have an inheritance path.
1835 case CK_Dynamic:
1836 case CK_ToUnion:
1837 case CK_ArrayToPointerDecay:
John McCall9320b872011-09-09 05:25:32 +00001838 case CK_NullToMemberPointer:
1839 case CK_NullToPointer:
1840 case CK_ConstructorConversion:
1841 case CK_IntegralToPointer:
1842 case CK_PointerToIntegral:
1843 case CK_ToVoid:
1844 case CK_VectorSplat:
1845 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +00001846 case CK_BooleanToSignedIntegral:
John McCall9320b872011-09-09 05:25:32 +00001847 case CK_IntegralToFloating:
1848 case CK_FloatingToIntegral:
1849 case CK_FloatingCast:
1850 case CK_ObjCObjectLValueCast:
1851 case CK_FloatingRealToComplex:
1852 case CK_FloatingComplexToReal:
1853 case CK_FloatingComplexCast:
1854 case CK_FloatingComplexToIntegralComplex:
1855 case CK_IntegralRealToComplex:
1856 case CK_IntegralComplexToReal:
1857 case CK_IntegralComplexCast:
1858 case CK_IntegralComplexToFloatingComplex:
John McCall2d637d22011-09-10 06:18:15 +00001859 case CK_ARCProduceObject:
1860 case CK_ARCConsumeObject:
1861 case CK_ARCReclaimReturnedObject:
1862 case CK_ARCExtendBlockObject:
Andrew Savonichevb555b762018-10-23 15:19:20 +00001863 case CK_ZeroToOCLOpaqueType:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00001864 case CK_IntToOCLSampler:
Leonard Chan99bda372018-10-15 16:07:02 +00001865 case CK_FixedPointCast:
Leonard Chan8f7caae2019-03-06 00:28:43 +00001866 case CK_FixedPointToIntegral:
1867 case CK_IntegralToFixedPoint:
John McCall9320b872011-09-09 05:25:32 +00001868 assert(!getType()->isBooleanType() && "unheralded conversion to bool");
1869 goto CheckNoBasePath;
1870
1871 case CK_Dependent:
1872 case CK_LValueToRValue:
John McCall9320b872011-09-09 05:25:32 +00001873 case CK_NoOp:
David Chisnallfa35df62012-01-16 17:27:18 +00001874 case CK_AtomicToNonAtomic:
1875 case CK_NonAtomicToAtomic:
John McCall9320b872011-09-09 05:25:32 +00001876 case CK_PointerToBoolean:
1877 case CK_IntegralToBoolean:
1878 case CK_FloatingToBoolean:
1879 case CK_MemberPointerToBoolean:
1880 case CK_FloatingComplexToBoolean:
1881 case CK_IntegralComplexToBoolean:
1882 case CK_LValueBitCast: // -> bool&
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00001883 case CK_LValueToRValueBitCast:
John McCall9320b872011-09-09 05:25:32 +00001884 case CK_UserDefinedConversion: // operator bool()
Eli Friedman34866c72012-08-31 00:14:07 +00001885 case CK_BuiltinFnToFnPtr:
Leonard Chanb4ba4672018-10-23 17:55:35 +00001886 case CK_FixedPointToBoolean:
John McCall9320b872011-09-09 05:25:32 +00001887 CheckNoBasePath:
1888 assert(path_empty() && "Cast kind should not have a base path!");
1889 break;
1890 }
Alp Tokerc1086762013-12-07 13:51:35 +00001891 return true;
John McCall9320b872011-09-09 05:25:32 +00001892}
1893
Eric Fiselier0683c0e2018-05-07 21:07:10 +00001894const char *CastExpr::getCastKindName(CastKind CK) {
1895 switch (CK) {
Etienne Bergeron5356d962016-05-12 20:58:56 +00001896#define CAST_OPERATION(Name) case CK_##Name: return #Name;
1897#include "clang/AST/OperationKinds.def"
Anders Carlsson496335e2009-09-03 00:59:21 +00001898 }
John McCallc5e62b42010-11-13 09:02:35 +00001899 llvm_unreachable("Unhandled cast kind!");
Anders Carlsson496335e2009-09-03 00:59:21 +00001900}
1901
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001902namespace {
Richard Smith1ef75542018-06-27 20:30:34 +00001903 const Expr *skipImplicitTemporary(const Expr *E) {
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001904 // Skip through reference binding to temporary.
Richard Smith1ef75542018-06-27 20:30:34 +00001905 if (auto *Materialize = dyn_cast<MaterializeTemporaryExpr>(E))
Tykerb0561b32019-11-17 11:41:55 +01001906 E = Materialize->getSubExpr();
Stephan Bergmannf31b0dc2017-06-27 08:19:09 +00001907
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001908 // Skip any temporary bindings; they're implicit.
Richard Smith1ef75542018-06-27 20:30:34 +00001909 if (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
1910 E = Binder->getSubExpr();
Stephan Bergmannf31b0dc2017-06-27 08:19:09 +00001911
Richard Smith1ef75542018-06-27 20:30:34 +00001912 return E;
Eugene Zelenkoae304b02017-11-17 18:09:48 +00001913 }
Stephan Bergmannf31b0dc2017-06-27 08:19:09 +00001914}
1915
Douglas Gregord196a582009-12-14 19:27:10 +00001916Expr *CastExpr::getSubExprAsWritten() {
Richard Smith1ef75542018-06-27 20:30:34 +00001917 const Expr *SubExpr = nullptr;
1918 const CastExpr *E = this;
Douglas Gregord196a582009-12-14 19:27:10 +00001919 do {
Stephan Bergmannf31b0dc2017-06-27 08:19:09 +00001920 SubExpr = skipImplicitTemporary(E->getSubExpr());
Douglas Gregorfe314812011-06-21 17:03:29 +00001921
Douglas Gregord196a582009-12-14 19:27:10 +00001922 // Conversions by constructor and conversion functions have a
1923 // subexpression describing the call; strip it off.
John McCalle3027922010-08-25 11:45:40 +00001924 if (E->getCastKind() == CK_ConstructorConversion)
Stephan Bergmannf31b0dc2017-06-27 08:19:09 +00001925 SubExpr =
1926 skipImplicitTemporary(cast<CXXConstructExpr>(SubExpr)->getArg(0));
Manman Ren8abc2e52016-02-02 22:23:03 +00001927 else if (E->getCastKind() == CK_UserDefinedConversion) {
1928 assert((isa<CXXMemberCallExpr>(SubExpr) ||
1929 isa<BlockExpr>(SubExpr)) &&
1930 "Unexpected SubExpr for CK_UserDefinedConversion.");
Richard Smith1ef75542018-06-27 20:30:34 +00001931 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SubExpr))
1932 SubExpr = MCE->getImplicitObjectArgument();
Manman Ren8abc2e52016-02-02 22:23:03 +00001933 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001934
Douglas Gregord196a582009-12-14 19:27:10 +00001935 // If the subexpression we're left with is an implicit cast, look
1936 // through that, too.
Fangrui Song6907ce22018-07-30 19:24:48 +00001937 } while ((E = dyn_cast<ImplicitCastExpr>(SubExpr)));
1938
Richard Smith1ef75542018-06-27 20:30:34 +00001939 return const_cast<Expr*>(SubExpr);
1940}
1941
1942NamedDecl *CastExpr::getConversionFunction() const {
1943 const Expr *SubExpr = nullptr;
1944
1945 for (const CastExpr *E = this; E; E = dyn_cast<ImplicitCastExpr>(SubExpr)) {
1946 SubExpr = skipImplicitTemporary(E->getSubExpr());
1947
1948 if (E->getCastKind() == CK_ConstructorConversion)
1949 return cast<CXXConstructExpr>(SubExpr)->getConstructor();
1950
1951 if (E->getCastKind() == CK_UserDefinedConversion) {
1952 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SubExpr))
1953 return MCE->getMethodDecl();
1954 }
1955 }
1956
1957 return nullptr;
Douglas Gregord196a582009-12-14 19:27:10 +00001958}
1959
John McCallcf142162010-08-07 06:22:56 +00001960CXXBaseSpecifier **CastExpr::path_buffer() {
1961 switch (getStmtClass()) {
1962#define ABSTRACT_STMT(x)
James Y Knight1d75c5e2015-12-30 02:27:28 +00001963#define CASTEXPR(Type, Base) \
1964 case Stmt::Type##Class: \
1965 return static_cast<Type *>(this)->getTrailingObjects<CXXBaseSpecifier *>();
John McCallcf142162010-08-07 06:22:56 +00001966#define STMT(Type, Base)
1967#include "clang/AST/StmtNodes.inc"
1968 default:
1969 llvm_unreachable("non-cast expressions not possible here");
John McCallcf142162010-08-07 06:22:56 +00001970 }
1971}
1972
John McCallf1ef7962017-08-15 21:42:47 +00001973const FieldDecl *CastExpr::getTargetFieldForToUnionCast(QualType unionType,
1974 QualType opType) {
1975 auto RD = unionType->castAs<RecordType>()->getDecl();
1976 return getTargetFieldForToUnionCast(RD, opType);
1977}
1978
1979const FieldDecl *CastExpr::getTargetFieldForToUnionCast(const RecordDecl *RD,
1980 QualType OpType) {
1981 auto &Ctx = RD->getASTContext();
1982 RecordDecl::field_iterator Field, FieldEnd;
1983 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
1984 Field != FieldEnd; ++Field) {
1985 if (Ctx.hasSameUnqualifiedType(Field->getType(), OpType) &&
1986 !Field->isUnnamedBitfield()) {
1987 return *Field;
1988 }
1989 }
1990 return nullptr;
1991}
1992
Craig Topper37932912013-08-18 10:09:15 +00001993ImplicitCastExpr *ImplicitCastExpr::Create(const ASTContext &C, QualType T,
John McCallcf142162010-08-07 06:22:56 +00001994 CastKind Kind, Expr *Operand,
1995 const CXXCastPath *BasePath,
John McCall2536c6d2010-08-25 10:28:54 +00001996 ExprValueKind VK) {
John McCallcf142162010-08-07 06:22:56 +00001997 unsigned PathSize = (BasePath ? BasePath->size() : 0);
Bruno Ricci49391652019-01-09 16:41:33 +00001998 void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
Richard Smith27252a12019-06-14 17:46:38 +00001999 // Per C++ [conv.lval]p3, lvalue-to-rvalue conversions on class and
2000 // std::nullptr_t have special semantics not captured by CK_LValueToRValue.
2001 assert((Kind != CK_LValueToRValue ||
2002 !(T->isNullPtrType() || T->getAsCXXRecordDecl())) &&
2003 "invalid type for lvalue-to-rvalue conversion");
John McCallcf142162010-08-07 06:22:56 +00002004 ImplicitCastExpr *E =
John McCall2536c6d2010-08-25 10:28:54 +00002005 new (Buffer) ImplicitCastExpr(T, Kind, Operand, PathSize, VK);
James Y Knight1d75c5e2015-12-30 02:27:28 +00002006 if (PathSize)
2007 std::uninitialized_copy_n(BasePath->data(), BasePath->size(),
2008 E->getTrailingObjects<CXXBaseSpecifier *>());
John McCallcf142162010-08-07 06:22:56 +00002009 return E;
2010}
2011
Craig Topper37932912013-08-18 10:09:15 +00002012ImplicitCastExpr *ImplicitCastExpr::CreateEmpty(const ASTContext &C,
John McCallcf142162010-08-07 06:22:56 +00002013 unsigned PathSize) {
Bruno Ricci49391652019-01-09 16:41:33 +00002014 void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
John McCallcf142162010-08-07 06:22:56 +00002015 return new (Buffer) ImplicitCastExpr(EmptyShell(), PathSize);
2016}
2017
2018
Craig Topper37932912013-08-18 10:09:15 +00002019CStyleCastExpr *CStyleCastExpr::Create(const ASTContext &C, QualType T,
John McCall7decc9e2010-11-18 06:31:45 +00002020 ExprValueKind VK, CastKind K, Expr *Op,
John McCallcf142162010-08-07 06:22:56 +00002021 const CXXCastPath *BasePath,
2022 TypeSourceInfo *WrittenTy,
2023 SourceLocation L, SourceLocation R) {
2024 unsigned PathSize = (BasePath ? BasePath->size() : 0);
Bruno Ricci49391652019-01-09 16:41:33 +00002025 void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
John McCallcf142162010-08-07 06:22:56 +00002026 CStyleCastExpr *E =
John McCall7decc9e2010-11-18 06:31:45 +00002027 new (Buffer) CStyleCastExpr(T, VK, K, Op, PathSize, WrittenTy, L, R);
James Y Knight1d75c5e2015-12-30 02:27:28 +00002028 if (PathSize)
2029 std::uninitialized_copy_n(BasePath->data(), BasePath->size(),
2030 E->getTrailingObjects<CXXBaseSpecifier *>());
John McCallcf142162010-08-07 06:22:56 +00002031 return E;
2032}
2033
Craig Topper37932912013-08-18 10:09:15 +00002034CStyleCastExpr *CStyleCastExpr::CreateEmpty(const ASTContext &C,
2035 unsigned PathSize) {
Bruno Ricci49391652019-01-09 16:41:33 +00002036 void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
John McCallcf142162010-08-07 06:22:56 +00002037 return new (Buffer) CStyleCastExpr(EmptyShell(), PathSize);
2038}
2039
Chris Lattner1b926492006-08-23 06:42:10 +00002040/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
2041/// corresponds to, e.g. "<<=".
David Blaikie1d202a62012-10-08 01:11:04 +00002042StringRef BinaryOperator::getOpcodeStr(Opcode Op) {
Chris Lattner1b926492006-08-23 06:42:10 +00002043 switch (Op) {
Etienne Bergeron5356d962016-05-12 20:58:56 +00002044#define BINARY_OPERATION(Name, Spelling) case BO_##Name: return Spelling;
2045#include "clang/AST/OperationKinds.def"
Chris Lattner1b926492006-08-23 06:42:10 +00002046 }
David Blaikiee4d798f2012-01-20 21:50:17 +00002047 llvm_unreachable("Invalid OpCode!");
Chris Lattner1b926492006-08-23 06:42:10 +00002048}
Steve Naroff47500512007-04-19 23:00:49 +00002049
John McCalle3027922010-08-25 11:45:40 +00002050BinaryOperatorKind
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002051BinaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO) {
2052 switch (OO) {
David Blaikie83d382b2011-09-23 05:06:16 +00002053 default: llvm_unreachable("Not an overloadable binary operator");
John McCalle3027922010-08-25 11:45:40 +00002054 case OO_Plus: return BO_Add;
2055 case OO_Minus: return BO_Sub;
2056 case OO_Star: return BO_Mul;
2057 case OO_Slash: return BO_Div;
2058 case OO_Percent: return BO_Rem;
2059 case OO_Caret: return BO_Xor;
2060 case OO_Amp: return BO_And;
2061 case OO_Pipe: return BO_Or;
2062 case OO_Equal: return BO_Assign;
Richard Smithc70f1d62017-12-14 15:16:18 +00002063 case OO_Spaceship: return BO_Cmp;
John McCalle3027922010-08-25 11:45:40 +00002064 case OO_Less: return BO_LT;
2065 case OO_Greater: return BO_GT;
2066 case OO_PlusEqual: return BO_AddAssign;
2067 case OO_MinusEqual: return BO_SubAssign;
2068 case OO_StarEqual: return BO_MulAssign;
2069 case OO_SlashEqual: return BO_DivAssign;
2070 case OO_PercentEqual: return BO_RemAssign;
2071 case OO_CaretEqual: return BO_XorAssign;
2072 case OO_AmpEqual: return BO_AndAssign;
2073 case OO_PipeEqual: return BO_OrAssign;
2074 case OO_LessLess: return BO_Shl;
2075 case OO_GreaterGreater: return BO_Shr;
2076 case OO_LessLessEqual: return BO_ShlAssign;
2077 case OO_GreaterGreaterEqual: return BO_ShrAssign;
2078 case OO_EqualEqual: return BO_EQ;
2079 case OO_ExclaimEqual: return BO_NE;
2080 case OO_LessEqual: return BO_LE;
2081 case OO_GreaterEqual: return BO_GE;
2082 case OO_AmpAmp: return BO_LAnd;
2083 case OO_PipePipe: return BO_LOr;
2084 case OO_Comma: return BO_Comma;
2085 case OO_ArrowStar: return BO_PtrMemI;
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002086 }
2087}
2088
2089OverloadedOperatorKind BinaryOperator::getOverloadedOperator(Opcode Opc) {
2090 static const OverloadedOperatorKind OverOps[] = {
2091 /* .* Cannot be overloaded */OO_None, OO_ArrowStar,
2092 OO_Star, OO_Slash, OO_Percent,
2093 OO_Plus, OO_Minus,
2094 OO_LessLess, OO_GreaterGreater,
Richard Smithc70f1d62017-12-14 15:16:18 +00002095 OO_Spaceship,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002096 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
2097 OO_EqualEqual, OO_ExclaimEqual,
2098 OO_Amp,
2099 OO_Caret,
2100 OO_Pipe,
2101 OO_AmpAmp,
2102 OO_PipePipe,
2103 OO_Equal, OO_StarEqual,
2104 OO_SlashEqual, OO_PercentEqual,
2105 OO_PlusEqual, OO_MinusEqual,
2106 OO_LessLessEqual, OO_GreaterGreaterEqual,
2107 OO_AmpEqual, OO_CaretEqual,
2108 OO_PipeEqual,
2109 OO_Comma
2110 };
2111 return OverOps[Opc];
2112}
2113
Andrew Kaylor3d0a5402017-09-19 20:26:40 +00002114bool BinaryOperator::isNullPointerArithmeticExtension(ASTContext &Ctx,
2115 Opcode Opc,
2116 Expr *LHS, Expr *RHS) {
2117 if (Opc != BO_Add)
2118 return false;
2119
2120 // Check that we have one pointer and one integer operand.
2121 Expr *PExp;
Andrew Kaylor3d0a5402017-09-19 20:26:40 +00002122 if (LHS->getType()->isPointerType()) {
2123 if (!RHS->getType()->isIntegerType())
2124 return false;
2125 PExp = LHS;
Andrew Kaylor3d0a5402017-09-19 20:26:40 +00002126 } else if (RHS->getType()->isPointerType()) {
2127 if (!LHS->getType()->isIntegerType())
2128 return false;
2129 PExp = RHS;
Andrew Kaylor3d0a5402017-09-19 20:26:40 +00002130 } else {
2131 return false;
2132 }
2133
2134 // Check that the pointer is a nullptr.
2135 if (!PExp->IgnoreParenCasts()
2136 ->isNullPointerConstant(Ctx, Expr::NPC_ValueDependentIsNotNull))
2137 return false;
2138
2139 // Check that the pointee type is char-sized.
2140 const PointerType *PTy = PExp->getType()->getAs<PointerType>();
2141 if (!PTy || !PTy->getPointeeType()->isCharType())
2142 return false;
2143
Andrew Kaylor3d0a5402017-09-19 20:26:40 +00002144 return true;
2145}
Eric Fiselier708afb52019-05-16 21:04:15 +00002146
2147static QualType getDecayedSourceLocExprType(const ASTContext &Ctx,
2148 SourceLocExpr::IdentKind Kind) {
2149 switch (Kind) {
2150 case SourceLocExpr::File:
2151 case SourceLocExpr::Function: {
2152 QualType ArrTy = Ctx.getStringLiteralArrayType(Ctx.CharTy, 0);
2153 return Ctx.getPointerType(ArrTy->getAsArrayTypeUnsafe()->getElementType());
2154 }
2155 case SourceLocExpr::Line:
2156 case SourceLocExpr::Column:
2157 return Ctx.UnsignedIntTy;
2158 }
2159 llvm_unreachable("unhandled case");
2160}
2161
2162SourceLocExpr::SourceLocExpr(const ASTContext &Ctx, IdentKind Kind,
2163 SourceLocation BLoc, SourceLocation RParenLoc,
2164 DeclContext *ParentContext)
2165 : Expr(SourceLocExprClass, getDecayedSourceLocExprType(Ctx, Kind),
2166 VK_RValue, OK_Ordinary, false, false, false, false),
2167 BuiltinLoc(BLoc), RParenLoc(RParenLoc), ParentContext(ParentContext) {
2168 SourceLocExprBits.Kind = Kind;
2169}
2170
2171StringRef SourceLocExpr::getBuiltinStr() const {
2172 switch (getIdentKind()) {
2173 case File:
2174 return "__builtin_FILE";
2175 case Function:
2176 return "__builtin_FUNCTION";
2177 case Line:
2178 return "__builtin_LINE";
2179 case Column:
2180 return "__builtin_COLUMN";
2181 }
2182 llvm_unreachable("unexpected IdentKind!");
2183}
2184
2185APValue SourceLocExpr::EvaluateInContext(const ASTContext &Ctx,
2186 const Expr *DefaultExpr) const {
2187 SourceLocation Loc;
2188 const DeclContext *Context;
2189
2190 std::tie(Loc,
2191 Context) = [&]() -> std::pair<SourceLocation, const DeclContext *> {
2192 if (auto *DIE = dyn_cast_or_null<CXXDefaultInitExpr>(DefaultExpr))
2193 return {DIE->getUsedLocation(), DIE->getUsedContext()};
2194 if (auto *DAE = dyn_cast_or_null<CXXDefaultArgExpr>(DefaultExpr))
2195 return {DAE->getUsedLocation(), DAE->getUsedContext()};
2196 return {this->getLocation(), this->getParentContext()};
2197 }();
2198
2199 PresumedLoc PLoc = Ctx.getSourceManager().getPresumedLoc(
2200 Ctx.getSourceManager().getExpansionRange(Loc).getEnd());
2201
2202 auto MakeStringLiteral = [&](StringRef Tmp) {
2203 using LValuePathEntry = APValue::LValuePathEntry;
2204 StringLiteral *Res = Ctx.getPredefinedStringLiteralFromCache(Tmp);
2205 // Decay the string to a pointer to the first character.
2206 LValuePathEntry Path[1] = {LValuePathEntry::ArrayIndex(0)};
2207 return APValue(Res, CharUnits::Zero(), Path, /*OnePastTheEnd=*/false);
2208 };
2209
2210 switch (getIdentKind()) {
2211 case SourceLocExpr::File:
2212 return MakeStringLiteral(PLoc.getFilename());
2213 case SourceLocExpr::Function: {
2214 const Decl *CurDecl = dyn_cast_or_null<Decl>(Context);
2215 return MakeStringLiteral(
2216 CurDecl ? PredefinedExpr::ComputeName(PredefinedExpr::Function, CurDecl)
2217 : std::string(""));
2218 }
2219 case SourceLocExpr::Line:
2220 case SourceLocExpr::Column: {
2221 llvm::APSInt IntVal(Ctx.getIntWidth(Ctx.UnsignedIntTy),
Rui Ueyama49a3ad22019-07-16 04:46:31 +00002222 /*isUnsigned=*/true);
Eric Fiselier708afb52019-05-16 21:04:15 +00002223 IntVal = getIdentKind() == SourceLocExpr::Line ? PLoc.getLine()
2224 : PLoc.getColumn();
2225 return APValue(IntVal);
2226 }
2227 }
2228 llvm_unreachable("unhandled case");
2229}
2230
Craig Topper37932912013-08-18 10:09:15 +00002231InitListExpr::InitListExpr(const ASTContext &C, SourceLocation lbraceloc,
Benjamin Kramerc215e762012-08-24 11:54:20 +00002232 ArrayRef<Expr*> initExprs, SourceLocation rbraceloc)
Eugene Zelenkoae304b02017-11-17 18:09:48 +00002233 : Expr(InitListExprClass, QualType(), VK_RValue, OK_Ordinary, false, false,
2234 false, false),
2235 InitExprs(C, initExprs.size()),
2236 LBraceLoc(lbraceloc), RBraceLoc(rbraceloc), AltForm(nullptr, true)
2237{
Sebastian Redlc83ed822012-02-17 08:42:25 +00002238 sawArrayRangeDesignator(false);
Benjamin Kramerc215e762012-08-24 11:54:20 +00002239 for (unsigned I = 0; I != initExprs.size(); ++I) {
Ted Kremenek013041e2010-02-19 01:50:18 +00002240 if (initExprs[I]->isTypeDependent())
John McCall925b16622010-10-26 08:39:16 +00002241 ExprBits.TypeDependent = true;
Ted Kremenek013041e2010-02-19 01:50:18 +00002242 if (initExprs[I]->isValueDependent())
John McCall925b16622010-10-26 08:39:16 +00002243 ExprBits.ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +00002244 if (initExprs[I]->isInstantiationDependent())
2245 ExprBits.InstantiationDependent = true;
Douglas Gregora6e053e2010-12-15 01:34:56 +00002246 if (initExprs[I]->containsUnexpandedParameterPack())
2247 ExprBits.ContainsUnexpandedParameterPack = true;
Douglas Gregordeebf6e2009-11-19 23:25:22 +00002248 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002249
Benjamin Kramerc215e762012-08-24 11:54:20 +00002250 InitExprs.insert(C, InitExprs.end(), initExprs.begin(), initExprs.end());
Anders Carlsson4692db02007-08-31 04:56:16 +00002251}
Chris Lattner1ec5f562007-06-27 05:38:08 +00002252
Craig Topper37932912013-08-18 10:09:15 +00002253void InitListExpr::reserveInits(const ASTContext &C, unsigned NumInits) {
Ted Kremenek013041e2010-02-19 01:50:18 +00002254 if (NumInits > InitExprs.size())
Ted Kremenekac034612010-04-13 23:39:13 +00002255 InitExprs.reserve(C, NumInits);
Douglas Gregor6d00c992009-03-20 23:58:33 +00002256}
2257
Craig Topper37932912013-08-18 10:09:15 +00002258void InitListExpr::resizeInits(const ASTContext &C, unsigned NumInits) {
Craig Topper36250ad2014-05-12 05:36:57 +00002259 InitExprs.resize(C, NumInits, nullptr);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002260}
2261
Craig Topper37932912013-08-18 10:09:15 +00002262Expr *InitListExpr::updateInit(const ASTContext &C, unsigned Init, Expr *expr) {
Ted Kremenek013041e2010-02-19 01:50:18 +00002263 if (Init >= InitExprs.size()) {
Craig Topper36250ad2014-05-12 05:36:57 +00002264 InitExprs.insert(C, InitExprs.end(), Init - InitExprs.size() + 1, nullptr);
Richard Smithc275da62013-12-06 01:27:24 +00002265 setInit(Init, expr);
Craig Topper36250ad2014-05-12 05:36:57 +00002266 return nullptr;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002267 }
Mike Stump11289f42009-09-09 15:08:12 +00002268
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002269 Expr *Result = cast_or_null<Expr>(InitExprs[Init]);
Richard Smithc275da62013-12-06 01:27:24 +00002270 setInit(Init, expr);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002271 return Result;
2272}
2273
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +00002274void InitListExpr::setArrayFiller(Expr *filler) {
Argyrios Kyrtzidisd4590a5d2011-10-21 23:02:22 +00002275 assert(!hasArrayFiller() && "Filler already set!");
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +00002276 ArrayFillerOrUnionFieldInit = filler;
2277 // Fill out any "holes" in the array due to designated initializers.
2278 Expr **inits = getInits();
2279 for (unsigned i = 0, e = getNumInits(); i != e; ++i)
Craig Topper36250ad2014-05-12 05:36:57 +00002280 if (inits[i] == nullptr)
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +00002281 inits[i] = filler;
2282}
2283
Richard Smith9ec1e482012-04-15 02:50:59 +00002284bool InitListExpr::isStringLiteralInit() const {
2285 if (getNumInits() != 1)
2286 return false;
Eli Friedmancf4ab082012-08-20 20:55:45 +00002287 const ArrayType *AT = getType()->getAsArrayTypeUnsafe();
2288 if (!AT || !AT->getElementType()->isIntegerType())
Richard Smith9ec1e482012-04-15 02:50:59 +00002289 return false;
Ted Kremenek256bd962014-01-19 06:31:34 +00002290 // It is possible for getInit() to return null.
2291 const Expr *Init = getInit(0);
2292 if (!Init)
2293 return false;
2294 Init = Init->IgnoreParens();
Richard Smith9ec1e482012-04-15 02:50:59 +00002295 return isa<StringLiteral>(Init) || isa<ObjCEncodeExpr>(Init);
2296}
2297
Richard Smith122f88d2016-12-06 23:52:28 +00002298bool InitListExpr::isTransparent() const {
2299 assert(isSemanticForm() && "syntactic form never semantically transparent");
2300
2301 // A glvalue InitListExpr is always just sugar.
2302 if (isGLValue()) {
2303 assert(getNumInits() == 1 && "multiple inits in glvalue init list");
2304 return true;
2305 }
2306
2307 // Otherwise, we're sugar if and only if we have exactly one initializer that
2308 // is of the same type.
2309 if (getNumInits() != 1 || !getInit(0))
2310 return false;
2311
Richard Smith382bc512017-02-23 22:41:47 +00002312 // Don't confuse aggregate initialization of a struct X { X &x; }; with a
2313 // transparent struct copy.
2314 if (!getInit(0)->isRValue() && getType()->isRecordType())
2315 return false;
2316
Richard Smith122f88d2016-12-06 23:52:28 +00002317 return getType().getCanonicalType() ==
2318 getInit(0)->getType().getCanonicalType();
2319}
2320
Daniel Marjamaki817a3bf2017-09-29 09:44:41 +00002321bool InitListExpr::isIdiomaticZeroInitializer(const LangOptions &LangOpts) const {
2322 assert(isSyntacticForm() && "only test syntactic form as zero initializer");
2323
Peter Wufa52e002019-07-16 01:13:36 +00002324 if (LangOpts.CPlusPlus || getNumInits() != 1 || !getInit(0)) {
Daniel Marjamaki817a3bf2017-09-29 09:44:41 +00002325 return false;
2326 }
2327
Peter Wufa52e002019-07-16 01:13:36 +00002328 const IntegerLiteral *Lit = dyn_cast<IntegerLiteral>(getInit(0)->IgnoreImplicit());
Daniel Marjamaki817a3bf2017-09-29 09:44:41 +00002329 return Lit && Lit->getValue() == 0;
2330}
2331
Stephen Kelly724e9e52018-08-09 20:05:03 +00002332SourceLocation InitListExpr::getBeginLoc() const {
Abramo Bagnara8d16bd42012-11-08 18:41:43 +00002333 if (InitListExpr *SyntacticForm = getSyntacticForm())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002334 return SyntacticForm->getBeginLoc();
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002335 SourceLocation Beg = LBraceLoc;
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002336 if (Beg.isInvalid()) {
2337 // Find the first non-null initializer.
2338 for (InitExprsTy::const_iterator I = InitExprs.begin(),
Fangrui Song6907ce22018-07-30 19:24:48 +00002339 E = InitExprs.end();
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002340 I != E; ++I) {
2341 if (Stmt *S = *I) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002342 Beg = S->getBeginLoc();
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002343 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00002344 }
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002345 }
2346 }
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002347 return Beg;
2348}
2349
Stephen Kelly02a67ba2018-08-09 20:05:47 +00002350SourceLocation InitListExpr::getEndLoc() const {
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002351 if (InitListExpr *SyntacticForm = getSyntacticForm())
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002352 return SyntacticForm->getEndLoc();
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002353 SourceLocation End = RBraceLoc;
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002354 if (End.isInvalid()) {
2355 // Find the first non-null initializer from the end.
2356 for (InitExprsTy::const_reverse_iterator I = InitExprs.rbegin(),
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002357 E = InitExprs.rend();
2358 I != E; ++I) {
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002359 if (Stmt *S = *I) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002360 End = S->getEndLoc();
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002361 break;
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002362 }
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002363 }
2364 }
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00002365 return End;
Ted Kremenek16e6026f2010-11-09 02:11:40 +00002366}
2367
Steve Naroff991e99d2008-09-04 15:31:07 +00002368/// getFunctionType - Return the underlying function type for this block.
Eugene Zelenkoae304b02017-11-17 18:09:48 +00002369///
John McCallc833dea2012-02-17 03:32:35 +00002370const FunctionProtoType *BlockExpr::getFunctionType() const {
2371 // The block pointer is never sugared, but the function type might be.
2372 return cast<BlockPointerType>(getType())
2373 ->getPointeeType()->castAs<FunctionProtoType>();
Steve Naroffc540d662008-09-03 18:15:37 +00002374}
2375
Mike Stump11289f42009-09-09 15:08:12 +00002376SourceLocation BlockExpr::getCaretLocation() const {
2377 return TheBlock->getCaretLocation();
Steve Naroff415d3d52008-10-08 17:01:13 +00002378}
Mike Stump11289f42009-09-09 15:08:12 +00002379const Stmt *BlockExpr::getBody() const {
Douglas Gregore3dcb2d2009-04-18 00:02:19 +00002380 return TheBlock->getBody();
2381}
Mike Stump11289f42009-09-09 15:08:12 +00002382Stmt *BlockExpr::getBody() {
2383 return TheBlock->getBody();
Douglas Gregore3dcb2d2009-04-18 00:02:19 +00002384}
Steve Naroff415d3d52008-10-08 17:01:13 +00002385
Eugene Zelenkoae304b02017-11-17 18:09:48 +00002386
Chris Lattner1ec5f562007-06-27 05:38:08 +00002387//===----------------------------------------------------------------------===//
2388// Generic Expression Routines
2389//===----------------------------------------------------------------------===//
2390
Chris Lattner237f2752009-02-14 07:37:35 +00002391/// isUnusedResultAWarning - Return true if this immediate expression should
2392/// be warned about if the result is unused. If so, fill in Loc and Ranges
2393/// with location to warn on and the source range[s] to report with the
2394/// warning.
Fangrui Song6907ce22018-07-30 19:24:48 +00002395bool Expr::isUnusedResultAWarning(const Expr *&WarnE, SourceLocation &Loc,
Eli Friedmanc11535c2012-05-24 00:47:05 +00002396 SourceRange &R1, SourceRange &R2,
2397 ASTContext &Ctx) const {
Anders Carlsson789e2cc2009-05-15 23:10:19 +00002398 // Don't warn if the expr is type dependent. The type could end up
2399 // instantiating to void.
2400 if (isTypeDependent())
2401 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002402
Chris Lattner1ec5f562007-06-27 05:38:08 +00002403 switch (getStmtClass()) {
2404 default:
John McCallc493a732010-03-12 07:11:26 +00002405 if (getType()->isVoidType())
2406 return false;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002407 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002408 Loc = getExprLoc();
2409 R1 = getSourceRange();
2410 return true;
Chris Lattner1ec5f562007-06-27 05:38:08 +00002411 case ParenExprClass:
Chris Lattner237f2752009-02-14 07:37:35 +00002412 return cast<ParenExpr>(this)->getSubExpr()->
Eli Friedmanc11535c2012-05-24 00:47:05 +00002413 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00002414 case GenericSelectionExprClass:
2415 return cast<GenericSelectionExpr>(this)->getResultExpr()->
Eli Friedmanc11535c2012-05-24 00:47:05 +00002416 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Eric Fiselier16269a82018-03-27 00:58:16 +00002417 case CoawaitExprClass:
Eric Fiselier855c0922018-03-27 03:33:06 +00002418 case CoyieldExprClass:
2419 return cast<CoroutineSuspendExpr>(this)->getResumeExpr()->
Eric Fiselier16269a82018-03-27 00:58:16 +00002420 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Eli Friedman75807f22013-07-20 00:40:58 +00002421 case ChooseExprClass:
2422 return cast<ChooseExpr>(this)->getChosenSubExpr()->
2423 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Chris Lattner1ec5f562007-06-27 05:38:08 +00002424 case UnaryOperatorClass: {
2425 const UnaryOperator *UO = cast<UnaryOperator>(this);
Mike Stump11289f42009-09-09 15:08:12 +00002426
Chris Lattner1ec5f562007-06-27 05:38:08 +00002427 switch (UO->getOpcode()) {
Eli Friedmanc11535c2012-05-24 00:47:05 +00002428 case UO_Plus:
2429 case UO_Minus:
2430 case UO_AddrOf:
2431 case UO_Not:
2432 case UO_LNot:
2433 case UO_Deref:
2434 break;
Richard Smith9f690bd2015-10-27 06:02:45 +00002435 case UO_Coawait:
2436 // This is just the 'operator co_await' call inside the guts of a
2437 // dependent co_await call.
John McCalle3027922010-08-25 11:45:40 +00002438 case UO_PostInc:
2439 case UO_PostDec:
2440 case UO_PreInc:
2441 case UO_PreDec: // ++/--
Chris Lattner237f2752009-02-14 07:37:35 +00002442 return false; // Not a warning.
John McCalle3027922010-08-25 11:45:40 +00002443 case UO_Real:
2444 case UO_Imag:
Chris Lattnera44d1162007-06-27 05:58:59 +00002445 // accessing a piece of a volatile complex is a side-effect.
Mike Stump53f9ded2009-11-03 23:25:48 +00002446 if (Ctx.getCanonicalType(UO->getSubExpr()->getType())
2447 .isVolatileQualified())
Chris Lattner237f2752009-02-14 07:37:35 +00002448 return false;
2449 break;
John McCalle3027922010-08-25 11:45:40 +00002450 case UO_Extension:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002451 return UO->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Chris Lattner1ec5f562007-06-27 05:38:08 +00002452 }
Eli Friedmanc11535c2012-05-24 00:47:05 +00002453 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002454 Loc = UO->getOperatorLoc();
2455 R1 = UO->getSubExpr()->getSourceRange();
2456 return true;
Chris Lattner1ec5f562007-06-27 05:38:08 +00002457 }
Chris Lattnerae7a8342007-12-01 06:07:34 +00002458 case BinaryOperatorClass: {
Chris Lattner237f2752009-02-14 07:37:35 +00002459 const BinaryOperator *BO = cast<BinaryOperator>(this);
Ted Kremenek43a9c962010-04-07 18:49:21 +00002460 switch (BO->getOpcode()) {
2461 default:
2462 break;
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00002463 // Consider the RHS of comma for side effects. LHS was checked by
2464 // Sema::CheckCommaOperands.
John McCalle3027922010-08-25 11:45:40 +00002465 case BO_Comma:
Ted Kremenek43a9c962010-04-07 18:49:21 +00002466 // ((foo = <blah>), 0) is an idiom for hiding the result (and
2467 // lvalue-ness) of an assignment written in a macro.
2468 if (IntegerLiteral *IE =
2469 dyn_cast<IntegerLiteral>(BO->getRHS()->IgnoreParens()))
2470 if (IE->getValue() == 0)
2471 return false;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002472 return BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00002473 // Consider '||', '&&' to have side effects if the LHS or RHS does.
John McCalle3027922010-08-25 11:45:40 +00002474 case BO_LAnd:
2475 case BO_LOr:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002476 if (!BO->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx) ||
2477 !BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx))
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00002478 return false;
2479 break;
John McCall1e3715a2010-02-16 04:10:53 +00002480 }
Chris Lattner237f2752009-02-14 07:37:35 +00002481 if (BO->isAssignmentOp())
2482 return false;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002483 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002484 Loc = BO->getOperatorLoc();
2485 R1 = BO->getLHS()->getSourceRange();
2486 R2 = BO->getRHS()->getSourceRange();
2487 return true;
Chris Lattnerae7a8342007-12-01 06:07:34 +00002488 }
Chris Lattner86928112007-08-25 02:00:02 +00002489 case CompoundAssignOperatorClass:
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00002490 case VAArgExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002491 case AtomicExprClass:
Chris Lattner237f2752009-02-14 07:37:35 +00002492 return false;
Chris Lattner1ec5f562007-06-27 05:38:08 +00002493
Fariborz Jahanian9fac54d2007-12-01 19:58:28 +00002494 case ConditionalOperatorClass: {
Ted Kremeneke96dad92011-03-01 20:34:48 +00002495 // If only one of the LHS or RHS is a warning, the operator might
2496 // be being used for control flow. Only warn if both the LHS and
2497 // RHS are warnings.
Nathan Huckleberry321f9022019-06-19 18:37:01 +00002498 const auto *Exp = cast<ConditionalOperator>(this);
2499 return Exp->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx) &&
2500 Exp->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2501 }
2502 case BinaryConditionalOperatorClass: {
2503 const auto *Exp = cast<BinaryConditionalOperator>(this);
2504 return Exp->getFalseExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Fariborz Jahanian9fac54d2007-12-01 19:58:28 +00002505 }
2506
Chris Lattnera44d1162007-06-27 05:58:59 +00002507 case MemberExprClass:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002508 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002509 Loc = cast<MemberExpr>(this)->getMemberLoc();
2510 R1 = SourceRange(Loc, Loc);
2511 R2 = cast<MemberExpr>(this)->getBase()->getSourceRange();
2512 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002513
Chris Lattner1ec5f562007-06-27 05:38:08 +00002514 case ArraySubscriptExprClass:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002515 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002516 Loc = cast<ArraySubscriptExpr>(this)->getRBracketLoc();
2517 R1 = cast<ArraySubscriptExpr>(this)->getLHS()->getSourceRange();
2518 R2 = cast<ArraySubscriptExpr>(this)->getRHS()->getSourceRange();
2519 return true;
Eli Friedman824f8c12008-05-27 15:24:04 +00002520
Chandler Carruth46339472011-08-17 09:49:44 +00002521 case CXXOperatorCallExprClass: {
Richard Trieu99e1c952014-03-11 03:11:08 +00002522 // Warn about operator ==,!=,<,>,<=, and >= even when user-defined operator
Chandler Carruth46339472011-08-17 09:49:44 +00002523 // overloads as there is no reasonable way to define these such that they
2524 // have non-trivial, desirable side-effects. See the -Wunused-comparison
Richard Trieu99e1c952014-03-11 03:11:08 +00002525 // warning: operators == and != are commonly typo'ed, and so warning on them
Chandler Carruth46339472011-08-17 09:49:44 +00002526 // provides additional value as well. If this list is updated,
2527 // DiagnoseUnusedComparison should be as well.
2528 const CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(this);
Richard Trieu99e1c952014-03-11 03:11:08 +00002529 switch (Op->getOperator()) {
2530 default:
2531 break;
2532 case OO_EqualEqual:
2533 case OO_ExclaimEqual:
2534 case OO_Less:
2535 case OO_Greater:
2536 case OO_GreaterEqual:
2537 case OO_LessEqual:
David Majnemerced8bdf2015-02-25 17:36:15 +00002538 if (Op->getCallReturnType(Ctx)->isReferenceType() ||
2539 Op->getCallReturnType(Ctx)->isVoidType())
Richard Trieu161132b2014-05-14 23:22:10 +00002540 break;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002541 WarnE = this;
Matt Beaumont-Gaydcaacaa2011-09-19 18:51:20 +00002542 Loc = Op->getOperatorLoc();
2543 R1 = Op->getSourceRange();
Chandler Carruth46339472011-08-17 09:49:44 +00002544 return true;
Matt Beaumont-Gaydcaacaa2011-09-19 18:51:20 +00002545 }
Chandler Carruth46339472011-08-17 09:49:44 +00002546
2547 // Fallthrough for generic call handling.
Galina Kistanovaf87496d2017-06-03 06:31:42 +00002548 LLVM_FALLTHROUGH;
Chandler Carruth46339472011-08-17 09:49:44 +00002549 }
Chris Lattner1ec5f562007-06-27 05:38:08 +00002550 case CallExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00002551 case CXXMemberCallExprClass:
2552 case UserDefinedLiteralClass: {
Chris Lattner237f2752009-02-14 07:37:35 +00002553 // If this is a direct call, get the callee.
2554 const CallExpr *CE = cast<CallExpr>(this);
Nuno Lopes518e3702009-12-20 23:11:08 +00002555 if (const Decl *FD = CE->getCalleeDecl()) {
Chris Lattner237f2752009-02-14 07:37:35 +00002556 // If the callee has attribute pure, const, or warn_unused_result, warn
2557 // about it. void foo() { strlen("bar"); } should warn.
Chris Lattner1a6babf2009-10-13 04:53:48 +00002558 //
2559 // Note: If new cases are added here, DiagnoseUnusedExprResult should be
2560 // updated to match for QoI.
Aaron Ballmand23e9bc2019-01-03 14:24:31 +00002561 if (CE->hasUnusedResultAttr(Ctx) ||
Aaron Ballman9ead1242013-12-19 02:39:40 +00002562 FD->hasAttr<PureAttr>() || FD->hasAttr<ConstAttr>()) {
Eli Friedmanc11535c2012-05-24 00:47:05 +00002563 WarnE = this;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002564 Loc = CE->getCallee()->getBeginLoc();
Chris Lattner1a6babf2009-10-13 04:53:48 +00002565 R1 = CE->getCallee()->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002566
Chris Lattner1a6babf2009-10-13 04:53:48 +00002567 if (unsigned NumArgs = CE->getNumArgs())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002568 R2 = SourceRange(CE->getArg(0)->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002569 CE->getArg(NumArgs - 1)->getEndLoc());
Chris Lattner1a6babf2009-10-13 04:53:48 +00002570 return true;
2571 }
Chris Lattner237f2752009-02-14 07:37:35 +00002572 }
2573 return false;
2574 }
Anders Carlsson6aa50392009-11-17 17:11:23 +00002575
Matt Beaumont-Gayabf836c2012-10-23 06:15:26 +00002576 // If we don't know precisely what we're looking at, let's not warn.
2577 case UnresolvedLookupExprClass:
2578 case CXXUnresolvedConstructExprClass:
2579 return false;
2580
Anders Carlsson6aa50392009-11-17 17:11:23 +00002581 case CXXTemporaryObjectExprClass:
Eugene Zelenkoae304b02017-11-17 18:09:48 +00002582 case CXXConstructExprClass: {
Lubos Lunak1f490f32013-07-21 13:15:58 +00002583 if (const CXXRecordDecl *Type = getType()->getAsCXXRecordDecl()) {
Erich Keane46441fd2019-07-25 15:10:56 +00002584 const auto *WarnURAttr = Type->getAttr<WarnUnusedResultAttr>();
2585 if (Type->hasAttr<WarnUnusedAttr>() ||
2586 (WarnURAttr && WarnURAttr->IsCXX11NoDiscard())) {
Lubos Lunak1f490f32013-07-21 13:15:58 +00002587 WarnE = this;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002588 Loc = getBeginLoc();
Lubos Lunak1f490f32013-07-21 13:15:58 +00002589 R1 = getSourceRange();
2590 return true;
2591 }
2592 }
Erich Keane46441fd2019-07-25 15:10:56 +00002593
2594 const auto *CE = cast<CXXConstructExpr>(this);
2595 if (const CXXConstructorDecl *Ctor = CE->getConstructor()) {
2596 const auto *WarnURAttr = Ctor->getAttr<WarnUnusedResultAttr>();
2597 if (WarnURAttr && WarnURAttr->IsCXX11NoDiscard()) {
2598 WarnE = this;
2599 Loc = getBeginLoc();
2600 R1 = getSourceRange();
2601
2602 if (unsigned NumArgs = CE->getNumArgs())
2603 R2 = SourceRange(CE->getArg(0)->getBeginLoc(),
2604 CE->getArg(NumArgs - 1)->getEndLoc());
2605 return true;
2606 }
2607 }
2608
Anders Carlsson6aa50392009-11-17 17:11:23 +00002609 return false;
Eugene Zelenkoae304b02017-11-17 18:09:48 +00002610 }
Anders Carlsson6aa50392009-11-17 17:11:23 +00002611
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +00002612 case ObjCMessageExprClass: {
2613 const ObjCMessageExpr *ME = cast<ObjCMessageExpr>(this);
David Blaikiebbafb8a2012-03-11 07:00:24 +00002614 if (Ctx.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00002615 ME->isInstanceMessage() &&
2616 !ME->getType()->isVoidType() &&
Jean-Daniel Dupas06028a52013-07-19 20:25:56 +00002617 ME->getMethodFamily() == OMF_init) {
Eli Friedmanc11535c2012-05-24 00:47:05 +00002618 WarnE = this;
John McCall31168b02011-06-15 23:02:42 +00002619 Loc = getExprLoc();
2620 R1 = ME->getSourceRange();
2621 return true;
2622 }
2623
Fariborz Jahanianac6b4ef2014-07-18 22:59:10 +00002624 if (const ObjCMethodDecl *MD = ME->getMethodDecl())
Fariborz Jahanianb0553e22015-02-16 23:49:44 +00002625 if (MD->hasAttr<WarnUnusedResultAttr>()) {
Fariborz Jahanianac6b4ef2014-07-18 22:59:10 +00002626 WarnE = this;
2627 Loc = getExprLoc();
2628 return true;
2629 }
2630
Chris Lattner237f2752009-02-14 07:37:35 +00002631 return false;
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +00002632 }
Mike Stump11289f42009-09-09 15:08:12 +00002633
John McCallb7bd14f2010-12-02 01:19:52 +00002634 case ObjCPropertyRefExprClass:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002635 WarnE = this;
Chris Lattnerd37f61c2009-08-16 16:51:50 +00002636 Loc = getExprLoc();
2637 R1 = getSourceRange();
Chris Lattnerd8b800a2009-08-16 16:45:18 +00002638 return true;
John McCallb7bd14f2010-12-02 01:19:52 +00002639
John McCallfe96e0b2011-11-06 09:01:30 +00002640 case PseudoObjectExprClass: {
2641 const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this);
2642
2643 // Only complain about things that have the form of a getter.
2644 if (isa<UnaryOperator>(PO->getSyntacticForm()) ||
2645 isa<BinaryOperator>(PO->getSyntacticForm()))
2646 return false;
2647
Eli Friedmanc11535c2012-05-24 00:47:05 +00002648 WarnE = this;
John McCallfe96e0b2011-11-06 09:01:30 +00002649 Loc = getExprLoc();
2650 R1 = getSourceRange();
2651 return true;
2652 }
2653
Chris Lattner944d3062008-07-26 19:51:01 +00002654 case StmtExprClass: {
2655 // Statement exprs don't logically have side effects themselves, but are
2656 // sometimes used in macros in ways that give them a type that is unused.
2657 // For example ({ blah; foo(); }) will end up with a type if foo has a type.
2658 // however, if the result of the stmt expr is dead, we don't want to emit a
2659 // warning.
2660 const CompoundStmt *CS = cast<StmtExpr>(this)->getSubStmt();
Argyrios Kyrtzidis90963412010-09-19 21:21:10 +00002661 if (!CS->body_empty()) {
Chris Lattner944d3062008-07-26 19:51:01 +00002662 if (const Expr *E = dyn_cast<Expr>(CS->body_back()))
Eli Friedmanc11535c2012-05-24 00:47:05 +00002663 return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Argyrios Kyrtzidis90963412010-09-19 21:21:10 +00002664 if (const LabelStmt *Label = dyn_cast<LabelStmt>(CS->body_back()))
2665 if (const Expr *E = dyn_cast<Expr>(Label->getSubStmt()))
Eli Friedmanc11535c2012-05-24 00:47:05 +00002666 return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Argyrios Kyrtzidis90963412010-09-19 21:21:10 +00002667 }
Mike Stump11289f42009-09-09 15:08:12 +00002668
John McCallc493a732010-03-12 07:11:26 +00002669 if (getType()->isVoidType())
2670 return false;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002671 WarnE = this;
Chris Lattner237f2752009-02-14 07:37:35 +00002672 Loc = cast<StmtExpr>(this)->getLParenLoc();
2673 R1 = getSourceRange();
2674 return true;
Chris Lattner944d3062008-07-26 19:51:01 +00002675 }
Eli Friedmanbdd57532012-09-24 23:02:26 +00002676 case CXXFunctionalCastExprClass:
Eli Friedmanc11535c2012-05-24 00:47:05 +00002677 case CStyleCastExprClass: {
Eli Friedmanf92f6452012-05-24 21:05:41 +00002678 // Ignore an explicit cast to void unless the operand is a non-trivial
Eli Friedmanc11535c2012-05-24 00:47:05 +00002679 // volatile lvalue.
Eli Friedmanf92f6452012-05-24 21:05:41 +00002680 const CastExpr *CE = cast<CastExpr>(this);
Eli Friedmanc11535c2012-05-24 00:47:05 +00002681 if (CE->getCastKind() == CK_ToVoid) {
2682 if (CE->getSubExpr()->isGLValue() &&
Eli Friedmanf92f6452012-05-24 21:05:41 +00002683 CE->getSubExpr()->getType().isVolatileQualified()) {
2684 const DeclRefExpr *DRE =
2685 dyn_cast<DeclRefExpr>(CE->getSubExpr()->IgnoreParens());
2686 if (!(DRE && isa<VarDecl>(DRE->getDecl()) &&
Erich Keane80b0fb02017-10-19 15:58:58 +00002687 cast<VarDecl>(DRE->getDecl())->hasLocalStorage()) &&
2688 !isa<CallExpr>(CE->getSubExpr()->IgnoreParens())) {
Eli Friedmanf92f6452012-05-24 21:05:41 +00002689 return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc,
2690 R1, R2, Ctx);
2691 }
2692 }
Chris Lattner2706a552009-07-28 18:25:28 +00002693 return false;
Eli Friedmanc11535c2012-05-24 00:47:05 +00002694 }
Eli Friedmanf92f6452012-05-24 21:05:41 +00002695
Eli Friedmanc11535c2012-05-24 00:47:05 +00002696 // If this is a cast to a constructor conversion, check the operand.
Anders Carlsson6aa50392009-11-17 17:11:23 +00002697 // Otherwise, the result of the cast is unused.
Eli Friedmanc11535c2012-05-24 00:47:05 +00002698 if (CE->getCastKind() == CK_ConstructorConversion)
2699 return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Eli Friedmanf92f6452012-05-24 21:05:41 +00002700
Eli Friedmanc11535c2012-05-24 00:47:05 +00002701 WarnE = this;
Eli Friedmanf92f6452012-05-24 21:05:41 +00002702 if (const CXXFunctionalCastExpr *CXXCE =
2703 dyn_cast<CXXFunctionalCastExpr>(this)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002704 Loc = CXXCE->getBeginLoc();
Eli Friedmanf92f6452012-05-24 21:05:41 +00002705 R1 = CXXCE->getSubExpr()->getSourceRange();
2706 } else {
2707 const CStyleCastExpr *CStyleCE = cast<CStyleCastExpr>(this);
2708 Loc = CStyleCE->getLParenLoc();
2709 R1 = CStyleCE->getSubExpr()->getSourceRange();
2710 }
Chris Lattner237f2752009-02-14 07:37:35 +00002711 return true;
Anders Carlsson6aa50392009-11-17 17:11:23 +00002712 }
Eli Friedmanc11535c2012-05-24 00:47:05 +00002713 case ImplicitCastExprClass: {
2714 const CastExpr *ICE = cast<ImplicitCastExpr>(this);
Eli Friedmanca8da1d2008-05-19 21:24:43 +00002715
Eli Friedmanc11535c2012-05-24 00:47:05 +00002716 // lvalue-to-rvalue conversion on a volatile lvalue is a side-effect.
2717 if (ICE->getCastKind() == CK_LValueToRValue &&
2718 ICE->getSubExpr()->getType().isVolatileQualified())
2719 return false;
2720
2721 return ICE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2722 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002723 case CXXDefaultArgExprClass:
Mike Stump53f9ded2009-11-03 23:25:48 +00002724 return (cast<CXXDefaultArgExpr>(this)
Eli Friedmanc11535c2012-05-24 00:47:05 +00002725 ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
Richard Smith852c9db2013-04-20 22:23:05 +00002726 case CXXDefaultInitExprClass:
2727 return (cast<CXXDefaultInitExpr>(this)
2728 ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
Sebastian Redlbd150f42008-11-21 19:14:01 +00002729
2730 case CXXNewExprClass:
2731 // FIXME: In theory, there might be new expressions that don't have side
2732 // effects (e.g. a placement new with an uninitialized POD).
2733 case CXXDeleteExprClass:
Chris Lattner237f2752009-02-14 07:37:35 +00002734 return false;
Richard Smith122f88d2016-12-06 23:52:28 +00002735 case MaterializeTemporaryExprClass:
Tykerb0561b32019-11-17 11:41:55 +01002736 return cast<MaterializeTemporaryExpr>(this)
2737 ->getSubExpr()
2738 ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Anders Carlssone80ccac2009-08-16 04:11:06 +00002739 case CXXBindTemporaryExprClass:
Richard Smith122f88d2016-12-06 23:52:28 +00002740 return cast<CXXBindTemporaryExpr>(this)->getSubExpr()
2741 ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
John McCall5d413782010-12-06 08:20:24 +00002742 case ExprWithCleanupsClass:
Richard Smith122f88d2016-12-06 23:52:28 +00002743 return cast<ExprWithCleanups>(this)->getSubExpr()
2744 ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
Sebastian Redlbd150f42008-11-21 19:14:01 +00002745 }
Chris Lattner1ec5f562007-06-27 05:38:08 +00002746}
2747
Fariborz Jahanian07735332009-02-22 18:40:18 +00002748/// isOBJCGCCandidate - Check if an expression is objc gc'able.
Fariborz Jahanian063c7722009-09-08 23:38:54 +00002749/// returns true, if it is; false otherwise.
Fariborz Jahanianc6d98002009-06-01 21:29:32 +00002750bool Expr::isOBJCGCCandidate(ASTContext &Ctx) const {
Peter Collingbourne91147592011-04-15 00:35:48 +00002751 const Expr *E = IgnoreParens();
2752 switch (E->getStmtClass()) {
Fariborz Jahanian07735332009-02-22 18:40:18 +00002753 default:
2754 return false;
2755 case ObjCIvarRefExprClass:
2756 return true;
Fariborz Jahanian392124c2009-02-23 18:59:50 +00002757 case Expr::UnaryOperatorClass:
Peter Collingbourne91147592011-04-15 00:35:48 +00002758 return cast<UnaryOperator>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
Fariborz Jahanian07735332009-02-22 18:40:18 +00002759 case ImplicitCastExprClass:
Peter Collingbourne91147592011-04-15 00:35:48 +00002760 return cast<ImplicitCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
Douglas Gregorfe314812011-06-21 17:03:29 +00002761 case MaterializeTemporaryExprClass:
Tykerb0561b32019-11-17 11:41:55 +01002762 return cast<MaterializeTemporaryExpr>(E)->getSubExpr()->isOBJCGCCandidate(
2763 Ctx);
Fariborz Jahaniana16904b2009-05-05 23:28:21 +00002764 case CStyleCastExprClass:
Peter Collingbourne91147592011-04-15 00:35:48 +00002765 return cast<CStyleCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002766 case DeclRefExprClass: {
John McCall113bee02012-03-10 09:33:50 +00002767 const Decl *D = cast<DeclRefExpr>(E)->getDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +00002768
Fariborz Jahanianc6d98002009-06-01 21:29:32 +00002769 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2770 if (VD->hasGlobalStorage())
2771 return true;
2772 QualType T = VD->getType();
Fariborz Jahaniancceedbf2009-09-16 18:09:18 +00002773 // dereferencing to a pointer is always a gc'able candidate,
2774 // unless it is __weak.
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00002775 return T->isPointerType() &&
John McCall8ccfcb52009-09-24 19:53:00 +00002776 (Ctx.getObjCGCAttrKind(T) != Qualifiers::Weak);
Fariborz Jahanianc6d98002009-06-01 21:29:32 +00002777 }
Fariborz Jahanian07735332009-02-22 18:40:18 +00002778 return false;
2779 }
Douglas Gregorf405d7e2009-08-31 23:41:50 +00002780 case MemberExprClass: {
Peter Collingbourne91147592011-04-15 00:35:48 +00002781 const MemberExpr *M = cast<MemberExpr>(E);
Fariborz Jahanianc6d98002009-06-01 21:29:32 +00002782 return M->getBase()->isOBJCGCCandidate(Ctx);
Fariborz Jahanian07735332009-02-22 18:40:18 +00002783 }
2784 case ArraySubscriptExprClass:
Peter Collingbourne91147592011-04-15 00:35:48 +00002785 return cast<ArraySubscriptExpr>(E)->getBase()->isOBJCGCCandidate(Ctx);
Fariborz Jahanian07735332009-02-22 18:40:18 +00002786 }
2787}
Sebastian Redlce354af2010-09-10 20:55:33 +00002788
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +00002789bool Expr::isBoundMemberFunction(ASTContext &Ctx) const {
2790 if (isTypeDependent())
2791 return false;
John McCall086a4642010-11-24 05:12:34 +00002792 return ClassifyLValue(Ctx) == Expr::LV_MemberFunction;
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +00002793}
2794
John McCall0009fcc2011-04-26 20:42:42 +00002795QualType Expr::findBoundMemberType(const Expr *expr) {
John McCalle314e272011-10-18 21:02:43 +00002796 assert(expr->hasPlaceholderType(BuiltinType::BoundMember));
John McCall0009fcc2011-04-26 20:42:42 +00002797
2798 // Bound member expressions are always one of these possibilities:
2799 // x->m x.m x->*y x.*y
2800 // (possibly parenthesized)
2801
2802 expr = expr->IgnoreParens();
2803 if (const MemberExpr *mem = dyn_cast<MemberExpr>(expr)) {
2804 assert(isa<CXXMethodDecl>(mem->getMemberDecl()));
2805 return mem->getMemberDecl()->getType();
2806 }
2807
2808 if (const BinaryOperator *op = dyn_cast<BinaryOperator>(expr)) {
2809 QualType type = op->getRHS()->getType()->castAs<MemberPointerType>()
2810 ->getPointeeType();
2811 assert(type->isFunctionType());
2812 return type;
2813 }
2814
David Majnemerced8bdf2015-02-25 17:36:15 +00002815 assert(isa<UnresolvedMemberExpr>(expr) || isa<CXXPseudoDestructorExpr>(expr));
John McCall0009fcc2011-04-26 20:42:42 +00002816 return QualType();
2817}
2818
Bruno Ricci46148f22019-02-17 18:50:51 +00002819static Expr *IgnoreImpCastsSingleStep(Expr *E) {
2820 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
2821 return ICE->getSubExpr();
2822
2823 if (auto *FE = dyn_cast<FullExpr>(E))
2824 return FE->getSubExpr();
2825
Bruno Riccid4038002019-02-17 13:47:29 +00002826 return E;
Ted Kremenek6f375e52014-04-16 07:26:09 +00002827}
2828
Bruno Ricci46148f22019-02-17 18:50:51 +00002829static Expr *IgnoreImpCastsExtraSingleStep(Expr *E) {
2830 // FIXME: Skip MaterializeTemporaryExpr and SubstNonTypeTemplateParmExpr in
2831 // addition to what IgnoreImpCasts() skips to account for the current
2832 // behaviour of IgnoreParenImpCasts().
2833 Expr *SubE = IgnoreImpCastsSingleStep(E);
2834 if (SubE != E)
2835 return SubE;
2836
2837 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
Tykerb0561b32019-11-17 11:41:55 +01002838 return MTE->getSubExpr();
Bruno Ricci46148f22019-02-17 18:50:51 +00002839
2840 if (auto *NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E))
2841 return NTTP->getReplacement();
2842
2843 return E;
2844}
2845
2846static Expr *IgnoreCastsSingleStep(Expr *E) {
2847 if (auto *CE = dyn_cast<CastExpr>(E))
2848 return CE->getSubExpr();
2849
2850 if (auto *FE = dyn_cast<FullExpr>(E))
2851 return FE->getSubExpr();
2852
2853 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
Tykerb0561b32019-11-17 11:41:55 +01002854 return MTE->getSubExpr();
Bruno Ricci46148f22019-02-17 18:50:51 +00002855
2856 if (auto *NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E))
2857 return NTTP->getReplacement();
2858
2859 return E;
2860}
2861
2862static Expr *IgnoreLValueCastsSingleStep(Expr *E) {
2863 // Skip what IgnoreCastsSingleStep skips, except that only
2864 // lvalue-to-rvalue casts are skipped.
2865 if (auto *CE = dyn_cast<CastExpr>(E))
2866 if (CE->getCastKind() != CK_LValueToRValue)
2867 return E;
2868
2869 return IgnoreCastsSingleStep(E);
2870}
2871
2872static Expr *IgnoreBaseCastsSingleStep(Expr *E) {
2873 if (auto *CE = dyn_cast<CastExpr>(E))
2874 if (CE->getCastKind() == CK_DerivedToBase ||
2875 CE->getCastKind() == CK_UncheckedDerivedToBase ||
2876 CE->getCastKind() == CK_NoOp)
2877 return CE->getSubExpr();
2878
2879 return E;
2880}
2881
2882static Expr *IgnoreImplicitSingleStep(Expr *E) {
2883 Expr *SubE = IgnoreImpCastsSingleStep(E);
2884 if (SubE != E)
2885 return SubE;
2886
2887 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
Tykerb0561b32019-11-17 11:41:55 +01002888 return MTE->getSubExpr();
Bruno Ricci46148f22019-02-17 18:50:51 +00002889
2890 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(E))
2891 return BTE->getSubExpr();
2892
2893 return E;
2894}
2895
Richard Smith75990952019-12-05 18:04:46 -08002896static Expr *IgnoreImplicitAsWrittenSingleStep(Expr *E) {
2897 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
2898 return ICE->getSubExprAsWritten();
2899
2900 return IgnoreImplicitSingleStep(E);
2901}
2902
Bruno Ricci46148f22019-02-17 18:50:51 +00002903static Expr *IgnoreParensSingleStep(Expr *E) {
2904 if (auto *PE = dyn_cast<ParenExpr>(E))
2905 return PE->getSubExpr();
2906
2907 if (auto *UO = dyn_cast<UnaryOperator>(E)) {
2908 if (UO->getOpcode() == UO_Extension)
2909 return UO->getSubExpr();
2910 }
2911
2912 else if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
2913 if (!GSE->isResultDependent())
2914 return GSE->getResultExpr();
2915 }
2916
2917 else if (auto *CE = dyn_cast<ChooseExpr>(E)) {
2918 if (!CE->isConditionDependent())
2919 return CE->getChosenSubExpr();
2920 }
2921
2922 else if (auto *CE = dyn_cast<ConstantExpr>(E))
2923 return CE->getSubExpr();
2924
2925 return E;
2926}
2927
2928static Expr *IgnoreNoopCastsSingleStep(const ASTContext &Ctx, Expr *E) {
2929 if (auto *CE = dyn_cast<CastExpr>(E)) {
2930 // We ignore integer <-> casts that are of the same width, ptr<->ptr and
2931 // ptr<->int casts of the same width. We also ignore all identity casts.
2932 Expr *SubExpr = CE->getSubExpr();
2933 bool IsIdentityCast =
2934 Ctx.hasSameUnqualifiedType(E->getType(), SubExpr->getType());
2935 bool IsSameWidthCast =
2936 (E->getType()->isPointerType() || E->getType()->isIntegralType(Ctx)) &&
2937 (SubExpr->getType()->isPointerType() ||
2938 SubExpr->getType()->isIntegralType(Ctx)) &&
2939 (Ctx.getTypeSize(E->getType()) == Ctx.getTypeSize(SubExpr->getType()));
2940
2941 if (IsIdentityCast || IsSameWidthCast)
2942 return SubExpr;
2943 }
2944
2945 else if (auto *NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E))
2946 return NTTP->getReplacement();
2947
2948 return E;
2949}
2950
2951static Expr *IgnoreExprNodesImpl(Expr *E) { return E; }
2952template <typename FnTy, typename... FnTys>
2953static Expr *IgnoreExprNodesImpl(Expr *E, FnTy &&Fn, FnTys &&... Fns) {
2954 return IgnoreExprNodesImpl(Fn(E), std::forward<FnTys>(Fns)...);
2955}
2956
2957/// Given an expression E and functions Fn_1,...,Fn_n : Expr * -> Expr *,
2958/// Recursively apply each of the functions to E until reaching a fixed point.
2959/// Note that a null E is valid; in this case nothing is done.
2960template <typename... FnTys>
2961static Expr *IgnoreExprNodes(Expr *E, FnTys &&... Fns) {
Bruno Riccid4038002019-02-17 13:47:29 +00002962 Expr *LastE = nullptr;
2963 while (E != LastE) {
2964 LastE = E;
Bruno Ricci46148f22019-02-17 18:50:51 +00002965 E = IgnoreExprNodesImpl(E, std::forward<FnTys>(Fns)...);
Bruno Riccid4038002019-02-17 13:47:29 +00002966 }
2967 return E;
John McCall34376a62010-12-04 03:47:34 +00002968}
Rafael Espindolaecbe2e92012-06-28 01:56:38 +00002969
Bruno Ricci46148f22019-02-17 18:50:51 +00002970Expr *Expr::IgnoreImpCasts() {
2971 return IgnoreExprNodes(this, IgnoreImpCastsSingleStep);
Bruno Riccid4038002019-02-17 13:47:29 +00002972}
2973
2974Expr *Expr::IgnoreCasts() {
Bruno Ricci46148f22019-02-17 18:50:51 +00002975 return IgnoreExprNodes(this, IgnoreCastsSingleStep);
Bruno Riccid4038002019-02-17 13:47:29 +00002976}
2977
Bruno Ricci46148f22019-02-17 18:50:51 +00002978Expr *Expr::IgnoreImplicit() {
2979 return IgnoreExprNodes(this, IgnoreImplicitSingleStep);
Bruno Riccid4038002019-02-17 13:47:29 +00002980}
2981
Richard Smith75990952019-12-05 18:04:46 -08002982Expr *Expr::IgnoreImplicitAsWritten() {
2983 return IgnoreExprNodes(this, IgnoreImplicitAsWrittenSingleStep);
2984}
2985
Bruno Ricci46148f22019-02-17 18:50:51 +00002986Expr *Expr::IgnoreParens() {
2987 return IgnoreExprNodes(this, IgnoreParensSingleStep);
Rafael Espindolaecbe2e92012-06-28 01:56:38 +00002988}
2989
John McCalleebc8322010-05-05 22:59:52 +00002990Expr *Expr::IgnoreParenImpCasts() {
Bruno Ricci46148f22019-02-17 18:50:51 +00002991 return IgnoreExprNodes(this, IgnoreParensSingleStep,
2992 IgnoreImpCastsExtraSingleStep);
2993}
2994
2995Expr *Expr::IgnoreParenCasts() {
2996 return IgnoreExprNodes(this, IgnoreParensSingleStep, IgnoreCastsSingleStep);
John McCalleebc8322010-05-05 22:59:52 +00002997}
2998
Hans Wennborgde2e67e2011-06-09 17:06:51 +00002999Expr *Expr::IgnoreConversionOperator() {
Bruno Riccie64aee82019-02-03 19:50:56 +00003000 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(this)) {
Chandler Carruth4352b0b2011-06-21 17:22:09 +00003001 if (MCE->getMethodDecl() && isa<CXXConversionDecl>(MCE->getMethodDecl()))
Hans Wennborgde2e67e2011-06-09 17:06:51 +00003002 return MCE->getImplicitObjectArgument();
3003 }
3004 return this;
3005}
3006
Bruno Ricci46148f22019-02-17 18:50:51 +00003007Expr *Expr::IgnoreParenLValueCasts() {
3008 return IgnoreExprNodes(this, IgnoreParensSingleStep,
3009 IgnoreLValueCastsSingleStep);
3010}
3011
3012Expr *Expr::ignoreParenBaseCasts() {
3013 return IgnoreExprNodes(this, IgnoreParensSingleStep,
3014 IgnoreBaseCastsSingleStep);
3015}
3016
Bruno Riccie64aee82019-02-03 19:50:56 +00003017Expr *Expr::IgnoreParenNoopCasts(const ASTContext &Ctx) {
Bruno Ricci46148f22019-02-17 18:50:51 +00003018 return IgnoreExprNodes(this, IgnoreParensSingleStep, [&Ctx](Expr *E) {
3019 return IgnoreNoopCastsSingleStep(Ctx, E);
3020 });
Chris Lattneref26c772009-03-13 17:28:01 +00003021}
3022
Stephen Kelly98e8f772019-05-04 16:51:58 +01003023Expr *Expr::IgnoreUnlessSpelledInSource() {
3024 Expr *E = this;
3025
3026 Expr *LastE = nullptr;
3027 while (E != LastE) {
3028 LastE = E;
3029 E = E->IgnoreImplicit();
3030
3031 auto SR = E->getSourceRange();
3032
3033 if (auto *C = dyn_cast<CXXConstructExpr>(E)) {
3034 if (C->getNumArgs() == 1) {
3035 Expr *A = C->getArg(0);
3036 if (A->getSourceRange() == SR || !isa<CXXTemporaryObjectExpr>(C))
3037 E = A;
3038 }
3039 }
3040
3041 if (auto *C = dyn_cast<CXXMemberCallExpr>(E)) {
3042 Expr *ExprNode = C->getImplicitObjectArgument()->IgnoreParenImpCasts();
3043 if (ExprNode->getSourceRange() == SR)
3044 E = ExprNode;
3045 }
3046 }
3047
3048 return E;
3049}
3050
Douglas Gregord196a582009-12-14 19:27:10 +00003051bool Expr::isDefaultArgument() const {
3052 const Expr *E = this;
Douglas Gregorfe314812011-06-21 17:03:29 +00003053 if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
Tykerb0561b32019-11-17 11:41:55 +01003054 E = M->getSubExpr();
Douglas Gregorfe314812011-06-21 17:03:29 +00003055
Douglas Gregord196a582009-12-14 19:27:10 +00003056 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3057 E = ICE->getSubExprAsWritten();
Fangrui Song6907ce22018-07-30 19:24:48 +00003058
Douglas Gregord196a582009-12-14 19:27:10 +00003059 return isa<CXXDefaultArgExpr>(E);
3060}
Chris Lattneref26c772009-03-13 17:28:01 +00003061
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003062/// Skip over any no-op casts and any temporary-binding
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003063/// expressions.
Anders Carlsson66bbf502010-11-28 16:40:49 +00003064static const Expr *skipTemporaryBindingsNoOpCastsAndParens(const Expr *E) {
Douglas Gregorfe314812011-06-21 17:03:29 +00003065 if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
Tykerb0561b32019-11-17 11:41:55 +01003066 E = M->getSubExpr();
Douglas Gregorfe314812011-06-21 17:03:29 +00003067
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003068 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCalle3027922010-08-25 11:45:40 +00003069 if (ICE->getCastKind() == CK_NoOp)
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003070 E = ICE->getSubExpr();
3071 else
3072 break;
3073 }
3074
3075 while (const CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
3076 E = BE->getSubExpr();
3077
3078 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCalle3027922010-08-25 11:45:40 +00003079 if (ICE->getCastKind() == CK_NoOp)
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003080 E = ICE->getSubExpr();
3081 else
3082 break;
3083 }
Anders Carlsson66bbf502010-11-28 16:40:49 +00003084
3085 return E->IgnoreParens();
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003086}
3087
John McCall7a626f62010-09-15 10:14:12 +00003088/// isTemporaryObject - Determines if this expression produces a
3089/// temporary of the given class type.
3090bool Expr::isTemporaryObject(ASTContext &C, const CXXRecordDecl *TempTy) const {
3091 if (!C.hasSameUnqualifiedType(getType(), C.getTypeDeclType(TempTy)))
3092 return false;
3093
Anders Carlsson66bbf502010-11-28 16:40:49 +00003094 const Expr *E = skipTemporaryBindingsNoOpCastsAndParens(this);
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003095
John McCall02dc8c72010-09-15 20:59:13 +00003096 // Temporaries are by definition pr-values of class type.
Fariborz Jahanian30e8d582010-09-27 17:30:38 +00003097 if (!E->Classify(C).isPRValue()) {
3098 // In this context, property reference is a message call and is pr-value.
John McCallb7bd14f2010-12-02 01:19:52 +00003099 if (!isa<ObjCPropertyRefExpr>(E))
Fariborz Jahanian30e8d582010-09-27 17:30:38 +00003100 return false;
3101 }
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003102
John McCallf4ee1dd2010-09-16 06:57:56 +00003103 // Black-list a few cases which yield pr-values of class type that don't
3104 // refer to temporaries of that type:
3105
3106 // - implicit derived-to-base conversions
John McCall7a626f62010-09-15 10:14:12 +00003107 if (isa<ImplicitCastExpr>(E)) {
3108 switch (cast<ImplicitCastExpr>(E)->getCastKind()) {
3109 case CK_DerivedToBase:
3110 case CK_UncheckedDerivedToBase:
3111 return false;
3112 default:
3113 break;
3114 }
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003115 }
3116
John McCallf4ee1dd2010-09-16 06:57:56 +00003117 // - member expressions (all)
3118 if (isa<MemberExpr>(E))
3119 return false;
3120
Eli Friedman13ffdd82012-06-15 23:51:06 +00003121 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E))
3122 if (BO->isPtrMemOp())
3123 return false;
3124
John McCallc07a0c72011-02-17 10:25:35 +00003125 // - opaque values (all)
3126 if (isa<OpaqueValueExpr>(E))
3127 return false;
3128
John McCall7a626f62010-09-15 10:14:12 +00003129 return true;
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003130}
3131
Douglas Gregor25b7e052011-03-02 21:06:53 +00003132bool Expr::isImplicitCXXThis() const {
3133 const Expr *E = this;
Fangrui Song6907ce22018-07-30 19:24:48 +00003134
Douglas Gregor25b7e052011-03-02 21:06:53 +00003135 // Strip away parentheses and casts we don't care about.
3136 while (true) {
3137 if (const ParenExpr *Paren = dyn_cast<ParenExpr>(E)) {
3138 E = Paren->getSubExpr();
3139 continue;
3140 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003141
Douglas Gregor25b7e052011-03-02 21:06:53 +00003142 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3143 if (ICE->getCastKind() == CK_NoOp ||
3144 ICE->getCastKind() == CK_LValueToRValue ||
Fangrui Song6907ce22018-07-30 19:24:48 +00003145 ICE->getCastKind() == CK_DerivedToBase ||
Douglas Gregor25b7e052011-03-02 21:06:53 +00003146 ICE->getCastKind() == CK_UncheckedDerivedToBase) {
3147 E = ICE->getSubExpr();
3148 continue;
3149 }
3150 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003151
Douglas Gregor25b7e052011-03-02 21:06:53 +00003152 if (const UnaryOperator* UnOp = dyn_cast<UnaryOperator>(E)) {
3153 if (UnOp->getOpcode() == UO_Extension) {
3154 E = UnOp->getSubExpr();
3155 continue;
3156 }
3157 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003158
Douglas Gregorfe314812011-06-21 17:03:29 +00003159 if (const MaterializeTemporaryExpr *M
3160 = dyn_cast<MaterializeTemporaryExpr>(E)) {
Tykerb0561b32019-11-17 11:41:55 +01003161 E = M->getSubExpr();
Douglas Gregorfe314812011-06-21 17:03:29 +00003162 continue;
3163 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003164
Douglas Gregor25b7e052011-03-02 21:06:53 +00003165 break;
3166 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003167
Douglas Gregor25b7e052011-03-02 21:06:53 +00003168 if (const CXXThisExpr *This = dyn_cast<CXXThisExpr>(E))
3169 return This->isImplicit();
Fangrui Song6907ce22018-07-30 19:24:48 +00003170
Douglas Gregor25b7e052011-03-02 21:06:53 +00003171 return false;
3172}
3173
Douglas Gregor4619e432008-12-05 23:32:09 +00003174/// hasAnyTypeDependentArguments - Determines if any of the expressions
3175/// in Exprs is type-dependent.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003176bool Expr::hasAnyTypeDependentArguments(ArrayRef<Expr *> Exprs) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003177 for (unsigned I = 0; I < Exprs.size(); ++I)
Douglas Gregor4619e432008-12-05 23:32:09 +00003178 if (Exprs[I]->isTypeDependent())
3179 return true;
3180
3181 return false;
3182}
3183
Abramo Bagnara847c6602014-05-22 19:20:46 +00003184bool Expr::isConstantInitializer(ASTContext &Ctx, bool IsForRef,
3185 const Expr **Culprit) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +00003186 assert(!isValueDependent() &&
3187 "Expression evaluator can't be called on a dependent expression.");
3188
Eli Friedman384da272009-01-25 03:12:18 +00003189 // This function is attempting whether an expression is an initializer
Eli Friedman4c27ac22013-07-16 22:40:53 +00003190 // which can be evaluated at compile-time. It very closely parallels
3191 // ConstExprEmitter in CGExprConstant.cpp; if they don't match, it
3192 // will lead to unexpected results. Like ConstExprEmitter, it falls back
3193 // to isEvaluatable most of the time.
3194 //
John McCall8b0f4ff2010-08-02 21:13:48 +00003195 // If we ever capture reference-binding directly in the AST, we can
3196 // kill the second parameter.
3197
3198 if (IsForRef) {
3199 EvalResult Result;
Abramo Bagnara847c6602014-05-22 19:20:46 +00003200 if (EvaluateAsLValue(Result, Ctx) && !Result.HasSideEffects)
3201 return true;
3202 if (Culprit)
3203 *Culprit = this;
3204 return false;
John McCall8b0f4ff2010-08-02 21:13:48 +00003205 }
Eli Friedmancf7cbe72009-02-20 02:36:22 +00003206
Anders Carlssona7c5eb72008-11-24 05:23:59 +00003207 switch (getStmtClass()) {
Eli Friedman384da272009-01-25 03:12:18 +00003208 default: break;
Anders Carlssona7c5eb72008-11-24 05:23:59 +00003209 case StringLiteralClass:
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00003210 case ObjCEncodeExprClass:
Anders Carlssona7c5eb72008-11-24 05:23:59 +00003211 return true;
John McCall81c9cea2010-08-01 21:51:45 +00003212 case CXXTemporaryObjectExprClass:
3213 case CXXConstructExprClass: {
3214 const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
John McCall8b0f4ff2010-08-02 21:13:48 +00003215
Eli Friedman4c27ac22013-07-16 22:40:53 +00003216 if (CE->getConstructor()->isTrivial() &&
3217 CE->getConstructor()->getParent()->hasTrivialDestructor()) {
3218 // Trivial default constructor
Richard Smithd62306a2011-11-10 06:34:14 +00003219 if (!CE->getNumArgs()) return true;
John McCall8b0f4ff2010-08-02 21:13:48 +00003220
Eli Friedman4c27ac22013-07-16 22:40:53 +00003221 // Trivial copy constructor
3222 assert(CE->getNumArgs() == 1 && "trivial ctor with > 1 argument");
Abramo Bagnara847c6602014-05-22 19:20:46 +00003223 return CE->getArg(0)->isConstantInitializer(Ctx, false, Culprit);
Richard Smithd62306a2011-11-10 06:34:14 +00003224 }
3225
Richard Smithd62306a2011-11-10 06:34:14 +00003226 break;
John McCall81c9cea2010-08-01 21:51:45 +00003227 }
Fangrui Song407659a2018-11-30 23:41:18 +00003228 case ConstantExprClass: {
3229 // FIXME: We should be able to return "true" here, but it can lead to extra
3230 // error messages. E.g. in Sema/array-init.c.
3231 const Expr *Exp = cast<ConstantExpr>(this)->getSubExpr();
3232 return Exp->isConstantInitializer(Ctx, false, Culprit);
3233 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003234 case CompoundLiteralExprClass: {
Eli Friedmancf7cbe72009-02-20 02:36:22 +00003235 // This handles gcc's extension that allows global initializers like
3236 // "struct x {int x;} x = (struct x) {};".
3237 // FIXME: This accepts other cases it shouldn't!
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003238 const Expr *Exp = cast<CompoundLiteralExpr>(this)->getInitializer();
Abramo Bagnara847c6602014-05-22 19:20:46 +00003239 return Exp->isConstantInitializer(Ctx, false, Culprit);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003240 }
Yunzhong Gaocb779302015-06-10 00:27:52 +00003241 case DesignatedInitUpdateExprClass: {
3242 const DesignatedInitUpdateExpr *DIUE = cast<DesignatedInitUpdateExpr>(this);
3243 return DIUE->getBase()->isConstantInitializer(Ctx, false, Culprit) &&
3244 DIUE->getUpdater()->isConstantInitializer(Ctx, false, Culprit);
3245 }
Anders Carlssona7c5eb72008-11-24 05:23:59 +00003246 case InitListExprClass: {
Eli Friedman4c27ac22013-07-16 22:40:53 +00003247 const InitListExpr *ILE = cast<InitListExpr>(this);
Dmitri Gribenkoc5f25442019-05-10 06:39:20 +00003248 assert(ILE->isSemanticForm() && "InitListExpr must be in semantic form");
Eli Friedman4c27ac22013-07-16 22:40:53 +00003249 if (ILE->getType()->isArrayType()) {
3250 unsigned numInits = ILE->getNumInits();
3251 for (unsigned i = 0; i < numInits; i++) {
Abramo Bagnara847c6602014-05-22 19:20:46 +00003252 if (!ILE->getInit(i)->isConstantInitializer(Ctx, false, Culprit))
Eli Friedman4c27ac22013-07-16 22:40:53 +00003253 return false;
3254 }
3255 return true;
Anders Carlssona7c5eb72008-11-24 05:23:59 +00003256 }
Eli Friedman4c27ac22013-07-16 22:40:53 +00003257
3258 if (ILE->getType()->isRecordType()) {
3259 unsigned ElementNo = 0;
Simon Pilgrim1cd399c2019-10-03 11:22:48 +00003260 RecordDecl *RD = ILE->getType()->castAs<RecordType>()->getDecl();
Hans Wennborga302cd92014-08-21 16:06:57 +00003261 for (const auto *Field : RD->fields()) {
Eli Friedman4c27ac22013-07-16 22:40:53 +00003262 // If this is a union, skip all the fields that aren't being initialized.
Hans Wennborga302cd92014-08-21 16:06:57 +00003263 if (RD->isUnion() && ILE->getInitializedFieldInUnion() != Field)
Eli Friedman4c27ac22013-07-16 22:40:53 +00003264 continue;
3265
3266 // Don't emit anonymous bitfields, they just affect layout.
3267 if (Field->isUnnamedBitfield())
3268 continue;
3269
3270 if (ElementNo < ILE->getNumInits()) {
3271 const Expr *Elt = ILE->getInit(ElementNo++);
3272 if (Field->isBitField()) {
3273 // Bitfields have to evaluate to an integer.
Fangrui Song407659a2018-11-30 23:41:18 +00003274 EvalResult Result;
3275 if (!Elt->EvaluateAsInt(Result, Ctx)) {
Abramo Bagnara847c6602014-05-22 19:20:46 +00003276 if (Culprit)
3277 *Culprit = Elt;
Eli Friedman4c27ac22013-07-16 22:40:53 +00003278 return false;
Abramo Bagnara847c6602014-05-22 19:20:46 +00003279 }
Eli Friedman4c27ac22013-07-16 22:40:53 +00003280 } else {
3281 bool RefType = Field->getType()->isReferenceType();
Abramo Bagnara847c6602014-05-22 19:20:46 +00003282 if (!Elt->isConstantInitializer(Ctx, RefType, Culprit))
Eli Friedman4c27ac22013-07-16 22:40:53 +00003283 return false;
3284 }
3285 }
3286 }
3287 return true;
3288 }
3289
3290 break;
Anders Carlssona7c5eb72008-11-24 05:23:59 +00003291 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00003292 case ImplicitValueInitExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00003293 case NoInitExprClass:
Douglas Gregor0202cb42009-01-29 17:44:32 +00003294 return true;
Chris Lattner3eb172a2009-10-13 07:14:16 +00003295 case ParenExprClass:
John McCall8b0f4ff2010-08-02 21:13:48 +00003296 return cast<ParenExpr>(this)->getSubExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00003297 ->isConstantInitializer(Ctx, IsForRef, Culprit);
Peter Collingbourne91147592011-04-15 00:35:48 +00003298 case GenericSelectionExprClass:
Peter Collingbourne91147592011-04-15 00:35:48 +00003299 return cast<GenericSelectionExpr>(this)->getResultExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00003300 ->isConstantInitializer(Ctx, IsForRef, Culprit);
Abramo Bagnarab59a5b62010-09-27 07:13:32 +00003301 case ChooseExprClass:
Abramo Bagnara847c6602014-05-22 19:20:46 +00003302 if (cast<ChooseExpr>(this)->isConditionDependent()) {
3303 if (Culprit)
3304 *Culprit = this;
Eli Friedman75807f22013-07-20 00:40:58 +00003305 return false;
Abramo Bagnara847c6602014-05-22 19:20:46 +00003306 }
Eli Friedman75807f22013-07-20 00:40:58 +00003307 return cast<ChooseExpr>(this)->getChosenSubExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00003308 ->isConstantInitializer(Ctx, IsForRef, Culprit);
Eli Friedman384da272009-01-25 03:12:18 +00003309 case UnaryOperatorClass: {
3310 const UnaryOperator* Exp = cast<UnaryOperator>(this);
John McCalle3027922010-08-25 11:45:40 +00003311 if (Exp->getOpcode() == UO_Extension)
Abramo Bagnara847c6602014-05-22 19:20:46 +00003312 return Exp->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
Eli Friedman384da272009-01-25 03:12:18 +00003313 break;
3314 }
John McCall8b0f4ff2010-08-02 21:13:48 +00003315 case CXXFunctionalCastExprClass:
John McCall81c9cea2010-08-01 21:51:45 +00003316 case CXXStaticCastExprClass:
Chris Lattner1f02e052009-04-21 05:19:11 +00003317 case ImplicitCastExprClass:
Eli Friedman4c27ac22013-07-16 22:40:53 +00003318 case CStyleCastExprClass:
3319 case ObjCBridgedCastExprClass:
3320 case CXXDynamicCastExprClass:
3321 case CXXReinterpretCastExprClass:
3322 case CXXConstCastExprClass: {
Richard Smith161f09a2011-12-06 22:44:34 +00003323 const CastExpr *CE = cast<CastExpr>(this);
3324
Eli Friedman13ec75b2011-12-21 00:43:02 +00003325 // Handle misc casts we want to ignore.
Eli Friedman13ec75b2011-12-21 00:43:02 +00003326 if (CE->getCastKind() == CK_NoOp ||
3327 CE->getCastKind() == CK_LValueToRValue ||
3328 CE->getCastKind() == CK_ToUnion ||
Eli Friedman4c27ac22013-07-16 22:40:53 +00003329 CE->getCastKind() == CK_ConstructorConversion ||
3330 CE->getCastKind() == CK_NonAtomicToAtomic ||
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00003331 CE->getCastKind() == CK_AtomicToNonAtomic ||
3332 CE->getCastKind() == CK_IntToOCLSampler)
Abramo Bagnara847c6602014-05-22 19:20:46 +00003333 return CE->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
Richard Smith161f09a2011-12-06 22:44:34 +00003334
Eli Friedman384da272009-01-25 03:12:18 +00003335 break;
Richard Smith161f09a2011-12-06 22:44:34 +00003336 }
Douglas Gregorfe314812011-06-21 17:03:29 +00003337 case MaterializeTemporaryExprClass:
Tykerb0561b32019-11-17 11:41:55 +01003338 return cast<MaterializeTemporaryExpr>(this)
3339 ->getSubExpr()
3340 ->isConstantInitializer(Ctx, false, Culprit);
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003341
Eli Friedman4c27ac22013-07-16 22:40:53 +00003342 case SubstNonTypeTemplateParmExprClass:
3343 return cast<SubstNonTypeTemplateParmExpr>(this)->getReplacement()
Abramo Bagnara847c6602014-05-22 19:20:46 +00003344 ->isConstantInitializer(Ctx, false, Culprit);
Eli Friedman4c27ac22013-07-16 22:40:53 +00003345 case CXXDefaultArgExprClass:
3346 return cast<CXXDefaultArgExpr>(this)->getExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00003347 ->isConstantInitializer(Ctx, false, Culprit);
Eli Friedman4c27ac22013-07-16 22:40:53 +00003348 case CXXDefaultInitExprClass:
3349 return cast<CXXDefaultInitExpr>(this)->getExpr()
Abramo Bagnara847c6602014-05-22 19:20:46 +00003350 ->isConstantInitializer(Ctx, false, Culprit);
Anders Carlssona7c5eb72008-11-24 05:23:59 +00003351 }
Richard Smithce8eca52015-12-08 03:21:47 +00003352 // Allow certain forms of UB in constant initializers: signed integer
3353 // overflow and floating-point division by zero. We'll give a warning on
3354 // these, but they're common enough that we have to accept them.
3355 if (isEvaluatable(Ctx, SE_AllowUndefinedBehavior))
Abramo Bagnara847c6602014-05-22 19:20:46 +00003356 return true;
3357 if (Culprit)
3358 *Culprit = this;
3359 return false;
Steve Naroffb03f5942007-09-02 20:30:18 +00003360}
3361
Nico Weber758fbac2018-02-13 21:31:47 +00003362bool CallExpr::isBuiltinAssumeFalse(const ASTContext &Ctx) const {
3363 const FunctionDecl* FD = getDirectCallee();
3364 if (!FD || (FD->getBuiltinID() != Builtin::BI__assume &&
3365 FD->getBuiltinID() != Builtin::BI__builtin_assume))
3366 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00003367
Nico Weber758fbac2018-02-13 21:31:47 +00003368 const Expr* Arg = getArg(0);
3369 bool ArgVal;
3370 return !Arg->isValueDependent() &&
3371 Arg->EvaluateAsBooleanCondition(ArgVal, Ctx) && !ArgVal;
3372}
3373
Scott Douglasscc013592015-06-10 15:18:23 +00003374namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003375 /// Look for any side effects within a Stmt.
Scott Douglasscc013592015-06-10 15:18:23 +00003376 class SideEffectFinder : public ConstEvaluatedExprVisitor<SideEffectFinder> {
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003377 typedef ConstEvaluatedExprVisitor<SideEffectFinder> Inherited;
Scott Douglasscc013592015-06-10 15:18:23 +00003378 const bool IncludePossibleEffects;
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003379 bool HasSideEffects;
Scott Douglasscc013592015-06-10 15:18:23 +00003380
3381 public:
3382 explicit SideEffectFinder(const ASTContext &Context, bool IncludePossible)
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003383 : Inherited(Context),
3384 IncludePossibleEffects(IncludePossible), HasSideEffects(false) { }
Scott Douglasscc013592015-06-10 15:18:23 +00003385
3386 bool hasSideEffects() const { return HasSideEffects; }
3387
3388 void VisitExpr(const Expr *E) {
3389 if (!HasSideEffects &&
3390 E->HasSideEffects(Context, IncludePossibleEffects))
3391 HasSideEffects = true;
3392 }
3393 };
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003394}
Scott Douglasscc013592015-06-10 15:18:23 +00003395
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003396bool Expr::HasSideEffects(const ASTContext &Ctx,
3397 bool IncludePossibleEffects) const {
3398 // In circumstances where we care about definite side effects instead of
3399 // potential side effects, we want to ignore expressions that are part of a
3400 // macro expansion as a potential side effect.
3401 if (!IncludePossibleEffects && getExprLoc().isMacroID())
3402 return false;
3403
Richard Smith0421ce72012-08-07 04:16:51 +00003404 if (isInstantiationDependent())
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003405 return IncludePossibleEffects;
Richard Smith0421ce72012-08-07 04:16:51 +00003406
3407 switch (getStmtClass()) {
3408 case NoStmtClass:
3409 #define ABSTRACT_STMT(Type)
3410 #define STMT(Type, Base) case Type##Class:
3411 #define EXPR(Type, Base)
3412 #include "clang/AST/StmtNodes.inc"
3413 llvm_unreachable("unexpected Expr kind");
3414
3415 case DependentScopeDeclRefExprClass:
3416 case CXXUnresolvedConstructExprClass:
3417 case CXXDependentScopeMemberExprClass:
3418 case UnresolvedLookupExprClass:
3419 case UnresolvedMemberExprClass:
3420 case PackExpansionExprClass:
3421 case SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +00003422 case FunctionParmPackExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +00003423 case TypoExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +00003424 case CXXFoldExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003425 llvm_unreachable("shouldn't see dependent / unresolved nodes here");
3426
Richard Smitha33e4fe2012-08-07 05:18:29 +00003427 case DeclRefExprClass:
3428 case ObjCIvarRefExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003429 case PredefinedExprClass:
3430 case IntegerLiteralClass:
Leonard Chandb01c3a2018-06-20 17:19:40 +00003431 case FixedPointLiteralClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003432 case FloatingLiteralClass:
3433 case ImaginaryLiteralClass:
3434 case StringLiteralClass:
3435 case CharacterLiteralClass:
3436 case OffsetOfExprClass:
3437 case ImplicitValueInitExprClass:
3438 case UnaryExprOrTypeTraitExprClass:
3439 case AddrLabelExprClass:
3440 case GNUNullExprClass:
Richard Smith410306b2016-12-12 02:53:20 +00003441 case ArrayInitIndexExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00003442 case NoInitExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003443 case CXXBoolLiteralExprClass:
3444 case CXXNullPtrLiteralExprClass:
3445 case CXXThisExprClass:
3446 case CXXScalarValueInitExprClass:
3447 case TypeTraitExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003448 case ArrayTypeTraitExprClass:
3449 case ExpressionTraitExprClass:
3450 case CXXNoexceptExprClass:
3451 case SizeOfPackExprClass:
3452 case ObjCStringLiteralClass:
3453 case ObjCEncodeExprClass:
3454 case ObjCBoolLiteralExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +00003455 case ObjCAvailabilityCheckExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003456 case CXXUuidofExprClass:
3457 case OpaqueValueExprClass:
Eric Fiselier708afb52019-05-16 21:04:15 +00003458 case SourceLocExprClass:
Saar Raz5d98ba62019-10-15 15:24:26 +00003459 case ConceptSpecializationExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003460 // These never have a side-effect.
3461 return false;
3462
Bill Wendling7c44da22018-10-31 03:48:47 +00003463 case ConstantExprClass:
3464 // FIXME: Move this into the "return false;" block above.
3465 return cast<ConstantExpr>(this)->getSubExpr()->HasSideEffects(
3466 Ctx, IncludePossibleEffects);
3467
Richard Smith0421ce72012-08-07 04:16:51 +00003468 case CallExprClass:
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003469 case CXXOperatorCallExprClass:
3470 case CXXMemberCallExprClass:
3471 case CUDAKernelCallExprClass:
Michael Kupersteinaed5ccd2015-04-06 13:22:01 +00003472 case UserDefinedLiteralClass: {
3473 // We don't know a call definitely has side effects, except for calls
3474 // to pure/const functions that definitely don't.
3475 // If the call itself is considered side-effect free, check the operands.
3476 const Decl *FD = cast<CallExpr>(this)->getCalleeDecl();
3477 bool IsPure = FD && (FD->hasAttr<ConstAttr>() || FD->hasAttr<PureAttr>());
3478 if (IsPure || !IncludePossibleEffects)
3479 break;
3480 return true;
3481 }
3482
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003483 case BlockExprClass:
3484 case CXXBindTemporaryExprClass:
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003485 if (!IncludePossibleEffects)
3486 break;
3487 return true;
3488
John McCall5e77d762013-04-16 07:28:30 +00003489 case MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +00003490 case MSPropertySubscriptExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003491 case CompoundAssignOperatorClass:
3492 case VAArgExprClass:
3493 case AtomicExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003494 case CXXThrowExprClass:
3495 case CXXNewExprClass:
3496 case CXXDeleteExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +00003497 case CoawaitExprClass:
Eric Fiselier20f25cb2017-03-06 23:38:15 +00003498 case DependentCoawaitExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +00003499 case CoyieldExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003500 // These always have a side-effect.
3501 return true;
3502
Scott Douglasscc013592015-06-10 15:18:23 +00003503 case StmtExprClass: {
3504 // StmtExprs have a side-effect if any substatement does.
3505 SideEffectFinder Finder(Ctx, IncludePossibleEffects);
3506 Finder.Visit(cast<StmtExpr>(this)->getSubStmt());
3507 return Finder.hasSideEffects();
3508 }
3509
Tim Shen4a05bb82016-06-21 20:29:17 +00003510 case ExprWithCleanupsClass:
3511 if (IncludePossibleEffects)
3512 if (cast<ExprWithCleanups>(this)->cleanupsHaveSideEffects())
3513 return true;
3514 break;
3515
Richard Smith0421ce72012-08-07 04:16:51 +00003516 case ParenExprClass:
3517 case ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +00003518 case OMPArraySectionExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003519 case MemberExprClass:
3520 case ConditionalOperatorClass:
3521 case BinaryConditionalOperatorClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003522 case CompoundLiteralExprClass:
3523 case ExtVectorElementExprClass:
3524 case DesignatedInitExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00003525 case DesignatedInitUpdateExprClass:
Richard Smith410306b2016-12-12 02:53:20 +00003526 case ArrayInitLoopExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003527 case ParenListExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003528 case CXXPseudoDestructorExprClass:
Richard Smith778dc0f2019-10-19 00:04:38 +00003529 case CXXRewrittenBinaryOperatorClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +00003530 case CXXStdInitializerListExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003531 case SubstNonTypeTemplateParmExprClass:
3532 case MaterializeTemporaryExprClass:
3533 case ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +00003534 case ConvertVectorExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003535 case AsTypeExprClass:
3536 // These have a side-effect if any subexpression does.
3537 break;
3538
Richard Smitha33e4fe2012-08-07 05:18:29 +00003539 case UnaryOperatorClass:
3540 if (cast<UnaryOperator>(this)->isIncrementDecrementOp())
Richard Smith0421ce72012-08-07 04:16:51 +00003541 return true;
3542 break;
Richard Smith0421ce72012-08-07 04:16:51 +00003543
3544 case BinaryOperatorClass:
3545 if (cast<BinaryOperator>(this)->isAssignmentOp())
3546 return true;
3547 break;
3548
Richard Smith0421ce72012-08-07 04:16:51 +00003549 case InitListExprClass:
3550 // FIXME: The children for an InitListExpr doesn't include the array filler.
3551 if (const Expr *E = cast<InitListExpr>(this)->getArrayFiller())
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003552 if (E->HasSideEffects(Ctx, IncludePossibleEffects))
Richard Smith0421ce72012-08-07 04:16:51 +00003553 return true;
3554 break;
3555
3556 case GenericSelectionExprClass:
3557 return cast<GenericSelectionExpr>(this)->getResultExpr()->
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003558 HasSideEffects(Ctx, IncludePossibleEffects);
Richard Smith0421ce72012-08-07 04:16:51 +00003559
3560 case ChooseExprClass:
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003561 return cast<ChooseExpr>(this)->getChosenSubExpr()->HasSideEffects(
3562 Ctx, IncludePossibleEffects);
Richard Smith0421ce72012-08-07 04:16:51 +00003563
3564 case CXXDefaultArgExprClass:
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003565 return cast<CXXDefaultArgExpr>(this)->getExpr()->HasSideEffects(
3566 Ctx, IncludePossibleEffects);
Richard Smith0421ce72012-08-07 04:16:51 +00003567
Reid Klecknerd60b82f2014-11-17 23:36:45 +00003568 case CXXDefaultInitExprClass: {
3569 const FieldDecl *FD = cast<CXXDefaultInitExpr>(this)->getField();
3570 if (const Expr *E = FD->getInClassInitializer())
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003571 return E->HasSideEffects(Ctx, IncludePossibleEffects);
Richard Smith852c9db2013-04-20 22:23:05 +00003572 // If we've not yet parsed the initializer, assume it has side-effects.
3573 return true;
Reid Klecknerd60b82f2014-11-17 23:36:45 +00003574 }
Richard Smith852c9db2013-04-20 22:23:05 +00003575
Richard Smith0421ce72012-08-07 04:16:51 +00003576 case CXXDynamicCastExprClass: {
3577 // A dynamic_cast expression has side-effects if it can throw.
3578 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(this);
3579 if (DCE->getTypeAsWritten()->isReferenceType() &&
3580 DCE->getCastKind() == CK_Dynamic)
3581 return true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00003582 }
3583 LLVM_FALLTHROUGH;
Richard Smitha33e4fe2012-08-07 05:18:29 +00003584 case ImplicitCastExprClass:
3585 case CStyleCastExprClass:
3586 case CXXStaticCastExprClass:
3587 case CXXReinterpretCastExprClass:
3588 case CXXConstCastExprClass:
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00003589 case CXXFunctionalCastExprClass:
3590 case BuiltinBitCastExprClass: {
Aaron Ballman409af502015-01-03 17:00:12 +00003591 // While volatile reads are side-effecting in both C and C++, we treat them
3592 // as having possible (not definite) side-effects. This allows idiomatic
3593 // code to behave without warning, such as sizeof(*v) for a volatile-
3594 // qualified pointer.
3595 if (!IncludePossibleEffects)
3596 break;
3597
Richard Smitha33e4fe2012-08-07 05:18:29 +00003598 const CastExpr *CE = cast<CastExpr>(this);
3599 if (CE->getCastKind() == CK_LValueToRValue &&
3600 CE->getSubExpr()->getType().isVolatileQualified())
3601 return true;
Richard Smith0421ce72012-08-07 04:16:51 +00003602 break;
3603 }
3604
Richard Smithef8bf432012-08-13 20:08:14 +00003605 case CXXTypeidExprClass:
3606 // typeid might throw if its subexpression is potentially-evaluated, so has
3607 // side-effects in that case whether or not its subexpression does.
3608 return cast<CXXTypeidExpr>(this)->isPotentiallyEvaluated();
Richard Smith0421ce72012-08-07 04:16:51 +00003609
3610 case CXXConstructExprClass:
3611 case CXXTemporaryObjectExprClass: {
3612 const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003613 if (!CE->getConstructor()->isTrivial() && IncludePossibleEffects)
Richard Smith0421ce72012-08-07 04:16:51 +00003614 return true;
Richard Smitha33e4fe2012-08-07 05:18:29 +00003615 // A trivial constructor does not add any side-effects of its own. Just look
3616 // at its arguments.
Richard Smith0421ce72012-08-07 04:16:51 +00003617 break;
3618 }
3619
Richard Smith5179eb72016-06-28 19:03:57 +00003620 case CXXInheritedCtorInitExprClass: {
3621 const auto *ICIE = cast<CXXInheritedCtorInitExpr>(this);
3622 if (!ICIE->getConstructor()->isTrivial() && IncludePossibleEffects)
3623 return true;
3624 break;
3625 }
3626
Richard Smith0421ce72012-08-07 04:16:51 +00003627 case LambdaExprClass: {
3628 const LambdaExpr *LE = cast<LambdaExpr>(this);
Richard Smithb3d203f2018-10-19 19:01:34 +00003629 for (Expr *E : LE->capture_inits())
3630 if (E->HasSideEffects(Ctx, IncludePossibleEffects))
Richard Smith0421ce72012-08-07 04:16:51 +00003631 return true;
3632 return false;
3633 }
3634
3635 case PseudoObjectExprClass: {
3636 // Only look for side-effects in the semantic form, and look past
3637 // OpaqueValueExpr bindings in that form.
3638 const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this);
3639 for (PseudoObjectExpr::const_semantics_iterator I = PO->semantics_begin(),
3640 E = PO->semantics_end();
3641 I != E; ++I) {
3642 const Expr *Subexpr = *I;
3643 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Subexpr))
3644 Subexpr = OVE->getSourceExpr();
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003645 if (Subexpr->HasSideEffects(Ctx, IncludePossibleEffects))
Richard Smith0421ce72012-08-07 04:16:51 +00003646 return true;
3647 }
3648 return false;
3649 }
3650
3651 case ObjCBoxedExprClass:
3652 case ObjCArrayLiteralClass:
3653 case ObjCDictionaryLiteralClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003654 case ObjCSelectorExprClass:
3655 case ObjCProtocolExprClass:
Richard Smith0421ce72012-08-07 04:16:51 +00003656 case ObjCIsaExprClass:
3657 case ObjCIndirectCopyRestoreExprClass:
3658 case ObjCSubscriptRefExprClass:
3659 case ObjCBridgedCastExprClass:
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003660 case ObjCMessageExprClass:
3661 case ObjCPropertyRefExprClass:
3662 // FIXME: Classify these cases better.
3663 if (IncludePossibleEffects)
3664 return true;
3665 break;
Richard Smith0421ce72012-08-07 04:16:51 +00003666 }
3667
3668 // Recurse to children.
Benjamin Kramer642f1732015-07-02 21:03:14 +00003669 for (const Stmt *SubStmt : children())
3670 if (SubStmt &&
3671 cast<Expr>(SubStmt)->HasSideEffects(Ctx, IncludePossibleEffects))
3672 return true;
Richard Smith0421ce72012-08-07 04:16:51 +00003673
3674 return false;
3675}
3676
Douglas Gregor1be329d2012-02-23 07:33:15 +00003677namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003678 /// Look for a call to a non-trivial function within an expression.
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003679 class NonTrivialCallFinder : public ConstEvaluatedExprVisitor<NonTrivialCallFinder>
3680 {
3681 typedef ConstEvaluatedExprVisitor<NonTrivialCallFinder> Inherited;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003682
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003683 bool NonTrivial;
Fangrui Song6907ce22018-07-30 19:24:48 +00003684
Douglas Gregor1be329d2012-02-23 07:33:15 +00003685 public:
Scott Douglass503fc392015-06-10 13:53:15 +00003686 explicit NonTrivialCallFinder(const ASTContext &Context)
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003687 : Inherited(Context), NonTrivial(false) { }
Fangrui Song6907ce22018-07-30 19:24:48 +00003688
Douglas Gregor1be329d2012-02-23 07:33:15 +00003689 bool hasNonTrivialCall() const { return NonTrivial; }
Scott Douglass503fc392015-06-10 13:53:15 +00003690
3691 void VisitCallExpr(const CallExpr *E) {
3692 if (const CXXMethodDecl *Method
3693 = dyn_cast_or_null<const CXXMethodDecl>(E->getCalleeDecl())) {
Douglas Gregor1be329d2012-02-23 07:33:15 +00003694 if (Method->isTrivial()) {
3695 // Recurse to children of the call.
3696 Inherited::VisitStmt(E);
3697 return;
3698 }
3699 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003700
Douglas Gregor1be329d2012-02-23 07:33:15 +00003701 NonTrivial = true;
3702 }
Scott Douglass503fc392015-06-10 13:53:15 +00003703
3704 void VisitCXXConstructExpr(const CXXConstructExpr *E) {
Douglas Gregor1be329d2012-02-23 07:33:15 +00003705 if (E->getConstructor()->isTrivial()) {
3706 // Recurse to children of the call.
3707 Inherited::VisitStmt(E);
3708 return;
3709 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003710
Douglas Gregor1be329d2012-02-23 07:33:15 +00003711 NonTrivial = true;
3712 }
Scott Douglass503fc392015-06-10 13:53:15 +00003713
3714 void VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
Douglas Gregor1be329d2012-02-23 07:33:15 +00003715 if (E->getTemporary()->getDestructor()->isTrivial()) {
3716 Inherited::VisitStmt(E);
3717 return;
3718 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003719
Douglas Gregor1be329d2012-02-23 07:33:15 +00003720 NonTrivial = true;
3721 }
3722 };
Eugene Zelenkoae304b02017-11-17 18:09:48 +00003723}
Douglas Gregor1be329d2012-02-23 07:33:15 +00003724
Scott Douglass503fc392015-06-10 13:53:15 +00003725bool Expr::hasNonTrivialCall(const ASTContext &Ctx) const {
Douglas Gregor1be329d2012-02-23 07:33:15 +00003726 NonTrivialCallFinder Finder(Ctx);
3727 Finder.Visit(this);
Fangrui Song6907ce22018-07-30 19:24:48 +00003728 return Finder.hasNonTrivialCall();
Douglas Gregor1be329d2012-02-23 07:33:15 +00003729}
3730
Fangrui Song6907ce22018-07-30 19:24:48 +00003731/// isNullPointerConstant - C99 6.3.2.3p3 - Return whether this is a null
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003732/// pointer constant or not, as well as the specific kind of constant detected.
3733/// Null pointer constants can be integer constant expressions with the
3734/// value zero, casts of zero to void*, nullptr (C++0X), or __null
3735/// (a GNU extension).
3736Expr::NullPointerConstantKind
3737Expr::isNullPointerConstant(ASTContext &Ctx,
3738 NullPointerConstantValueDependence NPC) const {
Reid Klecknera5eef142013-11-12 02:22:34 +00003739 if (isValueDependent() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00003740 (!Ctx.getLangOpts().CPlusPlus11 || Ctx.getLangOpts().MSVCCompat)) {
Douglas Gregor56751b52009-09-25 04:25:58 +00003741 switch (NPC) {
3742 case NPC_NeverValueDependent:
David Blaikie83d382b2011-09-23 05:06:16 +00003743 llvm_unreachable("Unexpected value dependent expression!");
Douglas Gregor56751b52009-09-25 04:25:58 +00003744 case NPC_ValueDependentIsNull:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003745 if (isTypeDependent() || getType()->isIntegralType(Ctx))
David Blaikie1c7c8f72012-08-08 17:33:31 +00003746 return NPCK_ZeroExpression;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003747 else
3748 return NPCK_NotNull;
Fangrui Song6907ce22018-07-30 19:24:48 +00003749
Douglas Gregor56751b52009-09-25 04:25:58 +00003750 case NPC_ValueDependentIsNotNull:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003751 return NPCK_NotNull;
Douglas Gregor56751b52009-09-25 04:25:58 +00003752 }
3753 }
Daniel Dunbarebc51402009-09-18 08:46:16 +00003754
Sebastian Redl72b8aef2008-10-31 14:43:28 +00003755 // Strip off a cast to void*, if it exists. Except in C++.
Argyrios Kyrtzidis3bab3d22008-08-18 23:01:59 +00003756 if (const ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(this)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003757 if (!Ctx.getLangOpts().CPlusPlus) {
Sebastian Redl72b8aef2008-10-31 14:43:28 +00003758 // Check that it is a cast to void*.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003759 if (const PointerType *PT = CE->getType()->getAs<PointerType>()) {
Sebastian Redl72b8aef2008-10-31 14:43:28 +00003760 QualType Pointee = PT->getPointeeType();
Richard Smithdab73ce2018-11-28 06:25:06 +00003761 Qualifiers Qs = Pointee.getQualifiers();
Yaxun Liub7318e02017-10-13 03:37:48 +00003762 // Only (void*)0 or equivalent are treated as nullptr. If pointee type
3763 // has non-default address space it is not treated as nullptr.
3764 // (__generic void*)0 in OpenCL 2.0 should not be treated as nullptr
3765 // since it cannot be assigned to a pointer to constant address space.
Richard Smithdab73ce2018-11-28 06:25:06 +00003766 if ((Ctx.getLangOpts().OpenCLVersion >= 200 &&
Yaxun Liub7318e02017-10-13 03:37:48 +00003767 Pointee.getAddressSpace() == LangAS::opencl_generic) ||
3768 (Ctx.getLangOpts().OpenCL &&
3769 Ctx.getLangOpts().OpenCLVersion < 200 &&
Richard Smithdab73ce2018-11-28 06:25:06 +00003770 Pointee.getAddressSpace() == LangAS::opencl_private))
3771 Qs.removeAddressSpace();
Anastasia Stulova2446b8b2015-12-11 17:41:19 +00003772
Richard Smithdab73ce2018-11-28 06:25:06 +00003773 if (Pointee->isVoidType() && Qs.empty() && // to void*
3774 CE->getSubExpr()->getType()->isIntegerType()) // from int
Douglas Gregor56751b52009-09-25 04:25:58 +00003775 return CE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
Sebastian Redl72b8aef2008-10-31 14:43:28 +00003776 }
Steve Naroffada7d422007-05-20 17:54:12 +00003777 }
Steve Naroff4871fe02008-01-14 16:10:57 +00003778 } else if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(this)) {
3779 // Ignore the ImplicitCastExpr type entirely.
Douglas Gregor56751b52009-09-25 04:25:58 +00003780 return ICE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
Steve Naroff4871fe02008-01-14 16:10:57 +00003781 } else if (const ParenExpr *PE = dyn_cast<ParenExpr>(this)) {
3782 // Accept ((void*)0) as a null pointer constant, as many other
3783 // implementations do.
Douglas Gregor56751b52009-09-25 04:25:58 +00003784 return PE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
Peter Collingbourne91147592011-04-15 00:35:48 +00003785 } else if (const GenericSelectionExpr *GE =
3786 dyn_cast<GenericSelectionExpr>(this)) {
Eli Friedman75807f22013-07-20 00:40:58 +00003787 if (GE->isResultDependent())
3788 return NPCK_NotNull;
Peter Collingbourne91147592011-04-15 00:35:48 +00003789 return GE->getResultExpr()->isNullPointerConstant(Ctx, NPC);
Eli Friedman75807f22013-07-20 00:40:58 +00003790 } else if (const ChooseExpr *CE = dyn_cast<ChooseExpr>(this)) {
3791 if (CE->isConditionDependent())
3792 return NPCK_NotNull;
3793 return CE->getChosenSubExpr()->isNullPointerConstant(Ctx, NPC);
Mike Stump11289f42009-09-09 15:08:12 +00003794 } else if (const CXXDefaultArgExpr *DefaultArg
Chris Lattner58258242008-04-10 02:22:51 +00003795 = dyn_cast<CXXDefaultArgExpr>(this)) {
Richard Smith852c9db2013-04-20 22:23:05 +00003796 // See through default argument expressions.
Douglas Gregor56751b52009-09-25 04:25:58 +00003797 return DefaultArg->getExpr()->isNullPointerConstant(Ctx, NPC);
Richard Smith852c9db2013-04-20 22:23:05 +00003798 } else if (const CXXDefaultInitExpr *DefaultInit
3799 = dyn_cast<CXXDefaultInitExpr>(this)) {
3800 // See through default initializer expressions.
3801 return DefaultInit->getExpr()->isNullPointerConstant(Ctx, NPC);
Douglas Gregor3be4b122008-11-29 04:51:27 +00003802 } else if (isa<GNUNullExpr>(this)) {
3803 // The GNU __null extension is always a null pointer constant.
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003804 return NPCK_GNUNull;
Fangrui Song6907ce22018-07-30 19:24:48 +00003805 } else if (const MaterializeTemporaryExpr *M
Douglas Gregorfe314812011-06-21 17:03:29 +00003806 = dyn_cast<MaterializeTemporaryExpr>(this)) {
Tykerb0561b32019-11-17 11:41:55 +01003807 return M->getSubExpr()->isNullPointerConstant(Ctx, NPC);
John McCallfe96e0b2011-11-06 09:01:30 +00003808 } else if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(this)) {
3809 if (const Expr *Source = OVE->getSourceExpr())
3810 return Source->isNullPointerConstant(Ctx, NPC);
Steve Naroff09035312008-01-14 02:53:34 +00003811 }
Douglas Gregor3be4b122008-11-29 04:51:27 +00003812
Richard Smith89645bc2013-01-02 12:01:23 +00003813 // C++11 nullptr_t is always a null pointer constant.
Sebastian Redl576fd422009-05-10 18:38:11 +00003814 if (getType()->isNullPtrType())
Richard Smith89645bc2013-01-02 12:01:23 +00003815 return NPCK_CXX11_nullptr;
Sebastian Redl576fd422009-05-10 18:38:11 +00003816
Fariborz Jahanian3567c422010-09-27 22:42:37 +00003817 if (const RecordType *UT = getType()->getAsUnionType())
Richard Smith4055de42013-06-13 02:46:14 +00003818 if (!Ctx.getLangOpts().CPlusPlus11 &&
3819 UT && UT->getDecl()->hasAttr<TransparentUnionAttr>())
Fariborz Jahanian3567c422010-09-27 22:42:37 +00003820 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(this)){
3821 const Expr *InitExpr = CLE->getInitializer();
3822 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(InitExpr))
3823 return ILE->getInit(0)->isNullPointerConstant(Ctx, NPC);
3824 }
Steve Naroff4871fe02008-01-14 16:10:57 +00003825 // This expression must be an integer type.
Fangrui Song6907ce22018-07-30 19:24:48 +00003826 if (!getType()->isIntegerType() ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00003827 (Ctx.getLangOpts().CPlusPlus && getType()->isEnumeralType()))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003828 return NPCK_NotNull;
Mike Stump11289f42009-09-09 15:08:12 +00003829
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003830 if (Ctx.getLangOpts().CPlusPlus11) {
Richard Smith4055de42013-06-13 02:46:14 +00003831 // C++11 [conv.ptr]p1: A null pointer constant is an integer literal with
3832 // value zero or a prvalue of type std::nullptr_t.
Reid Klecknera5eef142013-11-12 02:22:34 +00003833 // Microsoft mode permits C++98 rules reflecting MSVC behavior.
Richard Smith4055de42013-06-13 02:46:14 +00003834 const IntegerLiteral *Lit = dyn_cast<IntegerLiteral>(this);
Reid Klecknera5eef142013-11-12 02:22:34 +00003835 if (Lit && !Lit->getValue())
3836 return NPCK_ZeroLiteral;
Alp Tokerbfa39342014-01-14 12:51:41 +00003837 else if (!Ctx.getLangOpts().MSVCCompat || !isCXX98IntegralConstantExpr(Ctx))
Reid Klecknera5eef142013-11-12 02:22:34 +00003838 return NPCK_NotNull;
Richard Smith98a0a492012-02-14 21:38:30 +00003839 } else {
Richard Smith4055de42013-06-13 02:46:14 +00003840 // If we have an integer constant expression, we need to *evaluate* it and
3841 // test for the value 0.
Richard Smith98a0a492012-02-14 21:38:30 +00003842 if (!isIntegerConstantExpr(Ctx))
3843 return NPCK_NotNull;
3844 }
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003845
David Blaikie1c7c8f72012-08-08 17:33:31 +00003846 if (EvaluateKnownConstInt(Ctx) != 0)
3847 return NPCK_NotNull;
3848
3849 if (isa<IntegerLiteral>(this))
3850 return NPCK_ZeroLiteral;
3851 return NPCK_ZeroExpression;
Steve Naroff218bc2b2007-05-04 21:54:46 +00003852}
Steve Narofff7a5da12007-07-28 23:10:27 +00003853
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003854/// If this expression is an l-value for an Objective C
John McCall34376a62010-12-04 03:47:34 +00003855/// property, find the underlying property reference expression.
3856const ObjCPropertyRefExpr *Expr::getObjCProperty() const {
3857 const Expr *E = this;
3858 while (true) {
3859 assert((E->getValueKind() == VK_LValue &&
3860 E->getObjectKind() == OK_ObjCProperty) &&
3861 "expression is not a property reference");
3862 E = E->IgnoreParenCasts();
3863 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3864 if (BO->getOpcode() == BO_Comma) {
3865 E = BO->getRHS();
3866 continue;
3867 }
3868 }
3869
3870 break;
3871 }
3872
3873 return cast<ObjCPropertyRefExpr>(E);
3874}
3875
Anna Zaks97c7ce32012-10-01 20:34:04 +00003876bool Expr::isObjCSelfExpr() const {
3877 const Expr *E = IgnoreParenImpCasts();
3878
3879 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
3880 if (!DRE)
3881 return false;
3882
3883 const ImplicitParamDecl *Param = dyn_cast<ImplicitParamDecl>(DRE->getDecl());
3884 if (!Param)
3885 return false;
3886
3887 const ObjCMethodDecl *M = dyn_cast<ObjCMethodDecl>(Param->getDeclContext());
3888 if (!M)
3889 return false;
3890
3891 return M->getSelfDecl() == Param;
3892}
3893
John McCalld25db7e2013-05-06 21:39:12 +00003894FieldDecl *Expr::getSourceBitField() {
Douglas Gregor19623dc2009-07-06 15:38:40 +00003895 Expr *E = this->IgnoreParens();
Douglas Gregor71235ec2009-05-02 02:18:30 +00003896
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003897 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall34376a62010-12-04 03:47:34 +00003898 if (ICE->getCastKind() == CK_LValueToRValue ||
3899 (ICE->getValueKind() != VK_RValue && ICE->getCastKind() == CK_NoOp))
Douglas Gregor65eb86e2010-01-29 19:14:02 +00003900 E = ICE->getSubExpr()->IgnoreParens();
3901 else
3902 break;
3903 }
3904
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003905 if (MemberExpr *MemRef = dyn_cast<MemberExpr>(E))
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00003906 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemRef->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00003907 if (Field->isBitField())
3908 return Field;
3909
George Burgess IV00f70bd2018-03-01 05:43:23 +00003910 if (ObjCIvarRefExpr *IvarRef = dyn_cast<ObjCIvarRefExpr>(E)) {
3911 FieldDecl *Ivar = IvarRef->getDecl();
3912 if (Ivar->isBitField())
3913 return Ivar;
3914 }
John McCalld25db7e2013-05-06 21:39:12 +00003915
Richard Smith7873de02016-08-11 22:25:46 +00003916 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E)) {
Argyrios Kyrtzidisd3f00542010-10-30 19:52:22 +00003917 if (FieldDecl *Field = dyn_cast<FieldDecl>(DeclRef->getDecl()))
3918 if (Field->isBitField())
3919 return Field;
3920
Richard Smith7873de02016-08-11 22:25:46 +00003921 if (BindingDecl *BD = dyn_cast<BindingDecl>(DeclRef->getDecl()))
3922 if (Expr *E = BD->getBinding())
3923 return E->getSourceBitField();
3924 }
3925
Eli Friedman609ada22011-07-13 02:05:57 +00003926 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(E)) {
Douglas Gregor71235ec2009-05-02 02:18:30 +00003927 if (BinOp->isAssignmentOp() && BinOp->getLHS())
John McCalld25db7e2013-05-06 21:39:12 +00003928 return BinOp->getLHS()->getSourceBitField();
Douglas Gregor71235ec2009-05-02 02:18:30 +00003929
Eli Friedman609ada22011-07-13 02:05:57 +00003930 if (BinOp->getOpcode() == BO_Comma && BinOp->getRHS())
John McCalld25db7e2013-05-06 21:39:12 +00003931 return BinOp->getRHS()->getSourceBitField();
Eli Friedman609ada22011-07-13 02:05:57 +00003932 }
3933
Richard Smith5b571672014-09-24 23:55:00 +00003934 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E))
3935 if (UnOp->isPrefix() && UnOp->isIncrementDecrementOp())
3936 return UnOp->getSubExpr()->getSourceBitField();
3937
Craig Topper36250ad2014-05-12 05:36:57 +00003938 return nullptr;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003939}
3940
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003941bool Expr::refersToVectorElement() const {
Richard Smith7873de02016-08-11 22:25:46 +00003942 // FIXME: Why do we not just look at the ObjectKind here?
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003943 const Expr *E = this->IgnoreParens();
Fangrui Song6907ce22018-07-30 19:24:48 +00003944
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003945 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall2536c6d2010-08-25 10:28:54 +00003946 if (ICE->getValueKind() != VK_RValue &&
John McCalle3027922010-08-25 11:45:40 +00003947 ICE->getCastKind() == CK_NoOp)
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003948 E = ICE->getSubExpr()->IgnoreParens();
3949 else
3950 break;
3951 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003952
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003953 if (const ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(E))
3954 return ASE->getBase()->getType()->isVectorType();
3955
3956 if (isa<ExtVectorElementExpr>(E))
3957 return true;
3958
Richard Smith7873de02016-08-11 22:25:46 +00003959 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3960 if (auto *BD = dyn_cast<BindingDecl>(DRE->getDecl()))
3961 if (auto *E = BD->getBinding())
3962 return E->refersToVectorElement();
3963
Anders Carlsson8abde4b2010-01-31 17:18:49 +00003964 return false;
3965}
3966
Andrey Bokhankod9eab9c2015-08-03 10:38:10 +00003967bool Expr::refersToGlobalRegisterVar() const {
3968 const Expr *E = this->IgnoreParenImpCasts();
3969
3970 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
3971 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
3972 if (VD->getStorageClass() == SC_Register &&
3973 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
3974 return true;
3975
3976 return false;
3977}
3978
Richard Trieu4c05de82019-09-21 03:02:26 +00003979bool Expr::isSameComparisonOperand(const Expr* E1, const Expr* E2) {
3980 E1 = E1->IgnoreParens();
3981 E2 = E2->IgnoreParens();
3982
3983 if (E1->getStmtClass() != E2->getStmtClass())
3984 return false;
3985
3986 switch (E1->getStmtClass()) {
3987 default:
3988 return false;
3989 case CXXThisExprClass:
3990 return true;
3991 case DeclRefExprClass: {
3992 // DeclRefExpr without an ImplicitCastExpr can happen for integral
3993 // template parameters.
3994 const auto *DRE1 = cast<DeclRefExpr>(E1);
3995 const auto *DRE2 = cast<DeclRefExpr>(E2);
3996 return DRE1->isRValue() && DRE2->isRValue() &&
3997 DRE1->getDecl() == DRE2->getDecl();
3998 }
3999 case ImplicitCastExprClass: {
4000 // Peel off implicit casts.
4001 while (true) {
4002 const auto *ICE1 = dyn_cast<ImplicitCastExpr>(E1);
4003 const auto *ICE2 = dyn_cast<ImplicitCastExpr>(E2);
4004 if (!ICE1 || !ICE2)
4005 return false;
4006 if (ICE1->getCastKind() != ICE2->getCastKind())
4007 return false;
4008 E1 = ICE1->getSubExpr()->IgnoreParens();
4009 E2 = ICE2->getSubExpr()->IgnoreParens();
4010 // The final cast must be one of these types.
4011 if (ICE1->getCastKind() == CK_LValueToRValue ||
4012 ICE1->getCastKind() == CK_ArrayToPointerDecay ||
4013 ICE1->getCastKind() == CK_FunctionToPointerDecay) {
4014 break;
4015 }
4016 }
4017
4018 const auto *DRE1 = dyn_cast<DeclRefExpr>(E1);
4019 const auto *DRE2 = dyn_cast<DeclRefExpr>(E2);
4020 if (DRE1 && DRE2)
4021 return declaresSameEntity(DRE1->getDecl(), DRE2->getDecl());
4022
4023 const auto *Ivar1 = dyn_cast<ObjCIvarRefExpr>(E1);
4024 const auto *Ivar2 = dyn_cast<ObjCIvarRefExpr>(E2);
4025 if (Ivar1 && Ivar2) {
4026 return Ivar1->isFreeIvar() && Ivar2->isFreeIvar() &&
4027 declaresSameEntity(Ivar1->getDecl(), Ivar2->getDecl());
4028 }
4029
4030 const auto *Array1 = dyn_cast<ArraySubscriptExpr>(E1);
4031 const auto *Array2 = dyn_cast<ArraySubscriptExpr>(E2);
4032 if (Array1 && Array2) {
4033 if (!isSameComparisonOperand(Array1->getBase(), Array2->getBase()))
4034 return false;
4035
4036 auto Idx1 = Array1->getIdx();
4037 auto Idx2 = Array2->getIdx();
4038 const auto Integer1 = dyn_cast<IntegerLiteral>(Idx1);
4039 const auto Integer2 = dyn_cast<IntegerLiteral>(Idx2);
4040 if (Integer1 && Integer2) {
Richard Trieu77297f02019-09-21 04:18:54 +00004041 if (!llvm::APInt::isSameValue(Integer1->getValue(),
4042 Integer2->getValue()))
Richard Trieu4c05de82019-09-21 03:02:26 +00004043 return false;
4044 } else {
4045 if (!isSameComparisonOperand(Idx1, Idx2))
4046 return false;
4047 }
4048
4049 return true;
4050 }
4051
4052 // Walk the MemberExpr chain.
4053 while (isa<MemberExpr>(E1) && isa<MemberExpr>(E2)) {
4054 const auto *ME1 = cast<MemberExpr>(E1);
4055 const auto *ME2 = cast<MemberExpr>(E2);
4056 if (!declaresSameEntity(ME1->getMemberDecl(), ME2->getMemberDecl()))
4057 return false;
4058 if (const auto *D = dyn_cast<VarDecl>(ME1->getMemberDecl()))
4059 if (D->isStaticDataMember())
4060 return true;
4061 E1 = ME1->getBase()->IgnoreParenImpCasts();
4062 E2 = ME2->getBase()->IgnoreParenImpCasts();
4063 }
4064
4065 if (isa<CXXThisExpr>(E1) && isa<CXXThisExpr>(E2))
4066 return true;
4067
4068 // A static member variable can end the MemberExpr chain with either
4069 // a MemberExpr or a DeclRefExpr.
4070 auto getAnyDecl = [](const Expr *E) -> const ValueDecl * {
4071 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
4072 return DRE->getDecl();
4073 if (const auto *ME = dyn_cast<MemberExpr>(E))
4074 return ME->getMemberDecl();
4075 return nullptr;
4076 };
4077
4078 const ValueDecl *VD1 = getAnyDecl(E1);
4079 const ValueDecl *VD2 = getAnyDecl(E2);
4080 return declaresSameEntity(VD1, VD2);
4081 }
4082 }
4083}
4084
Chris Lattnerb8211f62009-02-16 22:14:05 +00004085/// isArrow - Return true if the base expression is a pointer to vector,
4086/// return false if the base expression is a vector.
4087bool ExtVectorElementExpr::isArrow() const {
4088 return getBase()->getType()->isPointerType();
4089}
4090
Nate Begemance4d7fc2008-04-18 23:10:10 +00004091unsigned ExtVectorElementExpr::getNumElements() const {
John McCall9dd450b2009-09-21 23:43:11 +00004092 if (const VectorType *VT = getType()->getAs<VectorType>())
Nate Begemanf322eab2008-05-09 06:41:27 +00004093 return VT->getNumElements();
4094 return 1;
Chris Lattner177bd452007-08-03 16:00:20 +00004095}
4096
Nate Begemanf322eab2008-05-09 06:41:27 +00004097/// containsDuplicateElements - Return true if any element access is repeated.
Nate Begemance4d7fc2008-04-18 23:10:10 +00004098bool ExtVectorElementExpr::containsDuplicateElements() const {
Daniel Dunbarcb2a0562009-10-18 02:09:09 +00004099 // FIXME: Refactor this code to an accessor on the AST node which returns the
4100 // "type" of component access, and share with code below and in Sema.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004101 StringRef Comp = Accessor->getName();
Nate Begeman7e5185b2009-01-18 02:01:21 +00004102
4103 // Halving swizzles do not contain duplicate elements.
Daniel Dunbar125c9c92009-10-17 23:53:04 +00004104 if (Comp == "hi" || Comp == "lo" || Comp == "even" || Comp == "odd")
Nate Begeman7e5185b2009-01-18 02:01:21 +00004105 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004106
Nate Begeman7e5185b2009-01-18 02:01:21 +00004107 // Advance past s-char prefix on hex swizzles.
Daniel Dunbar125c9c92009-10-17 23:53:04 +00004108 if (Comp[0] == 's' || Comp[0] == 'S')
4109 Comp = Comp.substr(1);
Mike Stump11289f42009-09-09 15:08:12 +00004110
Daniel Dunbar125c9c92009-10-17 23:53:04 +00004111 for (unsigned i = 0, e = Comp.size(); i != e; ++i)
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004112 if (Comp.substr(i + 1).find(Comp[i]) != StringRef::npos)
Steve Naroff0d595ca2007-07-30 03:29:09 +00004113 return true;
Daniel Dunbar125c9c92009-10-17 23:53:04 +00004114
Steve Naroff0d595ca2007-07-30 03:29:09 +00004115 return false;
4116}
Chris Lattner885b4952007-08-02 23:36:59 +00004117
Nate Begemanf322eab2008-05-09 06:41:27 +00004118/// getEncodedElementAccess - We encode the fields as a llvm ConstantArray.
Nate Begemand3862152008-05-13 21:03:02 +00004119void ExtVectorElementExpr::getEncodedElementAccess(
Benjamin Kramer99383102015-07-28 16:25:32 +00004120 SmallVectorImpl<uint32_t> &Elts) const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004121 StringRef Comp = Accessor->getName();
Pirama Arumuga Nainar98eaa622016-07-22 18:49:43 +00004122 bool isNumericAccessor = false;
4123 if (Comp[0] == 's' || Comp[0] == 'S') {
Daniel Dunbarce5a0b32009-10-18 02:09:31 +00004124 Comp = Comp.substr(1);
Pirama Arumuga Nainar98eaa622016-07-22 18:49:43 +00004125 isNumericAccessor = true;
4126 }
Mike Stump11289f42009-09-09 15:08:12 +00004127
Daniel Dunbarce5a0b32009-10-18 02:09:31 +00004128 bool isHi = Comp == "hi";
4129 bool isLo = Comp == "lo";
4130 bool isEven = Comp == "even";
4131 bool isOdd = Comp == "odd";
Mike Stump11289f42009-09-09 15:08:12 +00004132
Nate Begemanf322eab2008-05-09 06:41:27 +00004133 for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
4134 uint64_t Index;
Mike Stump11289f42009-09-09 15:08:12 +00004135
Nate Begemanf322eab2008-05-09 06:41:27 +00004136 if (isHi)
4137 Index = e + i;
4138 else if (isLo)
4139 Index = i;
4140 else if (isEven)
4141 Index = 2 * i;
4142 else if (isOdd)
4143 Index = 2 * i + 1;
4144 else
Pirama Arumuga Nainar98eaa622016-07-22 18:49:43 +00004145 Index = ExtVectorType::getAccessorIdx(Comp[i], isNumericAccessor);
Chris Lattner885b4952007-08-02 23:36:59 +00004146
Nate Begemand3862152008-05-13 21:03:02 +00004147 Elts.push_back(Index);
Chris Lattner885b4952007-08-02 23:36:59 +00004148 }
Nate Begemanf322eab2008-05-09 06:41:27 +00004149}
4150
Craig Topper37932912013-08-18 10:09:15 +00004151ShuffleVectorExpr::ShuffleVectorExpr(const ASTContext &C, ArrayRef<Expr*> args,
Douglas Gregora6e053e2010-12-15 01:34:56 +00004152 QualType Type, SourceLocation BLoc,
Fangrui Song6907ce22018-07-30 19:24:48 +00004153 SourceLocation RP)
Eugene Zelenkoae304b02017-11-17 18:09:48 +00004154 : Expr(ShuffleVectorExprClass, Type, VK_RValue, OK_Ordinary,
4155 Type->isDependentType(), Type->isDependentType(),
4156 Type->isInstantiationDependentType(),
4157 Type->containsUnexpandedParameterPack()),
4158 BuiltinLoc(BLoc), RParenLoc(RP), NumExprs(args.size())
4159{
Benjamin Kramerc215e762012-08-24 11:54:20 +00004160 SubExprs = new (C) Stmt*[args.size()];
4161 for (unsigned i = 0; i != args.size(); i++) {
Douglas Gregora6e053e2010-12-15 01:34:56 +00004162 if (args[i]->isTypeDependent())
4163 ExprBits.TypeDependent = true;
4164 if (args[i]->isValueDependent())
4165 ExprBits.ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +00004166 if (args[i]->isInstantiationDependent())
4167 ExprBits.InstantiationDependent = true;
Douglas Gregora6e053e2010-12-15 01:34:56 +00004168 if (args[i]->containsUnexpandedParameterPack())
4169 ExprBits.ContainsUnexpandedParameterPack = true;
4170
4171 SubExprs[i] = args[i];
4172 }
4173}
4174
Craig Topper37932912013-08-18 10:09:15 +00004175void ShuffleVectorExpr::setExprs(const ASTContext &C, ArrayRef<Expr *> Exprs) {
Nate Begeman48745922009-08-12 02:28:50 +00004176 if (SubExprs) C.Deallocate(SubExprs);
4177
Dmitri Gribenko674eaa22013-05-10 00:43:44 +00004178 this->NumExprs = Exprs.size();
Dmitri Gribenko48d6daf2013-05-10 17:30:13 +00004179 SubExprs = new (C) Stmt*[NumExprs];
Dmitri Gribenko674eaa22013-05-10 00:43:44 +00004180 memcpy(SubExprs, Exprs.data(), sizeof(Expr *) * Exprs.size());
Mike Stump11289f42009-09-09 15:08:12 +00004181}
Nate Begeman48745922009-08-12 02:28:50 +00004182
Bruno Ricci94498c72019-01-26 13:58:15 +00004183GenericSelectionExpr::GenericSelectionExpr(
Bruno Riccidb076832019-01-26 14:15:10 +00004184 const ASTContext &, SourceLocation GenericLoc, Expr *ControllingExpr,
Bruno Ricci94498c72019-01-26 13:58:15 +00004185 ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
4186 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4187 bool ContainsUnexpandedParameterPack, unsigned ResultIndex)
4188 : Expr(GenericSelectionExprClass, AssocExprs[ResultIndex]->getType(),
4189 AssocExprs[ResultIndex]->getValueKind(),
4190 AssocExprs[ResultIndex]->getObjectKind(),
4191 AssocExprs[ResultIndex]->isTypeDependent(),
4192 AssocExprs[ResultIndex]->isValueDependent(),
4193 AssocExprs[ResultIndex]->isInstantiationDependent(),
4194 ContainsUnexpandedParameterPack),
4195 NumAssocs(AssocExprs.size()), ResultIndex(ResultIndex),
Bruno Riccidb076832019-01-26 14:15:10 +00004196 DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
Bruno Ricci94498c72019-01-26 13:58:15 +00004197 assert(AssocTypes.size() == AssocExprs.size() &&
4198 "Must have the same number of association expressions"
4199 " and TypeSourceInfo!");
4200 assert(ResultIndex < NumAssocs && "ResultIndex is out-of-bounds!");
4201
Bruno Riccidb076832019-01-26 14:15:10 +00004202 GenericSelectionExprBits.GenericLoc = GenericLoc;
4203 getTrailingObjects<Stmt *>()[ControllingIndex] = ControllingExpr;
Bruno Ricci94498c72019-01-26 13:58:15 +00004204 std::copy(AssocExprs.begin(), AssocExprs.end(),
Bruno Riccidb076832019-01-26 14:15:10 +00004205 getTrailingObjects<Stmt *>() + AssocExprStartIndex);
4206 std::copy(AssocTypes.begin(), AssocTypes.end(),
4207 getTrailingObjects<TypeSourceInfo *>());
Peter Collingbourne91147592011-04-15 00:35:48 +00004208}
4209
Bruno Ricci94498c72019-01-26 13:58:15 +00004210GenericSelectionExpr::GenericSelectionExpr(
4211 const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,
4212 ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
4213 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4214 bool ContainsUnexpandedParameterPack)
4215 : Expr(GenericSelectionExprClass, Context.DependentTy, VK_RValue,
4216 OK_Ordinary,
4217 /*isTypeDependent=*/true,
4218 /*isValueDependent=*/true,
4219 /*isInstantiationDependent=*/true, ContainsUnexpandedParameterPack),
4220 NumAssocs(AssocExprs.size()), ResultIndex(ResultDependentIndex),
Bruno Riccidb076832019-01-26 14:15:10 +00004221 DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
Bruno Ricci94498c72019-01-26 13:58:15 +00004222 assert(AssocTypes.size() == AssocExprs.size() &&
4223 "Must have the same number of association expressions"
4224 " and TypeSourceInfo!");
4225
Bruno Riccidb076832019-01-26 14:15:10 +00004226 GenericSelectionExprBits.GenericLoc = GenericLoc;
4227 getTrailingObjects<Stmt *>()[ControllingIndex] = ControllingExpr;
Bruno Ricci94498c72019-01-26 13:58:15 +00004228 std::copy(AssocExprs.begin(), AssocExprs.end(),
Bruno Riccidb076832019-01-26 14:15:10 +00004229 getTrailingObjects<Stmt *>() + AssocExprStartIndex);
4230 std::copy(AssocTypes.begin(), AssocTypes.end(),
4231 getTrailingObjects<TypeSourceInfo *>());
4232}
4233
4234GenericSelectionExpr::GenericSelectionExpr(EmptyShell Empty, unsigned NumAssocs)
4235 : Expr(GenericSelectionExprClass, Empty), NumAssocs(NumAssocs) {}
4236
4237GenericSelectionExpr *GenericSelectionExpr::Create(
4238 const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,
4239 ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
4240 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4241 bool ContainsUnexpandedParameterPack, unsigned ResultIndex) {
4242 unsigned NumAssocs = AssocExprs.size();
4243 void *Mem = Context.Allocate(
4244 totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
4245 alignof(GenericSelectionExpr));
4246 return new (Mem) GenericSelectionExpr(
4247 Context, GenericLoc, ControllingExpr, AssocTypes, AssocExprs, DefaultLoc,
4248 RParenLoc, ContainsUnexpandedParameterPack, ResultIndex);
4249}
4250
4251GenericSelectionExpr *GenericSelectionExpr::Create(
4252 const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,
4253 ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
4254 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4255 bool ContainsUnexpandedParameterPack) {
4256 unsigned NumAssocs = AssocExprs.size();
4257 void *Mem = Context.Allocate(
4258 totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
4259 alignof(GenericSelectionExpr));
4260 return new (Mem) GenericSelectionExpr(
4261 Context, GenericLoc, ControllingExpr, AssocTypes, AssocExprs, DefaultLoc,
4262 RParenLoc, ContainsUnexpandedParameterPack);
4263}
4264
4265GenericSelectionExpr *
4266GenericSelectionExpr::CreateEmpty(const ASTContext &Context,
4267 unsigned NumAssocs) {
4268 void *Mem = Context.Allocate(
4269 totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
4270 alignof(GenericSelectionExpr));
4271 return new (Mem) GenericSelectionExpr(EmptyShell(), NumAssocs);
Peter Collingbourne91147592011-04-15 00:35:48 +00004272}
4273
Ted Kremenek85e92ec2007-08-24 18:13:47 +00004274//===----------------------------------------------------------------------===//
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004275// DesignatedInitExpr
4276//===----------------------------------------------------------------------===//
4277
Chandler Carruth631abd92011-06-16 06:47:06 +00004278IdentifierInfo *DesignatedInitExpr::Designator::getFieldName() const {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004279 assert(Kind == FieldDesignator && "Only valid on a field designator");
4280 if (Field.NameOrField & 0x01)
4281 return reinterpret_cast<IdentifierInfo *>(Field.NameOrField&~0x01);
4282 else
4283 return getField()->getIdentifier();
4284}
4285
Craig Topper37932912013-08-18 10:09:15 +00004286DesignatedInitExpr::DesignatedInitExpr(const ASTContext &C, QualType Ty,
David Majnemerf7e36092016-06-23 00:15:04 +00004287 llvm::ArrayRef<Designator> Designators,
Mike Stump11289f42009-09-09 15:08:12 +00004288 SourceLocation EqualOrColonLoc,
Douglas Gregord5846a12009-04-15 06:41:24 +00004289 bool GNUSyntax,
Benjamin Kramerc215e762012-08-24 11:54:20 +00004290 ArrayRef<Expr*> IndexExprs,
Douglas Gregorca1aeec2009-05-21 23:17:49 +00004291 Expr *Init)
Mike Stump11289f42009-09-09 15:08:12 +00004292 : Expr(DesignatedInitExprClass, Ty,
John McCall7decc9e2010-11-18 06:31:45 +00004293 Init->getValueKind(), Init->getObjectKind(),
Douglas Gregora6e053e2010-12-15 01:34:56 +00004294 Init->isTypeDependent(), Init->isValueDependent(),
Douglas Gregor678d76c2011-07-01 01:22:09 +00004295 Init->isInstantiationDependent(),
Douglas Gregora6e053e2010-12-15 01:34:56 +00004296 Init->containsUnexpandedParameterPack()),
Mike Stump11289f42009-09-09 15:08:12 +00004297 EqualOrColonLoc(EqualOrColonLoc), GNUSyntax(GNUSyntax),
David Majnemerf7e36092016-06-23 00:15:04 +00004298 NumDesignators(Designators.size()), NumSubExprs(IndexExprs.size() + 1) {
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00004299 this->Designators = new (C) Designator[NumDesignators];
Douglas Gregorca1aeec2009-05-21 23:17:49 +00004300
4301 // Record the initializer itself.
Benjamin Kramer5733e352015-07-18 17:09:36 +00004302 child_iterator Child = child_begin();
Douglas Gregorca1aeec2009-05-21 23:17:49 +00004303 *Child++ = Init;
4304
4305 // Copy the designators and their subexpressions, computing
4306 // value-dependence along the way.
4307 unsigned IndexIdx = 0;
4308 for (unsigned I = 0; I != NumDesignators; ++I) {
Douglas Gregord5846a12009-04-15 06:41:24 +00004309 this->Designators[I] = Designators[I];
Douglas Gregorca1aeec2009-05-21 23:17:49 +00004310
4311 if (this->Designators[I].isArrayDesignator()) {
4312 // Compute type- and value-dependence.
4313 Expr *Index = IndexExprs[IndexIdx];
Douglas Gregora6e053e2010-12-15 01:34:56 +00004314 if (Index->isTypeDependent() || Index->isValueDependent())
David Majnemer4f217682015-01-09 01:39:09 +00004315 ExprBits.TypeDependent = ExprBits.ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +00004316 if (Index->isInstantiationDependent())
4317 ExprBits.InstantiationDependent = true;
Douglas Gregora6e053e2010-12-15 01:34:56 +00004318 // Propagate unexpanded parameter packs.
4319 if (Index->containsUnexpandedParameterPack())
4320 ExprBits.ContainsUnexpandedParameterPack = true;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00004321
4322 // Copy the index expressions into permanent storage.
4323 *Child++ = IndexExprs[IndexIdx++];
4324 } else if (this->Designators[I].isArrayRangeDesignator()) {
4325 // Compute type- and value-dependence.
4326 Expr *Start = IndexExprs[IndexIdx];
4327 Expr *End = IndexExprs[IndexIdx + 1];
Douglas Gregora6e053e2010-12-15 01:34:56 +00004328 if (Start->isTypeDependent() || Start->isValueDependent() ||
Douglas Gregor678d76c2011-07-01 01:22:09 +00004329 End->isTypeDependent() || End->isValueDependent()) {
David Majnemer4f217682015-01-09 01:39:09 +00004330 ExprBits.TypeDependent = ExprBits.ValueDependent = true;
Douglas Gregor678d76c2011-07-01 01:22:09 +00004331 ExprBits.InstantiationDependent = true;
Fangrui Song6907ce22018-07-30 19:24:48 +00004332 } else if (Start->isInstantiationDependent() ||
Douglas Gregor678d76c2011-07-01 01:22:09 +00004333 End->isInstantiationDependent()) {
4334 ExprBits.InstantiationDependent = true;
4335 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004336
Douglas Gregora6e053e2010-12-15 01:34:56 +00004337 // Propagate unexpanded parameter packs.
4338 if (Start->containsUnexpandedParameterPack() ||
4339 End->containsUnexpandedParameterPack())
4340 ExprBits.ContainsUnexpandedParameterPack = true;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00004341
4342 // Copy the start/end expressions into permanent storage.
4343 *Child++ = IndexExprs[IndexIdx++];
4344 *Child++ = IndexExprs[IndexIdx++];
4345 }
4346 }
4347
Benjamin Kramerc215e762012-08-24 11:54:20 +00004348 assert(IndexIdx == IndexExprs.size() && "Wrong number of index expressions");
Douglas Gregord5846a12009-04-15 06:41:24 +00004349}
4350
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004351DesignatedInitExpr *
David Majnemerf7e36092016-06-23 00:15:04 +00004352DesignatedInitExpr::Create(const ASTContext &C,
4353 llvm::ArrayRef<Designator> Designators,
Benjamin Kramerc215e762012-08-24 11:54:20 +00004354 ArrayRef<Expr*> IndexExprs,
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004355 SourceLocation ColonOrEqualLoc,
4356 bool UsesColonSyntax, Expr *Init) {
James Y Knighte00a67e2015-12-31 04:18:25 +00004357 void *Mem = C.Allocate(totalSizeToAlloc<Stmt *>(IndexExprs.size() + 1),
Benjamin Kramerc3f89252016-10-20 14:27:22 +00004358 alignof(DesignatedInitExpr));
David Majnemerf7e36092016-06-23 00:15:04 +00004359 return new (Mem) DesignatedInitExpr(C, C.VoidTy, Designators,
Douglas Gregorca1aeec2009-05-21 23:17:49 +00004360 ColonOrEqualLoc, UsesColonSyntax,
Benjamin Kramerc215e762012-08-24 11:54:20 +00004361 IndexExprs, Init);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004362}
4363
Craig Topper37932912013-08-18 10:09:15 +00004364DesignatedInitExpr *DesignatedInitExpr::CreateEmpty(const ASTContext &C,
Douglas Gregor38676d52009-04-16 00:55:48 +00004365 unsigned NumIndexExprs) {
James Y Knighte00a67e2015-12-31 04:18:25 +00004366 void *Mem = C.Allocate(totalSizeToAlloc<Stmt *>(NumIndexExprs + 1),
Benjamin Kramerc3f89252016-10-20 14:27:22 +00004367 alignof(DesignatedInitExpr));
Douglas Gregor38676d52009-04-16 00:55:48 +00004368 return new (Mem) DesignatedInitExpr(NumIndexExprs + 1);
4369}
4370
Craig Topper37932912013-08-18 10:09:15 +00004371void DesignatedInitExpr::setDesignators(const ASTContext &C,
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00004372 const Designator *Desigs,
Douglas Gregor38676d52009-04-16 00:55:48 +00004373 unsigned NumDesigs) {
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00004374 Designators = new (C) Designator[NumDesigs];
Douglas Gregor38676d52009-04-16 00:55:48 +00004375 NumDesignators = NumDesigs;
4376 for (unsigned I = 0; I != NumDesigs; ++I)
4377 Designators[I] = Desigs[I];
4378}
4379
Abramo Bagnara22f8cd72011-03-16 15:08:46 +00004380SourceRange DesignatedInitExpr::getDesignatorsSourceRange() const {
4381 DesignatedInitExpr *DIE = const_cast<DesignatedInitExpr*>(this);
4382 if (size() == 1)
4383 return DIE->getDesignator(0)->getSourceRange();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004384 return SourceRange(DIE->getDesignator(0)->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00004385 DIE->getDesignator(size() - 1)->getEndLoc());
Abramo Bagnara22f8cd72011-03-16 15:08:46 +00004386}
4387
Stephen Kelly724e9e52018-08-09 20:05:03 +00004388SourceLocation DesignatedInitExpr::getBeginLoc() const {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004389 SourceLocation StartLoc;
David Majnemerf7e36092016-06-23 00:15:04 +00004390 auto *DIE = const_cast<DesignatedInitExpr *>(this);
4391 Designator &First = *DIE->getDesignator(0);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004392 if (First.isFieldDesignator()) {
Douglas Gregor5c7c9cb2009-03-28 00:41:23 +00004393 if (GNUSyntax)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004394 StartLoc = SourceLocation::getFromRawEncoding(First.Field.FieldLoc);
4395 else
4396 StartLoc = SourceLocation::getFromRawEncoding(First.Field.DotLoc);
4397 } else
Chris Lattner8ba22472009-02-16 22:33:34 +00004398 StartLoc =
4399 SourceLocation::getFromRawEncoding(First.ArrayOrRange.LBracketLoc);
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +00004400 return StartLoc;
4401}
4402
Stephen Kelly02a67ba2018-08-09 20:05:47 +00004403SourceLocation DesignatedInitExpr::getEndLoc() const {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00004404 return getInit()->getEndLoc();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004405}
4406
Dmitri Gribenkod06f7ff2013-01-26 15:15:52 +00004407Expr *DesignatedInitExpr::getArrayIndex(const Designator& D) const {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004408 assert(D.Kind == Designator::ArrayDesignator && "Requires array designator");
James Y Knighte00a67e2015-12-31 04:18:25 +00004409 return getSubExpr(D.ArrayOrRange.Index + 1);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004410}
4411
Dmitri Gribenkod06f7ff2013-01-26 15:15:52 +00004412Expr *DesignatedInitExpr::getArrayRangeStart(const Designator &D) const {
Mike Stump11289f42009-09-09 15:08:12 +00004413 assert(D.Kind == Designator::ArrayRangeDesignator &&
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004414 "Requires array range designator");
James Y Knighte00a67e2015-12-31 04:18:25 +00004415 return getSubExpr(D.ArrayOrRange.Index + 1);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004416}
4417
Dmitri Gribenkod06f7ff2013-01-26 15:15:52 +00004418Expr *DesignatedInitExpr::getArrayRangeEnd(const Designator &D) const {
Mike Stump11289f42009-09-09 15:08:12 +00004419 assert(D.Kind == Designator::ArrayRangeDesignator &&
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004420 "Requires array range designator");
James Y Knighte00a67e2015-12-31 04:18:25 +00004421 return getSubExpr(D.ArrayOrRange.Index + 2);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004422}
4423
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004424/// Replaces the designator at index @p Idx with the series
Douglas Gregord5846a12009-04-15 06:41:24 +00004425/// of designators in [First, Last).
Craig Topper37932912013-08-18 10:09:15 +00004426void DesignatedInitExpr::ExpandDesignator(const ASTContext &C, unsigned Idx,
Mike Stump11289f42009-09-09 15:08:12 +00004427 const Designator *First,
Douglas Gregord5846a12009-04-15 06:41:24 +00004428 const Designator *Last) {
4429 unsigned NumNewDesignators = Last - First;
4430 if (NumNewDesignators == 0) {
4431 std::copy_backward(Designators + Idx + 1,
4432 Designators + NumDesignators,
4433 Designators + Idx);
4434 --NumNewDesignators;
4435 return;
4436 } else if (NumNewDesignators == 1) {
4437 Designators[Idx] = *First;
4438 return;
4439 }
4440
Mike Stump11289f42009-09-09 15:08:12 +00004441 Designator *NewDesignators
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00004442 = new (C) Designator[NumDesignators - 1 + NumNewDesignators];
Douglas Gregord5846a12009-04-15 06:41:24 +00004443 std::copy(Designators, Designators + Idx, NewDesignators);
4444 std::copy(First, Last, NewDesignators + Idx);
4445 std::copy(Designators + Idx + 1, Designators + NumDesignators,
4446 NewDesignators + Idx + NumNewDesignators);
Douglas Gregord5846a12009-04-15 06:41:24 +00004447 Designators = NewDesignators;
4448 NumDesignators = NumDesignators - 1 + NumNewDesignators;
4449}
4450
Yunzhong Gaocb779302015-06-10 00:27:52 +00004451DesignatedInitUpdateExpr::DesignatedInitUpdateExpr(const ASTContext &C,
4452 SourceLocation lBraceLoc, Expr *baseExpr, SourceLocation rBraceLoc)
4453 : Expr(DesignatedInitUpdateExprClass, baseExpr->getType(), VK_RValue,
4454 OK_Ordinary, false, false, false, false) {
4455 BaseAndUpdaterExprs[0] = baseExpr;
4456
4457 InitListExpr *ILE = new (C) InitListExpr(C, lBraceLoc, None, rBraceLoc);
4458 ILE->setType(baseExpr->getType());
4459 BaseAndUpdaterExprs[1] = ILE;
4460}
4461
Stephen Kelly724e9e52018-08-09 20:05:03 +00004462SourceLocation DesignatedInitUpdateExpr::getBeginLoc() const {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004463 return getBase()->getBeginLoc();
Yunzhong Gaocb779302015-06-10 00:27:52 +00004464}
4465
Stephen Kelly02a67ba2018-08-09 20:05:47 +00004466SourceLocation DesignatedInitUpdateExpr::getEndLoc() const {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00004467 return getBase()->getEndLoc();
Yunzhong Gaocb779302015-06-10 00:27:52 +00004468}
4469
Bruno Riccif49e1ca2018-11-20 16:20:40 +00004470ParenListExpr::ParenListExpr(SourceLocation LParenLoc, ArrayRef<Expr *> Exprs,
4471 SourceLocation RParenLoc)
4472 : Expr(ParenListExprClass, QualType(), VK_RValue, OK_Ordinary, false, false,
4473 false, false),
4474 LParenLoc(LParenLoc), RParenLoc(RParenLoc) {
4475 ParenListExprBits.NumExprs = Exprs.size();
4476
4477 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
4478 if (Exprs[I]->isTypeDependent())
Douglas Gregora6e053e2010-12-15 01:34:56 +00004479 ExprBits.TypeDependent = true;
Bruno Riccif49e1ca2018-11-20 16:20:40 +00004480 if (Exprs[I]->isValueDependent())
Douglas Gregora6e053e2010-12-15 01:34:56 +00004481 ExprBits.ValueDependent = true;
Bruno Riccif49e1ca2018-11-20 16:20:40 +00004482 if (Exprs[I]->isInstantiationDependent())
Douglas Gregor678d76c2011-07-01 01:22:09 +00004483 ExprBits.InstantiationDependent = true;
Bruno Riccif49e1ca2018-11-20 16:20:40 +00004484 if (Exprs[I]->containsUnexpandedParameterPack())
Douglas Gregora6e053e2010-12-15 01:34:56 +00004485 ExprBits.ContainsUnexpandedParameterPack = true;
4486
Bruno Riccif49e1ca2018-11-20 16:20:40 +00004487 getTrailingObjects<Stmt *>()[I] = Exprs[I];
Douglas Gregora6e053e2010-12-15 01:34:56 +00004488 }
Nate Begeman5ec4b312009-08-10 23:49:36 +00004489}
4490
Bruno Riccif49e1ca2018-11-20 16:20:40 +00004491ParenListExpr::ParenListExpr(EmptyShell Empty, unsigned NumExprs)
4492 : Expr(ParenListExprClass, Empty) {
4493 ParenListExprBits.NumExprs = NumExprs;
4494}
4495
4496ParenListExpr *ParenListExpr::Create(const ASTContext &Ctx,
4497 SourceLocation LParenLoc,
4498 ArrayRef<Expr *> Exprs,
4499 SourceLocation RParenLoc) {
4500 void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *>(Exprs.size()),
4501 alignof(ParenListExpr));
4502 return new (Mem) ParenListExpr(LParenLoc, Exprs, RParenLoc);
4503}
4504
4505ParenListExpr *ParenListExpr::CreateEmpty(const ASTContext &Ctx,
4506 unsigned NumExprs) {
4507 void *Mem =
4508 Ctx.Allocate(totalSizeToAlloc<Stmt *>(NumExprs), alignof(ParenListExpr));
4509 return new (Mem) ParenListExpr(EmptyShell(), NumExprs);
4510}
4511
John McCall1bf58462011-02-16 08:02:54 +00004512const OpaqueValueExpr *OpaqueValueExpr::findInCopyConstruct(const Expr *e) {
4513 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(e))
4514 e = ewc->getSubExpr();
Douglas Gregorfe314812011-06-21 17:03:29 +00004515 if (const MaterializeTemporaryExpr *m = dyn_cast<MaterializeTemporaryExpr>(e))
Tykerb0561b32019-11-17 11:41:55 +01004516 e = m->getSubExpr();
John McCall1bf58462011-02-16 08:02:54 +00004517 e = cast<CXXConstructExpr>(e)->getArg(0);
4518 while (const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
4519 e = ice->getSubExpr();
4520 return cast<OpaqueValueExpr>(e);
4521}
4522
Craig Topper37932912013-08-18 10:09:15 +00004523PseudoObjectExpr *PseudoObjectExpr::Create(const ASTContext &Context,
4524 EmptyShell sh,
John McCallfe96e0b2011-11-06 09:01:30 +00004525 unsigned numSemanticExprs) {
James Y Knighte00a67e2015-12-31 04:18:25 +00004526 void *buffer =
4527 Context.Allocate(totalSizeToAlloc<Expr *>(1 + numSemanticExprs),
Benjamin Kramerc3f89252016-10-20 14:27:22 +00004528 alignof(PseudoObjectExpr));
John McCallfe96e0b2011-11-06 09:01:30 +00004529 return new(buffer) PseudoObjectExpr(sh, numSemanticExprs);
4530}
4531
4532PseudoObjectExpr::PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs)
4533 : Expr(PseudoObjectExprClass, shell) {
4534 PseudoObjectExprBits.NumSubExprs = numSemanticExprs + 1;
4535}
4536
Craig Topper37932912013-08-18 10:09:15 +00004537PseudoObjectExpr *PseudoObjectExpr::Create(const ASTContext &C, Expr *syntax,
John McCallfe96e0b2011-11-06 09:01:30 +00004538 ArrayRef<Expr*> semantics,
4539 unsigned resultIndex) {
4540 assert(syntax && "no syntactic expression!");
Eugene Zelenkoae304b02017-11-17 18:09:48 +00004541 assert(semantics.size() && "no semantic expressions!");
John McCallfe96e0b2011-11-06 09:01:30 +00004542
4543 QualType type;
4544 ExprValueKind VK;
4545 if (resultIndex == NoResult) {
4546 type = C.VoidTy;
4547 VK = VK_RValue;
4548 } else {
4549 assert(resultIndex < semantics.size());
4550 type = semantics[resultIndex]->getType();
4551 VK = semantics[resultIndex]->getValueKind();
4552 assert(semantics[resultIndex]->getObjectKind() == OK_Ordinary);
4553 }
4554
James Y Knighte00a67e2015-12-31 04:18:25 +00004555 void *buffer = C.Allocate(totalSizeToAlloc<Expr *>(semantics.size() + 1),
Benjamin Kramerc3f89252016-10-20 14:27:22 +00004556 alignof(PseudoObjectExpr));
John McCallfe96e0b2011-11-06 09:01:30 +00004557 return new(buffer) PseudoObjectExpr(type, VK, syntax, semantics,
4558 resultIndex);
4559}
4560
4561PseudoObjectExpr::PseudoObjectExpr(QualType type, ExprValueKind VK,
4562 Expr *syntax, ArrayRef<Expr*> semantics,
4563 unsigned resultIndex)
4564 : Expr(PseudoObjectExprClass, type, VK, OK_Ordinary,
4565 /*filled in at end of ctor*/ false, false, false, false) {
4566 PseudoObjectExprBits.NumSubExprs = semantics.size() + 1;
4567 PseudoObjectExprBits.ResultIndex = resultIndex + 1;
4568
4569 for (unsigned i = 0, e = semantics.size() + 1; i != e; ++i) {
4570 Expr *E = (i == 0 ? syntax : semantics[i-1]);
4571 getSubExprsBuffer()[i] = E;
4572
4573 if (E->isTypeDependent())
4574 ExprBits.TypeDependent = true;
4575 if (E->isValueDependent())
4576 ExprBits.ValueDependent = true;
4577 if (E->isInstantiationDependent())
4578 ExprBits.InstantiationDependent = true;
4579 if (E->containsUnexpandedParameterPack())
4580 ExprBits.ContainsUnexpandedParameterPack = true;
4581
4582 if (isa<OpaqueValueExpr>(E))
Craig Topper36250ad2014-05-12 05:36:57 +00004583 assert(cast<OpaqueValueExpr>(E)->getSourceExpr() != nullptr &&
John McCallfe96e0b2011-11-06 09:01:30 +00004584 "opaque-value semantic expressions for pseudo-object "
4585 "operations must have sources");
4586 }
4587}
4588
Douglas Gregore4a0bb72009-01-22 00:58:24 +00004589//===----------------------------------------------------------------------===//
Ted Kremenek85e92ec2007-08-24 18:13:47 +00004590// Child Iterators for iterating over subexpressions/substatements
4591//===----------------------------------------------------------------------===//
4592
Peter Collingbournee190dee2011-03-11 19:24:49 +00004593// UnaryExprOrTypeTraitExpr
4594Stmt::child_range UnaryExprOrTypeTraitExpr::children() {
Aaron Ballman4c54fe02017-04-11 20:21:30 +00004595 const_child_range CCR =
4596 const_cast<const UnaryExprOrTypeTraitExpr *>(this)->children();
4597 return child_range(cast_away_const(CCR.begin()), cast_away_const(CCR.end()));
4598}
4599
4600Stmt::const_child_range UnaryExprOrTypeTraitExpr::children() const {
Sebastian Redl6f282892008-11-11 17:56:53 +00004601 // If this is of a type and the type is a VLA type (and not a typedef), the
4602 // size expression of the VLA needs to be treated as an executable expression.
4603 // Why isn't this weirdness documented better in StmtIterator?
4604 if (isArgumentType()) {
Aaron Ballman4c54fe02017-04-11 20:21:30 +00004605 if (const VariableArrayType *T =
4606 dyn_cast<VariableArrayType>(getArgumentType().getTypePtr()))
4607 return const_child_range(const_child_iterator(T), const_child_iterator());
4608 return const_child_range(const_child_iterator(), const_child_iterator());
Sebastian Redl6f282892008-11-11 17:56:53 +00004609 }
Aaron Ballman4c54fe02017-04-11 20:21:30 +00004610 return const_child_range(&Argument.Ex, &Argument.Ex + 1);
Ted Kremenek04746ce2007-10-18 23:28:49 +00004611}
Fariborz Jahaniana32aaef2007-10-17 16:58:11 +00004612
Benjamin Kramerc215e762012-08-24 11:54:20 +00004613AtomicExpr::AtomicExpr(SourceLocation BLoc, ArrayRef<Expr*> args,
Eli Friedman8d3e43f2011-10-14 22:48:56 +00004614 QualType t, AtomicOp op, SourceLocation RP)
Eugene Zelenkoae304b02017-11-17 18:09:48 +00004615 : Expr(AtomicExprClass, t, VK_RValue, OK_Ordinary,
4616 false, false, false, false),
4617 NumSubExprs(args.size()), BuiltinLoc(BLoc), RParenLoc(RP), Op(op)
4618{
Benjamin Kramerc215e762012-08-24 11:54:20 +00004619 assert(args.size() == getNumSubExprs(op) && "wrong number of subexpressions");
4620 for (unsigned i = 0; i != args.size(); i++) {
Eli Friedman8d3e43f2011-10-14 22:48:56 +00004621 if (args[i]->isTypeDependent())
4622 ExprBits.TypeDependent = true;
4623 if (args[i]->isValueDependent())
4624 ExprBits.ValueDependent = true;
4625 if (args[i]->isInstantiationDependent())
4626 ExprBits.InstantiationDependent = true;
4627 if (args[i]->containsUnexpandedParameterPack())
4628 ExprBits.ContainsUnexpandedParameterPack = true;
4629
4630 SubExprs[i] = args[i];
4631 }
4632}
Richard Smithaa22a8c2012-04-10 22:49:28 +00004633
4634unsigned AtomicExpr::getNumSubExprs(AtomicOp Op) {
4635 switch (Op) {
Richard Smithfeea8832012-04-12 05:08:17 +00004636 case AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +00004637 case AO__opencl_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +00004638 case AO__c11_atomic_load:
Yaxun Liu39195062017-08-04 18:16:31 +00004639 case AO__atomic_load_n:
Yaxun Liu30d652a2017-08-15 16:02:49 +00004640 return 2;
Richard Smithfeea8832012-04-12 05:08:17 +00004641
Yaxun Liu30d652a2017-08-15 16:02:49 +00004642 case AO__opencl_atomic_load:
Richard Smithfeea8832012-04-12 05:08:17 +00004643 case AO__c11_atomic_store:
4644 case AO__c11_atomic_exchange:
4645 case AO__atomic_load:
4646 case AO__atomic_store:
4647 case AO__atomic_store_n:
4648 case AO__atomic_exchange_n:
4649 case AO__c11_atomic_fetch_add:
4650 case AO__c11_atomic_fetch_sub:
4651 case AO__c11_atomic_fetch_and:
4652 case AO__c11_atomic_fetch_or:
4653 case AO__c11_atomic_fetch_xor:
Tim Northover5cf58762019-11-21 10:31:30 +00004654 case AO__c11_atomic_fetch_max:
4655 case AO__c11_atomic_fetch_min:
Richard Smithfeea8832012-04-12 05:08:17 +00004656 case AO__atomic_fetch_add:
4657 case AO__atomic_fetch_sub:
4658 case AO__atomic_fetch_and:
4659 case AO__atomic_fetch_or:
4660 case AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00004661 case AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00004662 case AO__atomic_add_fetch:
4663 case AO__atomic_sub_fetch:
4664 case AO__atomic_and_fetch:
4665 case AO__atomic_or_fetch:
4666 case AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00004667 case AO__atomic_nand_fetch:
Tim Northover5cf58762019-11-21 10:31:30 +00004668 case AO__atomic_min_fetch:
4669 case AO__atomic_max_fetch:
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00004670 case AO__atomic_fetch_min:
4671 case AO__atomic_fetch_max:
Yaxun Liu30d652a2017-08-15 16:02:49 +00004672 return 3;
Richard Smithfeea8832012-04-12 05:08:17 +00004673
Yaxun Liu30d652a2017-08-15 16:02:49 +00004674 case AO__opencl_atomic_store:
4675 case AO__opencl_atomic_exchange:
4676 case AO__opencl_atomic_fetch_add:
4677 case AO__opencl_atomic_fetch_sub:
4678 case AO__opencl_atomic_fetch_and:
4679 case AO__opencl_atomic_fetch_or:
4680 case AO__opencl_atomic_fetch_xor:
4681 case AO__opencl_atomic_fetch_min:
4682 case AO__opencl_atomic_fetch_max:
Richard Smithfeea8832012-04-12 05:08:17 +00004683 case AO__atomic_exchange:
Yaxun Liu30d652a2017-08-15 16:02:49 +00004684 return 4;
Richard Smithfeea8832012-04-12 05:08:17 +00004685
4686 case AO__c11_atomic_compare_exchange_strong:
4687 case AO__c11_atomic_compare_exchange_weak:
Yaxun Liu30d652a2017-08-15 16:02:49 +00004688 return 5;
4689
Yaxun Liu39195062017-08-04 18:16:31 +00004690 case AO__opencl_atomic_compare_exchange_strong:
4691 case AO__opencl_atomic_compare_exchange_weak:
Richard Smithfeea8832012-04-12 05:08:17 +00004692 case AO__atomic_compare_exchange:
4693 case AO__atomic_compare_exchange_n:
Yaxun Liu30d652a2017-08-15 16:02:49 +00004694 return 6;
Richard Smithaa22a8c2012-04-10 22:49:28 +00004695 }
4696 llvm_unreachable("unknown atomic op");
4697}
Alexey Bataeva1764212015-09-30 09:22:36 +00004698
Yaxun Liu39195062017-08-04 18:16:31 +00004699QualType AtomicExpr::getValueType() const {
4700 auto T = getPtr()->getType()->castAs<PointerType>()->getPointeeType();
4701 if (auto AT = T->getAs<AtomicType>())
4702 return AT->getValueType();
4703 return T;
4704}
4705
Alexey Bataev31300ed2016-02-04 11:27:03 +00004706QualType OMPArraySectionExpr::getBaseOriginalType(const Expr *Base) {
Alexey Bataeva1764212015-09-30 09:22:36 +00004707 unsigned ArraySectionCount = 0;
4708 while (auto *OASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParens())) {
4709 Base = OASE->getBase();
4710 ++ArraySectionCount;
4711 }
Alexey Bataev31300ed2016-02-04 11:27:03 +00004712 while (auto *ASE =
4713 dyn_cast<ArraySubscriptExpr>(Base->IgnoreParenImpCasts())) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004714 Base = ASE->getBase();
4715 ++ArraySectionCount;
4716 }
Alexey Bataev31300ed2016-02-04 11:27:03 +00004717 Base = Base->IgnoreParenImpCasts();
Alexey Bataeva1764212015-09-30 09:22:36 +00004718 auto OriginalTy = Base->getType();
4719 if (auto *DRE = dyn_cast<DeclRefExpr>(Base))
4720 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
4721 OriginalTy = PVD->getOriginalType().getNonReferenceType();
4722
4723 for (unsigned Cnt = 0; Cnt < ArraySectionCount; ++Cnt) {
4724 if (OriginalTy->isAnyPointerType())
4725 OriginalTy = OriginalTy->getPointeeType();
4726 else {
Eugene Zelenkoae304b02017-11-17 18:09:48 +00004727 assert (OriginalTy->isArrayType());
Alexey Bataeva1764212015-09-30 09:22:36 +00004728 OriginalTy = OriginalTy->castAsArrayTypeUnsafe()->getElementType();
4729 }
4730 }
4731 return OriginalTy;
4732}