[clang-tidy][NFC]remove deps of clang in clang tidy test (#116588)
[llvm-project.git] / clang / lib / AST / Expr.cpp
bloba4fb4d5a1f2ec419c5875c22fc0feba1e6f19a42
1 //===--- Expr.cpp - Expression AST Node Implementation --------------------===//
2 //
3 // 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
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the Expr class and subclasses.
11 //===----------------------------------------------------------------------===//
13 #include "clang/AST/Expr.h"
14 #include "clang/AST/APValue.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTLambda.h"
17 #include "clang/AST/Attr.h"
18 #include "clang/AST/ComputeDependence.h"
19 #include "clang/AST/DeclCXX.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/DependenceFlags.h"
23 #include "clang/AST/EvaluatedExprVisitor.h"
24 #include "clang/AST/ExprCXX.h"
25 #include "clang/AST/IgnoreExpr.h"
26 #include "clang/AST/Mangle.h"
27 #include "clang/AST/RecordLayout.h"
28 #include "clang/Basic/Builtins.h"
29 #include "clang/Basic/CharInfo.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Lex/Lexer.h"
33 #include "clang/Lex/LiteralSupport.h"
34 #include "clang/Lex/Preprocessor.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/Format.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include <algorithm>
39 #include <cstring>
40 #include <optional>
41 using namespace clang;
43 const Expr *Expr::getBestDynamicClassTypeExpr() const {
44 const Expr *E = this;
45 while (true) {
46 E = E->IgnoreParenBaseCasts();
48 // Follow the RHS of a comma operator.
49 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
50 if (BO->getOpcode() == BO_Comma) {
51 E = BO->getRHS();
52 continue;
56 // Step into initializer for materialized temporaries.
57 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
58 E = MTE->getSubExpr();
59 continue;
62 break;
65 return E;
68 const CXXRecordDecl *Expr::getBestDynamicClassType() const {
69 const Expr *E = getBestDynamicClassTypeExpr();
70 QualType DerivedType = E->getType();
71 if (const PointerType *PTy = DerivedType->getAs<PointerType>())
72 DerivedType = PTy->getPointeeType();
74 if (DerivedType->isDependentType())
75 return nullptr;
77 const RecordType *Ty = DerivedType->castAs<RecordType>();
78 Decl *D = Ty->getDecl();
79 return cast<CXXRecordDecl>(D);
82 const Expr *Expr::skipRValueSubobjectAdjustments(
83 SmallVectorImpl<const Expr *> &CommaLHSs,
84 SmallVectorImpl<SubobjectAdjustment> &Adjustments) const {
85 const Expr *E = this;
86 while (true) {
87 E = E->IgnoreParens();
89 if (const auto *CE = dyn_cast<CastExpr>(E)) {
90 if ((CE->getCastKind() == CK_DerivedToBase ||
91 CE->getCastKind() == CK_UncheckedDerivedToBase) &&
92 E->getType()->isRecordType()) {
93 E = CE->getSubExpr();
94 const auto *Derived =
95 cast<CXXRecordDecl>(E->getType()->castAs<RecordType>()->getDecl());
96 Adjustments.push_back(SubobjectAdjustment(CE, Derived));
97 continue;
100 if (CE->getCastKind() == CK_NoOp) {
101 E = CE->getSubExpr();
102 continue;
104 } else if (const auto *ME = dyn_cast<MemberExpr>(E)) {
105 if (!ME->isArrow()) {
106 assert(ME->getBase()->getType()->getAsRecordDecl());
107 if (const auto *Field = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
108 if (!Field->isBitField() && !Field->getType()->isReferenceType()) {
109 E = ME->getBase();
110 Adjustments.push_back(SubobjectAdjustment(Field));
111 continue;
115 } else if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
116 if (BO->getOpcode() == BO_PtrMemD) {
117 assert(BO->getRHS()->isPRValue());
118 E = BO->getLHS();
119 const auto *MPT = BO->getRHS()->getType()->getAs<MemberPointerType>();
120 Adjustments.push_back(SubobjectAdjustment(MPT, BO->getRHS()));
121 continue;
123 if (BO->getOpcode() == BO_Comma) {
124 CommaLHSs.push_back(BO->getLHS());
125 E = BO->getRHS();
126 continue;
130 // Nothing changed.
131 break;
133 return E;
136 bool Expr::isKnownToHaveBooleanValue(bool Semantic) const {
137 const Expr *E = IgnoreParens();
139 // If this value has _Bool type, it is obvious 0/1.
140 if (E->getType()->isBooleanType()) return true;
141 // If this is a non-scalar-integer type, we don't care enough to try.
142 if (!E->getType()->isIntegralOrEnumerationType()) return false;
144 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
145 switch (UO->getOpcode()) {
146 case UO_Plus:
147 return UO->getSubExpr()->isKnownToHaveBooleanValue(Semantic);
148 case UO_LNot:
149 return true;
150 default:
151 return false;
155 // Only look through implicit casts. If the user writes
156 // '(int) (a && b)' treat it as an arbitrary int.
157 // FIXME: Should we look through any cast expression in !Semantic mode?
158 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
159 return CE->getSubExpr()->isKnownToHaveBooleanValue(Semantic);
161 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
162 switch (BO->getOpcode()) {
163 default: return false;
164 case BO_LT: // Relational operators.
165 case BO_GT:
166 case BO_LE:
167 case BO_GE:
168 case BO_EQ: // Equality operators.
169 case BO_NE:
170 case BO_LAnd: // AND operator.
171 case BO_LOr: // Logical OR operator.
172 return true;
174 case BO_And: // Bitwise AND operator.
175 case BO_Xor: // Bitwise XOR operator.
176 case BO_Or: // Bitwise OR operator.
177 // Handle things like (x==2)|(y==12).
178 return BO->getLHS()->isKnownToHaveBooleanValue(Semantic) &&
179 BO->getRHS()->isKnownToHaveBooleanValue(Semantic);
181 case BO_Comma:
182 case BO_Assign:
183 return BO->getRHS()->isKnownToHaveBooleanValue(Semantic);
187 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
188 return CO->getTrueExpr()->isKnownToHaveBooleanValue(Semantic) &&
189 CO->getFalseExpr()->isKnownToHaveBooleanValue(Semantic);
191 if (isa<ObjCBoolLiteralExpr>(E))
192 return true;
194 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
195 return OVE->getSourceExpr()->isKnownToHaveBooleanValue(Semantic);
197 if (const FieldDecl *FD = E->getSourceBitField())
198 if (!Semantic && FD->getType()->isUnsignedIntegerType() &&
199 !FD->getBitWidth()->isValueDependent() &&
200 FD->getBitWidthValue(FD->getASTContext()) == 1)
201 return true;
203 return false;
206 bool Expr::isFlexibleArrayMemberLike(
207 ASTContext &Ctx,
208 LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel,
209 bool IgnoreTemplateOrMacroSubstitution) const {
210 const Expr *E = IgnoreParens();
211 const Decl *D = nullptr;
213 if (const auto *ME = dyn_cast<MemberExpr>(E))
214 D = ME->getMemberDecl();
215 else if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
216 D = DRE->getDecl();
217 else if (const auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
218 D = IRE->getDecl();
220 return Decl::isFlexibleArrayMemberLike(Ctx, D, E->getType(),
221 StrictFlexArraysLevel,
222 IgnoreTemplateOrMacroSubstitution);
225 const ValueDecl *
226 Expr::getAsBuiltinConstantDeclRef(const ASTContext &Context) const {
227 Expr::EvalResult Eval;
229 if (EvaluateAsConstantExpr(Eval, Context)) {
230 APValue &Value = Eval.Val;
232 if (Value.isMemberPointer())
233 return Value.getMemberPointerDecl();
235 if (Value.isLValue() && Value.getLValueOffset().isZero())
236 return Value.getLValueBase().dyn_cast<const ValueDecl *>();
239 return nullptr;
242 // Amusing macro metaprogramming hack: check whether a class provides
243 // a more specific implementation of getExprLoc().
245 // See also Stmt.cpp:{getBeginLoc(),getEndLoc()}.
246 namespace {
247 /// This implementation is used when a class provides a custom
248 /// implementation of getExprLoc.
249 template <class E, class T>
250 SourceLocation getExprLocImpl(const Expr *expr,
251 SourceLocation (T::*v)() const) {
252 return static_cast<const E*>(expr)->getExprLoc();
255 /// This implementation is used when a class doesn't provide
256 /// a custom implementation of getExprLoc. Overload resolution
257 /// should pick it over the implementation above because it's
258 /// more specialized according to function template partial ordering.
259 template <class E>
260 SourceLocation getExprLocImpl(const Expr *expr,
261 SourceLocation (Expr::*v)() const) {
262 return static_cast<const E *>(expr)->getBeginLoc();
266 QualType Expr::getEnumCoercedType(const ASTContext &Ctx) const {
267 if (isa<EnumType>(getType()))
268 return getType();
269 if (const auto *ECD = getEnumConstantDecl()) {
270 const auto *ED = cast<EnumDecl>(ECD->getDeclContext());
271 if (ED->isCompleteDefinition())
272 return Ctx.getTypeDeclType(ED);
274 return getType();
277 SourceLocation Expr::getExprLoc() const {
278 switch (getStmtClass()) {
279 case Stmt::NoStmtClass: llvm_unreachable("statement without class");
280 #define ABSTRACT_STMT(type)
281 #define STMT(type, base) \
282 case Stmt::type##Class: break;
283 #define EXPR(type, base) \
284 case Stmt::type##Class: return getExprLocImpl<type>(this, &type::getExprLoc);
285 #include "clang/AST/StmtNodes.inc"
287 llvm_unreachable("unknown expression kind");
290 //===----------------------------------------------------------------------===//
291 // Primary Expressions.
292 //===----------------------------------------------------------------------===//
294 static void AssertResultStorageKind(ConstantResultStorageKind Kind) {
295 assert((Kind == ConstantResultStorageKind::APValue ||
296 Kind == ConstantResultStorageKind::Int64 ||
297 Kind == ConstantResultStorageKind::None) &&
298 "Invalid StorageKind Value");
299 (void)Kind;
302 ConstantResultStorageKind ConstantExpr::getStorageKind(const APValue &Value) {
303 switch (Value.getKind()) {
304 case APValue::None:
305 case APValue::Indeterminate:
306 return ConstantResultStorageKind::None;
307 case APValue::Int:
308 if (!Value.getInt().needsCleanup())
309 return ConstantResultStorageKind::Int64;
310 [[fallthrough]];
311 default:
312 return ConstantResultStorageKind::APValue;
316 ConstantResultStorageKind
317 ConstantExpr::getStorageKind(const Type *T, const ASTContext &Context) {
318 if (T->isIntegralOrEnumerationType() && Context.getTypeInfo(T).Width <= 64)
319 return ConstantResultStorageKind::Int64;
320 return ConstantResultStorageKind::APValue;
323 ConstantExpr::ConstantExpr(Expr *SubExpr, ConstantResultStorageKind StorageKind,
324 bool IsImmediateInvocation)
325 : FullExpr(ConstantExprClass, SubExpr) {
326 ConstantExprBits.ResultKind = llvm::to_underlying(StorageKind);
327 ConstantExprBits.APValueKind = APValue::None;
328 ConstantExprBits.IsUnsigned = false;
329 ConstantExprBits.BitWidth = 0;
330 ConstantExprBits.HasCleanup = false;
331 ConstantExprBits.IsImmediateInvocation = IsImmediateInvocation;
333 if (StorageKind == ConstantResultStorageKind::APValue)
334 ::new (getTrailingObjects<APValue>()) APValue();
337 ConstantExpr *ConstantExpr::Create(const ASTContext &Context, Expr *E,
338 ConstantResultStorageKind StorageKind,
339 bool IsImmediateInvocation) {
340 assert(!isa<ConstantExpr>(E));
341 AssertResultStorageKind(StorageKind);
343 unsigned Size = totalSizeToAlloc<APValue, uint64_t>(
344 StorageKind == ConstantResultStorageKind::APValue,
345 StorageKind == ConstantResultStorageKind::Int64);
346 void *Mem = Context.Allocate(Size, alignof(ConstantExpr));
347 return new (Mem) ConstantExpr(E, StorageKind, IsImmediateInvocation);
350 ConstantExpr *ConstantExpr::Create(const ASTContext &Context, Expr *E,
351 const APValue &Result) {
352 ConstantResultStorageKind StorageKind = getStorageKind(Result);
353 ConstantExpr *Self = Create(Context, E, StorageKind);
354 Self->SetResult(Result, Context);
355 return Self;
358 ConstantExpr::ConstantExpr(EmptyShell Empty,
359 ConstantResultStorageKind StorageKind)
360 : FullExpr(ConstantExprClass, Empty) {
361 ConstantExprBits.ResultKind = llvm::to_underlying(StorageKind);
363 if (StorageKind == ConstantResultStorageKind::APValue)
364 ::new (getTrailingObjects<APValue>()) APValue();
367 ConstantExpr *ConstantExpr::CreateEmpty(const ASTContext &Context,
368 ConstantResultStorageKind StorageKind) {
369 AssertResultStorageKind(StorageKind);
371 unsigned Size = totalSizeToAlloc<APValue, uint64_t>(
372 StorageKind == ConstantResultStorageKind::APValue,
373 StorageKind == ConstantResultStorageKind::Int64);
374 void *Mem = Context.Allocate(Size, alignof(ConstantExpr));
375 return new (Mem) ConstantExpr(EmptyShell(), StorageKind);
378 void ConstantExpr::MoveIntoResult(APValue &Value, const ASTContext &Context) {
379 assert((unsigned)getStorageKind(Value) <= ConstantExprBits.ResultKind &&
380 "Invalid storage for this value kind");
381 ConstantExprBits.APValueKind = Value.getKind();
382 switch (getResultStorageKind()) {
383 case ConstantResultStorageKind::None:
384 return;
385 case ConstantResultStorageKind::Int64:
386 Int64Result() = *Value.getInt().getRawData();
387 ConstantExprBits.BitWidth = Value.getInt().getBitWidth();
388 ConstantExprBits.IsUnsigned = Value.getInt().isUnsigned();
389 return;
390 case ConstantResultStorageKind::APValue:
391 if (!ConstantExprBits.HasCleanup && Value.needsCleanup()) {
392 ConstantExprBits.HasCleanup = true;
393 Context.addDestruction(&APValueResult());
395 APValueResult() = std::move(Value);
396 return;
398 llvm_unreachable("Invalid ResultKind Bits");
401 llvm::APSInt ConstantExpr::getResultAsAPSInt() const {
402 switch (getResultStorageKind()) {
403 case ConstantResultStorageKind::APValue:
404 return APValueResult().getInt();
405 case ConstantResultStorageKind::Int64:
406 return llvm::APSInt(llvm::APInt(ConstantExprBits.BitWidth, Int64Result()),
407 ConstantExprBits.IsUnsigned);
408 default:
409 llvm_unreachable("invalid Accessor");
413 APValue ConstantExpr::getAPValueResult() const {
415 switch (getResultStorageKind()) {
416 case ConstantResultStorageKind::APValue:
417 return APValueResult();
418 case ConstantResultStorageKind::Int64:
419 return APValue(
420 llvm::APSInt(llvm::APInt(ConstantExprBits.BitWidth, Int64Result()),
421 ConstantExprBits.IsUnsigned));
422 case ConstantResultStorageKind::None:
423 if (ConstantExprBits.APValueKind == APValue::Indeterminate)
424 return APValue::IndeterminateValue();
425 return APValue();
427 llvm_unreachable("invalid ResultKind");
430 DeclRefExpr::DeclRefExpr(const ASTContext &Ctx, ValueDecl *D,
431 bool RefersToEnclosingVariableOrCapture, QualType T,
432 ExprValueKind VK, SourceLocation L,
433 const DeclarationNameLoc &LocInfo,
434 NonOdrUseReason NOUR)
435 : Expr(DeclRefExprClass, T, VK, OK_Ordinary), D(D), DNLoc(LocInfo) {
436 DeclRefExprBits.HasQualifier = false;
437 DeclRefExprBits.HasTemplateKWAndArgsInfo = false;
438 DeclRefExprBits.HasFoundDecl = false;
439 DeclRefExprBits.HadMultipleCandidates = false;
440 DeclRefExprBits.RefersToEnclosingVariableOrCapture =
441 RefersToEnclosingVariableOrCapture;
442 DeclRefExprBits.CapturedByCopyInLambdaWithExplicitObjectParameter = false;
443 DeclRefExprBits.NonOdrUseReason = NOUR;
444 DeclRefExprBits.IsImmediateEscalating = false;
445 DeclRefExprBits.Loc = L;
446 setDependence(computeDependence(this, Ctx));
449 DeclRefExpr::DeclRefExpr(const ASTContext &Ctx,
450 NestedNameSpecifierLoc QualifierLoc,
451 SourceLocation TemplateKWLoc, ValueDecl *D,
452 bool RefersToEnclosingVariableOrCapture,
453 const DeclarationNameInfo &NameInfo, NamedDecl *FoundD,
454 const TemplateArgumentListInfo *TemplateArgs,
455 QualType T, ExprValueKind VK, NonOdrUseReason NOUR)
456 : Expr(DeclRefExprClass, T, VK, OK_Ordinary), D(D),
457 DNLoc(NameInfo.getInfo()) {
458 DeclRefExprBits.Loc = NameInfo.getLoc();
459 DeclRefExprBits.HasQualifier = QualifierLoc ? 1 : 0;
460 if (QualifierLoc)
461 new (getTrailingObjects<NestedNameSpecifierLoc>())
462 NestedNameSpecifierLoc(QualifierLoc);
463 DeclRefExprBits.HasFoundDecl = FoundD ? 1 : 0;
464 if (FoundD)
465 *getTrailingObjects<NamedDecl *>() = FoundD;
466 DeclRefExprBits.HasTemplateKWAndArgsInfo
467 = (TemplateArgs || TemplateKWLoc.isValid()) ? 1 : 0;
468 DeclRefExprBits.RefersToEnclosingVariableOrCapture =
469 RefersToEnclosingVariableOrCapture;
470 DeclRefExprBits.CapturedByCopyInLambdaWithExplicitObjectParameter = false;
471 DeclRefExprBits.NonOdrUseReason = NOUR;
472 if (TemplateArgs) {
473 auto Deps = TemplateArgumentDependence::None;
474 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
475 TemplateKWLoc, *TemplateArgs, getTrailingObjects<TemplateArgumentLoc>(),
476 Deps);
477 assert(!(Deps & TemplateArgumentDependence::Dependent) &&
478 "built a DeclRefExpr with dependent template args");
479 } else if (TemplateKWLoc.isValid()) {
480 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
481 TemplateKWLoc);
483 DeclRefExprBits.IsImmediateEscalating = false;
484 DeclRefExprBits.HadMultipleCandidates = 0;
485 setDependence(computeDependence(this, Ctx));
488 DeclRefExpr *DeclRefExpr::Create(const ASTContext &Context,
489 NestedNameSpecifierLoc QualifierLoc,
490 SourceLocation TemplateKWLoc, ValueDecl *D,
491 bool RefersToEnclosingVariableOrCapture,
492 SourceLocation NameLoc, QualType T,
493 ExprValueKind VK, NamedDecl *FoundD,
494 const TemplateArgumentListInfo *TemplateArgs,
495 NonOdrUseReason NOUR) {
496 return Create(Context, QualifierLoc, TemplateKWLoc, D,
497 RefersToEnclosingVariableOrCapture,
498 DeclarationNameInfo(D->getDeclName(), NameLoc),
499 T, VK, FoundD, TemplateArgs, NOUR);
502 DeclRefExpr *DeclRefExpr::Create(const ASTContext &Context,
503 NestedNameSpecifierLoc QualifierLoc,
504 SourceLocation TemplateKWLoc, ValueDecl *D,
505 bool RefersToEnclosingVariableOrCapture,
506 const DeclarationNameInfo &NameInfo,
507 QualType T, ExprValueKind VK,
508 NamedDecl *FoundD,
509 const TemplateArgumentListInfo *TemplateArgs,
510 NonOdrUseReason NOUR) {
511 // Filter out cases where the found Decl is the same as the value refenenced.
512 if (D == FoundD)
513 FoundD = nullptr;
515 bool HasTemplateKWAndArgsInfo = TemplateArgs || TemplateKWLoc.isValid();
516 std::size_t Size =
517 totalSizeToAlloc<NestedNameSpecifierLoc, NamedDecl *,
518 ASTTemplateKWAndArgsInfo, TemplateArgumentLoc>(
519 QualifierLoc ? 1 : 0, FoundD ? 1 : 0,
520 HasTemplateKWAndArgsInfo ? 1 : 0,
521 TemplateArgs ? TemplateArgs->size() : 0);
523 void *Mem = Context.Allocate(Size, alignof(DeclRefExpr));
524 return new (Mem) DeclRefExpr(Context, QualifierLoc, TemplateKWLoc, D,
525 RefersToEnclosingVariableOrCapture, NameInfo,
526 FoundD, TemplateArgs, T, VK, NOUR);
529 DeclRefExpr *DeclRefExpr::CreateEmpty(const ASTContext &Context,
530 bool HasQualifier,
531 bool HasFoundDecl,
532 bool HasTemplateKWAndArgsInfo,
533 unsigned NumTemplateArgs) {
534 assert(NumTemplateArgs == 0 || HasTemplateKWAndArgsInfo);
535 std::size_t Size =
536 totalSizeToAlloc<NestedNameSpecifierLoc, NamedDecl *,
537 ASTTemplateKWAndArgsInfo, TemplateArgumentLoc>(
538 HasQualifier ? 1 : 0, HasFoundDecl ? 1 : 0, HasTemplateKWAndArgsInfo,
539 NumTemplateArgs);
540 void *Mem = Context.Allocate(Size, alignof(DeclRefExpr));
541 return new (Mem) DeclRefExpr(EmptyShell());
544 void DeclRefExpr::setDecl(ValueDecl *NewD) {
545 D = NewD;
546 if (getType()->isUndeducedType())
547 setType(NewD->getType());
548 setDependence(computeDependence(this, NewD->getASTContext()));
551 SourceLocation DeclRefExpr::getBeginLoc() const {
552 if (hasQualifier())
553 return getQualifierLoc().getBeginLoc();
554 return getNameInfo().getBeginLoc();
556 SourceLocation DeclRefExpr::getEndLoc() const {
557 if (hasExplicitTemplateArgs())
558 return getRAngleLoc();
559 return getNameInfo().getEndLoc();
562 SYCLUniqueStableNameExpr::SYCLUniqueStableNameExpr(SourceLocation OpLoc,
563 SourceLocation LParen,
564 SourceLocation RParen,
565 QualType ResultTy,
566 TypeSourceInfo *TSI)
567 : Expr(SYCLUniqueStableNameExprClass, ResultTy, VK_PRValue, OK_Ordinary),
568 OpLoc(OpLoc), LParen(LParen), RParen(RParen) {
569 setTypeSourceInfo(TSI);
570 setDependence(computeDependence(this));
573 SYCLUniqueStableNameExpr::SYCLUniqueStableNameExpr(EmptyShell Empty,
574 QualType ResultTy)
575 : Expr(SYCLUniqueStableNameExprClass, ResultTy, VK_PRValue, OK_Ordinary) {}
577 SYCLUniqueStableNameExpr *
578 SYCLUniqueStableNameExpr::Create(const ASTContext &Ctx, SourceLocation OpLoc,
579 SourceLocation LParen, SourceLocation RParen,
580 TypeSourceInfo *TSI) {
581 QualType ResultTy = Ctx.getPointerType(Ctx.CharTy.withConst());
582 return new (Ctx)
583 SYCLUniqueStableNameExpr(OpLoc, LParen, RParen, ResultTy, TSI);
586 SYCLUniqueStableNameExpr *
587 SYCLUniqueStableNameExpr::CreateEmpty(const ASTContext &Ctx) {
588 QualType ResultTy = Ctx.getPointerType(Ctx.CharTy.withConst());
589 return new (Ctx) SYCLUniqueStableNameExpr(EmptyShell(), ResultTy);
592 std::string SYCLUniqueStableNameExpr::ComputeName(ASTContext &Context) const {
593 return SYCLUniqueStableNameExpr::ComputeName(Context,
594 getTypeSourceInfo()->getType());
597 std::string SYCLUniqueStableNameExpr::ComputeName(ASTContext &Context,
598 QualType Ty) {
599 auto MangleCallback = [](ASTContext &Ctx,
600 const NamedDecl *ND) -> std::optional<unsigned> {
601 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND))
602 return RD->getDeviceLambdaManglingNumber();
603 return std::nullopt;
606 std::unique_ptr<MangleContext> Ctx{ItaniumMangleContext::create(
607 Context, Context.getDiagnostics(), MangleCallback)};
609 std::string Buffer;
610 Buffer.reserve(128);
611 llvm::raw_string_ostream Out(Buffer);
612 Ctx->mangleCanonicalTypeName(Ty, Out);
614 return Buffer;
617 PredefinedExpr::PredefinedExpr(SourceLocation L, QualType FNTy,
618 PredefinedIdentKind IK, bool IsTransparent,
619 StringLiteral *SL)
620 : Expr(PredefinedExprClass, FNTy, VK_LValue, OK_Ordinary) {
621 PredefinedExprBits.Kind = llvm::to_underlying(IK);
622 assert((getIdentKind() == IK) &&
623 "IdentKind do not fit in PredefinedExprBitfields!");
624 bool HasFunctionName = SL != nullptr;
625 PredefinedExprBits.HasFunctionName = HasFunctionName;
626 PredefinedExprBits.IsTransparent = IsTransparent;
627 PredefinedExprBits.Loc = L;
628 if (HasFunctionName)
629 setFunctionName(SL);
630 setDependence(computeDependence(this));
633 PredefinedExpr::PredefinedExpr(EmptyShell Empty, bool HasFunctionName)
634 : Expr(PredefinedExprClass, Empty) {
635 PredefinedExprBits.HasFunctionName = HasFunctionName;
638 PredefinedExpr *PredefinedExpr::Create(const ASTContext &Ctx, SourceLocation L,
639 QualType FNTy, PredefinedIdentKind IK,
640 bool IsTransparent, StringLiteral *SL) {
641 bool HasFunctionName = SL != nullptr;
642 void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *>(HasFunctionName),
643 alignof(PredefinedExpr));
644 return new (Mem) PredefinedExpr(L, FNTy, IK, IsTransparent, SL);
647 PredefinedExpr *PredefinedExpr::CreateEmpty(const ASTContext &Ctx,
648 bool HasFunctionName) {
649 void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *>(HasFunctionName),
650 alignof(PredefinedExpr));
651 return new (Mem) PredefinedExpr(EmptyShell(), HasFunctionName);
654 StringRef PredefinedExpr::getIdentKindName(PredefinedIdentKind IK) {
655 switch (IK) {
656 case PredefinedIdentKind::Func:
657 return "__func__";
658 case PredefinedIdentKind::Function:
659 return "__FUNCTION__";
660 case PredefinedIdentKind::FuncDName:
661 return "__FUNCDNAME__";
662 case PredefinedIdentKind::LFunction:
663 return "L__FUNCTION__";
664 case PredefinedIdentKind::PrettyFunction:
665 return "__PRETTY_FUNCTION__";
666 case PredefinedIdentKind::FuncSig:
667 return "__FUNCSIG__";
668 case PredefinedIdentKind::LFuncSig:
669 return "L__FUNCSIG__";
670 case PredefinedIdentKind::PrettyFunctionNoVirtual:
671 break;
673 llvm_unreachable("Unknown ident kind for PredefinedExpr");
676 // FIXME: Maybe this should use DeclPrinter with a special "print predefined
677 // expr" policy instead.
678 std::string PredefinedExpr::ComputeName(PredefinedIdentKind IK,
679 const Decl *CurrentDecl,
680 bool ForceElaboratedPrinting) {
681 ASTContext &Context = CurrentDecl->getASTContext();
683 if (IK == PredefinedIdentKind::FuncDName) {
684 if (const NamedDecl *ND = dyn_cast<NamedDecl>(CurrentDecl)) {
685 std::unique_ptr<MangleContext> MC;
686 MC.reset(Context.createMangleContext());
688 if (MC->shouldMangleDeclName(ND)) {
689 SmallString<256> Buffer;
690 llvm::raw_svector_ostream Out(Buffer);
691 GlobalDecl GD;
692 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(ND))
693 GD = GlobalDecl(CD, Ctor_Base);
694 else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(ND))
695 GD = GlobalDecl(DD, Dtor_Base);
696 else if (ND->hasAttr<CUDAGlobalAttr>())
697 GD = GlobalDecl(cast<FunctionDecl>(ND));
698 else
699 GD = GlobalDecl(ND);
700 MC->mangleName(GD, Out);
702 if (!Buffer.empty() && Buffer.front() == '\01')
703 return std::string(Buffer.substr(1));
704 return std::string(Buffer);
706 return std::string(ND->getIdentifier()->getName());
708 return "";
710 if (isa<BlockDecl>(CurrentDecl)) {
711 // For blocks we only emit something if it is enclosed in a function
712 // For top-level block we'd like to include the name of variable, but we
713 // don't have it at this point.
714 auto DC = CurrentDecl->getDeclContext();
715 if (DC->isFileContext())
716 return "";
718 SmallString<256> Buffer;
719 llvm::raw_svector_ostream Out(Buffer);
720 if (auto *DCBlock = dyn_cast<BlockDecl>(DC))
721 // For nested blocks, propagate up to the parent.
722 Out << ComputeName(IK, DCBlock);
723 else if (auto *DCDecl = dyn_cast<Decl>(DC))
724 Out << ComputeName(IK, DCDecl) << "_block_invoke";
725 return std::string(Out.str());
727 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CurrentDecl)) {
728 const auto &LO = Context.getLangOpts();
729 bool IsFuncOrFunctionInNonMSVCCompatEnv =
730 ((IK == PredefinedIdentKind::Func ||
731 IK == PredefinedIdentKind ::Function) &&
732 !LO.MSVCCompat);
733 bool IsLFunctionInMSVCCommpatEnv =
734 IK == PredefinedIdentKind::LFunction && LO.MSVCCompat;
735 bool IsFuncOrFunctionOrLFunctionOrFuncDName =
736 IK != PredefinedIdentKind::PrettyFunction &&
737 IK != PredefinedIdentKind::PrettyFunctionNoVirtual &&
738 IK != PredefinedIdentKind::FuncSig &&
739 IK != PredefinedIdentKind::LFuncSig;
740 if ((ForceElaboratedPrinting &&
741 (IsFuncOrFunctionInNonMSVCCompatEnv || IsLFunctionInMSVCCommpatEnv)) ||
742 (!ForceElaboratedPrinting && IsFuncOrFunctionOrLFunctionOrFuncDName))
743 return FD->getNameAsString();
745 SmallString<256> Name;
746 llvm::raw_svector_ostream Out(Name);
748 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
749 if (MD->isVirtual() && IK != PredefinedIdentKind::PrettyFunctionNoVirtual)
750 Out << "virtual ";
751 if (MD->isStatic())
752 Out << "static ";
755 class PrettyCallbacks final : public PrintingCallbacks {
756 public:
757 PrettyCallbacks(const LangOptions &LO) : LO(LO) {}
758 std::string remapPath(StringRef Path) const override {
759 SmallString<128> p(Path);
760 LO.remapPathPrefix(p);
761 return std::string(p);
764 private:
765 const LangOptions &LO;
767 PrintingPolicy Policy(Context.getLangOpts());
768 PrettyCallbacks PrettyCB(Context.getLangOpts());
769 Policy.Callbacks = &PrettyCB;
770 if (IK == PredefinedIdentKind::Function && ForceElaboratedPrinting)
771 Policy.SuppressTagKeyword = !LO.MSVCCompat;
772 std::string Proto;
773 llvm::raw_string_ostream POut(Proto);
775 const FunctionDecl *Decl = FD;
776 if (const FunctionDecl* Pattern = FD->getTemplateInstantiationPattern())
777 Decl = Pattern;
778 const FunctionType *AFT = Decl->getType()->getAs<FunctionType>();
779 const FunctionProtoType *FT = nullptr;
780 if (FD->hasWrittenPrototype())
781 FT = dyn_cast<FunctionProtoType>(AFT);
783 if (IK == PredefinedIdentKind::FuncSig ||
784 IK == PredefinedIdentKind::LFuncSig) {
785 switch (AFT->getCallConv()) {
786 case CC_C: POut << "__cdecl "; break;
787 case CC_X86StdCall: POut << "__stdcall "; break;
788 case CC_X86FastCall: POut << "__fastcall "; break;
789 case CC_X86ThisCall: POut << "__thiscall "; break;
790 case CC_X86VectorCall: POut << "__vectorcall "; break;
791 case CC_X86RegCall: POut << "__regcall "; break;
792 // Only bother printing the conventions that MSVC knows about.
793 default: break;
797 FD->printQualifiedName(POut, Policy);
799 if (IK == PredefinedIdentKind::Function) {
800 Out << Proto;
801 return std::string(Name);
804 POut << "(";
805 if (FT) {
806 for (unsigned i = 0, e = Decl->getNumParams(); i != e; ++i) {
807 if (i) POut << ", ";
808 POut << Decl->getParamDecl(i)->getType().stream(Policy);
811 if (FT->isVariadic()) {
812 if (FD->getNumParams()) POut << ", ";
813 POut << "...";
814 } else if ((IK == PredefinedIdentKind::FuncSig ||
815 IK == PredefinedIdentKind::LFuncSig ||
816 !Context.getLangOpts().CPlusPlus) &&
817 !Decl->getNumParams()) {
818 POut << "void";
821 POut << ")";
823 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
824 assert(FT && "We must have a written prototype in this case.");
825 if (FT->isConst())
826 POut << " const";
827 if (FT->isVolatile())
828 POut << " volatile";
829 RefQualifierKind Ref = MD->getRefQualifier();
830 if (Ref == RQ_LValue)
831 POut << " &";
832 else if (Ref == RQ_RValue)
833 POut << " &&";
836 typedef SmallVector<const ClassTemplateSpecializationDecl *, 8> SpecsTy;
837 SpecsTy Specs;
838 const DeclContext *Ctx = FD->getDeclContext();
839 while (isa_and_nonnull<NamedDecl>(Ctx)) {
840 const ClassTemplateSpecializationDecl *Spec
841 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx);
842 if (Spec && !Spec->isExplicitSpecialization())
843 Specs.push_back(Spec);
844 Ctx = Ctx->getParent();
847 std::string TemplateParams;
848 llvm::raw_string_ostream TOut(TemplateParams);
849 for (const ClassTemplateSpecializationDecl *D : llvm::reverse(Specs)) {
850 const TemplateParameterList *Params =
851 D->getSpecializedTemplate()->getTemplateParameters();
852 const TemplateArgumentList &Args = D->getTemplateArgs();
853 assert(Params->size() == Args.size());
854 for (unsigned i = 0, numParams = Params->size(); i != numParams; ++i) {
855 StringRef Param = Params->getParam(i)->getName();
856 if (Param.empty()) continue;
857 TOut << Param << " = ";
858 Args.get(i).print(Policy, TOut,
859 TemplateParameterList::shouldIncludeTypeForArgument(
860 Policy, Params, i));
861 TOut << ", ";
865 FunctionTemplateSpecializationInfo *FSI
866 = FD->getTemplateSpecializationInfo();
867 if (FSI && !FSI->isExplicitSpecialization()) {
868 const TemplateParameterList* Params
869 = FSI->getTemplate()->getTemplateParameters();
870 const TemplateArgumentList* Args = FSI->TemplateArguments;
871 assert(Params->size() == Args->size());
872 for (unsigned i = 0, e = Params->size(); i != e; ++i) {
873 StringRef Param = Params->getParam(i)->getName();
874 if (Param.empty()) continue;
875 TOut << Param << " = ";
876 Args->get(i).print(Policy, TOut, /*IncludeType*/ true);
877 TOut << ", ";
881 if (!TemplateParams.empty()) {
882 // remove the trailing comma and space
883 TemplateParams.resize(TemplateParams.size() - 2);
884 POut << " [" << TemplateParams << "]";
887 // Print "auto" for all deduced return types. This includes C++1y return
888 // type deduction and lambdas. For trailing return types resolve the
889 // decltype expression. Otherwise print the real type when this is
890 // not a constructor or destructor.
891 if (isa<CXXMethodDecl>(FD) &&
892 cast<CXXMethodDecl>(FD)->getParent()->isLambda())
893 Proto = "auto " + Proto;
894 else if (FT && FT->getReturnType()->getAs<DecltypeType>())
895 FT->getReturnType()
896 ->getAs<DecltypeType>()
897 ->getUnderlyingType()
898 .getAsStringInternal(Proto, Policy);
899 else if (!isa<CXXConstructorDecl>(FD) && !isa<CXXDestructorDecl>(FD))
900 AFT->getReturnType().getAsStringInternal(Proto, Policy);
902 Out << Proto;
904 return std::string(Name);
906 if (const CapturedDecl *CD = dyn_cast<CapturedDecl>(CurrentDecl)) {
907 for (const DeclContext *DC = CD->getParent(); DC; DC = DC->getParent())
908 // Skip to its enclosing function or method, but not its enclosing
909 // CapturedDecl.
910 if (DC->isFunctionOrMethod() && (DC->getDeclKind() != Decl::Captured)) {
911 const Decl *D = Decl::castFromDeclContext(DC);
912 return ComputeName(IK, D);
914 llvm_unreachable("CapturedDecl not inside a function or method");
916 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurrentDecl)) {
917 SmallString<256> Name;
918 llvm::raw_svector_ostream Out(Name);
919 Out << (MD->isInstanceMethod() ? '-' : '+');
920 Out << '[';
922 // For incorrect code, there might not be an ObjCInterfaceDecl. Do
923 // a null check to avoid a crash.
924 if (const ObjCInterfaceDecl *ID = MD->getClassInterface())
925 Out << *ID;
927 if (const ObjCCategoryImplDecl *CID =
928 dyn_cast<ObjCCategoryImplDecl>(MD->getDeclContext()))
929 Out << '(' << *CID << ')';
931 Out << ' ';
932 MD->getSelector().print(Out);
933 Out << ']';
935 return std::string(Name);
937 if (isa<TranslationUnitDecl>(CurrentDecl) &&
938 IK == PredefinedIdentKind::PrettyFunction) {
939 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
940 return "top level";
942 return "";
945 void APNumericStorage::setIntValue(const ASTContext &C,
946 const llvm::APInt &Val) {
947 if (hasAllocation())
948 C.Deallocate(pVal);
950 BitWidth = Val.getBitWidth();
951 unsigned NumWords = Val.getNumWords();
952 const uint64_t* Words = Val.getRawData();
953 if (NumWords > 1) {
954 pVal = new (C) uint64_t[NumWords];
955 std::copy(Words, Words + NumWords, pVal);
956 } else if (NumWords == 1)
957 VAL = Words[0];
958 else
959 VAL = 0;
962 IntegerLiteral::IntegerLiteral(const ASTContext &C, const llvm::APInt &V,
963 QualType type, SourceLocation l)
964 : Expr(IntegerLiteralClass, type, VK_PRValue, OK_Ordinary), Loc(l) {
965 assert(type->isIntegerType() && "Illegal type in IntegerLiteral");
966 assert(V.getBitWidth() == C.getIntWidth(type) &&
967 "Integer type is not the correct size for constant.");
968 setValue(C, V);
969 setDependence(ExprDependence::None);
972 IntegerLiteral *
973 IntegerLiteral::Create(const ASTContext &C, const llvm::APInt &V,
974 QualType type, SourceLocation l) {
975 return new (C) IntegerLiteral(C, V, type, l);
978 IntegerLiteral *
979 IntegerLiteral::Create(const ASTContext &C, EmptyShell Empty) {
980 return new (C) IntegerLiteral(Empty);
983 FixedPointLiteral::FixedPointLiteral(const ASTContext &C, const llvm::APInt &V,
984 QualType type, SourceLocation l,
985 unsigned Scale)
986 : Expr(FixedPointLiteralClass, type, VK_PRValue, OK_Ordinary), Loc(l),
987 Scale(Scale) {
988 assert(type->isFixedPointType() && "Illegal type in FixedPointLiteral");
989 assert(V.getBitWidth() == C.getTypeInfo(type).Width &&
990 "Fixed point type is not the correct size for constant.");
991 setValue(C, V);
992 setDependence(ExprDependence::None);
995 FixedPointLiteral *FixedPointLiteral::CreateFromRawInt(const ASTContext &C,
996 const llvm::APInt &V,
997 QualType type,
998 SourceLocation l,
999 unsigned Scale) {
1000 return new (C) FixedPointLiteral(C, V, type, l, Scale);
1003 FixedPointLiteral *FixedPointLiteral::Create(const ASTContext &C,
1004 EmptyShell Empty) {
1005 return new (C) FixedPointLiteral(Empty);
1008 std::string FixedPointLiteral::getValueAsString(unsigned Radix) const {
1009 // Currently the longest decimal number that can be printed is the max for an
1010 // unsigned long _Accum: 4294967295.99999999976716935634613037109375
1011 // which is 43 characters.
1012 SmallString<64> S;
1013 FixedPointValueToString(
1014 S, llvm::APSInt::getUnsigned(getValue().getZExtValue()), Scale);
1015 return std::string(S);
1018 void CharacterLiteral::print(unsigned Val, CharacterLiteralKind Kind,
1019 raw_ostream &OS) {
1020 switch (Kind) {
1021 case CharacterLiteralKind::Ascii:
1022 break; // no prefix.
1023 case CharacterLiteralKind::Wide:
1024 OS << 'L';
1025 break;
1026 case CharacterLiteralKind::UTF8:
1027 OS << "u8";
1028 break;
1029 case CharacterLiteralKind::UTF16:
1030 OS << 'u';
1031 break;
1032 case CharacterLiteralKind::UTF32:
1033 OS << 'U';
1034 break;
1037 StringRef Escaped = escapeCStyle<EscapeChar::Single>(Val);
1038 if (!Escaped.empty()) {
1039 OS << "'" << Escaped << "'";
1040 } else {
1041 // A character literal might be sign-extended, which
1042 // would result in an invalid \U escape sequence.
1043 // FIXME: multicharacter literals such as '\xFF\xFF\xFF\xFF'
1044 // are not correctly handled.
1045 if ((Val & ~0xFFu) == ~0xFFu && Kind == CharacterLiteralKind::Ascii)
1046 Val &= 0xFFu;
1047 if (Val < 256 && isPrintable((unsigned char)Val))
1048 OS << "'" << (char)Val << "'";
1049 else if (Val < 256)
1050 OS << "'\\x" << llvm::format("%02x", Val) << "'";
1051 else if (Val <= 0xFFFF)
1052 OS << "'\\u" << llvm::format("%04x", Val) << "'";
1053 else
1054 OS << "'\\U" << llvm::format("%08x", Val) << "'";
1058 FloatingLiteral::FloatingLiteral(const ASTContext &C, const llvm::APFloat &V,
1059 bool isexact, QualType Type, SourceLocation L)
1060 : Expr(FloatingLiteralClass, Type, VK_PRValue, OK_Ordinary), Loc(L) {
1061 setSemantics(V.getSemantics());
1062 FloatingLiteralBits.IsExact = isexact;
1063 setValue(C, V);
1064 setDependence(ExprDependence::None);
1067 FloatingLiteral::FloatingLiteral(const ASTContext &C, EmptyShell Empty)
1068 : Expr(FloatingLiteralClass, Empty) {
1069 setRawSemantics(llvm::APFloatBase::S_IEEEhalf);
1070 FloatingLiteralBits.IsExact = false;
1073 FloatingLiteral *
1074 FloatingLiteral::Create(const ASTContext &C, const llvm::APFloat &V,
1075 bool isexact, QualType Type, SourceLocation L) {
1076 return new (C) FloatingLiteral(C, V, isexact, Type, L);
1079 FloatingLiteral *
1080 FloatingLiteral::Create(const ASTContext &C, EmptyShell Empty) {
1081 return new (C) FloatingLiteral(C, Empty);
1084 /// getValueAsApproximateDouble - This returns the value as an inaccurate
1085 /// double. Note that this may cause loss of precision, but is useful for
1086 /// debugging dumps, etc.
1087 double FloatingLiteral::getValueAsApproximateDouble() const {
1088 llvm::APFloat V = getValue();
1089 bool ignored;
1090 V.convert(llvm::APFloat::IEEEdouble(), llvm::APFloat::rmNearestTiesToEven,
1091 &ignored);
1092 return V.convertToDouble();
1095 unsigned StringLiteral::mapCharByteWidth(TargetInfo const &Target,
1096 StringLiteralKind SK) {
1097 unsigned CharByteWidth = 0;
1098 switch (SK) {
1099 case StringLiteralKind::Ordinary:
1100 case StringLiteralKind::UTF8:
1101 CharByteWidth = Target.getCharWidth();
1102 break;
1103 case StringLiteralKind::Wide:
1104 CharByteWidth = Target.getWCharWidth();
1105 break;
1106 case StringLiteralKind::UTF16:
1107 CharByteWidth = Target.getChar16Width();
1108 break;
1109 case StringLiteralKind::UTF32:
1110 CharByteWidth = Target.getChar32Width();
1111 break;
1112 case StringLiteralKind::Unevaluated:
1113 return sizeof(char); // Host;
1115 assert((CharByteWidth & 7) == 0 && "Assumes character size is byte multiple");
1116 CharByteWidth /= 8;
1117 assert((CharByteWidth == 1 || CharByteWidth == 2 || CharByteWidth == 4) &&
1118 "The only supported character byte widths are 1,2 and 4!");
1119 return CharByteWidth;
1122 StringLiteral::StringLiteral(const ASTContext &Ctx, StringRef Str,
1123 StringLiteralKind Kind, bool Pascal, QualType Ty,
1124 const SourceLocation *Loc,
1125 unsigned NumConcatenated)
1126 : Expr(StringLiteralClass, Ty, VK_LValue, OK_Ordinary) {
1128 unsigned Length = Str.size();
1130 StringLiteralBits.Kind = llvm::to_underlying(Kind);
1131 StringLiteralBits.NumConcatenated = NumConcatenated;
1133 if (Kind != StringLiteralKind::Unevaluated) {
1134 assert(Ctx.getAsConstantArrayType(Ty) &&
1135 "StringLiteral must be of constant array type!");
1136 unsigned CharByteWidth = mapCharByteWidth(Ctx.getTargetInfo(), Kind);
1137 unsigned ByteLength = Str.size();
1138 assert((ByteLength % CharByteWidth == 0) &&
1139 "The size of the data must be a multiple of CharByteWidth!");
1141 // Avoid the expensive division. The compiler should be able to figure it
1142 // out by itself. However as of clang 7, even with the appropriate
1143 // llvm_unreachable added just here, it is not able to do so.
1144 switch (CharByteWidth) {
1145 case 1:
1146 Length = ByteLength;
1147 break;
1148 case 2:
1149 Length = ByteLength / 2;
1150 break;
1151 case 4:
1152 Length = ByteLength / 4;
1153 break;
1154 default:
1155 llvm_unreachable("Unsupported character width!");
1158 StringLiteralBits.CharByteWidth = CharByteWidth;
1159 StringLiteralBits.IsPascal = Pascal;
1160 } else {
1161 assert(!Pascal && "Can't make an unevaluated Pascal string");
1162 StringLiteralBits.CharByteWidth = 1;
1163 StringLiteralBits.IsPascal = false;
1166 *getTrailingObjects<unsigned>() = Length;
1168 // Initialize the trailing array of SourceLocation.
1169 // This is safe since SourceLocation is POD-like.
1170 std::memcpy(getTrailingObjects<SourceLocation>(), Loc,
1171 NumConcatenated * sizeof(SourceLocation));
1173 // Initialize the trailing array of char holding the string data.
1174 std::memcpy(getTrailingObjects<char>(), Str.data(), Str.size());
1176 setDependence(ExprDependence::None);
1179 StringLiteral::StringLiteral(EmptyShell Empty, unsigned NumConcatenated,
1180 unsigned Length, unsigned CharByteWidth)
1181 : Expr(StringLiteralClass, Empty) {
1182 StringLiteralBits.CharByteWidth = CharByteWidth;
1183 StringLiteralBits.NumConcatenated = NumConcatenated;
1184 *getTrailingObjects<unsigned>() = Length;
1187 StringLiteral *StringLiteral::Create(const ASTContext &Ctx, StringRef Str,
1188 StringLiteralKind Kind, bool Pascal,
1189 QualType Ty, const SourceLocation *Loc,
1190 unsigned NumConcatenated) {
1191 void *Mem = Ctx.Allocate(totalSizeToAlloc<unsigned, SourceLocation, char>(
1192 1, NumConcatenated, Str.size()),
1193 alignof(StringLiteral));
1194 return new (Mem)
1195 StringLiteral(Ctx, Str, Kind, Pascal, Ty, Loc, NumConcatenated);
1198 StringLiteral *StringLiteral::CreateEmpty(const ASTContext &Ctx,
1199 unsigned NumConcatenated,
1200 unsigned Length,
1201 unsigned CharByteWidth) {
1202 void *Mem = Ctx.Allocate(totalSizeToAlloc<unsigned, SourceLocation, char>(
1203 1, NumConcatenated, Length * CharByteWidth),
1204 alignof(StringLiteral));
1205 return new (Mem)
1206 StringLiteral(EmptyShell(), NumConcatenated, Length, CharByteWidth);
1209 void StringLiteral::outputString(raw_ostream &OS) const {
1210 switch (getKind()) {
1211 case StringLiteralKind::Unevaluated:
1212 case StringLiteralKind::Ordinary:
1213 break; // no prefix.
1214 case StringLiteralKind::Wide:
1215 OS << 'L';
1216 break;
1217 case StringLiteralKind::UTF8:
1218 OS << "u8";
1219 break;
1220 case StringLiteralKind::UTF16:
1221 OS << 'u';
1222 break;
1223 case StringLiteralKind::UTF32:
1224 OS << 'U';
1225 break;
1227 OS << '"';
1228 static const char Hex[] = "0123456789ABCDEF";
1230 unsigned LastSlashX = getLength();
1231 for (unsigned I = 0, N = getLength(); I != N; ++I) {
1232 uint32_t Char = getCodeUnit(I);
1233 StringRef Escaped = escapeCStyle<EscapeChar::Double>(Char);
1234 if (Escaped.empty()) {
1235 // FIXME: Convert UTF-8 back to codepoints before rendering.
1237 // Convert UTF-16 surrogate pairs back to codepoints before rendering.
1238 // Leave invalid surrogates alone; we'll use \x for those.
1239 if (getKind() == StringLiteralKind::UTF16 && I != N - 1 &&
1240 Char >= 0xd800 && Char <= 0xdbff) {
1241 uint32_t Trail = getCodeUnit(I + 1);
1242 if (Trail >= 0xdc00 && Trail <= 0xdfff) {
1243 Char = 0x10000 + ((Char - 0xd800) << 10) + (Trail - 0xdc00);
1244 ++I;
1248 if (Char > 0xff) {
1249 // If this is a wide string, output characters over 0xff using \x
1250 // escapes. Otherwise, this is a UTF-16 or UTF-32 string, and Char is a
1251 // codepoint: use \x escapes for invalid codepoints.
1252 if (getKind() == StringLiteralKind::Wide ||
1253 (Char >= 0xd800 && Char <= 0xdfff) || Char >= 0x110000) {
1254 // FIXME: Is this the best way to print wchar_t?
1255 OS << "\\x";
1256 int Shift = 28;
1257 while ((Char >> Shift) == 0)
1258 Shift -= 4;
1259 for (/**/; Shift >= 0; Shift -= 4)
1260 OS << Hex[(Char >> Shift) & 15];
1261 LastSlashX = I;
1262 continue;
1265 if (Char > 0xffff)
1266 OS << "\\U00"
1267 << Hex[(Char >> 20) & 15]
1268 << Hex[(Char >> 16) & 15];
1269 else
1270 OS << "\\u";
1271 OS << Hex[(Char >> 12) & 15]
1272 << Hex[(Char >> 8) & 15]
1273 << Hex[(Char >> 4) & 15]
1274 << Hex[(Char >> 0) & 15];
1275 continue;
1278 // If we used \x... for the previous character, and this character is a
1279 // hexadecimal digit, prevent it being slurped as part of the \x.
1280 if (LastSlashX + 1 == I) {
1281 switch (Char) {
1282 case '0': case '1': case '2': case '3': case '4':
1283 case '5': case '6': case '7': case '8': case '9':
1284 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
1285 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
1286 OS << "\"\"";
1290 assert(Char <= 0xff &&
1291 "Characters above 0xff should already have been handled.");
1293 if (isPrintable(Char))
1294 OS << (char)Char;
1295 else // Output anything hard as an octal escape.
1296 OS << '\\'
1297 << (char)('0' + ((Char >> 6) & 7))
1298 << (char)('0' + ((Char >> 3) & 7))
1299 << (char)('0' + ((Char >> 0) & 7));
1300 } else {
1301 // Handle some common non-printable cases to make dumps prettier.
1302 OS << Escaped;
1305 OS << '"';
1308 /// getLocationOfByte - Return a source location that points to the specified
1309 /// byte of this string literal.
1311 /// Strings are amazingly complex. They can be formed from multiple tokens and
1312 /// can have escape sequences in them in addition to the usual trigraph and
1313 /// escaped newline business. This routine handles this complexity.
1315 /// The *StartToken sets the first token to be searched in this function and
1316 /// the *StartTokenByteOffset is the byte offset of the first token. Before
1317 /// returning, it updates the *StartToken to the TokNo of the token being found
1318 /// and sets *StartTokenByteOffset to the byte offset of the token in the
1319 /// string.
1320 /// Using these two parameters can reduce the time complexity from O(n^2) to
1321 /// O(n) if one wants to get the location of byte for all the tokens in a
1322 /// string.
1324 SourceLocation
1325 StringLiteral::getLocationOfByte(unsigned ByteNo, const SourceManager &SM,
1326 const LangOptions &Features,
1327 const TargetInfo &Target, unsigned *StartToken,
1328 unsigned *StartTokenByteOffset) const {
1329 assert((getKind() == StringLiteralKind::Ordinary ||
1330 getKind() == StringLiteralKind::UTF8 ||
1331 getKind() == StringLiteralKind::Unevaluated) &&
1332 "Only narrow string literals are currently supported");
1334 // Loop over all of the tokens in this string until we find the one that
1335 // contains the byte we're looking for.
1336 unsigned TokNo = 0;
1337 unsigned StringOffset = 0;
1338 if (StartToken)
1339 TokNo = *StartToken;
1340 if (StartTokenByteOffset) {
1341 StringOffset = *StartTokenByteOffset;
1342 ByteNo -= StringOffset;
1344 while (true) {
1345 assert(TokNo < getNumConcatenated() && "Invalid byte number!");
1346 SourceLocation StrTokLoc = getStrTokenLoc(TokNo);
1348 // Get the spelling of the string so that we can get the data that makes up
1349 // the string literal, not the identifier for the macro it is potentially
1350 // expanded through.
1351 SourceLocation StrTokSpellingLoc = SM.getSpellingLoc(StrTokLoc);
1353 // Re-lex the token to get its length and original spelling.
1354 std::pair<FileID, unsigned> LocInfo =
1355 SM.getDecomposedLoc(StrTokSpellingLoc);
1356 bool Invalid = false;
1357 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
1358 if (Invalid) {
1359 if (StartTokenByteOffset != nullptr)
1360 *StartTokenByteOffset = StringOffset;
1361 if (StartToken != nullptr)
1362 *StartToken = TokNo;
1363 return StrTokSpellingLoc;
1366 const char *StrData = Buffer.data()+LocInfo.second;
1368 // Create a lexer starting at the beginning of this token.
1369 Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), Features,
1370 Buffer.begin(), StrData, Buffer.end());
1371 Token TheTok;
1372 TheLexer.LexFromRawLexer(TheTok);
1374 // Use the StringLiteralParser to compute the length of the string in bytes.
1375 StringLiteralParser SLP(TheTok, SM, Features, Target);
1376 unsigned TokNumBytes = SLP.GetStringLength();
1378 // If the byte is in this token, return the location of the byte.
1379 if (ByteNo < TokNumBytes ||
1380 (ByteNo == TokNumBytes && TokNo == getNumConcatenated() - 1)) {
1381 unsigned Offset = SLP.getOffsetOfStringByte(TheTok, ByteNo);
1383 // Now that we know the offset of the token in the spelling, use the
1384 // preprocessor to get the offset in the original source.
1385 if (StartTokenByteOffset != nullptr)
1386 *StartTokenByteOffset = StringOffset;
1387 if (StartToken != nullptr)
1388 *StartToken = TokNo;
1389 return Lexer::AdvanceToTokenCharacter(StrTokLoc, Offset, SM, Features);
1392 // Move to the next string token.
1393 StringOffset += TokNumBytes;
1394 ++TokNo;
1395 ByteNo -= TokNumBytes;
1399 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1400 /// corresponds to, e.g. "sizeof" or "[pre]++".
1401 StringRef UnaryOperator::getOpcodeStr(Opcode Op) {
1402 switch (Op) {
1403 #define UNARY_OPERATION(Name, Spelling) case UO_##Name: return Spelling;
1404 #include "clang/AST/OperationKinds.def"
1406 llvm_unreachable("Unknown unary operator");
1409 UnaryOperatorKind
1410 UnaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix) {
1411 switch (OO) {
1412 default: llvm_unreachable("No unary operator for overloaded function");
1413 case OO_PlusPlus: return Postfix ? UO_PostInc : UO_PreInc;
1414 case OO_MinusMinus: return Postfix ? UO_PostDec : UO_PreDec;
1415 case OO_Amp: return UO_AddrOf;
1416 case OO_Star: return UO_Deref;
1417 case OO_Plus: return UO_Plus;
1418 case OO_Minus: return UO_Minus;
1419 case OO_Tilde: return UO_Not;
1420 case OO_Exclaim: return UO_LNot;
1421 case OO_Coawait: return UO_Coawait;
1425 OverloadedOperatorKind UnaryOperator::getOverloadedOperator(Opcode Opc) {
1426 switch (Opc) {
1427 case UO_PostInc: case UO_PreInc: return OO_PlusPlus;
1428 case UO_PostDec: case UO_PreDec: return OO_MinusMinus;
1429 case UO_AddrOf: return OO_Amp;
1430 case UO_Deref: return OO_Star;
1431 case UO_Plus: return OO_Plus;
1432 case UO_Minus: return OO_Minus;
1433 case UO_Not: return OO_Tilde;
1434 case UO_LNot: return OO_Exclaim;
1435 case UO_Coawait: return OO_Coawait;
1436 default: return OO_None;
1441 //===----------------------------------------------------------------------===//
1442 // Postfix Operators.
1443 //===----------------------------------------------------------------------===//
1445 CallExpr::CallExpr(StmtClass SC, Expr *Fn, ArrayRef<Expr *> PreArgs,
1446 ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,
1447 SourceLocation RParenLoc, FPOptionsOverride FPFeatures,
1448 unsigned MinNumArgs, ADLCallKind UsesADL)
1449 : Expr(SC, Ty, VK, OK_Ordinary), RParenLoc(RParenLoc) {
1450 NumArgs = std::max<unsigned>(Args.size(), MinNumArgs);
1451 unsigned NumPreArgs = PreArgs.size();
1452 CallExprBits.NumPreArgs = NumPreArgs;
1453 assert((NumPreArgs == getNumPreArgs()) && "NumPreArgs overflow!");
1455 unsigned OffsetToTrailingObjects = offsetToTrailingObjects(SC);
1456 CallExprBits.OffsetToTrailingObjects = OffsetToTrailingObjects;
1457 assert((CallExprBits.OffsetToTrailingObjects == OffsetToTrailingObjects) &&
1458 "OffsetToTrailingObjects overflow!");
1460 CallExprBits.UsesADL = static_cast<bool>(UsesADL);
1462 setCallee(Fn);
1463 for (unsigned I = 0; I != NumPreArgs; ++I)
1464 setPreArg(I, PreArgs[I]);
1465 for (unsigned I = 0; I != Args.size(); ++I)
1466 setArg(I, Args[I]);
1467 for (unsigned I = Args.size(); I != NumArgs; ++I)
1468 setArg(I, nullptr);
1470 this->computeDependence();
1472 CallExprBits.HasFPFeatures = FPFeatures.requiresTrailingStorage();
1473 CallExprBits.IsCoroElideSafe = false;
1474 if (hasStoredFPFeatures())
1475 setStoredFPFeatures(FPFeatures);
1478 CallExpr::CallExpr(StmtClass SC, unsigned NumPreArgs, unsigned NumArgs,
1479 bool HasFPFeatures, EmptyShell Empty)
1480 : Expr(SC, Empty), NumArgs(NumArgs) {
1481 CallExprBits.NumPreArgs = NumPreArgs;
1482 assert((NumPreArgs == getNumPreArgs()) && "NumPreArgs overflow!");
1484 unsigned OffsetToTrailingObjects = offsetToTrailingObjects(SC);
1485 CallExprBits.OffsetToTrailingObjects = OffsetToTrailingObjects;
1486 assert((CallExprBits.OffsetToTrailingObjects == OffsetToTrailingObjects) &&
1487 "OffsetToTrailingObjects overflow!");
1488 CallExprBits.HasFPFeatures = HasFPFeatures;
1489 CallExprBits.IsCoroElideSafe = false;
1492 CallExpr *CallExpr::Create(const ASTContext &Ctx, Expr *Fn,
1493 ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,
1494 SourceLocation RParenLoc,
1495 FPOptionsOverride FPFeatures, unsigned MinNumArgs,
1496 ADLCallKind UsesADL) {
1497 unsigned NumArgs = std::max<unsigned>(Args.size(), MinNumArgs);
1498 unsigned SizeOfTrailingObjects = CallExpr::sizeOfTrailingObjects(
1499 /*NumPreArgs=*/0, NumArgs, FPFeatures.requiresTrailingStorage());
1500 void *Mem =
1501 Ctx.Allocate(sizeof(CallExpr) + SizeOfTrailingObjects, alignof(CallExpr));
1502 return new (Mem) CallExpr(CallExprClass, Fn, /*PreArgs=*/{}, Args, Ty, VK,
1503 RParenLoc, FPFeatures, MinNumArgs, UsesADL);
1506 CallExpr *CallExpr::CreateTemporary(void *Mem, Expr *Fn, QualType Ty,
1507 ExprValueKind VK, SourceLocation RParenLoc,
1508 ADLCallKind UsesADL) {
1509 assert(!(reinterpret_cast<uintptr_t>(Mem) % alignof(CallExpr)) &&
1510 "Misaligned memory in CallExpr::CreateTemporary!");
1511 return new (Mem) CallExpr(CallExprClass, Fn, /*PreArgs=*/{}, /*Args=*/{}, Ty,
1512 VK, RParenLoc, FPOptionsOverride(),
1513 /*MinNumArgs=*/0, UsesADL);
1516 CallExpr *CallExpr::CreateEmpty(const ASTContext &Ctx, unsigned NumArgs,
1517 bool HasFPFeatures, EmptyShell Empty) {
1518 unsigned SizeOfTrailingObjects =
1519 CallExpr::sizeOfTrailingObjects(/*NumPreArgs=*/0, NumArgs, HasFPFeatures);
1520 void *Mem =
1521 Ctx.Allocate(sizeof(CallExpr) + SizeOfTrailingObjects, alignof(CallExpr));
1522 return new (Mem)
1523 CallExpr(CallExprClass, /*NumPreArgs=*/0, NumArgs, HasFPFeatures, Empty);
1526 unsigned CallExpr::offsetToTrailingObjects(StmtClass SC) {
1527 switch (SC) {
1528 case CallExprClass:
1529 return sizeof(CallExpr);
1530 case CXXOperatorCallExprClass:
1531 return sizeof(CXXOperatorCallExpr);
1532 case CXXMemberCallExprClass:
1533 return sizeof(CXXMemberCallExpr);
1534 case UserDefinedLiteralClass:
1535 return sizeof(UserDefinedLiteral);
1536 case CUDAKernelCallExprClass:
1537 return sizeof(CUDAKernelCallExpr);
1538 default:
1539 llvm_unreachable("unexpected class deriving from CallExpr!");
1543 Decl *Expr::getReferencedDeclOfCallee() {
1544 Expr *CEE = IgnoreParenImpCasts();
1546 while (auto *NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(CEE))
1547 CEE = NTTP->getReplacement()->IgnoreParenImpCasts();
1549 // If we're calling a dereference, look at the pointer instead.
1550 while (true) {
1551 if (auto *BO = dyn_cast<BinaryOperator>(CEE)) {
1552 if (BO->isPtrMemOp()) {
1553 CEE = BO->getRHS()->IgnoreParenImpCasts();
1554 continue;
1556 } else if (auto *UO = dyn_cast<UnaryOperator>(CEE)) {
1557 if (UO->getOpcode() == UO_Deref || UO->getOpcode() == UO_AddrOf ||
1558 UO->getOpcode() == UO_Plus) {
1559 CEE = UO->getSubExpr()->IgnoreParenImpCasts();
1560 continue;
1563 break;
1566 if (auto *DRE = dyn_cast<DeclRefExpr>(CEE))
1567 return DRE->getDecl();
1568 if (auto *ME = dyn_cast<MemberExpr>(CEE))
1569 return ME->getMemberDecl();
1570 if (auto *BE = dyn_cast<BlockExpr>(CEE))
1571 return BE->getBlockDecl();
1573 return nullptr;
1576 /// If this is a call to a builtin, return the builtin ID. If not, return 0.
1577 unsigned CallExpr::getBuiltinCallee() const {
1578 const auto *FDecl = getDirectCallee();
1579 return FDecl ? FDecl->getBuiltinID() : 0;
1582 bool CallExpr::isUnevaluatedBuiltinCall(const ASTContext &Ctx) const {
1583 if (unsigned BI = getBuiltinCallee())
1584 return Ctx.BuiltinInfo.isUnevaluated(BI);
1585 return false;
1588 QualType CallExpr::getCallReturnType(const ASTContext &Ctx) const {
1589 const Expr *Callee = getCallee();
1590 QualType CalleeType = Callee->getType();
1591 if (const auto *FnTypePtr = CalleeType->getAs<PointerType>()) {
1592 CalleeType = FnTypePtr->getPointeeType();
1593 } else if (const auto *BPT = CalleeType->getAs<BlockPointerType>()) {
1594 CalleeType = BPT->getPointeeType();
1595 } else if (CalleeType->isSpecificPlaceholderType(BuiltinType::BoundMember)) {
1596 if (isa<CXXPseudoDestructorExpr>(Callee->IgnoreParens()))
1597 return Ctx.VoidTy;
1599 if (isa<UnresolvedMemberExpr>(Callee->IgnoreParens()))
1600 return Ctx.DependentTy;
1602 // This should never be overloaded and so should never return null.
1603 CalleeType = Expr::findBoundMemberType(Callee);
1604 assert(!CalleeType.isNull());
1605 } else if (CalleeType->isRecordType()) {
1606 // If the Callee is a record type, then it is a not-yet-resolved
1607 // dependent call to the call operator of that type.
1608 return Ctx.DependentTy;
1609 } else if (CalleeType->isDependentType() ||
1610 CalleeType->isSpecificPlaceholderType(BuiltinType::Overload)) {
1611 return Ctx.DependentTy;
1614 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
1615 return FnType->getReturnType();
1618 std::pair<const NamedDecl *, const Attr *>
1619 CallExpr::getUnusedResultAttr(const ASTContext &Ctx) const {
1620 // If the callee is marked nodiscard, return that attribute
1621 const Decl *D = getCalleeDecl();
1622 if (const auto *A = D->getAttr<WarnUnusedResultAttr>())
1623 return {nullptr, A};
1625 // If the return type is a struct, union, or enum that is marked nodiscard,
1626 // then return the return type attribute.
1627 if (const TagDecl *TD = getCallReturnType(Ctx)->getAsTagDecl())
1628 if (const auto *A = TD->getAttr<WarnUnusedResultAttr>())
1629 return {TD, A};
1631 for (const auto *TD = getCallReturnType(Ctx)->getAs<TypedefType>(); TD;
1632 TD = TD->desugar()->getAs<TypedefType>())
1633 if (const auto *A = TD->getDecl()->getAttr<WarnUnusedResultAttr>())
1634 return {TD->getDecl(), A};
1635 return {nullptr, nullptr};
1638 SourceLocation CallExpr::getBeginLoc() const {
1639 if (const auto *OCE = dyn_cast<CXXOperatorCallExpr>(this))
1640 return OCE->getBeginLoc();
1642 SourceLocation begin = getCallee()->getBeginLoc();
1643 if (begin.isInvalid() && getNumArgs() > 0 && getArg(0))
1644 begin = getArg(0)->getBeginLoc();
1645 return begin;
1647 SourceLocation CallExpr::getEndLoc() const {
1648 if (const auto *OCE = dyn_cast<CXXOperatorCallExpr>(this))
1649 return OCE->getEndLoc();
1651 SourceLocation end = getRParenLoc();
1652 if (end.isInvalid() && getNumArgs() > 0 && getArg(getNumArgs() - 1))
1653 end = getArg(getNumArgs() - 1)->getEndLoc();
1654 return end;
1657 OffsetOfExpr *OffsetOfExpr::Create(const ASTContext &C, QualType type,
1658 SourceLocation OperatorLoc,
1659 TypeSourceInfo *tsi,
1660 ArrayRef<OffsetOfNode> comps,
1661 ArrayRef<Expr*> exprs,
1662 SourceLocation RParenLoc) {
1663 void *Mem = C.Allocate(
1664 totalSizeToAlloc<OffsetOfNode, Expr *>(comps.size(), exprs.size()));
1666 return new (Mem) OffsetOfExpr(C, type, OperatorLoc, tsi, comps, exprs,
1667 RParenLoc);
1670 OffsetOfExpr *OffsetOfExpr::CreateEmpty(const ASTContext &C,
1671 unsigned numComps, unsigned numExprs) {
1672 void *Mem =
1673 C.Allocate(totalSizeToAlloc<OffsetOfNode, Expr *>(numComps, numExprs));
1674 return new (Mem) OffsetOfExpr(numComps, numExprs);
1677 OffsetOfExpr::OffsetOfExpr(const ASTContext &C, QualType type,
1678 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
1679 ArrayRef<OffsetOfNode> comps, ArrayRef<Expr *> exprs,
1680 SourceLocation RParenLoc)
1681 : Expr(OffsetOfExprClass, type, VK_PRValue, OK_Ordinary),
1682 OperatorLoc(OperatorLoc), RParenLoc(RParenLoc), TSInfo(tsi),
1683 NumComps(comps.size()), NumExprs(exprs.size()) {
1684 for (unsigned i = 0; i != comps.size(); ++i)
1685 setComponent(i, comps[i]);
1686 for (unsigned i = 0; i != exprs.size(); ++i)
1687 setIndexExpr(i, exprs[i]);
1689 setDependence(computeDependence(this));
1692 IdentifierInfo *OffsetOfNode::getFieldName() const {
1693 assert(getKind() == Field || getKind() == Identifier);
1694 if (getKind() == Field)
1695 return getField()->getIdentifier();
1697 return reinterpret_cast<IdentifierInfo *> (Data & ~(uintptr_t)Mask);
1700 UnaryExprOrTypeTraitExpr::UnaryExprOrTypeTraitExpr(
1701 UnaryExprOrTypeTrait ExprKind, Expr *E, QualType resultType,
1702 SourceLocation op, SourceLocation rp)
1703 : Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_PRValue, OK_Ordinary),
1704 OpLoc(op), RParenLoc(rp) {
1705 assert(ExprKind <= UETT_Last && "invalid enum value!");
1706 UnaryExprOrTypeTraitExprBits.Kind = ExprKind;
1707 assert(static_cast<unsigned>(ExprKind) == UnaryExprOrTypeTraitExprBits.Kind &&
1708 "UnaryExprOrTypeTraitExprBits.Kind overflow!");
1709 UnaryExprOrTypeTraitExprBits.IsType = false;
1710 Argument.Ex = E;
1711 setDependence(computeDependence(this));
1714 MemberExpr::MemberExpr(Expr *Base, bool IsArrow, SourceLocation OperatorLoc,
1715 NestedNameSpecifierLoc QualifierLoc,
1716 SourceLocation TemplateKWLoc, ValueDecl *MemberDecl,
1717 DeclAccessPair FoundDecl,
1718 const DeclarationNameInfo &NameInfo,
1719 const TemplateArgumentListInfo *TemplateArgs, QualType T,
1720 ExprValueKind VK, ExprObjectKind OK,
1721 NonOdrUseReason NOUR)
1722 : Expr(MemberExprClass, T, VK, OK), Base(Base), MemberDecl(MemberDecl),
1723 MemberDNLoc(NameInfo.getInfo()), MemberLoc(NameInfo.getLoc()) {
1724 assert(!NameInfo.getName() ||
1725 MemberDecl->getDeclName() == NameInfo.getName());
1726 MemberExprBits.IsArrow = IsArrow;
1727 MemberExprBits.HasQualifier = QualifierLoc.hasQualifier();
1728 MemberExprBits.HasFoundDecl =
1729 FoundDecl.getDecl() != MemberDecl ||
1730 FoundDecl.getAccess() != MemberDecl->getAccess();
1731 MemberExprBits.HasTemplateKWAndArgsInfo =
1732 TemplateArgs || TemplateKWLoc.isValid();
1733 MemberExprBits.HadMultipleCandidates = false;
1734 MemberExprBits.NonOdrUseReason = NOUR;
1735 MemberExprBits.OperatorLoc = OperatorLoc;
1737 if (hasQualifier())
1738 new (getTrailingObjects<NestedNameSpecifierLoc>())
1739 NestedNameSpecifierLoc(QualifierLoc);
1740 if (hasFoundDecl())
1741 *getTrailingObjects<DeclAccessPair>() = FoundDecl;
1742 if (TemplateArgs) {
1743 auto Deps = TemplateArgumentDependence::None;
1744 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
1745 TemplateKWLoc, *TemplateArgs, getTrailingObjects<TemplateArgumentLoc>(),
1746 Deps);
1747 } else if (TemplateKWLoc.isValid()) {
1748 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
1749 TemplateKWLoc);
1751 setDependence(computeDependence(this));
1754 MemberExpr *MemberExpr::Create(
1755 const ASTContext &C, Expr *Base, bool IsArrow, SourceLocation OperatorLoc,
1756 NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,
1757 ValueDecl *MemberDecl, DeclAccessPair FoundDecl,
1758 DeclarationNameInfo NameInfo, const TemplateArgumentListInfo *TemplateArgs,
1759 QualType T, ExprValueKind VK, ExprObjectKind OK, NonOdrUseReason NOUR) {
1760 bool HasQualifier = QualifierLoc.hasQualifier();
1761 bool HasFoundDecl = FoundDecl.getDecl() != MemberDecl ||
1762 FoundDecl.getAccess() != MemberDecl->getAccess();
1763 bool HasTemplateKWAndArgsInfo = TemplateArgs || TemplateKWLoc.isValid();
1764 std::size_t Size =
1765 totalSizeToAlloc<NestedNameSpecifierLoc, DeclAccessPair,
1766 ASTTemplateKWAndArgsInfo, TemplateArgumentLoc>(
1767 HasQualifier, HasFoundDecl, HasTemplateKWAndArgsInfo,
1768 TemplateArgs ? TemplateArgs->size() : 0);
1770 void *Mem = C.Allocate(Size, alignof(MemberExpr));
1771 return new (Mem) MemberExpr(Base, IsArrow, OperatorLoc, QualifierLoc,
1772 TemplateKWLoc, MemberDecl, FoundDecl, NameInfo,
1773 TemplateArgs, T, VK, OK, NOUR);
1776 MemberExpr *MemberExpr::CreateEmpty(const ASTContext &Context,
1777 bool HasQualifier, bool HasFoundDecl,
1778 bool HasTemplateKWAndArgsInfo,
1779 unsigned NumTemplateArgs) {
1780 assert((!NumTemplateArgs || HasTemplateKWAndArgsInfo) &&
1781 "template args but no template arg info?");
1782 std::size_t Size =
1783 totalSizeToAlloc<NestedNameSpecifierLoc, DeclAccessPair,
1784 ASTTemplateKWAndArgsInfo, TemplateArgumentLoc>(
1785 HasQualifier, HasFoundDecl, HasTemplateKWAndArgsInfo,
1786 NumTemplateArgs);
1787 void *Mem = Context.Allocate(Size, alignof(MemberExpr));
1788 return new (Mem) MemberExpr(EmptyShell());
1791 void MemberExpr::setMemberDecl(ValueDecl *NewD) {
1792 MemberDecl = NewD;
1793 if (getType()->isUndeducedType())
1794 setType(NewD->getType());
1795 setDependence(computeDependence(this));
1798 SourceLocation MemberExpr::getBeginLoc() const {
1799 if (isImplicitAccess()) {
1800 if (hasQualifier())
1801 return getQualifierLoc().getBeginLoc();
1802 return MemberLoc;
1805 // FIXME: We don't want this to happen. Rather, we should be able to
1806 // detect all kinds of implicit accesses more cleanly.
1807 SourceLocation BaseStartLoc = getBase()->getBeginLoc();
1808 if (BaseStartLoc.isValid())
1809 return BaseStartLoc;
1810 return MemberLoc;
1812 SourceLocation MemberExpr::getEndLoc() const {
1813 SourceLocation EndLoc = getMemberNameInfo().getEndLoc();
1814 if (hasExplicitTemplateArgs())
1815 EndLoc = getRAngleLoc();
1816 else if (EndLoc.isInvalid())
1817 EndLoc = getBase()->getEndLoc();
1818 return EndLoc;
1821 bool CastExpr::CastConsistency() const {
1822 switch (getCastKind()) {
1823 case CK_DerivedToBase:
1824 case CK_UncheckedDerivedToBase:
1825 case CK_DerivedToBaseMemberPointer:
1826 case CK_BaseToDerived:
1827 case CK_BaseToDerivedMemberPointer:
1828 assert(!path_empty() && "Cast kind should have a base path!");
1829 break;
1831 case CK_CPointerToObjCPointerCast:
1832 assert(getType()->isObjCObjectPointerType());
1833 assert(getSubExpr()->getType()->isPointerType());
1834 goto CheckNoBasePath;
1836 case CK_BlockPointerToObjCPointerCast:
1837 assert(getType()->isObjCObjectPointerType());
1838 assert(getSubExpr()->getType()->isBlockPointerType());
1839 goto CheckNoBasePath;
1841 case CK_ReinterpretMemberPointer:
1842 assert(getType()->isMemberPointerType());
1843 assert(getSubExpr()->getType()->isMemberPointerType());
1844 goto CheckNoBasePath;
1846 case CK_BitCast:
1847 // Arbitrary casts to C pointer types count as bitcasts.
1848 // Otherwise, we should only have block and ObjC pointer casts
1849 // here if they stay within the type kind.
1850 if (!getType()->isPointerType()) {
1851 assert(getType()->isObjCObjectPointerType() ==
1852 getSubExpr()->getType()->isObjCObjectPointerType());
1853 assert(getType()->isBlockPointerType() ==
1854 getSubExpr()->getType()->isBlockPointerType());
1856 goto CheckNoBasePath;
1858 case CK_AnyPointerToBlockPointerCast:
1859 assert(getType()->isBlockPointerType());
1860 assert(getSubExpr()->getType()->isAnyPointerType() &&
1861 !getSubExpr()->getType()->isBlockPointerType());
1862 goto CheckNoBasePath;
1864 case CK_CopyAndAutoreleaseBlockObject:
1865 assert(getType()->isBlockPointerType());
1866 assert(getSubExpr()->getType()->isBlockPointerType());
1867 goto CheckNoBasePath;
1869 case CK_FunctionToPointerDecay:
1870 assert(getType()->isPointerType());
1871 assert(getSubExpr()->getType()->isFunctionType());
1872 goto CheckNoBasePath;
1874 case CK_AddressSpaceConversion: {
1875 auto Ty = getType();
1876 auto SETy = getSubExpr()->getType();
1877 assert(getValueKindForType(Ty) == Expr::getValueKindForType(SETy));
1878 if (isPRValue() && !Ty->isDependentType() && !SETy->isDependentType()) {
1879 Ty = Ty->getPointeeType();
1880 SETy = SETy->getPointeeType();
1882 assert((Ty->isDependentType() || SETy->isDependentType()) ||
1883 (!Ty.isNull() && !SETy.isNull() &&
1884 Ty.getAddressSpace() != SETy.getAddressSpace()));
1885 goto CheckNoBasePath;
1887 // These should not have an inheritance path.
1888 case CK_Dynamic:
1889 case CK_ToUnion:
1890 case CK_ArrayToPointerDecay:
1891 case CK_NullToMemberPointer:
1892 case CK_NullToPointer:
1893 case CK_ConstructorConversion:
1894 case CK_IntegralToPointer:
1895 case CK_PointerToIntegral:
1896 case CK_ToVoid:
1897 case CK_VectorSplat:
1898 case CK_IntegralCast:
1899 case CK_BooleanToSignedIntegral:
1900 case CK_IntegralToFloating:
1901 case CK_FloatingToIntegral:
1902 case CK_FloatingCast:
1903 case CK_ObjCObjectLValueCast:
1904 case CK_FloatingRealToComplex:
1905 case CK_FloatingComplexToReal:
1906 case CK_FloatingComplexCast:
1907 case CK_FloatingComplexToIntegralComplex:
1908 case CK_IntegralRealToComplex:
1909 case CK_IntegralComplexToReal:
1910 case CK_IntegralComplexCast:
1911 case CK_IntegralComplexToFloatingComplex:
1912 case CK_ARCProduceObject:
1913 case CK_ARCConsumeObject:
1914 case CK_ARCReclaimReturnedObject:
1915 case CK_ARCExtendBlockObject:
1916 case CK_ZeroToOCLOpaqueType:
1917 case CK_IntToOCLSampler:
1918 case CK_FloatingToFixedPoint:
1919 case CK_FixedPointToFloating:
1920 case CK_FixedPointCast:
1921 case CK_FixedPointToIntegral:
1922 case CK_IntegralToFixedPoint:
1923 case CK_MatrixCast:
1924 assert(!getType()->isBooleanType() && "unheralded conversion to bool");
1925 goto CheckNoBasePath;
1927 case CK_Dependent:
1928 case CK_LValueToRValue:
1929 case CK_NoOp:
1930 case CK_AtomicToNonAtomic:
1931 case CK_NonAtomicToAtomic:
1932 case CK_PointerToBoolean:
1933 case CK_IntegralToBoolean:
1934 case CK_FloatingToBoolean:
1935 case CK_MemberPointerToBoolean:
1936 case CK_FloatingComplexToBoolean:
1937 case CK_IntegralComplexToBoolean:
1938 case CK_LValueBitCast: // -> bool&
1939 case CK_LValueToRValueBitCast:
1940 case CK_UserDefinedConversion: // operator bool()
1941 case CK_BuiltinFnToFnPtr:
1942 case CK_FixedPointToBoolean:
1943 case CK_HLSLArrayRValue:
1944 case CK_HLSLVectorTruncation:
1945 CheckNoBasePath:
1946 assert(path_empty() && "Cast kind should not have a base path!");
1947 break;
1949 return true;
1952 const char *CastExpr::getCastKindName(CastKind CK) {
1953 switch (CK) {
1954 #define CAST_OPERATION(Name) case CK_##Name: return #Name;
1955 #include "clang/AST/OperationKinds.def"
1957 llvm_unreachable("Unhandled cast kind!");
1960 namespace {
1961 // Skip over implicit nodes produced as part of semantic analysis.
1962 // Designed for use with IgnoreExprNodes.
1963 static Expr *ignoreImplicitSemaNodes(Expr *E) {
1964 if (auto *Materialize = dyn_cast<MaterializeTemporaryExpr>(E))
1965 return Materialize->getSubExpr();
1967 if (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
1968 return Binder->getSubExpr();
1970 if (auto *Full = dyn_cast<FullExpr>(E))
1971 return Full->getSubExpr();
1973 if (auto *CPLIE = dyn_cast<CXXParenListInitExpr>(E);
1974 CPLIE && CPLIE->getInitExprs().size() == 1)
1975 return CPLIE->getInitExprs()[0];
1977 return E;
1979 } // namespace
1981 Expr *CastExpr::getSubExprAsWritten() {
1982 const Expr *SubExpr = nullptr;
1984 for (const CastExpr *E = this; E; E = dyn_cast<ImplicitCastExpr>(SubExpr)) {
1985 SubExpr = IgnoreExprNodes(E->getSubExpr(), ignoreImplicitSemaNodes);
1987 // Conversions by constructor and conversion functions have a
1988 // subexpression describing the call; strip it off.
1989 if (E->getCastKind() == CK_ConstructorConversion) {
1990 SubExpr = IgnoreExprNodes(cast<CXXConstructExpr>(SubExpr)->getArg(0),
1991 ignoreImplicitSemaNodes);
1992 } else if (E->getCastKind() == CK_UserDefinedConversion) {
1993 assert((isa<CallExpr, BlockExpr>(SubExpr)) &&
1994 "Unexpected SubExpr for CK_UserDefinedConversion.");
1995 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SubExpr))
1996 SubExpr = MCE->getImplicitObjectArgument();
2000 return const_cast<Expr *>(SubExpr);
2003 NamedDecl *CastExpr::getConversionFunction() const {
2004 const Expr *SubExpr = nullptr;
2006 for (const CastExpr *E = this; E; E = dyn_cast<ImplicitCastExpr>(SubExpr)) {
2007 SubExpr = IgnoreExprNodes(E->getSubExpr(), ignoreImplicitSemaNodes);
2009 if (E->getCastKind() == CK_ConstructorConversion)
2010 return cast<CXXConstructExpr>(SubExpr)->getConstructor();
2012 if (E->getCastKind() == CK_UserDefinedConversion) {
2013 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SubExpr))
2014 return MCE->getMethodDecl();
2018 return nullptr;
2021 CXXBaseSpecifier **CastExpr::path_buffer() {
2022 switch (getStmtClass()) {
2023 #define ABSTRACT_STMT(x)
2024 #define CASTEXPR(Type, Base) \
2025 case Stmt::Type##Class: \
2026 return static_cast<Type *>(this)->getTrailingObjects<CXXBaseSpecifier *>();
2027 #define STMT(Type, Base)
2028 #include "clang/AST/StmtNodes.inc"
2029 default:
2030 llvm_unreachable("non-cast expressions not possible here");
2034 const FieldDecl *CastExpr::getTargetFieldForToUnionCast(QualType unionType,
2035 QualType opType) {
2036 auto RD = unionType->castAs<RecordType>()->getDecl();
2037 return getTargetFieldForToUnionCast(RD, opType);
2040 const FieldDecl *CastExpr::getTargetFieldForToUnionCast(const RecordDecl *RD,
2041 QualType OpType) {
2042 auto &Ctx = RD->getASTContext();
2043 RecordDecl::field_iterator Field, FieldEnd;
2044 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
2045 Field != FieldEnd; ++Field) {
2046 if (Ctx.hasSameUnqualifiedType(Field->getType(), OpType) &&
2047 !Field->isUnnamedBitField()) {
2048 return *Field;
2051 return nullptr;
2054 FPOptionsOverride *CastExpr::getTrailingFPFeatures() {
2055 assert(hasStoredFPFeatures());
2056 switch (getStmtClass()) {
2057 case ImplicitCastExprClass:
2058 return static_cast<ImplicitCastExpr *>(this)
2059 ->getTrailingObjects<FPOptionsOverride>();
2060 case CStyleCastExprClass:
2061 return static_cast<CStyleCastExpr *>(this)
2062 ->getTrailingObjects<FPOptionsOverride>();
2063 case CXXFunctionalCastExprClass:
2064 return static_cast<CXXFunctionalCastExpr *>(this)
2065 ->getTrailingObjects<FPOptionsOverride>();
2066 case CXXStaticCastExprClass:
2067 return static_cast<CXXStaticCastExpr *>(this)
2068 ->getTrailingObjects<FPOptionsOverride>();
2069 default:
2070 llvm_unreachable("Cast does not have FPFeatures");
2074 ImplicitCastExpr *ImplicitCastExpr::Create(const ASTContext &C, QualType T,
2075 CastKind Kind, Expr *Operand,
2076 const CXXCastPath *BasePath,
2077 ExprValueKind VK,
2078 FPOptionsOverride FPO) {
2079 unsigned PathSize = (BasePath ? BasePath->size() : 0);
2080 void *Buffer =
2081 C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *, FPOptionsOverride>(
2082 PathSize, FPO.requiresTrailingStorage()));
2083 // Per C++ [conv.lval]p3, lvalue-to-rvalue conversions on class and
2084 // std::nullptr_t have special semantics not captured by CK_LValueToRValue.
2085 assert((Kind != CK_LValueToRValue ||
2086 !(T->isNullPtrType() || T->getAsCXXRecordDecl())) &&
2087 "invalid type for lvalue-to-rvalue conversion");
2088 ImplicitCastExpr *E =
2089 new (Buffer) ImplicitCastExpr(T, Kind, Operand, PathSize, FPO, VK);
2090 if (PathSize)
2091 std::uninitialized_copy_n(BasePath->data(), BasePath->size(),
2092 E->getTrailingObjects<CXXBaseSpecifier *>());
2093 return E;
2096 ImplicitCastExpr *ImplicitCastExpr::CreateEmpty(const ASTContext &C,
2097 unsigned PathSize,
2098 bool HasFPFeatures) {
2099 void *Buffer =
2100 C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *, FPOptionsOverride>(
2101 PathSize, HasFPFeatures));
2102 return new (Buffer) ImplicitCastExpr(EmptyShell(), PathSize, HasFPFeatures);
2105 CStyleCastExpr *CStyleCastExpr::Create(const ASTContext &C, QualType T,
2106 ExprValueKind VK, CastKind K, Expr *Op,
2107 const CXXCastPath *BasePath,
2108 FPOptionsOverride FPO,
2109 TypeSourceInfo *WrittenTy,
2110 SourceLocation L, SourceLocation R) {
2111 unsigned PathSize = (BasePath ? BasePath->size() : 0);
2112 void *Buffer =
2113 C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *, FPOptionsOverride>(
2114 PathSize, FPO.requiresTrailingStorage()));
2115 CStyleCastExpr *E =
2116 new (Buffer) CStyleCastExpr(T, VK, K, Op, PathSize, FPO, WrittenTy, L, R);
2117 if (PathSize)
2118 std::uninitialized_copy_n(BasePath->data(), BasePath->size(),
2119 E->getTrailingObjects<CXXBaseSpecifier *>());
2120 return E;
2123 CStyleCastExpr *CStyleCastExpr::CreateEmpty(const ASTContext &C,
2124 unsigned PathSize,
2125 bool HasFPFeatures) {
2126 void *Buffer =
2127 C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *, FPOptionsOverride>(
2128 PathSize, HasFPFeatures));
2129 return new (Buffer) CStyleCastExpr(EmptyShell(), PathSize, HasFPFeatures);
2132 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
2133 /// corresponds to, e.g. "<<=".
2134 StringRef BinaryOperator::getOpcodeStr(Opcode Op) {
2135 switch (Op) {
2136 #define BINARY_OPERATION(Name, Spelling) case BO_##Name: return Spelling;
2137 #include "clang/AST/OperationKinds.def"
2139 llvm_unreachable("Invalid OpCode!");
2142 BinaryOperatorKind
2143 BinaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO) {
2144 switch (OO) {
2145 default: llvm_unreachable("Not an overloadable binary operator");
2146 case OO_Plus: return BO_Add;
2147 case OO_Minus: return BO_Sub;
2148 case OO_Star: return BO_Mul;
2149 case OO_Slash: return BO_Div;
2150 case OO_Percent: return BO_Rem;
2151 case OO_Caret: return BO_Xor;
2152 case OO_Amp: return BO_And;
2153 case OO_Pipe: return BO_Or;
2154 case OO_Equal: return BO_Assign;
2155 case OO_Spaceship: return BO_Cmp;
2156 case OO_Less: return BO_LT;
2157 case OO_Greater: return BO_GT;
2158 case OO_PlusEqual: return BO_AddAssign;
2159 case OO_MinusEqual: return BO_SubAssign;
2160 case OO_StarEqual: return BO_MulAssign;
2161 case OO_SlashEqual: return BO_DivAssign;
2162 case OO_PercentEqual: return BO_RemAssign;
2163 case OO_CaretEqual: return BO_XorAssign;
2164 case OO_AmpEqual: return BO_AndAssign;
2165 case OO_PipeEqual: return BO_OrAssign;
2166 case OO_LessLess: return BO_Shl;
2167 case OO_GreaterGreater: return BO_Shr;
2168 case OO_LessLessEqual: return BO_ShlAssign;
2169 case OO_GreaterGreaterEqual: return BO_ShrAssign;
2170 case OO_EqualEqual: return BO_EQ;
2171 case OO_ExclaimEqual: return BO_NE;
2172 case OO_LessEqual: return BO_LE;
2173 case OO_GreaterEqual: return BO_GE;
2174 case OO_AmpAmp: return BO_LAnd;
2175 case OO_PipePipe: return BO_LOr;
2176 case OO_Comma: return BO_Comma;
2177 case OO_ArrowStar: return BO_PtrMemI;
2181 OverloadedOperatorKind BinaryOperator::getOverloadedOperator(Opcode Opc) {
2182 static const OverloadedOperatorKind OverOps[] = {
2183 /* .* Cannot be overloaded */OO_None, OO_ArrowStar,
2184 OO_Star, OO_Slash, OO_Percent,
2185 OO_Plus, OO_Minus,
2186 OO_LessLess, OO_GreaterGreater,
2187 OO_Spaceship,
2188 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
2189 OO_EqualEqual, OO_ExclaimEqual,
2190 OO_Amp,
2191 OO_Caret,
2192 OO_Pipe,
2193 OO_AmpAmp,
2194 OO_PipePipe,
2195 OO_Equal, OO_StarEqual,
2196 OO_SlashEqual, OO_PercentEqual,
2197 OO_PlusEqual, OO_MinusEqual,
2198 OO_LessLessEqual, OO_GreaterGreaterEqual,
2199 OO_AmpEqual, OO_CaretEqual,
2200 OO_PipeEqual,
2201 OO_Comma
2203 return OverOps[Opc];
2206 bool BinaryOperator::isNullPointerArithmeticExtension(ASTContext &Ctx,
2207 Opcode Opc,
2208 const Expr *LHS,
2209 const Expr *RHS) {
2210 if (Opc != BO_Add)
2211 return false;
2213 // Check that we have one pointer and one integer operand.
2214 const Expr *PExp;
2215 if (LHS->getType()->isPointerType()) {
2216 if (!RHS->getType()->isIntegerType())
2217 return false;
2218 PExp = LHS;
2219 } else if (RHS->getType()->isPointerType()) {
2220 if (!LHS->getType()->isIntegerType())
2221 return false;
2222 PExp = RHS;
2223 } else {
2224 return false;
2227 // Check that the pointer is a nullptr.
2228 if (!PExp->IgnoreParenCasts()
2229 ->isNullPointerConstant(Ctx, Expr::NPC_ValueDependentIsNotNull))
2230 return false;
2232 // Check that the pointee type is char-sized.
2233 const PointerType *PTy = PExp->getType()->getAs<PointerType>();
2234 if (!PTy || !PTy->getPointeeType()->isCharType())
2235 return false;
2237 return true;
2240 SourceLocExpr::SourceLocExpr(const ASTContext &Ctx, SourceLocIdentKind Kind,
2241 QualType ResultTy, SourceLocation BLoc,
2242 SourceLocation RParenLoc,
2243 DeclContext *ParentContext)
2244 : Expr(SourceLocExprClass, ResultTy, VK_PRValue, OK_Ordinary),
2245 BuiltinLoc(BLoc), RParenLoc(RParenLoc), ParentContext(ParentContext) {
2246 SourceLocExprBits.Kind = llvm::to_underlying(Kind);
2247 // In dependent contexts, function names may change.
2248 setDependence(MayBeDependent(Kind) && ParentContext->isDependentContext()
2249 ? ExprDependence::Value
2250 : ExprDependence::None);
2253 StringRef SourceLocExpr::getBuiltinStr() const {
2254 switch (getIdentKind()) {
2255 case SourceLocIdentKind::File:
2256 return "__builtin_FILE";
2257 case SourceLocIdentKind::FileName:
2258 return "__builtin_FILE_NAME";
2259 case SourceLocIdentKind::Function:
2260 return "__builtin_FUNCTION";
2261 case SourceLocIdentKind::FuncSig:
2262 return "__builtin_FUNCSIG";
2263 case SourceLocIdentKind::Line:
2264 return "__builtin_LINE";
2265 case SourceLocIdentKind::Column:
2266 return "__builtin_COLUMN";
2267 case SourceLocIdentKind::SourceLocStruct:
2268 return "__builtin_source_location";
2270 llvm_unreachable("unexpected IdentKind!");
2273 APValue SourceLocExpr::EvaluateInContext(const ASTContext &Ctx,
2274 const Expr *DefaultExpr) const {
2275 SourceLocation Loc;
2276 const DeclContext *Context;
2278 if (const auto *DIE = dyn_cast_if_present<CXXDefaultInitExpr>(DefaultExpr)) {
2279 Loc = DIE->getUsedLocation();
2280 Context = DIE->getUsedContext();
2281 } else if (const auto *DAE =
2282 dyn_cast_if_present<CXXDefaultArgExpr>(DefaultExpr)) {
2283 Loc = DAE->getUsedLocation();
2284 Context = DAE->getUsedContext();
2285 } else {
2286 Loc = getLocation();
2287 Context = getParentContext();
2290 // If we are currently parsing a lambda declarator, we might not have a fully
2291 // formed call operator declaration yet, and we could not form a function name
2292 // for it. Because we do not have access to Sema/function scopes here, we
2293 // detect this case by relying on the fact such method doesn't yet have a
2294 // type.
2295 if (const auto *D = dyn_cast<CXXMethodDecl>(Context);
2296 D && D->getFunctionTypeLoc().isNull() && isLambdaCallOperator(D))
2297 Context = D->getParent()->getParent();
2299 PresumedLoc PLoc = Ctx.getSourceManager().getPresumedLoc(
2300 Ctx.getSourceManager().getExpansionRange(Loc).getEnd());
2302 auto MakeStringLiteral = [&](StringRef Tmp) {
2303 using LValuePathEntry = APValue::LValuePathEntry;
2304 StringLiteral *Res = Ctx.getPredefinedStringLiteralFromCache(Tmp);
2305 // Decay the string to a pointer to the first character.
2306 LValuePathEntry Path[1] = {LValuePathEntry::ArrayIndex(0)};
2307 return APValue(Res, CharUnits::Zero(), Path, /*OnePastTheEnd=*/false);
2310 switch (getIdentKind()) {
2311 case SourceLocIdentKind::FileName: {
2312 // __builtin_FILE_NAME() is a Clang-specific extension that expands to the
2313 // the last part of __builtin_FILE().
2314 SmallString<256> FileName;
2315 clang::Preprocessor::processPathToFileName(
2316 FileName, PLoc, Ctx.getLangOpts(), Ctx.getTargetInfo());
2317 return MakeStringLiteral(FileName);
2319 case SourceLocIdentKind::File: {
2320 SmallString<256> Path(PLoc.getFilename());
2321 clang::Preprocessor::processPathForFileMacro(Path, Ctx.getLangOpts(),
2322 Ctx.getTargetInfo());
2323 return MakeStringLiteral(Path);
2325 case SourceLocIdentKind::Function:
2326 case SourceLocIdentKind::FuncSig: {
2327 const auto *CurDecl = dyn_cast<Decl>(Context);
2328 const auto Kind = getIdentKind() == SourceLocIdentKind::Function
2329 ? PredefinedIdentKind::Function
2330 : PredefinedIdentKind::FuncSig;
2331 return MakeStringLiteral(
2332 CurDecl ? PredefinedExpr::ComputeName(Kind, CurDecl) : std::string(""));
2334 case SourceLocIdentKind::Line:
2335 return APValue(Ctx.MakeIntValue(PLoc.getLine(), Ctx.UnsignedIntTy));
2336 case SourceLocIdentKind::Column:
2337 return APValue(Ctx.MakeIntValue(PLoc.getColumn(), Ctx.UnsignedIntTy));
2338 case SourceLocIdentKind::SourceLocStruct: {
2339 // Fill in a std::source_location::__impl structure, by creating an
2340 // artificial file-scoped CompoundLiteralExpr, and returning a pointer to
2341 // that.
2342 const CXXRecordDecl *ImplDecl = getType()->getPointeeCXXRecordDecl();
2343 assert(ImplDecl);
2345 // Construct an APValue for the __impl struct, and get or create a Decl
2346 // corresponding to that. Note that we've already verified that the shape of
2347 // the ImplDecl type is as expected.
2349 APValue Value(APValue::UninitStruct(), 0, 4);
2350 for (const FieldDecl *F : ImplDecl->fields()) {
2351 StringRef Name = F->getName();
2352 if (Name == "_M_file_name") {
2353 SmallString<256> Path(PLoc.getFilename());
2354 clang::Preprocessor::processPathForFileMacro(Path, Ctx.getLangOpts(),
2355 Ctx.getTargetInfo());
2356 Value.getStructField(F->getFieldIndex()) = MakeStringLiteral(Path);
2357 } else if (Name == "_M_function_name") {
2358 // Note: this emits the PrettyFunction name -- different than what
2359 // __builtin_FUNCTION() above returns!
2360 const auto *CurDecl = dyn_cast<Decl>(Context);
2361 Value.getStructField(F->getFieldIndex()) = MakeStringLiteral(
2362 CurDecl && !isa<TranslationUnitDecl>(CurDecl)
2363 ? StringRef(PredefinedExpr::ComputeName(
2364 PredefinedIdentKind::PrettyFunction, CurDecl))
2365 : "");
2366 } else if (Name == "_M_line") {
2367 llvm::APSInt IntVal = Ctx.MakeIntValue(PLoc.getLine(), F->getType());
2368 Value.getStructField(F->getFieldIndex()) = APValue(IntVal);
2369 } else if (Name == "_M_column") {
2370 llvm::APSInt IntVal = Ctx.MakeIntValue(PLoc.getColumn(), F->getType());
2371 Value.getStructField(F->getFieldIndex()) = APValue(IntVal);
2375 UnnamedGlobalConstantDecl *GV =
2376 Ctx.getUnnamedGlobalConstantDecl(getType()->getPointeeType(), Value);
2378 return APValue(GV, CharUnits::Zero(), ArrayRef<APValue::LValuePathEntry>{},
2379 false);
2382 llvm_unreachable("unhandled case");
2385 EmbedExpr::EmbedExpr(const ASTContext &Ctx, SourceLocation Loc,
2386 EmbedDataStorage *Data, unsigned Begin,
2387 unsigned NumOfElements)
2388 : Expr(EmbedExprClass, Ctx.IntTy, VK_PRValue, OK_Ordinary),
2389 EmbedKeywordLoc(Loc), Ctx(&Ctx), Data(Data), Begin(Begin),
2390 NumOfElements(NumOfElements) {
2391 setDependence(ExprDependence::None);
2392 FakeChildNode = IntegerLiteral::Create(
2393 Ctx, llvm::APInt::getZero(Ctx.getTypeSize(getType())), getType(), Loc);
2396 InitListExpr::InitListExpr(const ASTContext &C, SourceLocation lbraceloc,
2397 ArrayRef<Expr *> initExprs, SourceLocation rbraceloc)
2398 : Expr(InitListExprClass, QualType(), VK_PRValue, OK_Ordinary),
2399 InitExprs(C, initExprs.size()), LBraceLoc(lbraceloc),
2400 RBraceLoc(rbraceloc), AltForm(nullptr, true) {
2401 sawArrayRangeDesignator(false);
2402 InitExprs.insert(C, InitExprs.end(), initExprs.begin(), initExprs.end());
2404 setDependence(computeDependence(this));
2407 void InitListExpr::reserveInits(const ASTContext &C, unsigned NumInits) {
2408 if (NumInits > InitExprs.size())
2409 InitExprs.reserve(C, NumInits);
2412 void InitListExpr::resizeInits(const ASTContext &C, unsigned NumInits) {
2413 InitExprs.resize(C, NumInits, nullptr);
2416 Expr *InitListExpr::updateInit(const ASTContext &C, unsigned Init, Expr *expr) {
2417 if (Init >= InitExprs.size()) {
2418 InitExprs.insert(C, InitExprs.end(), Init - InitExprs.size() + 1, nullptr);
2419 setInit(Init, expr);
2420 return nullptr;
2423 Expr *Result = cast_or_null<Expr>(InitExprs[Init]);
2424 setInit(Init, expr);
2425 return Result;
2428 void InitListExpr::setArrayFiller(Expr *filler) {
2429 assert(!hasArrayFiller() && "Filler already set!");
2430 ArrayFillerOrUnionFieldInit = filler;
2431 // Fill out any "holes" in the array due to designated initializers.
2432 Expr **inits = getInits();
2433 for (unsigned i = 0, e = getNumInits(); i != e; ++i)
2434 if (inits[i] == nullptr)
2435 inits[i] = filler;
2438 bool InitListExpr::isStringLiteralInit() const {
2439 if (getNumInits() != 1)
2440 return false;
2441 const ArrayType *AT = getType()->getAsArrayTypeUnsafe();
2442 if (!AT || !AT->getElementType()->isIntegerType())
2443 return false;
2444 // It is possible for getInit() to return null.
2445 const Expr *Init = getInit(0);
2446 if (!Init)
2447 return false;
2448 Init = Init->IgnoreParenImpCasts();
2449 return isa<StringLiteral>(Init) || isa<ObjCEncodeExpr>(Init);
2452 bool InitListExpr::isTransparent() const {
2453 assert(isSemanticForm() && "syntactic form never semantically transparent");
2455 // A glvalue InitListExpr is always just sugar.
2456 if (isGLValue()) {
2457 assert(getNumInits() == 1 && "multiple inits in glvalue init list");
2458 return true;
2461 // Otherwise, we're sugar if and only if we have exactly one initializer that
2462 // is of the same type.
2463 if (getNumInits() != 1 || !getInit(0))
2464 return false;
2466 // Don't confuse aggregate initialization of a struct X { X &x; }; with a
2467 // transparent struct copy.
2468 if (!getInit(0)->isPRValue() && getType()->isRecordType())
2469 return false;
2471 return getType().getCanonicalType() ==
2472 getInit(0)->getType().getCanonicalType();
2475 bool InitListExpr::isIdiomaticZeroInitializer(const LangOptions &LangOpts) const {
2476 assert(isSyntacticForm() && "only test syntactic form as zero initializer");
2478 if (LangOpts.CPlusPlus || getNumInits() != 1 || !getInit(0)) {
2479 return false;
2482 const IntegerLiteral *Lit = dyn_cast<IntegerLiteral>(getInit(0)->IgnoreImplicit());
2483 return Lit && Lit->getValue() == 0;
2486 SourceLocation InitListExpr::getBeginLoc() const {
2487 if (InitListExpr *SyntacticForm = getSyntacticForm())
2488 return SyntacticForm->getBeginLoc();
2489 SourceLocation Beg = LBraceLoc;
2490 if (Beg.isInvalid()) {
2491 // Find the first non-null initializer.
2492 for (InitExprsTy::const_iterator I = InitExprs.begin(),
2493 E = InitExprs.end();
2494 I != E; ++I) {
2495 if (Stmt *S = *I) {
2496 Beg = S->getBeginLoc();
2497 break;
2501 return Beg;
2504 SourceLocation InitListExpr::getEndLoc() const {
2505 if (InitListExpr *SyntacticForm = getSyntacticForm())
2506 return SyntacticForm->getEndLoc();
2507 SourceLocation End = RBraceLoc;
2508 if (End.isInvalid()) {
2509 // Find the first non-null initializer from the end.
2510 for (Stmt *S : llvm::reverse(InitExprs)) {
2511 if (S) {
2512 End = S->getEndLoc();
2513 break;
2517 return End;
2520 /// getFunctionType - Return the underlying function type for this block.
2522 const FunctionProtoType *BlockExpr::getFunctionType() const {
2523 // The block pointer is never sugared, but the function type might be.
2524 return cast<BlockPointerType>(getType())
2525 ->getPointeeType()->castAs<FunctionProtoType>();
2528 SourceLocation BlockExpr::getCaretLocation() const {
2529 return TheBlock->getCaretLocation();
2531 const Stmt *BlockExpr::getBody() const {
2532 return TheBlock->getBody();
2534 Stmt *BlockExpr::getBody() {
2535 return TheBlock->getBody();
2539 //===----------------------------------------------------------------------===//
2540 // Generic Expression Routines
2541 //===----------------------------------------------------------------------===//
2543 bool Expr::isReadIfDiscardedInCPlusPlus11() const {
2544 // In C++11, discarded-value expressions of a certain form are special,
2545 // according to [expr]p10:
2546 // The lvalue-to-rvalue conversion (4.1) is applied only if the
2547 // expression is a glvalue of volatile-qualified type and it has
2548 // one of the following forms:
2549 if (!isGLValue() || !getType().isVolatileQualified())
2550 return false;
2552 const Expr *E = IgnoreParens();
2554 // - id-expression (5.1.1),
2555 if (isa<DeclRefExpr>(E))
2556 return true;
2558 // - subscripting (5.2.1),
2559 if (isa<ArraySubscriptExpr>(E))
2560 return true;
2562 // - class member access (5.2.5),
2563 if (isa<MemberExpr>(E))
2564 return true;
2566 // - indirection (5.3.1),
2567 if (auto *UO = dyn_cast<UnaryOperator>(E))
2568 if (UO->getOpcode() == UO_Deref)
2569 return true;
2571 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
2572 // - pointer-to-member operation (5.5),
2573 if (BO->isPtrMemOp())
2574 return true;
2576 // - comma expression (5.18) where the right operand is one of the above.
2577 if (BO->getOpcode() == BO_Comma)
2578 return BO->getRHS()->isReadIfDiscardedInCPlusPlus11();
2581 // - conditional expression (5.16) where both the second and the third
2582 // operands are one of the above, or
2583 if (auto *CO = dyn_cast<ConditionalOperator>(E))
2584 return CO->getTrueExpr()->isReadIfDiscardedInCPlusPlus11() &&
2585 CO->getFalseExpr()->isReadIfDiscardedInCPlusPlus11();
2586 // The related edge case of "*x ?: *x".
2587 if (auto *BCO =
2588 dyn_cast<BinaryConditionalOperator>(E)) {
2589 if (auto *OVE = dyn_cast<OpaqueValueExpr>(BCO->getTrueExpr()))
2590 return OVE->getSourceExpr()->isReadIfDiscardedInCPlusPlus11() &&
2591 BCO->getFalseExpr()->isReadIfDiscardedInCPlusPlus11();
2594 // Objective-C++ extensions to the rule.
2595 if (isa<ObjCIvarRefExpr>(E))
2596 return true;
2597 if (const auto *POE = dyn_cast<PseudoObjectExpr>(E)) {
2598 if (isa<ObjCPropertyRefExpr, ObjCSubscriptRefExpr>(POE->getSyntacticForm()))
2599 return true;
2602 return false;
2605 /// isUnusedResultAWarning - Return true if this immediate expression should
2606 /// be warned about if the result is unused. If so, fill in Loc and Ranges
2607 /// with location to warn on and the source range[s] to report with the
2608 /// warning.
2609 bool Expr::isUnusedResultAWarning(const Expr *&WarnE, SourceLocation &Loc,
2610 SourceRange &R1, SourceRange &R2,
2611 ASTContext &Ctx) const {
2612 // Don't warn if the expr is type dependent. The type could end up
2613 // instantiating to void.
2614 if (isTypeDependent())
2615 return false;
2617 switch (getStmtClass()) {
2618 default:
2619 if (getType()->isVoidType())
2620 return false;
2621 WarnE = this;
2622 Loc = getExprLoc();
2623 R1 = getSourceRange();
2624 return true;
2625 case ParenExprClass:
2626 return cast<ParenExpr>(this)->getSubExpr()->
2627 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2628 case GenericSelectionExprClass:
2629 return cast<GenericSelectionExpr>(this)->getResultExpr()->
2630 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2631 case CoawaitExprClass:
2632 case CoyieldExprClass:
2633 return cast<CoroutineSuspendExpr>(this)->getResumeExpr()->
2634 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2635 case ChooseExprClass:
2636 return cast<ChooseExpr>(this)->getChosenSubExpr()->
2637 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2638 case UnaryOperatorClass: {
2639 const UnaryOperator *UO = cast<UnaryOperator>(this);
2641 switch (UO->getOpcode()) {
2642 case UO_Plus:
2643 case UO_Minus:
2644 case UO_AddrOf:
2645 case UO_Not:
2646 case UO_LNot:
2647 case UO_Deref:
2648 break;
2649 case UO_Coawait:
2650 // This is just the 'operator co_await' call inside the guts of a
2651 // dependent co_await call.
2652 case UO_PostInc:
2653 case UO_PostDec:
2654 case UO_PreInc:
2655 case UO_PreDec: // ++/--
2656 return false; // Not a warning.
2657 case UO_Real:
2658 case UO_Imag:
2659 // accessing a piece of a volatile complex is a side-effect.
2660 if (Ctx.getCanonicalType(UO->getSubExpr()->getType())
2661 .isVolatileQualified())
2662 return false;
2663 break;
2664 case UO_Extension:
2665 return UO->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2667 WarnE = this;
2668 Loc = UO->getOperatorLoc();
2669 R1 = UO->getSubExpr()->getSourceRange();
2670 return true;
2672 case BinaryOperatorClass: {
2673 const BinaryOperator *BO = cast<BinaryOperator>(this);
2674 switch (BO->getOpcode()) {
2675 default:
2676 break;
2677 // Consider the RHS of comma for side effects. LHS was checked by
2678 // Sema::CheckCommaOperands.
2679 case BO_Comma:
2680 // ((foo = <blah>), 0) is an idiom for hiding the result (and
2681 // lvalue-ness) of an assignment written in a macro.
2682 if (IntegerLiteral *IE =
2683 dyn_cast<IntegerLiteral>(BO->getRHS()->IgnoreParens()))
2684 if (IE->getValue() == 0)
2685 return false;
2686 return BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2687 // Consider '||', '&&' to have side effects if the LHS or RHS does.
2688 case BO_LAnd:
2689 case BO_LOr:
2690 if (!BO->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx) ||
2691 !BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx))
2692 return false;
2693 break;
2695 if (BO->isAssignmentOp())
2696 return false;
2697 WarnE = this;
2698 Loc = BO->getOperatorLoc();
2699 R1 = BO->getLHS()->getSourceRange();
2700 R2 = BO->getRHS()->getSourceRange();
2701 return true;
2703 case CompoundAssignOperatorClass:
2704 case VAArgExprClass:
2705 case AtomicExprClass:
2706 return false;
2708 case ConditionalOperatorClass: {
2709 // If only one of the LHS or RHS is a warning, the operator might
2710 // be being used for control flow. Only warn if both the LHS and
2711 // RHS are warnings.
2712 const auto *Exp = cast<ConditionalOperator>(this);
2713 return Exp->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx) &&
2714 Exp->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2716 case BinaryConditionalOperatorClass: {
2717 const auto *Exp = cast<BinaryConditionalOperator>(this);
2718 return Exp->getFalseExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2721 case MemberExprClass:
2722 WarnE = this;
2723 Loc = cast<MemberExpr>(this)->getMemberLoc();
2724 R1 = SourceRange(Loc, Loc);
2725 R2 = cast<MemberExpr>(this)->getBase()->getSourceRange();
2726 return true;
2728 case ArraySubscriptExprClass:
2729 WarnE = this;
2730 Loc = cast<ArraySubscriptExpr>(this)->getRBracketLoc();
2731 R1 = cast<ArraySubscriptExpr>(this)->getLHS()->getSourceRange();
2732 R2 = cast<ArraySubscriptExpr>(this)->getRHS()->getSourceRange();
2733 return true;
2735 case CXXOperatorCallExprClass: {
2736 // Warn about operator ==,!=,<,>,<=, and >= even when user-defined operator
2737 // overloads as there is no reasonable way to define these such that they
2738 // have non-trivial, desirable side-effects. See the -Wunused-comparison
2739 // warning: operators == and != are commonly typo'ed, and so warning on them
2740 // provides additional value as well. If this list is updated,
2741 // DiagnoseUnusedComparison should be as well.
2742 const CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(this);
2743 switch (Op->getOperator()) {
2744 default:
2745 break;
2746 case OO_EqualEqual:
2747 case OO_ExclaimEqual:
2748 case OO_Less:
2749 case OO_Greater:
2750 case OO_GreaterEqual:
2751 case OO_LessEqual:
2752 if (Op->getCallReturnType(Ctx)->isReferenceType() ||
2753 Op->getCallReturnType(Ctx)->isVoidType())
2754 break;
2755 WarnE = this;
2756 Loc = Op->getOperatorLoc();
2757 R1 = Op->getSourceRange();
2758 return true;
2761 // Fallthrough for generic call handling.
2762 [[fallthrough]];
2764 case CallExprClass:
2765 case CXXMemberCallExprClass:
2766 case UserDefinedLiteralClass: {
2767 // If this is a direct call, get the callee.
2768 const CallExpr *CE = cast<CallExpr>(this);
2769 if (const Decl *FD = CE->getCalleeDecl()) {
2770 // If the callee has attribute pure, const, or warn_unused_result, warn
2771 // about it. void foo() { strlen("bar"); } should warn.
2773 // Note: If new cases are added here, DiagnoseUnusedExprResult should be
2774 // updated to match for QoI.
2775 if (CE->hasUnusedResultAttr(Ctx) ||
2776 FD->hasAttr<PureAttr>() || FD->hasAttr<ConstAttr>()) {
2777 WarnE = this;
2778 Loc = CE->getCallee()->getBeginLoc();
2779 R1 = CE->getCallee()->getSourceRange();
2781 if (unsigned NumArgs = CE->getNumArgs())
2782 R2 = SourceRange(CE->getArg(0)->getBeginLoc(),
2783 CE->getArg(NumArgs - 1)->getEndLoc());
2784 return true;
2787 return false;
2790 // If we don't know precisely what we're looking at, let's not warn.
2791 case UnresolvedLookupExprClass:
2792 case CXXUnresolvedConstructExprClass:
2793 case RecoveryExprClass:
2794 return false;
2796 case CXXTemporaryObjectExprClass:
2797 case CXXConstructExprClass: {
2798 if (const CXXRecordDecl *Type = getType()->getAsCXXRecordDecl()) {
2799 const auto *WarnURAttr = Type->getAttr<WarnUnusedResultAttr>();
2800 if (Type->hasAttr<WarnUnusedAttr>() ||
2801 (WarnURAttr && WarnURAttr->IsCXX11NoDiscard())) {
2802 WarnE = this;
2803 Loc = getBeginLoc();
2804 R1 = getSourceRange();
2805 return true;
2809 const auto *CE = cast<CXXConstructExpr>(this);
2810 if (const CXXConstructorDecl *Ctor = CE->getConstructor()) {
2811 const auto *WarnURAttr = Ctor->getAttr<WarnUnusedResultAttr>();
2812 if (WarnURAttr && WarnURAttr->IsCXX11NoDiscard()) {
2813 WarnE = this;
2814 Loc = getBeginLoc();
2815 R1 = getSourceRange();
2817 if (unsigned NumArgs = CE->getNumArgs())
2818 R2 = SourceRange(CE->getArg(0)->getBeginLoc(),
2819 CE->getArg(NumArgs - 1)->getEndLoc());
2820 return true;
2824 return false;
2827 case ObjCMessageExprClass: {
2828 const ObjCMessageExpr *ME = cast<ObjCMessageExpr>(this);
2829 if (Ctx.getLangOpts().ObjCAutoRefCount &&
2830 ME->isInstanceMessage() &&
2831 !ME->getType()->isVoidType() &&
2832 ME->getMethodFamily() == OMF_init) {
2833 WarnE = this;
2834 Loc = getExprLoc();
2835 R1 = ME->getSourceRange();
2836 return true;
2839 if (const ObjCMethodDecl *MD = ME->getMethodDecl())
2840 if (MD->hasAttr<WarnUnusedResultAttr>()) {
2841 WarnE = this;
2842 Loc = getExprLoc();
2843 return true;
2846 return false;
2849 case ObjCPropertyRefExprClass:
2850 case ObjCSubscriptRefExprClass:
2851 WarnE = this;
2852 Loc = getExprLoc();
2853 R1 = getSourceRange();
2854 return true;
2856 case PseudoObjectExprClass: {
2857 const auto *POE = cast<PseudoObjectExpr>(this);
2859 // For some syntactic forms, we should always warn.
2860 if (isa<ObjCPropertyRefExpr, ObjCSubscriptRefExpr>(
2861 POE->getSyntacticForm())) {
2862 WarnE = this;
2863 Loc = getExprLoc();
2864 R1 = getSourceRange();
2865 return true;
2868 // For others, we should never warn.
2869 if (auto *BO = dyn_cast<BinaryOperator>(POE->getSyntacticForm()))
2870 if (BO->isAssignmentOp())
2871 return false;
2872 if (auto *UO = dyn_cast<UnaryOperator>(POE->getSyntacticForm()))
2873 if (UO->isIncrementDecrementOp())
2874 return false;
2876 // Otherwise, warn if the result expression would warn.
2877 const Expr *Result = POE->getResultExpr();
2878 return Result && Result->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2881 case StmtExprClass: {
2882 // Statement exprs don't logically have side effects themselves, but are
2883 // sometimes used in macros in ways that give them a type that is unused.
2884 // For example ({ blah; foo(); }) will end up with a type if foo has a type.
2885 // however, if the result of the stmt expr is dead, we don't want to emit a
2886 // warning.
2887 const CompoundStmt *CS = cast<StmtExpr>(this)->getSubStmt();
2888 if (!CS->body_empty()) {
2889 if (const Expr *E = dyn_cast<Expr>(CS->body_back()))
2890 return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2891 if (const LabelStmt *Label = dyn_cast<LabelStmt>(CS->body_back()))
2892 if (const Expr *E = dyn_cast<Expr>(Label->getSubStmt()))
2893 return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2896 if (getType()->isVoidType())
2897 return false;
2898 WarnE = this;
2899 Loc = cast<StmtExpr>(this)->getLParenLoc();
2900 R1 = getSourceRange();
2901 return true;
2903 case CXXFunctionalCastExprClass:
2904 case CStyleCastExprClass: {
2905 // Ignore an explicit cast to void, except in C++98 if the operand is a
2906 // volatile glvalue for which we would trigger an implicit read in any
2907 // other language mode. (Such an implicit read always happens as part of
2908 // the lvalue conversion in C, and happens in C++ for expressions of all
2909 // forms where it seems likely the user intended to trigger a volatile
2910 // load.)
2911 const CastExpr *CE = cast<CastExpr>(this);
2912 const Expr *SubE = CE->getSubExpr()->IgnoreParens();
2913 if (CE->getCastKind() == CK_ToVoid) {
2914 if (Ctx.getLangOpts().CPlusPlus && !Ctx.getLangOpts().CPlusPlus11 &&
2915 SubE->isReadIfDiscardedInCPlusPlus11()) {
2916 // Suppress the "unused value" warning for idiomatic usage of
2917 // '(void)var;' used to suppress "unused variable" warnings.
2918 if (auto *DRE = dyn_cast<DeclRefExpr>(SubE))
2919 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
2920 if (!VD->isExternallyVisible())
2921 return false;
2923 // The lvalue-to-rvalue conversion would have no effect for an array.
2924 // It's implausible that the programmer expected this to result in a
2925 // volatile array load, so don't warn.
2926 if (SubE->getType()->isArrayType())
2927 return false;
2929 return SubE->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2931 return false;
2934 // If this is a cast to a constructor conversion, check the operand.
2935 // Otherwise, the result of the cast is unused.
2936 if (CE->getCastKind() == CK_ConstructorConversion)
2937 return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2938 if (CE->getCastKind() == CK_Dependent)
2939 return false;
2941 WarnE = this;
2942 if (const CXXFunctionalCastExpr *CXXCE =
2943 dyn_cast<CXXFunctionalCastExpr>(this)) {
2944 Loc = CXXCE->getBeginLoc();
2945 R1 = CXXCE->getSubExpr()->getSourceRange();
2946 } else {
2947 const CStyleCastExpr *CStyleCE = cast<CStyleCastExpr>(this);
2948 Loc = CStyleCE->getLParenLoc();
2949 R1 = CStyleCE->getSubExpr()->getSourceRange();
2951 return true;
2953 case ImplicitCastExprClass: {
2954 const CastExpr *ICE = cast<ImplicitCastExpr>(this);
2956 // lvalue-to-rvalue conversion on a volatile lvalue is a side-effect.
2957 if (ICE->getCastKind() == CK_LValueToRValue &&
2958 ICE->getSubExpr()->getType().isVolatileQualified())
2959 return false;
2961 return ICE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2963 case CXXDefaultArgExprClass:
2964 return (cast<CXXDefaultArgExpr>(this)
2965 ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
2966 case CXXDefaultInitExprClass:
2967 return (cast<CXXDefaultInitExpr>(this)
2968 ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
2970 case CXXNewExprClass:
2971 // FIXME: In theory, there might be new expressions that don't have side
2972 // effects (e.g. a placement new with an uninitialized POD).
2973 case CXXDeleteExprClass:
2974 return false;
2975 case MaterializeTemporaryExprClass:
2976 return cast<MaterializeTemporaryExpr>(this)
2977 ->getSubExpr()
2978 ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2979 case CXXBindTemporaryExprClass:
2980 return cast<CXXBindTemporaryExpr>(this)->getSubExpr()
2981 ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2982 case ExprWithCleanupsClass:
2983 return cast<ExprWithCleanups>(this)->getSubExpr()
2984 ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2988 /// isOBJCGCCandidate - Check if an expression is objc gc'able.
2989 /// returns true, if it is; false otherwise.
2990 bool Expr::isOBJCGCCandidate(ASTContext &Ctx) const {
2991 const Expr *E = IgnoreParens();
2992 switch (E->getStmtClass()) {
2993 default:
2994 return false;
2995 case ObjCIvarRefExprClass:
2996 return true;
2997 case Expr::UnaryOperatorClass:
2998 return cast<UnaryOperator>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
2999 case ImplicitCastExprClass:
3000 return cast<ImplicitCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
3001 case MaterializeTemporaryExprClass:
3002 return cast<MaterializeTemporaryExpr>(E)->getSubExpr()->isOBJCGCCandidate(
3003 Ctx);
3004 case CStyleCastExprClass:
3005 return cast<CStyleCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
3006 case DeclRefExprClass: {
3007 const Decl *D = cast<DeclRefExpr>(E)->getDecl();
3009 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
3010 if (VD->hasGlobalStorage())
3011 return true;
3012 QualType T = VD->getType();
3013 // dereferencing to a pointer is always a gc'able candidate,
3014 // unless it is __weak.
3015 return T->isPointerType() &&
3016 (Ctx.getObjCGCAttrKind(T) != Qualifiers::Weak);
3018 return false;
3020 case MemberExprClass: {
3021 const MemberExpr *M = cast<MemberExpr>(E);
3022 return M->getBase()->isOBJCGCCandidate(Ctx);
3024 case ArraySubscriptExprClass:
3025 return cast<ArraySubscriptExpr>(E)->getBase()->isOBJCGCCandidate(Ctx);
3029 bool Expr::isBoundMemberFunction(ASTContext &Ctx) const {
3030 if (isTypeDependent())
3031 return false;
3032 return ClassifyLValue(Ctx) == Expr::LV_MemberFunction;
3035 QualType Expr::findBoundMemberType(const Expr *expr) {
3036 assert(expr->hasPlaceholderType(BuiltinType::BoundMember));
3038 // Bound member expressions are always one of these possibilities:
3039 // x->m x.m x->*y x.*y
3040 // (possibly parenthesized)
3042 expr = expr->IgnoreParens();
3043 if (const MemberExpr *mem = dyn_cast<MemberExpr>(expr)) {
3044 assert(isa<CXXMethodDecl>(mem->getMemberDecl()));
3045 return mem->getMemberDecl()->getType();
3048 if (const BinaryOperator *op = dyn_cast<BinaryOperator>(expr)) {
3049 QualType type = op->getRHS()->getType()->castAs<MemberPointerType>()
3050 ->getPointeeType();
3051 assert(type->isFunctionType());
3052 return type;
3055 assert(isa<UnresolvedMemberExpr>(expr) || isa<CXXPseudoDestructorExpr>(expr));
3056 return QualType();
3059 Expr *Expr::IgnoreImpCasts() {
3060 return IgnoreExprNodes(this, IgnoreImplicitCastsSingleStep);
3063 Expr *Expr::IgnoreCasts() {
3064 return IgnoreExprNodes(this, IgnoreCastsSingleStep);
3067 Expr *Expr::IgnoreImplicit() {
3068 return IgnoreExprNodes(this, IgnoreImplicitSingleStep);
3071 Expr *Expr::IgnoreImplicitAsWritten() {
3072 return IgnoreExprNodes(this, IgnoreImplicitAsWrittenSingleStep);
3075 Expr *Expr::IgnoreParens() {
3076 return IgnoreExprNodes(this, IgnoreParensSingleStep);
3079 Expr *Expr::IgnoreParenImpCasts() {
3080 return IgnoreExprNodes(this, IgnoreParensSingleStep,
3081 IgnoreImplicitCastsExtraSingleStep);
3084 Expr *Expr::IgnoreParenCasts() {
3085 return IgnoreExprNodes(this, IgnoreParensSingleStep, IgnoreCastsSingleStep);
3088 Expr *Expr::IgnoreConversionOperatorSingleStep() {
3089 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(this)) {
3090 if (isa_and_nonnull<CXXConversionDecl>(MCE->getMethodDecl()))
3091 return MCE->getImplicitObjectArgument();
3093 return this;
3096 Expr *Expr::IgnoreParenLValueCasts() {
3097 return IgnoreExprNodes(this, IgnoreParensSingleStep,
3098 IgnoreLValueCastsSingleStep);
3101 Expr *Expr::IgnoreParenBaseCasts() {
3102 return IgnoreExprNodes(this, IgnoreParensSingleStep,
3103 IgnoreBaseCastsSingleStep);
3106 Expr *Expr::IgnoreParenNoopCasts(const ASTContext &Ctx) {
3107 auto IgnoreNoopCastsSingleStep = [&Ctx](Expr *E) {
3108 if (auto *CE = dyn_cast<CastExpr>(E)) {
3109 // We ignore integer <-> casts that are of the same width, ptr<->ptr and
3110 // ptr<->int casts of the same width. We also ignore all identity casts.
3111 Expr *SubExpr = CE->getSubExpr();
3112 bool IsIdentityCast =
3113 Ctx.hasSameUnqualifiedType(E->getType(), SubExpr->getType());
3114 bool IsSameWidthCast = (E->getType()->isPointerType() ||
3115 E->getType()->isIntegralType(Ctx)) &&
3116 (SubExpr->getType()->isPointerType() ||
3117 SubExpr->getType()->isIntegralType(Ctx)) &&
3118 (Ctx.getTypeSize(E->getType()) ==
3119 Ctx.getTypeSize(SubExpr->getType()));
3121 if (IsIdentityCast || IsSameWidthCast)
3122 return SubExpr;
3123 } else if (auto *NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E))
3124 return NTTP->getReplacement();
3126 return E;
3128 return IgnoreExprNodes(this, IgnoreParensSingleStep,
3129 IgnoreNoopCastsSingleStep);
3132 Expr *Expr::IgnoreUnlessSpelledInSource() {
3133 auto IgnoreImplicitConstructorSingleStep = [](Expr *E) {
3134 if (auto *Cast = dyn_cast<CXXFunctionalCastExpr>(E)) {
3135 auto *SE = Cast->getSubExpr();
3136 if (SE->getSourceRange() == E->getSourceRange())
3137 return SE;
3140 if (auto *C = dyn_cast<CXXConstructExpr>(E)) {
3141 auto NumArgs = C->getNumArgs();
3142 if (NumArgs == 1 ||
3143 (NumArgs > 1 && isa<CXXDefaultArgExpr>(C->getArg(1)))) {
3144 Expr *A = C->getArg(0);
3145 if (A->getSourceRange() == E->getSourceRange() || C->isElidable())
3146 return A;
3149 return E;
3151 auto IgnoreImplicitMemberCallSingleStep = [](Expr *E) {
3152 if (auto *C = dyn_cast<CXXMemberCallExpr>(E)) {
3153 Expr *ExprNode = C->getImplicitObjectArgument();
3154 if (ExprNode->getSourceRange() == E->getSourceRange()) {
3155 return ExprNode;
3157 if (auto *PE = dyn_cast<ParenExpr>(ExprNode)) {
3158 if (PE->getSourceRange() == C->getSourceRange()) {
3159 return cast<Expr>(PE);
3162 ExprNode = ExprNode->IgnoreParenImpCasts();
3163 if (ExprNode->getSourceRange() == E->getSourceRange())
3164 return ExprNode;
3166 return E;
3168 return IgnoreExprNodes(
3169 this, IgnoreImplicitSingleStep, IgnoreImplicitCastsExtraSingleStep,
3170 IgnoreParensOnlySingleStep, IgnoreImplicitConstructorSingleStep,
3171 IgnoreImplicitMemberCallSingleStep);
3174 bool Expr::isDefaultArgument() const {
3175 const Expr *E = this;
3176 if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
3177 E = M->getSubExpr();
3179 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3180 E = ICE->getSubExprAsWritten();
3182 return isa<CXXDefaultArgExpr>(E);
3185 /// Skip over any no-op casts and any temporary-binding
3186 /// expressions.
3187 static const Expr *skipTemporaryBindingsNoOpCastsAndParens(const Expr *E) {
3188 if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
3189 E = M->getSubExpr();
3191 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3192 if (ICE->getCastKind() == CK_NoOp)
3193 E = ICE->getSubExpr();
3194 else
3195 break;
3198 while (const CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
3199 E = BE->getSubExpr();
3201 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3202 if (ICE->getCastKind() == CK_NoOp)
3203 E = ICE->getSubExpr();
3204 else
3205 break;
3208 return E->IgnoreParens();
3211 /// isTemporaryObject - Determines if this expression produces a
3212 /// temporary of the given class type.
3213 bool Expr::isTemporaryObject(ASTContext &C, const CXXRecordDecl *TempTy) const {
3214 if (!C.hasSameUnqualifiedType(getType(), C.getTypeDeclType(TempTy)))
3215 return false;
3217 const Expr *E = skipTemporaryBindingsNoOpCastsAndParens(this);
3219 // Temporaries are by definition pr-values of class type.
3220 if (!E->Classify(C).isPRValue()) {
3221 // In this context, property reference is a message call and is pr-value.
3222 if (!isa<ObjCPropertyRefExpr>(E))
3223 return false;
3226 // Black-list a few cases which yield pr-values of class type that don't
3227 // refer to temporaries of that type:
3229 // - implicit derived-to-base conversions
3230 if (isa<ImplicitCastExpr>(E)) {
3231 switch (cast<ImplicitCastExpr>(E)->getCastKind()) {
3232 case CK_DerivedToBase:
3233 case CK_UncheckedDerivedToBase:
3234 return false;
3235 default:
3236 break;
3240 // - member expressions (all)
3241 if (isa<MemberExpr>(E))
3242 return false;
3244 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E))
3245 if (BO->isPtrMemOp())
3246 return false;
3248 // - opaque values (all)
3249 if (isa<OpaqueValueExpr>(E))
3250 return false;
3252 return true;
3255 bool Expr::isImplicitCXXThis() const {
3256 const Expr *E = this;
3258 // Strip away parentheses and casts we don't care about.
3259 while (true) {
3260 if (const ParenExpr *Paren = dyn_cast<ParenExpr>(E)) {
3261 E = Paren->getSubExpr();
3262 continue;
3265 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3266 if (ICE->getCastKind() == CK_NoOp ||
3267 ICE->getCastKind() == CK_LValueToRValue ||
3268 ICE->getCastKind() == CK_DerivedToBase ||
3269 ICE->getCastKind() == CK_UncheckedDerivedToBase) {
3270 E = ICE->getSubExpr();
3271 continue;
3275 if (const UnaryOperator* UnOp = dyn_cast<UnaryOperator>(E)) {
3276 if (UnOp->getOpcode() == UO_Extension) {
3277 E = UnOp->getSubExpr();
3278 continue;
3282 if (const MaterializeTemporaryExpr *M
3283 = dyn_cast<MaterializeTemporaryExpr>(E)) {
3284 E = M->getSubExpr();
3285 continue;
3288 break;
3291 if (const CXXThisExpr *This = dyn_cast<CXXThisExpr>(E))
3292 return This->isImplicit();
3294 return false;
3297 /// hasAnyTypeDependentArguments - Determines if any of the expressions
3298 /// in Exprs is type-dependent.
3299 bool Expr::hasAnyTypeDependentArguments(ArrayRef<Expr *> Exprs) {
3300 for (unsigned I = 0; I < Exprs.size(); ++I)
3301 if (Exprs[I]->isTypeDependent())
3302 return true;
3304 return false;
3307 bool Expr::isConstantInitializer(ASTContext &Ctx, bool IsForRef,
3308 const Expr **Culprit) const {
3309 assert(!isValueDependent() &&
3310 "Expression evaluator can't be called on a dependent expression.");
3312 // This function is attempting whether an expression is an initializer
3313 // which can be evaluated at compile-time. It very closely parallels
3314 // ConstExprEmitter in CGExprConstant.cpp; if they don't match, it
3315 // will lead to unexpected results. Like ConstExprEmitter, it falls back
3316 // to isEvaluatable most of the time.
3318 // If we ever capture reference-binding directly in the AST, we can
3319 // kill the second parameter.
3321 if (IsForRef) {
3322 if (auto *EWC = dyn_cast<ExprWithCleanups>(this))
3323 return EWC->getSubExpr()->isConstantInitializer(Ctx, true, Culprit);
3324 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(this))
3325 return MTE->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
3326 EvalResult Result;
3327 if (EvaluateAsLValue(Result, Ctx) && !Result.HasSideEffects)
3328 return true;
3329 if (Culprit)
3330 *Culprit = this;
3331 return false;
3334 switch (getStmtClass()) {
3335 default: break;
3336 case Stmt::ExprWithCleanupsClass:
3337 return cast<ExprWithCleanups>(this)->getSubExpr()->isConstantInitializer(
3338 Ctx, IsForRef, Culprit);
3339 case StringLiteralClass:
3340 case ObjCEncodeExprClass:
3341 return true;
3342 case CXXTemporaryObjectExprClass:
3343 case CXXConstructExprClass: {
3344 const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
3346 if (CE->getConstructor()->isTrivial() &&
3347 CE->getConstructor()->getParent()->hasTrivialDestructor()) {
3348 // Trivial default constructor
3349 if (!CE->getNumArgs()) return true;
3351 // Trivial copy constructor
3352 assert(CE->getNumArgs() == 1 && "trivial ctor with > 1 argument");
3353 return CE->getArg(0)->isConstantInitializer(Ctx, false, Culprit);
3356 break;
3358 case ConstantExprClass: {
3359 // FIXME: We should be able to return "true" here, but it can lead to extra
3360 // error messages. E.g. in Sema/array-init.c.
3361 const Expr *Exp = cast<ConstantExpr>(this)->getSubExpr();
3362 return Exp->isConstantInitializer(Ctx, false, Culprit);
3364 case CompoundLiteralExprClass: {
3365 // This handles gcc's extension that allows global initializers like
3366 // "struct x {int x;} x = (struct x) {};".
3367 // FIXME: This accepts other cases it shouldn't!
3368 const Expr *Exp = cast<CompoundLiteralExpr>(this)->getInitializer();
3369 return Exp->isConstantInitializer(Ctx, false, Culprit);
3371 case DesignatedInitUpdateExprClass: {
3372 const DesignatedInitUpdateExpr *DIUE = cast<DesignatedInitUpdateExpr>(this);
3373 return DIUE->getBase()->isConstantInitializer(Ctx, false, Culprit) &&
3374 DIUE->getUpdater()->isConstantInitializer(Ctx, false, Culprit);
3376 case InitListExprClass: {
3377 // C++ [dcl.init.aggr]p2:
3378 // The elements of an aggregate are:
3379 // - for an array, the array elements in increasing subscript order, or
3380 // - for a class, the direct base classes in declaration order, followed
3381 // by the direct non-static data members (11.4) that are not members of
3382 // an anonymous union, in declaration order.
3383 const InitListExpr *ILE = cast<InitListExpr>(this);
3384 assert(ILE->isSemanticForm() && "InitListExpr must be in semantic form");
3385 if (ILE->getType()->isArrayType()) {
3386 unsigned numInits = ILE->getNumInits();
3387 for (unsigned i = 0; i < numInits; i++) {
3388 if (!ILE->getInit(i)->isConstantInitializer(Ctx, false, Culprit))
3389 return false;
3391 return true;
3394 if (ILE->getType()->isRecordType()) {
3395 unsigned ElementNo = 0;
3396 RecordDecl *RD = ILE->getType()->castAs<RecordType>()->getDecl();
3398 // In C++17, bases were added to the list of members used by aggregate
3399 // initialization.
3400 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3401 for (unsigned i = 0, e = CXXRD->getNumBases(); i < e; i++) {
3402 if (ElementNo < ILE->getNumInits()) {
3403 const Expr *Elt = ILE->getInit(ElementNo++);
3404 if (!Elt->isConstantInitializer(Ctx, false, Culprit))
3405 return false;
3410 for (const auto *Field : RD->fields()) {
3411 // If this is a union, skip all the fields that aren't being initialized.
3412 if (RD->isUnion() && ILE->getInitializedFieldInUnion() != Field)
3413 continue;
3415 // Don't emit anonymous bitfields, they just affect layout.
3416 if (Field->isUnnamedBitField())
3417 continue;
3419 if (ElementNo < ILE->getNumInits()) {
3420 const Expr *Elt = ILE->getInit(ElementNo++);
3421 if (Field->isBitField()) {
3422 // Bitfields have to evaluate to an integer.
3423 EvalResult Result;
3424 if (!Elt->EvaluateAsInt(Result, Ctx)) {
3425 if (Culprit)
3426 *Culprit = Elt;
3427 return false;
3429 } else {
3430 bool RefType = Field->getType()->isReferenceType();
3431 if (!Elt->isConstantInitializer(Ctx, RefType, Culprit))
3432 return false;
3436 return true;
3439 break;
3441 case ImplicitValueInitExprClass:
3442 case NoInitExprClass:
3443 return true;
3444 case ParenExprClass:
3445 return cast<ParenExpr>(this)->getSubExpr()
3446 ->isConstantInitializer(Ctx, IsForRef, Culprit);
3447 case GenericSelectionExprClass:
3448 return cast<GenericSelectionExpr>(this)->getResultExpr()
3449 ->isConstantInitializer(Ctx, IsForRef, Culprit);
3450 case ChooseExprClass:
3451 if (cast<ChooseExpr>(this)->isConditionDependent()) {
3452 if (Culprit)
3453 *Culprit = this;
3454 return false;
3456 return cast<ChooseExpr>(this)->getChosenSubExpr()
3457 ->isConstantInitializer(Ctx, IsForRef, Culprit);
3458 case UnaryOperatorClass: {
3459 const UnaryOperator* Exp = cast<UnaryOperator>(this);
3460 if (Exp->getOpcode() == UO_Extension)
3461 return Exp->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
3462 break;
3464 case PackIndexingExprClass: {
3465 return cast<PackIndexingExpr>(this)
3466 ->getSelectedExpr()
3467 ->isConstantInitializer(Ctx, false, Culprit);
3469 case CXXFunctionalCastExprClass:
3470 case CXXStaticCastExprClass:
3471 case ImplicitCastExprClass:
3472 case CStyleCastExprClass:
3473 case ObjCBridgedCastExprClass:
3474 case CXXDynamicCastExprClass:
3475 case CXXReinterpretCastExprClass:
3476 case CXXAddrspaceCastExprClass:
3477 case CXXConstCastExprClass: {
3478 const CastExpr *CE = cast<CastExpr>(this);
3480 // Handle misc casts we want to ignore.
3481 if (CE->getCastKind() == CK_NoOp ||
3482 CE->getCastKind() == CK_LValueToRValue ||
3483 CE->getCastKind() == CK_ToUnion ||
3484 CE->getCastKind() == CK_ConstructorConversion ||
3485 CE->getCastKind() == CK_NonAtomicToAtomic ||
3486 CE->getCastKind() == CK_AtomicToNonAtomic ||
3487 CE->getCastKind() == CK_NullToPointer ||
3488 CE->getCastKind() == CK_IntToOCLSampler)
3489 return CE->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
3491 break;
3493 case MaterializeTemporaryExprClass:
3494 return cast<MaterializeTemporaryExpr>(this)
3495 ->getSubExpr()
3496 ->isConstantInitializer(Ctx, false, Culprit);
3498 case SubstNonTypeTemplateParmExprClass:
3499 return cast<SubstNonTypeTemplateParmExpr>(this)->getReplacement()
3500 ->isConstantInitializer(Ctx, false, Culprit);
3501 case CXXDefaultArgExprClass:
3502 return cast<CXXDefaultArgExpr>(this)->getExpr()
3503 ->isConstantInitializer(Ctx, false, Culprit);
3504 case CXXDefaultInitExprClass:
3505 return cast<CXXDefaultInitExpr>(this)->getExpr()
3506 ->isConstantInitializer(Ctx, false, Culprit);
3508 // Allow certain forms of UB in constant initializers: signed integer
3509 // overflow and floating-point division by zero. We'll give a warning on
3510 // these, but they're common enough that we have to accept them.
3511 if (isEvaluatable(Ctx, SE_AllowUndefinedBehavior))
3512 return true;
3513 if (Culprit)
3514 *Culprit = this;
3515 return false;
3518 bool CallExpr::isBuiltinAssumeFalse(const ASTContext &Ctx) const {
3519 unsigned BuiltinID = getBuiltinCallee();
3520 if (BuiltinID != Builtin::BI__assume &&
3521 BuiltinID != Builtin::BI__builtin_assume)
3522 return false;
3524 const Expr* Arg = getArg(0);
3525 bool ArgVal;
3526 return !Arg->isValueDependent() &&
3527 Arg->EvaluateAsBooleanCondition(ArgVal, Ctx) && !ArgVal;
3530 bool CallExpr::isCallToStdMove() const {
3531 return getBuiltinCallee() == Builtin::BImove;
3534 namespace {
3535 /// Look for any side effects within a Stmt.
3536 class SideEffectFinder : public ConstEvaluatedExprVisitor<SideEffectFinder> {
3537 typedef ConstEvaluatedExprVisitor<SideEffectFinder> Inherited;
3538 const bool IncludePossibleEffects;
3539 bool HasSideEffects;
3541 public:
3542 explicit SideEffectFinder(const ASTContext &Context, bool IncludePossible)
3543 : Inherited(Context),
3544 IncludePossibleEffects(IncludePossible), HasSideEffects(false) { }
3546 bool hasSideEffects() const { return HasSideEffects; }
3548 void VisitDecl(const Decl *D) {
3549 if (!D)
3550 return;
3552 // We assume the caller checks subexpressions (eg, the initializer, VLA
3553 // bounds) for side-effects on our behalf.
3554 if (auto *VD = dyn_cast<VarDecl>(D)) {
3555 // Registering a destructor is a side-effect.
3556 if (IncludePossibleEffects && VD->isThisDeclarationADefinition() &&
3557 VD->needsDestruction(Context))
3558 HasSideEffects = true;
3562 void VisitDeclStmt(const DeclStmt *DS) {
3563 for (auto *D : DS->decls())
3564 VisitDecl(D);
3565 Inherited::VisitDeclStmt(DS);
3568 void VisitExpr(const Expr *E) {
3569 if (!HasSideEffects &&
3570 E->HasSideEffects(Context, IncludePossibleEffects))
3571 HasSideEffects = true;
3576 bool Expr::HasSideEffects(const ASTContext &Ctx,
3577 bool IncludePossibleEffects) const {
3578 // In circumstances where we care about definite side effects instead of
3579 // potential side effects, we want to ignore expressions that are part of a
3580 // macro expansion as a potential side effect.
3581 if (!IncludePossibleEffects && getExprLoc().isMacroID())
3582 return false;
3584 switch (getStmtClass()) {
3585 case NoStmtClass:
3586 #define ABSTRACT_STMT(Type)
3587 #define STMT(Type, Base) case Type##Class:
3588 #define EXPR(Type, Base)
3589 #include "clang/AST/StmtNodes.inc"
3590 llvm_unreachable("unexpected Expr kind");
3592 case DependentScopeDeclRefExprClass:
3593 case CXXUnresolvedConstructExprClass:
3594 case CXXDependentScopeMemberExprClass:
3595 case UnresolvedLookupExprClass:
3596 case UnresolvedMemberExprClass:
3597 case PackExpansionExprClass:
3598 case SubstNonTypeTemplateParmPackExprClass:
3599 case FunctionParmPackExprClass:
3600 case TypoExprClass:
3601 case RecoveryExprClass:
3602 case CXXFoldExprClass:
3603 // Make a conservative assumption for dependent nodes.
3604 return IncludePossibleEffects;
3606 case DeclRefExprClass:
3607 case ObjCIvarRefExprClass:
3608 case PredefinedExprClass:
3609 case IntegerLiteralClass:
3610 case FixedPointLiteralClass:
3611 case FloatingLiteralClass:
3612 case ImaginaryLiteralClass:
3613 case StringLiteralClass:
3614 case CharacterLiteralClass:
3615 case OffsetOfExprClass:
3616 case ImplicitValueInitExprClass:
3617 case UnaryExprOrTypeTraitExprClass:
3618 case AddrLabelExprClass:
3619 case GNUNullExprClass:
3620 case ArrayInitIndexExprClass:
3621 case NoInitExprClass:
3622 case CXXBoolLiteralExprClass:
3623 case CXXNullPtrLiteralExprClass:
3624 case CXXThisExprClass:
3625 case CXXScalarValueInitExprClass:
3626 case TypeTraitExprClass:
3627 case ArrayTypeTraitExprClass:
3628 case ExpressionTraitExprClass:
3629 case CXXNoexceptExprClass:
3630 case SizeOfPackExprClass:
3631 case ObjCStringLiteralClass:
3632 case ObjCEncodeExprClass:
3633 case ObjCBoolLiteralExprClass:
3634 case ObjCAvailabilityCheckExprClass:
3635 case CXXUuidofExprClass:
3636 case OpaqueValueExprClass:
3637 case SourceLocExprClass:
3638 case EmbedExprClass:
3639 case ConceptSpecializationExprClass:
3640 case RequiresExprClass:
3641 case SYCLUniqueStableNameExprClass:
3642 case PackIndexingExprClass:
3643 case HLSLOutArgExprClass:
3644 case OpenACCAsteriskSizeExprClass:
3645 // These never have a side-effect.
3646 return false;
3648 case ConstantExprClass:
3649 // FIXME: Move this into the "return false;" block above.
3650 return cast<ConstantExpr>(this)->getSubExpr()->HasSideEffects(
3651 Ctx, IncludePossibleEffects);
3653 case CallExprClass:
3654 case CXXOperatorCallExprClass:
3655 case CXXMemberCallExprClass:
3656 case CUDAKernelCallExprClass:
3657 case UserDefinedLiteralClass: {
3658 // We don't know a call definitely has side effects, except for calls
3659 // to pure/const functions that definitely don't.
3660 // If the call itself is considered side-effect free, check the operands.
3661 const Decl *FD = cast<CallExpr>(this)->getCalleeDecl();
3662 bool IsPure = FD && (FD->hasAttr<ConstAttr>() || FD->hasAttr<PureAttr>());
3663 if (IsPure || !IncludePossibleEffects)
3664 break;
3665 return true;
3668 case BlockExprClass:
3669 case CXXBindTemporaryExprClass:
3670 if (!IncludePossibleEffects)
3671 break;
3672 return true;
3674 case MSPropertyRefExprClass:
3675 case MSPropertySubscriptExprClass:
3676 case CompoundAssignOperatorClass:
3677 case VAArgExprClass:
3678 case AtomicExprClass:
3679 case CXXThrowExprClass:
3680 case CXXNewExprClass:
3681 case CXXDeleteExprClass:
3682 case CoawaitExprClass:
3683 case DependentCoawaitExprClass:
3684 case CoyieldExprClass:
3685 // These always have a side-effect.
3686 return true;
3688 case StmtExprClass: {
3689 // StmtExprs have a side-effect if any substatement does.
3690 SideEffectFinder Finder(Ctx, IncludePossibleEffects);
3691 Finder.Visit(cast<StmtExpr>(this)->getSubStmt());
3692 return Finder.hasSideEffects();
3695 case ExprWithCleanupsClass:
3696 if (IncludePossibleEffects)
3697 if (cast<ExprWithCleanups>(this)->cleanupsHaveSideEffects())
3698 return true;
3699 break;
3701 case ParenExprClass:
3702 case ArraySubscriptExprClass:
3703 case MatrixSubscriptExprClass:
3704 case ArraySectionExprClass:
3705 case OMPArrayShapingExprClass:
3706 case OMPIteratorExprClass:
3707 case MemberExprClass:
3708 case ConditionalOperatorClass:
3709 case BinaryConditionalOperatorClass:
3710 case CompoundLiteralExprClass:
3711 case ExtVectorElementExprClass:
3712 case DesignatedInitExprClass:
3713 case DesignatedInitUpdateExprClass:
3714 case ArrayInitLoopExprClass:
3715 case ParenListExprClass:
3716 case CXXPseudoDestructorExprClass:
3717 case CXXRewrittenBinaryOperatorClass:
3718 case CXXStdInitializerListExprClass:
3719 case SubstNonTypeTemplateParmExprClass:
3720 case MaterializeTemporaryExprClass:
3721 case ShuffleVectorExprClass:
3722 case ConvertVectorExprClass:
3723 case AsTypeExprClass:
3724 case CXXParenListInitExprClass:
3725 // These have a side-effect if any subexpression does.
3726 break;
3728 case UnaryOperatorClass:
3729 if (cast<UnaryOperator>(this)->isIncrementDecrementOp())
3730 return true;
3731 break;
3733 case BinaryOperatorClass:
3734 if (cast<BinaryOperator>(this)->isAssignmentOp())
3735 return true;
3736 break;
3738 case InitListExprClass:
3739 // FIXME: The children for an InitListExpr doesn't include the array filler.
3740 if (const Expr *E = cast<InitListExpr>(this)->getArrayFiller())
3741 if (E->HasSideEffects(Ctx, IncludePossibleEffects))
3742 return true;
3743 break;
3745 case GenericSelectionExprClass:
3746 return cast<GenericSelectionExpr>(this)->getResultExpr()->
3747 HasSideEffects(Ctx, IncludePossibleEffects);
3749 case ChooseExprClass:
3750 return cast<ChooseExpr>(this)->getChosenSubExpr()->HasSideEffects(
3751 Ctx, IncludePossibleEffects);
3753 case CXXDefaultArgExprClass:
3754 return cast<CXXDefaultArgExpr>(this)->getExpr()->HasSideEffects(
3755 Ctx, IncludePossibleEffects);
3757 case CXXDefaultInitExprClass: {
3758 const FieldDecl *FD = cast<CXXDefaultInitExpr>(this)->getField();
3759 if (const Expr *E = FD->getInClassInitializer())
3760 return E->HasSideEffects(Ctx, IncludePossibleEffects);
3761 // If we've not yet parsed the initializer, assume it has side-effects.
3762 return true;
3765 case CXXDynamicCastExprClass: {
3766 // A dynamic_cast expression has side-effects if it can throw.
3767 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(this);
3768 if (DCE->getTypeAsWritten()->isReferenceType() &&
3769 DCE->getCastKind() == CK_Dynamic)
3770 return true;
3772 [[fallthrough]];
3773 case ImplicitCastExprClass:
3774 case CStyleCastExprClass:
3775 case CXXStaticCastExprClass:
3776 case CXXReinterpretCastExprClass:
3777 case CXXConstCastExprClass:
3778 case CXXAddrspaceCastExprClass:
3779 case CXXFunctionalCastExprClass:
3780 case BuiltinBitCastExprClass: {
3781 // While volatile reads are side-effecting in both C and C++, we treat them
3782 // as having possible (not definite) side-effects. This allows idiomatic
3783 // code to behave without warning, such as sizeof(*v) for a volatile-
3784 // qualified pointer.
3785 if (!IncludePossibleEffects)
3786 break;
3788 const CastExpr *CE = cast<CastExpr>(this);
3789 if (CE->getCastKind() == CK_LValueToRValue &&
3790 CE->getSubExpr()->getType().isVolatileQualified())
3791 return true;
3792 break;
3795 case CXXTypeidExprClass: {
3796 const auto *TE = cast<CXXTypeidExpr>(this);
3797 if (!TE->isPotentiallyEvaluated())
3798 return false;
3800 // If this type id expression can throw because of a null pointer, that is a
3801 // side-effect independent of if the operand has a side-effect
3802 if (IncludePossibleEffects && TE->hasNullCheck())
3803 return true;
3805 break;
3808 case CXXConstructExprClass:
3809 case CXXTemporaryObjectExprClass: {
3810 const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
3811 if (!CE->getConstructor()->isTrivial() && IncludePossibleEffects)
3812 return true;
3813 // A trivial constructor does not add any side-effects of its own. Just look
3814 // at its arguments.
3815 break;
3818 case CXXInheritedCtorInitExprClass: {
3819 const auto *ICIE = cast<CXXInheritedCtorInitExpr>(this);
3820 if (!ICIE->getConstructor()->isTrivial() && IncludePossibleEffects)
3821 return true;
3822 break;
3825 case LambdaExprClass: {
3826 const LambdaExpr *LE = cast<LambdaExpr>(this);
3827 for (Expr *E : LE->capture_inits())
3828 if (E && E->HasSideEffects(Ctx, IncludePossibleEffects))
3829 return true;
3830 return false;
3833 case PseudoObjectExprClass: {
3834 // Only look for side-effects in the semantic form, and look past
3835 // OpaqueValueExpr bindings in that form.
3836 const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this);
3837 for (PseudoObjectExpr::const_semantics_iterator I = PO->semantics_begin(),
3838 E = PO->semantics_end();
3839 I != E; ++I) {
3840 const Expr *Subexpr = *I;
3841 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Subexpr))
3842 Subexpr = OVE->getSourceExpr();
3843 if (Subexpr->HasSideEffects(Ctx, IncludePossibleEffects))
3844 return true;
3846 return false;
3849 case ObjCBoxedExprClass:
3850 case ObjCArrayLiteralClass:
3851 case ObjCDictionaryLiteralClass:
3852 case ObjCSelectorExprClass:
3853 case ObjCProtocolExprClass:
3854 case ObjCIsaExprClass:
3855 case ObjCIndirectCopyRestoreExprClass:
3856 case ObjCSubscriptRefExprClass:
3857 case ObjCBridgedCastExprClass:
3858 case ObjCMessageExprClass:
3859 case ObjCPropertyRefExprClass:
3860 // FIXME: Classify these cases better.
3861 if (IncludePossibleEffects)
3862 return true;
3863 break;
3866 // Recurse to children.
3867 for (const Stmt *SubStmt : children())
3868 if (SubStmt &&
3869 cast<Expr>(SubStmt)->HasSideEffects(Ctx, IncludePossibleEffects))
3870 return true;
3872 return false;
3875 FPOptions Expr::getFPFeaturesInEffect(const LangOptions &LO) const {
3876 if (auto Call = dyn_cast<CallExpr>(this))
3877 return Call->getFPFeaturesInEffect(LO);
3878 if (auto UO = dyn_cast<UnaryOperator>(this))
3879 return UO->getFPFeaturesInEffect(LO);
3880 if (auto BO = dyn_cast<BinaryOperator>(this))
3881 return BO->getFPFeaturesInEffect(LO);
3882 if (auto Cast = dyn_cast<CastExpr>(this))
3883 return Cast->getFPFeaturesInEffect(LO);
3884 return FPOptions::defaultWithoutTrailingStorage(LO);
3887 namespace {
3888 /// Look for a call to a non-trivial function within an expression.
3889 class NonTrivialCallFinder : public ConstEvaluatedExprVisitor<NonTrivialCallFinder>
3891 typedef ConstEvaluatedExprVisitor<NonTrivialCallFinder> Inherited;
3893 bool NonTrivial;
3895 public:
3896 explicit NonTrivialCallFinder(const ASTContext &Context)
3897 : Inherited(Context), NonTrivial(false) { }
3899 bool hasNonTrivialCall() const { return NonTrivial; }
3901 void VisitCallExpr(const CallExpr *E) {
3902 if (const CXXMethodDecl *Method
3903 = dyn_cast_or_null<const CXXMethodDecl>(E->getCalleeDecl())) {
3904 if (Method->isTrivial()) {
3905 // Recurse to children of the call.
3906 Inherited::VisitStmt(E);
3907 return;
3911 NonTrivial = true;
3914 void VisitCXXConstructExpr(const CXXConstructExpr *E) {
3915 if (E->getConstructor()->isTrivial()) {
3916 // Recurse to children of the call.
3917 Inherited::VisitStmt(E);
3918 return;
3921 NonTrivial = true;
3924 void VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
3925 // Destructor of the temporary might be null if destructor declaration
3926 // is not valid.
3927 if (const CXXDestructorDecl *DtorDecl =
3928 E->getTemporary()->getDestructor()) {
3929 if (DtorDecl->isTrivial()) {
3930 Inherited::VisitStmt(E);
3931 return;
3935 NonTrivial = true;
3940 bool Expr::hasNonTrivialCall(const ASTContext &Ctx) const {
3941 NonTrivialCallFinder Finder(Ctx);
3942 Finder.Visit(this);
3943 return Finder.hasNonTrivialCall();
3946 /// isNullPointerConstant - C99 6.3.2.3p3 - Return whether this is a null
3947 /// pointer constant or not, as well as the specific kind of constant detected.
3948 /// Null pointer constants can be integer constant expressions with the
3949 /// value zero, casts of zero to void*, nullptr (C++0X), or __null
3950 /// (a GNU extension).
3951 Expr::NullPointerConstantKind
3952 Expr::isNullPointerConstant(ASTContext &Ctx,
3953 NullPointerConstantValueDependence NPC) const {
3954 if (isValueDependent() &&
3955 (!Ctx.getLangOpts().CPlusPlus11 || Ctx.getLangOpts().MSVCCompat)) {
3956 // Error-dependent expr should never be a null pointer.
3957 if (containsErrors())
3958 return NPCK_NotNull;
3959 switch (NPC) {
3960 case NPC_NeverValueDependent:
3961 llvm_unreachable("Unexpected value dependent expression!");
3962 case NPC_ValueDependentIsNull:
3963 if (isTypeDependent() || getType()->isIntegralType(Ctx))
3964 return NPCK_ZeroExpression;
3965 else
3966 return NPCK_NotNull;
3968 case NPC_ValueDependentIsNotNull:
3969 return NPCK_NotNull;
3973 // Strip off a cast to void*, if it exists. Except in C++.
3974 if (const ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(this)) {
3975 if (!Ctx.getLangOpts().CPlusPlus) {
3976 // Check that it is a cast to void*.
3977 if (const PointerType *PT = CE->getType()->getAs<PointerType>()) {
3978 QualType Pointee = PT->getPointeeType();
3979 Qualifiers Qs = Pointee.getQualifiers();
3980 // Only (void*)0 or equivalent are treated as nullptr. If pointee type
3981 // has non-default address space it is not treated as nullptr.
3982 // (__generic void*)0 in OpenCL 2.0 should not be treated as nullptr
3983 // since it cannot be assigned to a pointer to constant address space.
3984 if (Ctx.getLangOpts().OpenCL &&
3985 Pointee.getAddressSpace() == Ctx.getDefaultOpenCLPointeeAddrSpace())
3986 Qs.removeAddressSpace();
3988 if (Pointee->isVoidType() && Qs.empty() && // to void*
3989 CE->getSubExpr()->getType()->isIntegerType()) // from int
3990 return CE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
3993 } else if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(this)) {
3994 // Ignore the ImplicitCastExpr type entirely.
3995 return ICE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
3996 } else if (const ParenExpr *PE = dyn_cast<ParenExpr>(this)) {
3997 // Accept ((void*)0) as a null pointer constant, as many other
3998 // implementations do.
3999 return PE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
4000 } else if (const GenericSelectionExpr *GE =
4001 dyn_cast<GenericSelectionExpr>(this)) {
4002 if (GE->isResultDependent())
4003 return NPCK_NotNull;
4004 return GE->getResultExpr()->isNullPointerConstant(Ctx, NPC);
4005 } else if (const ChooseExpr *CE = dyn_cast<ChooseExpr>(this)) {
4006 if (CE->isConditionDependent())
4007 return NPCK_NotNull;
4008 return CE->getChosenSubExpr()->isNullPointerConstant(Ctx, NPC);
4009 } else if (const CXXDefaultArgExpr *DefaultArg
4010 = dyn_cast<CXXDefaultArgExpr>(this)) {
4011 // See through default argument expressions.
4012 return DefaultArg->getExpr()->isNullPointerConstant(Ctx, NPC);
4013 } else if (const CXXDefaultInitExpr *DefaultInit
4014 = dyn_cast<CXXDefaultInitExpr>(this)) {
4015 // See through default initializer expressions.
4016 return DefaultInit->getExpr()->isNullPointerConstant(Ctx, NPC);
4017 } else if (isa<GNUNullExpr>(this)) {
4018 // The GNU __null extension is always a null pointer constant.
4019 return NPCK_GNUNull;
4020 } else if (const MaterializeTemporaryExpr *M
4021 = dyn_cast<MaterializeTemporaryExpr>(this)) {
4022 return M->getSubExpr()->isNullPointerConstant(Ctx, NPC);
4023 } else if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(this)) {
4024 if (const Expr *Source = OVE->getSourceExpr())
4025 return Source->isNullPointerConstant(Ctx, NPC);
4028 // If the expression has no type information, it cannot be a null pointer
4029 // constant.
4030 if (getType().isNull())
4031 return NPCK_NotNull;
4033 // C++11/C23 nullptr_t is always a null pointer constant.
4034 if (getType()->isNullPtrType())
4035 return NPCK_CXX11_nullptr;
4037 if (const RecordType *UT = getType()->getAsUnionType())
4038 if (!Ctx.getLangOpts().CPlusPlus11 &&
4039 UT && UT->getDecl()->hasAttr<TransparentUnionAttr>())
4040 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(this)){
4041 const Expr *InitExpr = CLE->getInitializer();
4042 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(InitExpr))
4043 return ILE->getInit(0)->isNullPointerConstant(Ctx, NPC);
4045 // This expression must be an integer type.
4046 if (!getType()->isIntegerType() ||
4047 (Ctx.getLangOpts().CPlusPlus && getType()->isEnumeralType()))
4048 return NPCK_NotNull;
4050 if (Ctx.getLangOpts().CPlusPlus11) {
4051 // C++11 [conv.ptr]p1: A null pointer constant is an integer literal with
4052 // value zero or a prvalue of type std::nullptr_t.
4053 // Microsoft mode permits C++98 rules reflecting MSVC behavior.
4054 const IntegerLiteral *Lit = dyn_cast<IntegerLiteral>(this);
4055 if (Lit && !Lit->getValue())
4056 return NPCK_ZeroLiteral;
4057 if (!Ctx.getLangOpts().MSVCCompat || !isCXX98IntegralConstantExpr(Ctx))
4058 return NPCK_NotNull;
4059 } else {
4060 // If we have an integer constant expression, we need to *evaluate* it and
4061 // test for the value 0.
4062 if (!isIntegerConstantExpr(Ctx))
4063 return NPCK_NotNull;
4066 if (EvaluateKnownConstInt(Ctx) != 0)
4067 return NPCK_NotNull;
4069 if (isa<IntegerLiteral>(this))
4070 return NPCK_ZeroLiteral;
4071 return NPCK_ZeroExpression;
4074 /// If this expression is an l-value for an Objective C
4075 /// property, find the underlying property reference expression.
4076 const ObjCPropertyRefExpr *Expr::getObjCProperty() const {
4077 const Expr *E = this;
4078 while (true) {
4079 assert((E->isLValue() && E->getObjectKind() == OK_ObjCProperty) &&
4080 "expression is not a property reference");
4081 E = E->IgnoreParenCasts();
4082 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
4083 if (BO->getOpcode() == BO_Comma) {
4084 E = BO->getRHS();
4085 continue;
4089 break;
4092 return cast<ObjCPropertyRefExpr>(E);
4095 bool Expr::isObjCSelfExpr() const {
4096 const Expr *E = IgnoreParenImpCasts();
4098 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
4099 if (!DRE)
4100 return false;
4102 const ImplicitParamDecl *Param = dyn_cast<ImplicitParamDecl>(DRE->getDecl());
4103 if (!Param)
4104 return false;
4106 const ObjCMethodDecl *M = dyn_cast<ObjCMethodDecl>(Param->getDeclContext());
4107 if (!M)
4108 return false;
4110 return M->getSelfDecl() == Param;
4113 FieldDecl *Expr::getSourceBitField() {
4114 Expr *E = this->IgnoreParens();
4116 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
4117 if (ICE->getCastKind() == CK_LValueToRValue ||
4118 (ICE->isGLValue() && ICE->getCastKind() == CK_NoOp))
4119 E = ICE->getSubExpr()->IgnoreParens();
4120 else
4121 break;
4124 if (MemberExpr *MemRef = dyn_cast<MemberExpr>(E))
4125 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemRef->getMemberDecl()))
4126 if (Field->isBitField())
4127 return Field;
4129 if (ObjCIvarRefExpr *IvarRef = dyn_cast<ObjCIvarRefExpr>(E)) {
4130 FieldDecl *Ivar = IvarRef->getDecl();
4131 if (Ivar->isBitField())
4132 return Ivar;
4135 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E)) {
4136 if (FieldDecl *Field = dyn_cast<FieldDecl>(DeclRef->getDecl()))
4137 if (Field->isBitField())
4138 return Field;
4140 if (BindingDecl *BD = dyn_cast<BindingDecl>(DeclRef->getDecl()))
4141 if (Expr *E = BD->getBinding())
4142 return E->getSourceBitField();
4145 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(E)) {
4146 if (BinOp->isAssignmentOp() && BinOp->getLHS())
4147 return BinOp->getLHS()->getSourceBitField();
4149 if (BinOp->getOpcode() == BO_Comma && BinOp->getRHS())
4150 return BinOp->getRHS()->getSourceBitField();
4153 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E))
4154 if (UnOp->isPrefix() && UnOp->isIncrementDecrementOp())
4155 return UnOp->getSubExpr()->getSourceBitField();
4157 return nullptr;
4160 EnumConstantDecl *Expr::getEnumConstantDecl() {
4161 Expr *E = this->IgnoreParenImpCasts();
4162 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
4163 return dyn_cast<EnumConstantDecl>(DRE->getDecl());
4164 return nullptr;
4167 bool Expr::refersToVectorElement() const {
4168 // FIXME: Why do we not just look at the ObjectKind here?
4169 const Expr *E = this->IgnoreParens();
4171 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
4172 if (ICE->isGLValue() && ICE->getCastKind() == CK_NoOp)
4173 E = ICE->getSubExpr()->IgnoreParens();
4174 else
4175 break;
4178 if (const ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(E))
4179 return ASE->getBase()->getType()->isVectorType();
4181 if (isa<ExtVectorElementExpr>(E))
4182 return true;
4184 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
4185 if (auto *BD = dyn_cast<BindingDecl>(DRE->getDecl()))
4186 if (auto *E = BD->getBinding())
4187 return E->refersToVectorElement();
4189 return false;
4192 bool Expr::refersToGlobalRegisterVar() const {
4193 const Expr *E = this->IgnoreParenImpCasts();
4195 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
4196 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
4197 if (VD->getStorageClass() == SC_Register &&
4198 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
4199 return true;
4201 return false;
4204 bool Expr::isSameComparisonOperand(const Expr* E1, const Expr* E2) {
4205 E1 = E1->IgnoreParens();
4206 E2 = E2->IgnoreParens();
4208 if (E1->getStmtClass() != E2->getStmtClass())
4209 return false;
4211 switch (E1->getStmtClass()) {
4212 default:
4213 return false;
4214 case CXXThisExprClass:
4215 return true;
4216 case DeclRefExprClass: {
4217 // DeclRefExpr without an ImplicitCastExpr can happen for integral
4218 // template parameters.
4219 const auto *DRE1 = cast<DeclRefExpr>(E1);
4220 const auto *DRE2 = cast<DeclRefExpr>(E2);
4221 return DRE1->isPRValue() && DRE2->isPRValue() &&
4222 DRE1->getDecl() == DRE2->getDecl();
4224 case ImplicitCastExprClass: {
4225 // Peel off implicit casts.
4226 while (true) {
4227 const auto *ICE1 = dyn_cast<ImplicitCastExpr>(E1);
4228 const auto *ICE2 = dyn_cast<ImplicitCastExpr>(E2);
4229 if (!ICE1 || !ICE2)
4230 return false;
4231 if (ICE1->getCastKind() != ICE2->getCastKind())
4232 return false;
4233 E1 = ICE1->getSubExpr()->IgnoreParens();
4234 E2 = ICE2->getSubExpr()->IgnoreParens();
4235 // The final cast must be one of these types.
4236 if (ICE1->getCastKind() == CK_LValueToRValue ||
4237 ICE1->getCastKind() == CK_ArrayToPointerDecay ||
4238 ICE1->getCastKind() == CK_FunctionToPointerDecay) {
4239 break;
4243 const auto *DRE1 = dyn_cast<DeclRefExpr>(E1);
4244 const auto *DRE2 = dyn_cast<DeclRefExpr>(E2);
4245 if (DRE1 && DRE2)
4246 return declaresSameEntity(DRE1->getDecl(), DRE2->getDecl());
4248 const auto *Ivar1 = dyn_cast<ObjCIvarRefExpr>(E1);
4249 const auto *Ivar2 = dyn_cast<ObjCIvarRefExpr>(E2);
4250 if (Ivar1 && Ivar2) {
4251 return Ivar1->isFreeIvar() && Ivar2->isFreeIvar() &&
4252 declaresSameEntity(Ivar1->getDecl(), Ivar2->getDecl());
4255 const auto *Array1 = dyn_cast<ArraySubscriptExpr>(E1);
4256 const auto *Array2 = dyn_cast<ArraySubscriptExpr>(E2);
4257 if (Array1 && Array2) {
4258 if (!isSameComparisonOperand(Array1->getBase(), Array2->getBase()))
4259 return false;
4261 auto Idx1 = Array1->getIdx();
4262 auto Idx2 = Array2->getIdx();
4263 const auto Integer1 = dyn_cast<IntegerLiteral>(Idx1);
4264 const auto Integer2 = dyn_cast<IntegerLiteral>(Idx2);
4265 if (Integer1 && Integer2) {
4266 if (!llvm::APInt::isSameValue(Integer1->getValue(),
4267 Integer2->getValue()))
4268 return false;
4269 } else {
4270 if (!isSameComparisonOperand(Idx1, Idx2))
4271 return false;
4274 return true;
4277 // Walk the MemberExpr chain.
4278 while (isa<MemberExpr>(E1) && isa<MemberExpr>(E2)) {
4279 const auto *ME1 = cast<MemberExpr>(E1);
4280 const auto *ME2 = cast<MemberExpr>(E2);
4281 if (!declaresSameEntity(ME1->getMemberDecl(), ME2->getMemberDecl()))
4282 return false;
4283 if (const auto *D = dyn_cast<VarDecl>(ME1->getMemberDecl()))
4284 if (D->isStaticDataMember())
4285 return true;
4286 E1 = ME1->getBase()->IgnoreParenImpCasts();
4287 E2 = ME2->getBase()->IgnoreParenImpCasts();
4290 if (isa<CXXThisExpr>(E1) && isa<CXXThisExpr>(E2))
4291 return true;
4293 // A static member variable can end the MemberExpr chain with either
4294 // a MemberExpr or a DeclRefExpr.
4295 auto getAnyDecl = [](const Expr *E) -> const ValueDecl * {
4296 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
4297 return DRE->getDecl();
4298 if (const auto *ME = dyn_cast<MemberExpr>(E))
4299 return ME->getMemberDecl();
4300 return nullptr;
4303 const ValueDecl *VD1 = getAnyDecl(E1);
4304 const ValueDecl *VD2 = getAnyDecl(E2);
4305 return declaresSameEntity(VD1, VD2);
4310 /// isArrow - Return true if the base expression is a pointer to vector,
4311 /// return false if the base expression is a vector.
4312 bool ExtVectorElementExpr::isArrow() const {
4313 return getBase()->getType()->isPointerType();
4316 unsigned ExtVectorElementExpr::getNumElements() const {
4317 if (const VectorType *VT = getType()->getAs<VectorType>())
4318 return VT->getNumElements();
4319 return 1;
4322 /// containsDuplicateElements - Return true if any element access is repeated.
4323 bool ExtVectorElementExpr::containsDuplicateElements() const {
4324 // FIXME: Refactor this code to an accessor on the AST node which returns the
4325 // "type" of component access, and share with code below and in Sema.
4326 StringRef Comp = Accessor->getName();
4328 // Halving swizzles do not contain duplicate elements.
4329 if (Comp == "hi" || Comp == "lo" || Comp == "even" || Comp == "odd")
4330 return false;
4332 // Advance past s-char prefix on hex swizzles.
4333 if (Comp[0] == 's' || Comp[0] == 'S')
4334 Comp = Comp.substr(1);
4336 for (unsigned i = 0, e = Comp.size(); i != e; ++i)
4337 if (Comp.substr(i + 1).contains(Comp[i]))
4338 return true;
4340 return false;
4343 /// getEncodedElementAccess - We encode the fields as a llvm ConstantArray.
4344 void ExtVectorElementExpr::getEncodedElementAccess(
4345 SmallVectorImpl<uint32_t> &Elts) const {
4346 StringRef Comp = Accessor->getName();
4347 bool isNumericAccessor = false;
4348 if (Comp[0] == 's' || Comp[0] == 'S') {
4349 Comp = Comp.substr(1);
4350 isNumericAccessor = true;
4353 bool isHi = Comp == "hi";
4354 bool isLo = Comp == "lo";
4355 bool isEven = Comp == "even";
4356 bool isOdd = Comp == "odd";
4358 for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
4359 uint64_t Index;
4361 if (isHi)
4362 Index = e + i;
4363 else if (isLo)
4364 Index = i;
4365 else if (isEven)
4366 Index = 2 * i;
4367 else if (isOdd)
4368 Index = 2 * i + 1;
4369 else
4370 Index = ExtVectorType::getAccessorIdx(Comp[i], isNumericAccessor);
4372 Elts.push_back(Index);
4376 ShuffleVectorExpr::ShuffleVectorExpr(const ASTContext &C, ArrayRef<Expr *> args,
4377 QualType Type, SourceLocation BLoc,
4378 SourceLocation RP)
4379 : Expr(ShuffleVectorExprClass, Type, VK_PRValue, OK_Ordinary),
4380 BuiltinLoc(BLoc), RParenLoc(RP), NumExprs(args.size()) {
4381 SubExprs = new (C) Stmt*[args.size()];
4382 for (unsigned i = 0; i != args.size(); i++)
4383 SubExprs[i] = args[i];
4385 setDependence(computeDependence(this));
4388 void ShuffleVectorExpr::setExprs(const ASTContext &C, ArrayRef<Expr *> Exprs) {
4389 if (SubExprs) C.Deallocate(SubExprs);
4391 this->NumExprs = Exprs.size();
4392 SubExprs = new (C) Stmt*[NumExprs];
4393 memcpy(SubExprs, Exprs.data(), sizeof(Expr *) * Exprs.size());
4396 GenericSelectionExpr::GenericSelectionExpr(
4397 const ASTContext &, SourceLocation GenericLoc, Expr *ControllingExpr,
4398 ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
4399 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4400 bool ContainsUnexpandedParameterPack, unsigned ResultIndex)
4401 : Expr(GenericSelectionExprClass, AssocExprs[ResultIndex]->getType(),
4402 AssocExprs[ResultIndex]->getValueKind(),
4403 AssocExprs[ResultIndex]->getObjectKind()),
4404 NumAssocs(AssocExprs.size()), ResultIndex(ResultIndex),
4405 IsExprPredicate(true), DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
4406 assert(AssocTypes.size() == AssocExprs.size() &&
4407 "Must have the same number of association expressions"
4408 " and TypeSourceInfo!");
4409 assert(ResultIndex < NumAssocs && "ResultIndex is out-of-bounds!");
4411 GenericSelectionExprBits.GenericLoc = GenericLoc;
4412 getTrailingObjects<Stmt *>()[getIndexOfControllingExpression()] =
4413 ControllingExpr;
4414 std::copy(AssocExprs.begin(), AssocExprs.end(),
4415 getTrailingObjects<Stmt *>() + getIndexOfStartOfAssociatedExprs());
4416 std::copy(AssocTypes.begin(), AssocTypes.end(),
4417 getTrailingObjects<TypeSourceInfo *>() +
4418 getIndexOfStartOfAssociatedTypes());
4420 setDependence(computeDependence(this, ContainsUnexpandedParameterPack));
4423 GenericSelectionExpr::GenericSelectionExpr(
4424 const ASTContext &, SourceLocation GenericLoc,
4425 TypeSourceInfo *ControllingType, ArrayRef<TypeSourceInfo *> AssocTypes,
4426 ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,
4427 SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack,
4428 unsigned ResultIndex)
4429 : Expr(GenericSelectionExprClass, AssocExprs[ResultIndex]->getType(),
4430 AssocExprs[ResultIndex]->getValueKind(),
4431 AssocExprs[ResultIndex]->getObjectKind()),
4432 NumAssocs(AssocExprs.size()), ResultIndex(ResultIndex),
4433 IsExprPredicate(false), DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
4434 assert(AssocTypes.size() == AssocExprs.size() &&
4435 "Must have the same number of association expressions"
4436 " and TypeSourceInfo!");
4437 assert(ResultIndex < NumAssocs && "ResultIndex is out-of-bounds!");
4439 GenericSelectionExprBits.GenericLoc = GenericLoc;
4440 getTrailingObjects<TypeSourceInfo *>()[getIndexOfControllingType()] =
4441 ControllingType;
4442 std::copy(AssocExprs.begin(), AssocExprs.end(),
4443 getTrailingObjects<Stmt *>() + getIndexOfStartOfAssociatedExprs());
4444 std::copy(AssocTypes.begin(), AssocTypes.end(),
4445 getTrailingObjects<TypeSourceInfo *>() +
4446 getIndexOfStartOfAssociatedTypes());
4448 setDependence(computeDependence(this, ContainsUnexpandedParameterPack));
4451 GenericSelectionExpr::GenericSelectionExpr(
4452 const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,
4453 ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
4454 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4455 bool ContainsUnexpandedParameterPack)
4456 : Expr(GenericSelectionExprClass, Context.DependentTy, VK_PRValue,
4457 OK_Ordinary),
4458 NumAssocs(AssocExprs.size()), ResultIndex(ResultDependentIndex),
4459 IsExprPredicate(true), DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
4460 assert(AssocTypes.size() == AssocExprs.size() &&
4461 "Must have the same number of association expressions"
4462 " and TypeSourceInfo!");
4464 GenericSelectionExprBits.GenericLoc = GenericLoc;
4465 getTrailingObjects<Stmt *>()[getIndexOfControllingExpression()] =
4466 ControllingExpr;
4467 std::copy(AssocExprs.begin(), AssocExprs.end(),
4468 getTrailingObjects<Stmt *>() + getIndexOfStartOfAssociatedExprs());
4469 std::copy(AssocTypes.begin(), AssocTypes.end(),
4470 getTrailingObjects<TypeSourceInfo *>() +
4471 getIndexOfStartOfAssociatedTypes());
4473 setDependence(computeDependence(this, ContainsUnexpandedParameterPack));
4476 GenericSelectionExpr::GenericSelectionExpr(
4477 const ASTContext &Context, SourceLocation GenericLoc,
4478 TypeSourceInfo *ControllingType, ArrayRef<TypeSourceInfo *> AssocTypes,
4479 ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,
4480 SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack)
4481 : Expr(GenericSelectionExprClass, Context.DependentTy, VK_PRValue,
4482 OK_Ordinary),
4483 NumAssocs(AssocExprs.size()), ResultIndex(ResultDependentIndex),
4484 IsExprPredicate(false), DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
4485 assert(AssocTypes.size() == AssocExprs.size() &&
4486 "Must have the same number of association expressions"
4487 " and TypeSourceInfo!");
4489 GenericSelectionExprBits.GenericLoc = GenericLoc;
4490 getTrailingObjects<TypeSourceInfo *>()[getIndexOfControllingType()] =
4491 ControllingType;
4492 std::copy(AssocExprs.begin(), AssocExprs.end(),
4493 getTrailingObjects<Stmt *>() + getIndexOfStartOfAssociatedExprs());
4494 std::copy(AssocTypes.begin(), AssocTypes.end(),
4495 getTrailingObjects<TypeSourceInfo *>() +
4496 getIndexOfStartOfAssociatedTypes());
4498 setDependence(computeDependence(this, ContainsUnexpandedParameterPack));
4501 GenericSelectionExpr::GenericSelectionExpr(EmptyShell Empty, unsigned NumAssocs)
4502 : Expr(GenericSelectionExprClass, Empty), NumAssocs(NumAssocs) {}
4504 GenericSelectionExpr *GenericSelectionExpr::Create(
4505 const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,
4506 ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
4507 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4508 bool ContainsUnexpandedParameterPack, unsigned ResultIndex) {
4509 unsigned NumAssocs = AssocExprs.size();
4510 void *Mem = Context.Allocate(
4511 totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
4512 alignof(GenericSelectionExpr));
4513 return new (Mem) GenericSelectionExpr(
4514 Context, GenericLoc, ControllingExpr, AssocTypes, AssocExprs, DefaultLoc,
4515 RParenLoc, ContainsUnexpandedParameterPack, ResultIndex);
4518 GenericSelectionExpr *GenericSelectionExpr::Create(
4519 const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,
4520 ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
4521 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4522 bool ContainsUnexpandedParameterPack) {
4523 unsigned NumAssocs = AssocExprs.size();
4524 void *Mem = Context.Allocate(
4525 totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
4526 alignof(GenericSelectionExpr));
4527 return new (Mem) GenericSelectionExpr(
4528 Context, GenericLoc, ControllingExpr, AssocTypes, AssocExprs, DefaultLoc,
4529 RParenLoc, ContainsUnexpandedParameterPack);
4532 GenericSelectionExpr *GenericSelectionExpr::Create(
4533 const ASTContext &Context, SourceLocation GenericLoc,
4534 TypeSourceInfo *ControllingType, ArrayRef<TypeSourceInfo *> AssocTypes,
4535 ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,
4536 SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack,
4537 unsigned ResultIndex) {
4538 unsigned NumAssocs = AssocExprs.size();
4539 void *Mem = Context.Allocate(
4540 totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
4541 alignof(GenericSelectionExpr));
4542 return new (Mem) GenericSelectionExpr(
4543 Context, GenericLoc, ControllingType, AssocTypes, AssocExprs, DefaultLoc,
4544 RParenLoc, ContainsUnexpandedParameterPack, ResultIndex);
4547 GenericSelectionExpr *GenericSelectionExpr::Create(
4548 const ASTContext &Context, SourceLocation GenericLoc,
4549 TypeSourceInfo *ControllingType, ArrayRef<TypeSourceInfo *> AssocTypes,
4550 ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,
4551 SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack) {
4552 unsigned NumAssocs = AssocExprs.size();
4553 void *Mem = Context.Allocate(
4554 totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
4555 alignof(GenericSelectionExpr));
4556 return new (Mem) GenericSelectionExpr(
4557 Context, GenericLoc, ControllingType, AssocTypes, AssocExprs, DefaultLoc,
4558 RParenLoc, ContainsUnexpandedParameterPack);
4561 GenericSelectionExpr *
4562 GenericSelectionExpr::CreateEmpty(const ASTContext &Context,
4563 unsigned NumAssocs) {
4564 void *Mem = Context.Allocate(
4565 totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
4566 alignof(GenericSelectionExpr));
4567 return new (Mem) GenericSelectionExpr(EmptyShell(), NumAssocs);
4570 //===----------------------------------------------------------------------===//
4571 // DesignatedInitExpr
4572 //===----------------------------------------------------------------------===//
4574 const IdentifierInfo *DesignatedInitExpr::Designator::getFieldName() const {
4575 assert(isFieldDesignator() && "Only valid on a field designator");
4576 if (FieldInfo.NameOrField & 0x01)
4577 return reinterpret_cast<IdentifierInfo *>(FieldInfo.NameOrField & ~0x01);
4578 return getFieldDecl()->getIdentifier();
4581 DesignatedInitExpr::DesignatedInitExpr(const ASTContext &C, QualType Ty,
4582 llvm::ArrayRef<Designator> Designators,
4583 SourceLocation EqualOrColonLoc,
4584 bool GNUSyntax,
4585 ArrayRef<Expr *> IndexExprs, Expr *Init)
4586 : Expr(DesignatedInitExprClass, Ty, Init->getValueKind(),
4587 Init->getObjectKind()),
4588 EqualOrColonLoc(EqualOrColonLoc), GNUSyntax(GNUSyntax),
4589 NumDesignators(Designators.size()), NumSubExprs(IndexExprs.size() + 1) {
4590 this->Designators = new (C) Designator[NumDesignators];
4592 // Record the initializer itself.
4593 child_iterator Child = child_begin();
4594 *Child++ = Init;
4596 // Copy the designators and their subexpressions, computing
4597 // value-dependence along the way.
4598 unsigned IndexIdx = 0;
4599 for (unsigned I = 0; I != NumDesignators; ++I) {
4600 this->Designators[I] = Designators[I];
4601 if (this->Designators[I].isArrayDesignator()) {
4602 // Copy the index expressions into permanent storage.
4603 *Child++ = IndexExprs[IndexIdx++];
4604 } else if (this->Designators[I].isArrayRangeDesignator()) {
4605 // Copy the start/end expressions into permanent storage.
4606 *Child++ = IndexExprs[IndexIdx++];
4607 *Child++ = IndexExprs[IndexIdx++];
4611 assert(IndexIdx == IndexExprs.size() && "Wrong number of index expressions");
4612 setDependence(computeDependence(this));
4615 DesignatedInitExpr *
4616 DesignatedInitExpr::Create(const ASTContext &C,
4617 llvm::ArrayRef<Designator> Designators,
4618 ArrayRef<Expr*> IndexExprs,
4619 SourceLocation ColonOrEqualLoc,
4620 bool UsesColonSyntax, Expr *Init) {
4621 void *Mem = C.Allocate(totalSizeToAlloc<Stmt *>(IndexExprs.size() + 1),
4622 alignof(DesignatedInitExpr));
4623 return new (Mem) DesignatedInitExpr(C, C.VoidTy, Designators,
4624 ColonOrEqualLoc, UsesColonSyntax,
4625 IndexExprs, Init);
4628 DesignatedInitExpr *DesignatedInitExpr::CreateEmpty(const ASTContext &C,
4629 unsigned NumIndexExprs) {
4630 void *Mem = C.Allocate(totalSizeToAlloc<Stmt *>(NumIndexExprs + 1),
4631 alignof(DesignatedInitExpr));
4632 return new (Mem) DesignatedInitExpr(NumIndexExprs + 1);
4635 void DesignatedInitExpr::setDesignators(const ASTContext &C,
4636 const Designator *Desigs,
4637 unsigned NumDesigs) {
4638 Designators = new (C) Designator[NumDesigs];
4639 NumDesignators = NumDesigs;
4640 for (unsigned I = 0; I != NumDesigs; ++I)
4641 Designators[I] = Desigs[I];
4644 SourceRange DesignatedInitExpr::getDesignatorsSourceRange() const {
4645 DesignatedInitExpr *DIE = const_cast<DesignatedInitExpr*>(this);
4646 if (size() == 1)
4647 return DIE->getDesignator(0)->getSourceRange();
4648 return SourceRange(DIE->getDesignator(0)->getBeginLoc(),
4649 DIE->getDesignator(size() - 1)->getEndLoc());
4652 SourceLocation DesignatedInitExpr::getBeginLoc() const {
4653 auto *DIE = const_cast<DesignatedInitExpr *>(this);
4654 Designator &First = *DIE->getDesignator(0);
4655 if (First.isFieldDesignator()) {
4656 // Skip past implicit designators for anonymous structs/unions, since
4657 // these do not have valid source locations.
4658 for (unsigned int i = 0; i < DIE->size(); i++) {
4659 Designator &Des = *DIE->getDesignator(i);
4660 SourceLocation retval = GNUSyntax ? Des.getFieldLoc() : Des.getDotLoc();
4661 if (!retval.isValid())
4662 continue;
4663 return retval;
4666 return First.getLBracketLoc();
4669 SourceLocation DesignatedInitExpr::getEndLoc() const {
4670 return getInit()->getEndLoc();
4673 Expr *DesignatedInitExpr::getArrayIndex(const Designator& D) const {
4674 assert(D.isArrayDesignator() && "Requires array designator");
4675 return getSubExpr(D.getArrayIndex() + 1);
4678 Expr *DesignatedInitExpr::getArrayRangeStart(const Designator &D) const {
4679 assert(D.isArrayRangeDesignator() && "Requires array range designator");
4680 return getSubExpr(D.getArrayIndex() + 1);
4683 Expr *DesignatedInitExpr::getArrayRangeEnd(const Designator &D) const {
4684 assert(D.isArrayRangeDesignator() && "Requires array range designator");
4685 return getSubExpr(D.getArrayIndex() + 2);
4688 /// Replaces the designator at index @p Idx with the series
4689 /// of designators in [First, Last).
4690 void DesignatedInitExpr::ExpandDesignator(const ASTContext &C, unsigned Idx,
4691 const Designator *First,
4692 const Designator *Last) {
4693 unsigned NumNewDesignators = Last - First;
4694 if (NumNewDesignators == 0) {
4695 std::copy_backward(Designators + Idx + 1,
4696 Designators + NumDesignators,
4697 Designators + Idx);
4698 --NumNewDesignators;
4699 return;
4701 if (NumNewDesignators == 1) {
4702 Designators[Idx] = *First;
4703 return;
4706 Designator *NewDesignators
4707 = new (C) Designator[NumDesignators - 1 + NumNewDesignators];
4708 std::copy(Designators, Designators + Idx, NewDesignators);
4709 std::copy(First, Last, NewDesignators + Idx);
4710 std::copy(Designators + Idx + 1, Designators + NumDesignators,
4711 NewDesignators + Idx + NumNewDesignators);
4712 Designators = NewDesignators;
4713 NumDesignators = NumDesignators - 1 + NumNewDesignators;
4716 DesignatedInitUpdateExpr::DesignatedInitUpdateExpr(const ASTContext &C,
4717 SourceLocation lBraceLoc,
4718 Expr *baseExpr,
4719 SourceLocation rBraceLoc)
4720 : Expr(DesignatedInitUpdateExprClass, baseExpr->getType(), VK_PRValue,
4721 OK_Ordinary) {
4722 BaseAndUpdaterExprs[0] = baseExpr;
4724 InitListExpr *ILE = new (C) InitListExpr(C, lBraceLoc, {}, rBraceLoc);
4725 ILE->setType(baseExpr->getType());
4726 BaseAndUpdaterExprs[1] = ILE;
4728 // FIXME: this is wrong, set it correctly.
4729 setDependence(ExprDependence::None);
4732 SourceLocation DesignatedInitUpdateExpr::getBeginLoc() const {
4733 return getBase()->getBeginLoc();
4736 SourceLocation DesignatedInitUpdateExpr::getEndLoc() const {
4737 return getBase()->getEndLoc();
4740 ParenListExpr::ParenListExpr(SourceLocation LParenLoc, ArrayRef<Expr *> Exprs,
4741 SourceLocation RParenLoc)
4742 : Expr(ParenListExprClass, QualType(), VK_PRValue, OK_Ordinary),
4743 LParenLoc(LParenLoc), RParenLoc(RParenLoc) {
4744 ParenListExprBits.NumExprs = Exprs.size();
4746 for (unsigned I = 0, N = Exprs.size(); I != N; ++I)
4747 getTrailingObjects<Stmt *>()[I] = Exprs[I];
4748 setDependence(computeDependence(this));
4751 ParenListExpr::ParenListExpr(EmptyShell Empty, unsigned NumExprs)
4752 : Expr(ParenListExprClass, Empty) {
4753 ParenListExprBits.NumExprs = NumExprs;
4756 ParenListExpr *ParenListExpr::Create(const ASTContext &Ctx,
4757 SourceLocation LParenLoc,
4758 ArrayRef<Expr *> Exprs,
4759 SourceLocation RParenLoc) {
4760 void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *>(Exprs.size()),
4761 alignof(ParenListExpr));
4762 return new (Mem) ParenListExpr(LParenLoc, Exprs, RParenLoc);
4765 ParenListExpr *ParenListExpr::CreateEmpty(const ASTContext &Ctx,
4766 unsigned NumExprs) {
4767 void *Mem =
4768 Ctx.Allocate(totalSizeToAlloc<Stmt *>(NumExprs), alignof(ParenListExpr));
4769 return new (Mem) ParenListExpr(EmptyShell(), NumExprs);
4772 /// Certain overflow-dependent code patterns can have their integer overflow
4773 /// sanitization disabled. Check for the common pattern `if (a + b < a)` and
4774 /// return the resulting BinaryOperator responsible for the addition so we can
4775 /// elide overflow checks during codegen.
4776 static std::optional<BinaryOperator *>
4777 getOverflowPatternBinOp(const BinaryOperator *E) {
4778 Expr *Addition, *ComparedTo;
4779 if (E->getOpcode() == BO_LT) {
4780 Addition = E->getLHS();
4781 ComparedTo = E->getRHS();
4782 } else if (E->getOpcode() == BO_GT) {
4783 Addition = E->getRHS();
4784 ComparedTo = E->getLHS();
4785 } else {
4786 return {};
4789 const Expr *AddLHS = nullptr, *AddRHS = nullptr;
4790 BinaryOperator *BO = dyn_cast<BinaryOperator>(Addition);
4792 if (BO && BO->getOpcode() == clang::BO_Add) {
4793 // now store addends for lookup on other side of '>'
4794 AddLHS = BO->getLHS();
4795 AddRHS = BO->getRHS();
4798 if (!AddLHS || !AddRHS)
4799 return {};
4801 const Decl *LHSDecl, *RHSDecl, *OtherDecl;
4803 LHSDecl = AddLHS->IgnoreParenImpCasts()->getReferencedDeclOfCallee();
4804 RHSDecl = AddRHS->IgnoreParenImpCasts()->getReferencedDeclOfCallee();
4805 OtherDecl = ComparedTo->IgnoreParenImpCasts()->getReferencedDeclOfCallee();
4807 if (!OtherDecl)
4808 return {};
4810 if (!LHSDecl && !RHSDecl)
4811 return {};
4813 if ((LHSDecl && LHSDecl == OtherDecl && LHSDecl != RHSDecl) ||
4814 (RHSDecl && RHSDecl == OtherDecl && RHSDecl != LHSDecl))
4815 return BO;
4816 return {};
4819 /// Compute and set the OverflowPatternExclusion bit based on whether the
4820 /// BinaryOperator expression matches an overflow pattern being ignored by
4821 /// -fsanitize-undefined-ignore-overflow-pattern=add-signed-overflow-test or
4822 /// -fsanitize-undefined-ignore-overflow-pattern=add-unsigned-overflow-test
4823 static void computeOverflowPatternExclusion(const ASTContext &Ctx,
4824 const BinaryOperator *E) {
4825 std::optional<BinaryOperator *> Result = getOverflowPatternBinOp(E);
4826 if (!Result.has_value())
4827 return;
4828 QualType AdditionResultType = Result.value()->getType();
4830 if ((AdditionResultType->isSignedIntegerType() &&
4831 Ctx.getLangOpts().isOverflowPatternExcluded(
4832 LangOptions::OverflowPatternExclusionKind::AddSignedOverflowTest)) ||
4833 (AdditionResultType->isUnsignedIntegerType() &&
4834 Ctx.getLangOpts().isOverflowPatternExcluded(
4835 LangOptions::OverflowPatternExclusionKind::AddUnsignedOverflowTest)))
4836 Result.value()->setExcludedOverflowPattern(true);
4839 BinaryOperator::BinaryOperator(const ASTContext &Ctx, Expr *lhs, Expr *rhs,
4840 Opcode opc, QualType ResTy, ExprValueKind VK,
4841 ExprObjectKind OK, SourceLocation opLoc,
4842 FPOptionsOverride FPFeatures)
4843 : Expr(BinaryOperatorClass, ResTy, VK, OK) {
4844 BinaryOperatorBits.Opc = opc;
4845 assert(!isCompoundAssignmentOp() &&
4846 "Use CompoundAssignOperator for compound assignments");
4847 BinaryOperatorBits.OpLoc = opLoc;
4848 BinaryOperatorBits.ExcludedOverflowPattern = false;
4849 SubExprs[LHS] = lhs;
4850 SubExprs[RHS] = rhs;
4851 computeOverflowPatternExclusion(Ctx, this);
4852 BinaryOperatorBits.HasFPFeatures = FPFeatures.requiresTrailingStorage();
4853 if (hasStoredFPFeatures())
4854 setStoredFPFeatures(FPFeatures);
4855 setDependence(computeDependence(this));
4858 BinaryOperator::BinaryOperator(const ASTContext &Ctx, Expr *lhs, Expr *rhs,
4859 Opcode opc, QualType ResTy, ExprValueKind VK,
4860 ExprObjectKind OK, SourceLocation opLoc,
4861 FPOptionsOverride FPFeatures, bool dead2)
4862 : Expr(CompoundAssignOperatorClass, ResTy, VK, OK) {
4863 BinaryOperatorBits.Opc = opc;
4864 BinaryOperatorBits.ExcludedOverflowPattern = false;
4865 assert(isCompoundAssignmentOp() &&
4866 "Use CompoundAssignOperator for compound assignments");
4867 BinaryOperatorBits.OpLoc = opLoc;
4868 SubExprs[LHS] = lhs;
4869 SubExprs[RHS] = rhs;
4870 BinaryOperatorBits.HasFPFeatures = FPFeatures.requiresTrailingStorage();
4871 if (hasStoredFPFeatures())
4872 setStoredFPFeatures(FPFeatures);
4873 setDependence(computeDependence(this));
4876 BinaryOperator *BinaryOperator::CreateEmpty(const ASTContext &C,
4877 bool HasFPFeatures) {
4878 unsigned Extra = sizeOfTrailingObjects(HasFPFeatures);
4879 void *Mem =
4880 C.Allocate(sizeof(BinaryOperator) + Extra, alignof(BinaryOperator));
4881 return new (Mem) BinaryOperator(EmptyShell());
4884 BinaryOperator *BinaryOperator::Create(const ASTContext &C, Expr *lhs,
4885 Expr *rhs, Opcode opc, QualType ResTy,
4886 ExprValueKind VK, ExprObjectKind OK,
4887 SourceLocation opLoc,
4888 FPOptionsOverride FPFeatures) {
4889 bool HasFPFeatures = FPFeatures.requiresTrailingStorage();
4890 unsigned Extra = sizeOfTrailingObjects(HasFPFeatures);
4891 void *Mem =
4892 C.Allocate(sizeof(BinaryOperator) + Extra, alignof(BinaryOperator));
4893 return new (Mem)
4894 BinaryOperator(C, lhs, rhs, opc, ResTy, VK, OK, opLoc, FPFeatures);
4897 CompoundAssignOperator *
4898 CompoundAssignOperator::CreateEmpty(const ASTContext &C, bool HasFPFeatures) {
4899 unsigned Extra = sizeOfTrailingObjects(HasFPFeatures);
4900 void *Mem = C.Allocate(sizeof(CompoundAssignOperator) + Extra,
4901 alignof(CompoundAssignOperator));
4902 return new (Mem) CompoundAssignOperator(C, EmptyShell(), HasFPFeatures);
4905 CompoundAssignOperator *
4906 CompoundAssignOperator::Create(const ASTContext &C, Expr *lhs, Expr *rhs,
4907 Opcode opc, QualType ResTy, ExprValueKind VK,
4908 ExprObjectKind OK, SourceLocation opLoc,
4909 FPOptionsOverride FPFeatures,
4910 QualType CompLHSType, QualType CompResultType) {
4911 bool HasFPFeatures = FPFeatures.requiresTrailingStorage();
4912 unsigned Extra = sizeOfTrailingObjects(HasFPFeatures);
4913 void *Mem = C.Allocate(sizeof(CompoundAssignOperator) + Extra,
4914 alignof(CompoundAssignOperator));
4915 return new (Mem)
4916 CompoundAssignOperator(C, lhs, rhs, opc, ResTy, VK, OK, opLoc, FPFeatures,
4917 CompLHSType, CompResultType);
4920 UnaryOperator *UnaryOperator::CreateEmpty(const ASTContext &C,
4921 bool hasFPFeatures) {
4922 void *Mem = C.Allocate(totalSizeToAlloc<FPOptionsOverride>(hasFPFeatures),
4923 alignof(UnaryOperator));
4924 return new (Mem) UnaryOperator(hasFPFeatures, EmptyShell());
4927 UnaryOperator::UnaryOperator(const ASTContext &Ctx, Expr *input, Opcode opc,
4928 QualType type, ExprValueKind VK, ExprObjectKind OK,
4929 SourceLocation l, bool CanOverflow,
4930 FPOptionsOverride FPFeatures)
4931 : Expr(UnaryOperatorClass, type, VK, OK), Val(input) {
4932 UnaryOperatorBits.Opc = opc;
4933 UnaryOperatorBits.CanOverflow = CanOverflow;
4934 UnaryOperatorBits.Loc = l;
4935 UnaryOperatorBits.HasFPFeatures = FPFeatures.requiresTrailingStorage();
4936 if (hasStoredFPFeatures())
4937 setStoredFPFeatures(FPFeatures);
4938 setDependence(computeDependence(this, Ctx));
4941 UnaryOperator *UnaryOperator::Create(const ASTContext &C, Expr *input,
4942 Opcode opc, QualType type,
4943 ExprValueKind VK, ExprObjectKind OK,
4944 SourceLocation l, bool CanOverflow,
4945 FPOptionsOverride FPFeatures) {
4946 bool HasFPFeatures = FPFeatures.requiresTrailingStorage();
4947 unsigned Size = totalSizeToAlloc<FPOptionsOverride>(HasFPFeatures);
4948 void *Mem = C.Allocate(Size, alignof(UnaryOperator));
4949 return new (Mem)
4950 UnaryOperator(C, input, opc, type, VK, OK, l, CanOverflow, FPFeatures);
4953 const OpaqueValueExpr *OpaqueValueExpr::findInCopyConstruct(const Expr *e) {
4954 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(e))
4955 e = ewc->getSubExpr();
4956 if (const MaterializeTemporaryExpr *m = dyn_cast<MaterializeTemporaryExpr>(e))
4957 e = m->getSubExpr();
4958 e = cast<CXXConstructExpr>(e)->getArg(0);
4959 while (const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
4960 e = ice->getSubExpr();
4961 return cast<OpaqueValueExpr>(e);
4964 PseudoObjectExpr *PseudoObjectExpr::Create(const ASTContext &Context,
4965 EmptyShell sh,
4966 unsigned numSemanticExprs) {
4967 void *buffer =
4968 Context.Allocate(totalSizeToAlloc<Expr *>(1 + numSemanticExprs),
4969 alignof(PseudoObjectExpr));
4970 return new(buffer) PseudoObjectExpr(sh, numSemanticExprs);
4973 PseudoObjectExpr::PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs)
4974 : Expr(PseudoObjectExprClass, shell) {
4975 PseudoObjectExprBits.NumSubExprs = numSemanticExprs + 1;
4978 PseudoObjectExpr *PseudoObjectExpr::Create(const ASTContext &C, Expr *syntax,
4979 ArrayRef<Expr*> semantics,
4980 unsigned resultIndex) {
4981 assert(syntax && "no syntactic expression!");
4982 assert(semantics.size() && "no semantic expressions!");
4984 QualType type;
4985 ExprValueKind VK;
4986 if (resultIndex == NoResult) {
4987 type = C.VoidTy;
4988 VK = VK_PRValue;
4989 } else {
4990 assert(resultIndex < semantics.size());
4991 type = semantics[resultIndex]->getType();
4992 VK = semantics[resultIndex]->getValueKind();
4993 assert(semantics[resultIndex]->getObjectKind() == OK_Ordinary);
4996 void *buffer = C.Allocate(totalSizeToAlloc<Expr *>(semantics.size() + 1),
4997 alignof(PseudoObjectExpr));
4998 return new(buffer) PseudoObjectExpr(type, VK, syntax, semantics,
4999 resultIndex);
5002 PseudoObjectExpr::PseudoObjectExpr(QualType type, ExprValueKind VK,
5003 Expr *syntax, ArrayRef<Expr *> semantics,
5004 unsigned resultIndex)
5005 : Expr(PseudoObjectExprClass, type, VK, OK_Ordinary) {
5006 PseudoObjectExprBits.NumSubExprs = semantics.size() + 1;
5007 PseudoObjectExprBits.ResultIndex = resultIndex + 1;
5009 for (unsigned i = 0, e = semantics.size() + 1; i != e; ++i) {
5010 Expr *E = (i == 0 ? syntax : semantics[i-1]);
5011 getSubExprsBuffer()[i] = E;
5013 if (isa<OpaqueValueExpr>(E))
5014 assert(cast<OpaqueValueExpr>(E)->getSourceExpr() != nullptr &&
5015 "opaque-value semantic expressions for pseudo-object "
5016 "operations must have sources");
5019 setDependence(computeDependence(this));
5022 //===----------------------------------------------------------------------===//
5023 // Child Iterators for iterating over subexpressions/substatements
5024 //===----------------------------------------------------------------------===//
5026 // UnaryExprOrTypeTraitExpr
5027 Stmt::child_range UnaryExprOrTypeTraitExpr::children() {
5028 const_child_range CCR =
5029 const_cast<const UnaryExprOrTypeTraitExpr *>(this)->children();
5030 return child_range(cast_away_const(CCR.begin()), cast_away_const(CCR.end()));
5033 Stmt::const_child_range UnaryExprOrTypeTraitExpr::children() const {
5034 // If this is of a type and the type is a VLA type (and not a typedef), the
5035 // size expression of the VLA needs to be treated as an executable expression.
5036 // Why isn't this weirdness documented better in StmtIterator?
5037 if (isArgumentType()) {
5038 if (const VariableArrayType *T =
5039 dyn_cast<VariableArrayType>(getArgumentType().getTypePtr()))
5040 return const_child_range(const_child_iterator(T), const_child_iterator());
5041 return const_child_range(const_child_iterator(), const_child_iterator());
5043 return const_child_range(&Argument.Ex, &Argument.Ex + 1);
5046 AtomicExpr::AtomicExpr(SourceLocation BLoc, ArrayRef<Expr *> args, QualType t,
5047 AtomicOp op, SourceLocation RP)
5048 : Expr(AtomicExprClass, t, VK_PRValue, OK_Ordinary),
5049 NumSubExprs(args.size()), BuiltinLoc(BLoc), RParenLoc(RP), Op(op) {
5050 assert(args.size() == getNumSubExprs(op) && "wrong number of subexpressions");
5051 for (unsigned i = 0; i != args.size(); i++)
5052 SubExprs[i] = args[i];
5053 setDependence(computeDependence(this));
5056 unsigned AtomicExpr::getNumSubExprs(AtomicOp Op) {
5057 switch (Op) {
5058 case AO__c11_atomic_init:
5059 case AO__opencl_atomic_init:
5060 case AO__c11_atomic_load:
5061 case AO__atomic_load_n:
5062 return 2;
5064 case AO__scoped_atomic_load_n:
5065 case AO__opencl_atomic_load:
5066 case AO__hip_atomic_load:
5067 case AO__c11_atomic_store:
5068 case AO__c11_atomic_exchange:
5069 case AO__atomic_load:
5070 case AO__atomic_store:
5071 case AO__atomic_store_n:
5072 case AO__atomic_exchange_n:
5073 case AO__c11_atomic_fetch_add:
5074 case AO__c11_atomic_fetch_sub:
5075 case AO__c11_atomic_fetch_and:
5076 case AO__c11_atomic_fetch_or:
5077 case AO__c11_atomic_fetch_xor:
5078 case AO__c11_atomic_fetch_nand:
5079 case AO__c11_atomic_fetch_max:
5080 case AO__c11_atomic_fetch_min:
5081 case AO__atomic_fetch_add:
5082 case AO__atomic_fetch_sub:
5083 case AO__atomic_fetch_and:
5084 case AO__atomic_fetch_or:
5085 case AO__atomic_fetch_xor:
5086 case AO__atomic_fetch_nand:
5087 case AO__atomic_add_fetch:
5088 case AO__atomic_sub_fetch:
5089 case AO__atomic_and_fetch:
5090 case AO__atomic_or_fetch:
5091 case AO__atomic_xor_fetch:
5092 case AO__atomic_nand_fetch:
5093 case AO__atomic_min_fetch:
5094 case AO__atomic_max_fetch:
5095 case AO__atomic_fetch_min:
5096 case AO__atomic_fetch_max:
5097 return 3;
5099 case AO__scoped_atomic_load:
5100 case AO__scoped_atomic_store:
5101 case AO__scoped_atomic_store_n:
5102 case AO__scoped_atomic_fetch_add:
5103 case AO__scoped_atomic_fetch_sub:
5104 case AO__scoped_atomic_fetch_and:
5105 case AO__scoped_atomic_fetch_or:
5106 case AO__scoped_atomic_fetch_xor:
5107 case AO__scoped_atomic_fetch_nand:
5108 case AO__scoped_atomic_add_fetch:
5109 case AO__scoped_atomic_sub_fetch:
5110 case AO__scoped_atomic_and_fetch:
5111 case AO__scoped_atomic_or_fetch:
5112 case AO__scoped_atomic_xor_fetch:
5113 case AO__scoped_atomic_nand_fetch:
5114 case AO__scoped_atomic_min_fetch:
5115 case AO__scoped_atomic_max_fetch:
5116 case AO__scoped_atomic_fetch_min:
5117 case AO__scoped_atomic_fetch_max:
5118 case AO__scoped_atomic_exchange_n:
5119 case AO__hip_atomic_exchange:
5120 case AO__hip_atomic_fetch_add:
5121 case AO__hip_atomic_fetch_sub:
5122 case AO__hip_atomic_fetch_and:
5123 case AO__hip_atomic_fetch_or:
5124 case AO__hip_atomic_fetch_xor:
5125 case AO__hip_atomic_fetch_min:
5126 case AO__hip_atomic_fetch_max:
5127 case AO__opencl_atomic_store:
5128 case AO__hip_atomic_store:
5129 case AO__opencl_atomic_exchange:
5130 case AO__opencl_atomic_fetch_add:
5131 case AO__opencl_atomic_fetch_sub:
5132 case AO__opencl_atomic_fetch_and:
5133 case AO__opencl_atomic_fetch_or:
5134 case AO__opencl_atomic_fetch_xor:
5135 case AO__opencl_atomic_fetch_min:
5136 case AO__opencl_atomic_fetch_max:
5137 case AO__atomic_exchange:
5138 return 4;
5140 case AO__scoped_atomic_exchange:
5141 case AO__c11_atomic_compare_exchange_strong:
5142 case AO__c11_atomic_compare_exchange_weak:
5143 return 5;
5144 case AO__hip_atomic_compare_exchange_strong:
5145 case AO__opencl_atomic_compare_exchange_strong:
5146 case AO__opencl_atomic_compare_exchange_weak:
5147 case AO__hip_atomic_compare_exchange_weak:
5148 case AO__atomic_compare_exchange:
5149 case AO__atomic_compare_exchange_n:
5150 return 6;
5152 case AO__scoped_atomic_compare_exchange:
5153 case AO__scoped_atomic_compare_exchange_n:
5154 return 7;
5156 llvm_unreachable("unknown atomic op");
5159 QualType AtomicExpr::getValueType() const {
5160 auto T = getPtr()->getType()->castAs<PointerType>()->getPointeeType();
5161 if (auto AT = T->getAs<AtomicType>())
5162 return AT->getValueType();
5163 return T;
5166 QualType ArraySectionExpr::getBaseOriginalType(const Expr *Base) {
5167 unsigned ArraySectionCount = 0;
5168 while (auto *OASE = dyn_cast<ArraySectionExpr>(Base->IgnoreParens())) {
5169 Base = OASE->getBase();
5170 ++ArraySectionCount;
5172 while (auto *ASE =
5173 dyn_cast<ArraySubscriptExpr>(Base->IgnoreParenImpCasts())) {
5174 Base = ASE->getBase();
5175 ++ArraySectionCount;
5177 Base = Base->IgnoreParenImpCasts();
5178 auto OriginalTy = Base->getType();
5179 if (auto *DRE = dyn_cast<DeclRefExpr>(Base))
5180 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
5181 OriginalTy = PVD->getOriginalType().getNonReferenceType();
5183 for (unsigned Cnt = 0; Cnt < ArraySectionCount; ++Cnt) {
5184 if (OriginalTy->isAnyPointerType())
5185 OriginalTy = OriginalTy->getPointeeType();
5186 else if (OriginalTy->isArrayType())
5187 OriginalTy = OriginalTy->castAsArrayTypeUnsafe()->getElementType();
5188 else
5189 return {};
5191 return OriginalTy;
5194 RecoveryExpr::RecoveryExpr(ASTContext &Ctx, QualType T, SourceLocation BeginLoc,
5195 SourceLocation EndLoc, ArrayRef<Expr *> SubExprs)
5196 : Expr(RecoveryExprClass, T.getNonReferenceType(),
5197 T->isDependentType() ? VK_LValue : getValueKindForType(T),
5198 OK_Ordinary),
5199 BeginLoc(BeginLoc), EndLoc(EndLoc), NumExprs(SubExprs.size()) {
5200 assert(!T.isNull());
5201 assert(!llvm::is_contained(SubExprs, nullptr));
5203 llvm::copy(SubExprs, getTrailingObjects<Expr *>());
5204 setDependence(computeDependence(this));
5207 RecoveryExpr *RecoveryExpr::Create(ASTContext &Ctx, QualType T,
5208 SourceLocation BeginLoc,
5209 SourceLocation EndLoc,
5210 ArrayRef<Expr *> SubExprs) {
5211 void *Mem = Ctx.Allocate(totalSizeToAlloc<Expr *>(SubExprs.size()),
5212 alignof(RecoveryExpr));
5213 return new (Mem) RecoveryExpr(Ctx, T, BeginLoc, EndLoc, SubExprs);
5216 RecoveryExpr *RecoveryExpr::CreateEmpty(ASTContext &Ctx, unsigned NumSubExprs) {
5217 void *Mem = Ctx.Allocate(totalSizeToAlloc<Expr *>(NumSubExprs),
5218 alignof(RecoveryExpr));
5219 return new (Mem) RecoveryExpr(EmptyShell(), NumSubExprs);
5222 void OMPArrayShapingExpr::setDimensions(ArrayRef<Expr *> Dims) {
5223 assert(
5224 NumDims == Dims.size() &&
5225 "Preallocated number of dimensions is different from the provided one.");
5226 llvm::copy(Dims, getTrailingObjects<Expr *>());
5229 void OMPArrayShapingExpr::setBracketsRanges(ArrayRef<SourceRange> BR) {
5230 assert(
5231 NumDims == BR.size() &&
5232 "Preallocated number of dimensions is different from the provided one.");
5233 llvm::copy(BR, getTrailingObjects<SourceRange>());
5236 OMPArrayShapingExpr::OMPArrayShapingExpr(QualType ExprTy, Expr *Op,
5237 SourceLocation L, SourceLocation R,
5238 ArrayRef<Expr *> Dims)
5239 : Expr(OMPArrayShapingExprClass, ExprTy, VK_LValue, OK_Ordinary), LPLoc(L),
5240 RPLoc(R), NumDims(Dims.size()) {
5241 setBase(Op);
5242 setDimensions(Dims);
5243 setDependence(computeDependence(this));
5246 OMPArrayShapingExpr *
5247 OMPArrayShapingExpr::Create(const ASTContext &Context, QualType T, Expr *Op,
5248 SourceLocation L, SourceLocation R,
5249 ArrayRef<Expr *> Dims,
5250 ArrayRef<SourceRange> BracketRanges) {
5251 assert(Dims.size() == BracketRanges.size() &&
5252 "Different number of dimensions and brackets ranges.");
5253 void *Mem = Context.Allocate(
5254 totalSizeToAlloc<Expr *, SourceRange>(Dims.size() + 1, Dims.size()),
5255 alignof(OMPArrayShapingExpr));
5256 auto *E = new (Mem) OMPArrayShapingExpr(T, Op, L, R, Dims);
5257 E->setBracketsRanges(BracketRanges);
5258 return E;
5261 OMPArrayShapingExpr *OMPArrayShapingExpr::CreateEmpty(const ASTContext &Context,
5262 unsigned NumDims) {
5263 void *Mem = Context.Allocate(
5264 totalSizeToAlloc<Expr *, SourceRange>(NumDims + 1, NumDims),
5265 alignof(OMPArrayShapingExpr));
5266 return new (Mem) OMPArrayShapingExpr(EmptyShell(), NumDims);
5269 void OMPIteratorExpr::setIteratorDeclaration(unsigned I, Decl *D) {
5270 assert(I < NumIterators &&
5271 "Idx is greater or equal the number of iterators definitions.");
5272 getTrailingObjects<Decl *>()[I] = D;
5275 void OMPIteratorExpr::setAssignmentLoc(unsigned I, SourceLocation Loc) {
5276 assert(I < NumIterators &&
5277 "Idx is greater or equal the number of iterators definitions.");
5278 getTrailingObjects<
5279 SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +
5280 static_cast<int>(RangeLocOffset::AssignLoc)] = Loc;
5283 void OMPIteratorExpr::setIteratorRange(unsigned I, Expr *Begin,
5284 SourceLocation ColonLoc, Expr *End,
5285 SourceLocation SecondColonLoc,
5286 Expr *Step) {
5287 assert(I < NumIterators &&
5288 "Idx is greater or equal the number of iterators definitions.");
5289 getTrailingObjects<Expr *>()[I * static_cast<int>(RangeExprOffset::Total) +
5290 static_cast<int>(RangeExprOffset::Begin)] =
5291 Begin;
5292 getTrailingObjects<Expr *>()[I * static_cast<int>(RangeExprOffset::Total) +
5293 static_cast<int>(RangeExprOffset::End)] = End;
5294 getTrailingObjects<Expr *>()[I * static_cast<int>(RangeExprOffset::Total) +
5295 static_cast<int>(RangeExprOffset::Step)] = Step;
5296 getTrailingObjects<
5297 SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +
5298 static_cast<int>(RangeLocOffset::FirstColonLoc)] =
5299 ColonLoc;
5300 getTrailingObjects<
5301 SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +
5302 static_cast<int>(RangeLocOffset::SecondColonLoc)] =
5303 SecondColonLoc;
5306 Decl *OMPIteratorExpr::getIteratorDecl(unsigned I) {
5307 return getTrailingObjects<Decl *>()[I];
5310 OMPIteratorExpr::IteratorRange OMPIteratorExpr::getIteratorRange(unsigned I) {
5311 IteratorRange Res;
5312 Res.Begin =
5313 getTrailingObjects<Expr *>()[I * static_cast<int>(
5314 RangeExprOffset::Total) +
5315 static_cast<int>(RangeExprOffset::Begin)];
5316 Res.End =
5317 getTrailingObjects<Expr *>()[I * static_cast<int>(
5318 RangeExprOffset::Total) +
5319 static_cast<int>(RangeExprOffset::End)];
5320 Res.Step =
5321 getTrailingObjects<Expr *>()[I * static_cast<int>(
5322 RangeExprOffset::Total) +
5323 static_cast<int>(RangeExprOffset::Step)];
5324 return Res;
5327 SourceLocation OMPIteratorExpr::getAssignLoc(unsigned I) const {
5328 return getTrailingObjects<
5329 SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +
5330 static_cast<int>(RangeLocOffset::AssignLoc)];
5333 SourceLocation OMPIteratorExpr::getColonLoc(unsigned I) const {
5334 return getTrailingObjects<
5335 SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +
5336 static_cast<int>(RangeLocOffset::FirstColonLoc)];
5339 SourceLocation OMPIteratorExpr::getSecondColonLoc(unsigned I) const {
5340 return getTrailingObjects<
5341 SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +
5342 static_cast<int>(RangeLocOffset::SecondColonLoc)];
5345 void OMPIteratorExpr::setHelper(unsigned I, const OMPIteratorHelperData &D) {
5346 getTrailingObjects<OMPIteratorHelperData>()[I] = D;
5349 OMPIteratorHelperData &OMPIteratorExpr::getHelper(unsigned I) {
5350 return getTrailingObjects<OMPIteratorHelperData>()[I];
5353 const OMPIteratorHelperData &OMPIteratorExpr::getHelper(unsigned I) const {
5354 return getTrailingObjects<OMPIteratorHelperData>()[I];
5357 OMPIteratorExpr::OMPIteratorExpr(
5358 QualType ExprTy, SourceLocation IteratorKwLoc, SourceLocation L,
5359 SourceLocation R, ArrayRef<OMPIteratorExpr::IteratorDefinition> Data,
5360 ArrayRef<OMPIteratorHelperData> Helpers)
5361 : Expr(OMPIteratorExprClass, ExprTy, VK_LValue, OK_Ordinary),
5362 IteratorKwLoc(IteratorKwLoc), LPLoc(L), RPLoc(R),
5363 NumIterators(Data.size()) {
5364 for (unsigned I = 0, E = Data.size(); I < E; ++I) {
5365 const IteratorDefinition &D = Data[I];
5366 setIteratorDeclaration(I, D.IteratorDecl);
5367 setAssignmentLoc(I, D.AssignmentLoc);
5368 setIteratorRange(I, D.Range.Begin, D.ColonLoc, D.Range.End,
5369 D.SecondColonLoc, D.Range.Step);
5370 setHelper(I, Helpers[I]);
5372 setDependence(computeDependence(this));
5375 OMPIteratorExpr *
5376 OMPIteratorExpr::Create(const ASTContext &Context, QualType T,
5377 SourceLocation IteratorKwLoc, SourceLocation L,
5378 SourceLocation R,
5379 ArrayRef<OMPIteratorExpr::IteratorDefinition> Data,
5380 ArrayRef<OMPIteratorHelperData> Helpers) {
5381 assert(Data.size() == Helpers.size() &&
5382 "Data and helpers must have the same size.");
5383 void *Mem = Context.Allocate(
5384 totalSizeToAlloc<Decl *, Expr *, SourceLocation, OMPIteratorHelperData>(
5385 Data.size(), Data.size() * static_cast<int>(RangeExprOffset::Total),
5386 Data.size() * static_cast<int>(RangeLocOffset::Total),
5387 Helpers.size()),
5388 alignof(OMPIteratorExpr));
5389 return new (Mem) OMPIteratorExpr(T, IteratorKwLoc, L, R, Data, Helpers);
5392 OMPIteratorExpr *OMPIteratorExpr::CreateEmpty(const ASTContext &Context,
5393 unsigned NumIterators) {
5394 void *Mem = Context.Allocate(
5395 totalSizeToAlloc<Decl *, Expr *, SourceLocation, OMPIteratorHelperData>(
5396 NumIterators, NumIterators * static_cast<int>(RangeExprOffset::Total),
5397 NumIterators * static_cast<int>(RangeLocOffset::Total), NumIterators),
5398 alignof(OMPIteratorExpr));
5399 return new (Mem) OMPIteratorExpr(EmptyShell(), NumIterators);
5402 HLSLOutArgExpr *HLSLOutArgExpr::Create(const ASTContext &C, QualType Ty,
5403 OpaqueValueExpr *Base,
5404 OpaqueValueExpr *OpV, Expr *WB,
5405 bool IsInOut) {
5406 return new (C) HLSLOutArgExpr(Ty, Base, OpV, WB, IsInOut);
5409 HLSLOutArgExpr *HLSLOutArgExpr::CreateEmpty(const ASTContext &C) {
5410 return new (C) HLSLOutArgExpr(EmptyShell());
5413 OpenACCAsteriskSizeExpr *OpenACCAsteriskSizeExpr::Create(const ASTContext &C,
5414 SourceLocation Loc) {
5415 return new (C) OpenACCAsteriskSizeExpr(Loc, C.IntTy);
5418 OpenACCAsteriskSizeExpr *
5419 OpenACCAsteriskSizeExpr::CreateEmpty(const ASTContext &C) {
5420 return new (C) OpenACCAsteriskSizeExpr({}, C.IntTy);