clang 19.0.0git
Expr.cpp
Go to the documentation of this file.
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.
10//
11//===----------------------------------------------------------------------===//
12
13#include "clang/AST/Expr.h"
14#include "clang/AST/APValue.h"
16#include "clang/AST/Attr.h"
18#include "clang/AST/DeclCXX.h"
19#include "clang/AST/DeclObjC.h"
23#include "clang/AST/ExprCXX.h"
25#include "clang/AST/Mangle.h"
32#include "clang/Lex/Lexer.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>
41using namespace clang;
42
44 const Expr *E = this;
45 while (true) {
46 E = E->IgnoreParenBaseCasts();
47
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;
53 }
54 }
55
56 // Step into initializer for materialized temporaries.
57 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
58 E = MTE->getSubExpr();
59 continue;
60 }
61
62 break;
63 }
64
65 return E;
66}
67
70 QualType DerivedType = E->getType();
71 if (const PointerType *PTy = DerivedType->getAs<PointerType>())
72 DerivedType = PTy->getPointeeType();
73
74 if (DerivedType->isDependentType())
75 return nullptr;
76
77 const RecordType *Ty = DerivedType->castAs<RecordType>();
78 Decl *D = Ty->getDecl();
79 return cast<CXXRecordDecl>(D);
80}
81
84 SmallVectorImpl<SubobjectAdjustment> &Adjustments) const {
85 const Expr *E = this;
86 while (true) {
87 E = E->IgnoreParens();
88
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;
98 }
99
100 if (CE->getCastKind() == CK_NoOp) {
101 E = CE->getSubExpr();
102 continue;
103 }
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;
112 }
113 }
114 }
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;
122 }
123 if (BO->getOpcode() == BO_Comma) {
124 CommaLHSs.push_back(BO->getLHS());
125 E = BO->getRHS();
126 continue;
127 }
128 }
129
130 // Nothing changed.
131 break;
132 }
133 return E;
134}
135
136bool Expr::isKnownToHaveBooleanValue(bool Semantic) const {
137 const Expr *E = IgnoreParens();
138
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;
143
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;
152 }
153 }
154
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);
160
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;
173
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);
180
181 case BO_Comma:
182 case BO_Assign:
183 return BO->getRHS()->isKnownToHaveBooleanValue(Semantic);
184 }
185 }
186
187 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
188 return CO->getTrueExpr()->isKnownToHaveBooleanValue(Semantic) &&
189 CO->getFalseExpr()->isKnownToHaveBooleanValue(Semantic);
190
191 if (isa<ObjCBoolLiteralExpr>(E))
192 return true;
193
194 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
195 return OVE->getSourceExpr()->isKnownToHaveBooleanValue(Semantic);
196
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;
202
203 return false;
204}
205
207 ASTContext &Ctx,
208 LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel,
209 bool IgnoreTemplateOrMacroSubstitution) const {
210 const Expr *E = IgnoreParens();
211 const Decl *D = nullptr;
212
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();
219
220 return Decl::isFlexibleArrayMemberLike(Ctx, D, E->getType(),
221 StrictFlexArraysLevel,
222 IgnoreTemplateOrMacroSubstitution);
223}
224
225const ValueDecl *
227 Expr::EvalResult Eval;
228
229 if (EvaluateAsConstantExpr(Eval, Context)) {
230 APValue &Value = Eval.Val;
231
232 if (Value.isMemberPointer())
233 return Value.getMemberPointerDecl();
234
235 if (Value.isLValue() && Value.getLValueOffset().isZero())
236 return Value.getLValueBase().dyn_cast<const ValueDecl *>();
237 }
238
239 return nullptr;
240}
241
242// Amusing macro metaprogramming hack: check whether a class provides
243// a more specific implementation of getExprLoc().
244//
245// See also Stmt.cpp:{getBeginLoc(),getEndLoc()}.
246namespace {
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();
253 }
254
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();
263 }
264}
265
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);
273 }
274 return getType();
275}
276
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"
286 }
287 llvm_unreachable("unknown expression kind");
288}
289
290//===----------------------------------------------------------------------===//
291// Primary Expressions.
292//===----------------------------------------------------------------------===//
293
295 assert((Kind == ConstantResultStorageKind::APValue ||
298 "Invalid StorageKind Value");
299 (void)Kind;
300}
301
303 switch (Value.getKind()) {
304 case APValue::None:
307 case APValue::Int:
308 if (!Value.getInt().needsCleanup())
310 [[fallthrough]];
311 default:
313 }
314}
315
318 if (T->isIntegralOrEnumerationType() && Context.getTypeInfo(T).Width <= 64)
321}
322
323ConstantExpr::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;
332
333 if (StorageKind == ConstantResultStorageKind::APValue)
334 ::new (getTrailingObjects<APValue>()) APValue();
335}
336
338 ConstantResultStorageKind StorageKind,
339 bool IsImmediateInvocation) {
340 assert(!isa<ConstantExpr>(E));
341 AssertResultStorageKind(StorageKind);
342
343 unsigned Size = totalSizeToAlloc<APValue, uint64_t>(
345 StorageKind == ConstantResultStorageKind::Int64);
346 void *Mem = Context.Allocate(Size, alignof(ConstantExpr));
347 return new (Mem) ConstantExpr(E, StorageKind, IsImmediateInvocation);
348}
349
351 const APValue &Result) {
353 ConstantExpr *Self = Create(Context, E, StorageKind);
354 Self->SetResult(Result, Context);
355 return Self;
356}
357
358ConstantExpr::ConstantExpr(EmptyShell Empty,
359 ConstantResultStorageKind StorageKind)
360 : FullExpr(ConstantExprClass, Empty) {
361 ConstantExprBits.ResultKind = llvm::to_underlying(StorageKind);
362
363 if (StorageKind == ConstantResultStorageKind::APValue)
364 ::new (getTrailingObjects<APValue>()) APValue();
365}
366
368 ConstantResultStorageKind StorageKind) {
369 AssertResultStorageKind(StorageKind);
370
371 unsigned Size = totalSizeToAlloc<APValue, uint64_t>(
373 StorageKind == ConstantResultStorageKind::Int64);
374 void *Mem = Context.Allocate(Size, alignof(ConstantExpr));
375 return new (Mem) ConstantExpr(EmptyShell(), StorageKind);
376}
377
379 assert((unsigned)getStorageKind(Value) <= ConstantExprBits.ResultKind &&
380 "Invalid storage for this value kind");
381 ConstantExprBits.APValueKind = Value.getKind();
382 switch (getResultStorageKind()) {
384 return;
386 Int64Result() = *Value.getInt().getRawData();
387 ConstantExprBits.BitWidth = Value.getInt().getBitWidth();
388 ConstantExprBits.IsUnsigned = Value.getInt().isUnsigned();
389 return;
391 if (!ConstantExprBits.HasCleanup && Value.needsCleanup()) {
392 ConstantExprBits.HasCleanup = true;
393 Context.addDestruction(&APValueResult());
394 }
395 APValueResult() = std::move(Value);
396 return;
397 }
398 llvm_unreachable("Invalid ResultKind Bits");
399}
400
402 switch (getResultStorageKind()) {
404 return APValueResult().getInt();
406 return llvm::APSInt(llvm::APInt(ConstantExprBits.BitWidth, Int64Result()),
407 ConstantExprBits.IsUnsigned);
408 default:
409 llvm_unreachable("invalid Accessor");
410 }
411}
412
414
415 switch (getResultStorageKind()) {
417 return APValueResult();
419 return APValue(
420 llvm::APSInt(llvm::APInt(ConstantExprBits.BitWidth, Int64Result()),
421 ConstantExprBits.IsUnsigned));
423 if (ConstantExprBits.APValueKind == APValue::Indeterminate)
425 return APValue();
426 }
427 llvm_unreachable("invalid ResultKind");
428}
429
430DeclRefExpr::DeclRefExpr(const ASTContext &Ctx, ValueDecl *D,
431 bool RefersToEnclosingVariableOrCapture, QualType T,
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;
447}
448
449DeclRefExpr::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,
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);
482 }
483 DeclRefExprBits.IsImmediateEscalating = false;
484 DeclRefExprBits.HadMultipleCandidates = 0;
486}
487
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);
500}
501
503 NestedNameSpecifierLoc QualifierLoc,
504 SourceLocation TemplateKWLoc, ValueDecl *D,
505 bool RefersToEnclosingVariableOrCapture,
506 const DeclarationNameInfo &NameInfo,
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;
514
515 bool HasTemplateKWAndArgsInfo = TemplateArgs || TemplateKWLoc.isValid();
516 std::size_t Size =
517 totalSizeToAlloc<NestedNameSpecifierLoc, NamedDecl *,
519 QualifierLoc ? 1 : 0, FoundD ? 1 : 0,
520 HasTemplateKWAndArgsInfo ? 1 : 0,
521 TemplateArgs ? TemplateArgs->size() : 0);
522
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);
527}
528
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 *,
538 HasQualifier ? 1 : 0, HasFoundDecl ? 1 : 0, HasTemplateKWAndArgsInfo,
539 NumTemplateArgs);
540 void *Mem = Context.Allocate(Size, alignof(DeclRefExpr));
541 return new (Mem) DeclRefExpr(EmptyShell());
542}
543
545 D = NewD;
546 if (getType()->isUndeducedType())
547 setType(NewD->getType());
549}
550
552 if (hasQualifier())
553 return getQualifierLoc().getBeginLoc();
554 return getNameInfo().getBeginLoc();
555}
558 return getRAngleLoc();
559 return getNameInfo().getEndLoc();
560}
561
562SYCLUniqueStableNameExpr::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);
571}
572
573SYCLUniqueStableNameExpr::SYCLUniqueStableNameExpr(EmptyShell Empty,
574 QualType ResultTy)
575 : Expr(SYCLUniqueStableNameExprClass, ResultTy, VK_PRValue, OK_Ordinary) {}
576
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);
584}
585
588 QualType ResultTy = Ctx.getPointerType(Ctx.CharTy.withConst());
589 return new (Ctx) SYCLUniqueStableNameExpr(EmptyShell(), ResultTy);
590}
591
595}
596
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;
604 };
605
606 std::unique_ptr<MangleContext> Ctx{ItaniumMangleContext::create(
607 Context, Context.getDiagnostics(), MangleCallback)};
608
609 std::string Buffer;
610 Buffer.reserve(128);
611 llvm::raw_string_ostream Out(Buffer);
612 Ctx->mangleCanonicalTypeName(Ty, Out);
613
614 return Out.str();
615}
616
617PredefinedExpr::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);
631}
632
633PredefinedExpr::PredefinedExpr(EmptyShell Empty, bool HasFunctionName)
634 : Expr(PredefinedExprClass, Empty) {
635 PredefinedExprBits.HasFunctionName = HasFunctionName;
636}
637
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);
645}
646
648 bool HasFunctionName) {
649 void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *>(HasFunctionName),
650 alignof(PredefinedExpr));
651 return new (Mem) PredefinedExpr(EmptyShell(), HasFunctionName);
652}
653
655 switch (IK) {
657 return "__func__";
659 return "__FUNCTION__";
661 return "__FUNCDNAME__";
663 return "L__FUNCTION__";
665 return "__PRETTY_FUNCTION__";
667 return "__FUNCSIG__";
669 return "L__FUNCSIG__";
671 break;
672 }
673 llvm_unreachable("Unknown ident kind for PredefinedExpr");
674}
675
676// FIXME: Maybe this should use DeclPrinter with a special "print predefined
677// expr" policy instead.
679 const Decl *CurrentDecl,
680 bool ForceElaboratedPrinting) {
681 ASTContext &Context = CurrentDecl->getASTContext();
682
684 if (const NamedDecl *ND = dyn_cast<NamedDecl>(CurrentDecl)) {
685 std::unique_ptr<MangleContext> MC;
686 MC.reset(Context.createMangleContext());
687
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);
701
702 if (!Buffer.empty() && Buffer.front() == '\01')
703 return std::string(Buffer.substr(1));
704 return std::string(Buffer);
705 }
706 return std::string(ND->getIdentifier()->getName());
707 }
708 return "";
709 }
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 "";
717
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());
726 }
727 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CurrentDecl)) {
728 const auto &LO = Context.getLangOpts();
729 bool IsFuncOrFunctionInNonMSVCCompatEnv =
731 IK == PredefinedIdentKind ::Function) &&
732 !LO.MSVCCompat);
733 bool IsLFunctionInMSVCCommpatEnv =
734 IK == PredefinedIdentKind::LFunction && LO.MSVCCompat;
735 bool IsFuncOrFunctionOrLFunctionOrFuncDName =
740 if ((ForceElaboratedPrinting &&
741 (IsFuncOrFunctionInNonMSVCCompatEnv || IsLFunctionInMSVCCommpatEnv)) ||
742 (!ForceElaboratedPrinting && IsFuncOrFunctionOrLFunctionOrFuncDName))
743 return FD->getNameAsString();
744
745 SmallString<256> Name;
746 llvm::raw_svector_ostream Out(Name);
747
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 ";
753 }
754
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);
762 }
763
764 private:
765 const LangOptions &LO;
766 };
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);
774
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);
782
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;
794 }
795 }
796
797 FD->printQualifiedName(POut, Policy);
798
800 POut.flush();
801 Out << Proto;
802 return std::string(Name);
803 }
804
805 POut << "(";
806 if (FT) {
807 for (unsigned i = 0, e = Decl->getNumParams(); i != e; ++i) {
808 if (i) POut << ", ";
809 POut << Decl->getParamDecl(i)->getType().stream(Policy);
810 }
811
812 if (FT->isVariadic()) {
813 if (FD->getNumParams()) POut << ", ";
814 POut << "...";
815 } else if ((IK == PredefinedIdentKind::FuncSig ||
817 !Context.getLangOpts().CPlusPlus) &&
818 !Decl->getNumParams()) {
819 POut << "void";
820 }
821 }
822 POut << ")";
823
824 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
825 assert(FT && "We must have a written prototype in this case.");
826 if (FT->isConst())
827 POut << " const";
828 if (FT->isVolatile())
829 POut << " volatile";
830 RefQualifierKind Ref = MD->getRefQualifier();
831 if (Ref == RQ_LValue)
832 POut << " &";
833 else if (Ref == RQ_RValue)
834 POut << " &&";
835 }
836
838 SpecsTy Specs;
839 const DeclContext *Ctx = FD->getDeclContext();
840 while (isa_and_nonnull<NamedDecl>(Ctx)) {
842 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx);
843 if (Spec && !Spec->isExplicitSpecialization())
844 Specs.push_back(Spec);
845 Ctx = Ctx->getParent();
846 }
847
848 std::string TemplateParams;
849 llvm::raw_string_ostream TOut(TemplateParams);
850 for (const ClassTemplateSpecializationDecl *D : llvm::reverse(Specs)) {
851 const TemplateParameterList *Params =
852 D->getSpecializedTemplate()->getTemplateParameters();
853 const TemplateArgumentList &Args = D->getTemplateArgs();
854 assert(Params->size() == Args.size());
855 for (unsigned i = 0, numParams = Params->size(); i != numParams; ++i) {
856 StringRef Param = Params->getParam(i)->getName();
857 if (Param.empty()) continue;
858 TOut << Param << " = ";
859 Args.get(i).print(Policy, TOut,
861 Policy, Params, i));
862 TOut << ", ";
863 }
864 }
865
867 = FD->getTemplateSpecializationInfo();
868 if (FSI && !FSI->isExplicitSpecialization()) {
869 const TemplateParameterList* Params
871 const TemplateArgumentList* Args = FSI->TemplateArguments;
872 assert(Params->size() == Args->size());
873 for (unsigned i = 0, e = Params->size(); i != e; ++i) {
874 StringRef Param = Params->getParam(i)->getName();
875 if (Param.empty()) continue;
876 TOut << Param << " = ";
877 Args->get(i).print(Policy, TOut, /*IncludeType*/ true);
878 TOut << ", ";
879 }
880 }
881
882 TOut.flush();
883 if (!TemplateParams.empty()) {
884 // remove the trailing comma and space
885 TemplateParams.resize(TemplateParams.size() - 2);
886 POut << " [" << TemplateParams << "]";
887 }
888
889 POut.flush();
890
891 // Print "auto" for all deduced return types. This includes C++1y return
892 // type deduction and lambdas. For trailing return types resolve the
893 // decltype expression. Otherwise print the real type when this is
894 // not a constructor or destructor.
895 if (isa<CXXMethodDecl>(FD) &&
896 cast<CXXMethodDecl>(FD)->getParent()->isLambda())
897 Proto = "auto " + Proto;
898 else if (FT && FT->getReturnType()->getAs<DecltypeType>())
899 FT->getReturnType()
900 ->getAs<DecltypeType>()
902 .getAsStringInternal(Proto, Policy);
903 else if (!isa<CXXConstructorDecl>(FD) && !isa<CXXDestructorDecl>(FD))
904 AFT->getReturnType().getAsStringInternal(Proto, Policy);
905
906 Out << Proto;
907
908 return std::string(Name);
909 }
910 if (const CapturedDecl *CD = dyn_cast<CapturedDecl>(CurrentDecl)) {
911 for (const DeclContext *DC = CD->getParent(); DC; DC = DC->getParent())
912 // Skip to its enclosing function or method, but not its enclosing
913 // CapturedDecl.
914 if (DC->isFunctionOrMethod() && (DC->getDeclKind() != Decl::Captured)) {
915 const Decl *D = Decl::castFromDeclContext(DC);
916 return ComputeName(IK, D);
917 }
918 llvm_unreachable("CapturedDecl not inside a function or method");
919 }
920 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurrentDecl)) {
921 SmallString<256> Name;
922 llvm::raw_svector_ostream Out(Name);
923 Out << (MD->isInstanceMethod() ? '-' : '+');
924 Out << '[';
925
926 // For incorrect code, there might not be an ObjCInterfaceDecl. Do
927 // a null check to avoid a crash.
928 if (const ObjCInterfaceDecl *ID = MD->getClassInterface())
929 Out << *ID;
930
931 if (const ObjCCategoryImplDecl *CID =
932 dyn_cast<ObjCCategoryImplDecl>(MD->getDeclContext()))
933 Out << '(' << *CID << ')';
934
935 Out << ' ';
936 MD->getSelector().print(Out);
937 Out << ']';
938
939 return std::string(Name);
940 }
941 if (isa<TranslationUnitDecl>(CurrentDecl) &&
943 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
944 return "top level";
945 }
946 return "";
947}
948
950 const llvm::APInt &Val) {
951 if (hasAllocation())
952 C.Deallocate(pVal);
953
954 BitWidth = Val.getBitWidth();
955 unsigned NumWords = Val.getNumWords();
956 const uint64_t* Words = Val.getRawData();
957 if (NumWords > 1) {
958 pVal = new (C) uint64_t[NumWords];
959 std::copy(Words, Words + NumWords, pVal);
960 } else if (NumWords == 1)
961 VAL = Words[0];
962 else
963 VAL = 0;
964}
965
966IntegerLiteral::IntegerLiteral(const ASTContext &C, const llvm::APInt &V,
968 : Expr(IntegerLiteralClass, type, VK_PRValue, OK_Ordinary), Loc(l) {
969 assert(type->isIntegerType() && "Illegal type in IntegerLiteral");
970 assert(V.getBitWidth() == C.getIntWidth(type) &&
971 "Integer type is not the correct size for constant.");
972 setValue(C, V);
973 setDependence(ExprDependence::None);
974}
975
977IntegerLiteral::Create(const ASTContext &C, const llvm::APInt &V,
979 return new (C) IntegerLiteral(C, V, type, l);
980}
981
984 return new (C) IntegerLiteral(Empty);
985}
986
987FixedPointLiteral::FixedPointLiteral(const ASTContext &C, const llvm::APInt &V,
989 unsigned Scale)
990 : Expr(FixedPointLiteralClass, type, VK_PRValue, OK_Ordinary), Loc(l),
991 Scale(Scale) {
992 assert(type->isFixedPointType() && "Illegal type in FixedPointLiteral");
993 assert(V.getBitWidth() == C.getTypeInfo(type).Width &&
994 "Fixed point type is not the correct size for constant.");
995 setValue(C, V);
996 setDependence(ExprDependence::None);
997}
998
1000 const llvm::APInt &V,
1001 QualType type,
1003 unsigned Scale) {
1004 return new (C) FixedPointLiteral(C, V, type, l, Scale);
1005}
1006
1008 EmptyShell Empty) {
1009 return new (C) FixedPointLiteral(Empty);
1010}
1011
1012std::string FixedPointLiteral::getValueAsString(unsigned Radix) const {
1013 // Currently the longest decimal number that can be printed is the max for an
1014 // unsigned long _Accum: 4294967295.99999999976716935634613037109375
1015 // which is 43 characters.
1018 S, llvm::APSInt::getUnsigned(getValue().getZExtValue()), Scale);
1019 return std::string(S);
1020}
1021
1023 raw_ostream &OS) {
1024 switch (Kind) {
1026 break; // no prefix.
1028 OS << 'L';
1029 break;
1031 OS << "u8";
1032 break;
1034 OS << 'u';
1035 break;
1037 OS << 'U';
1038 break;
1039 }
1040
1041 StringRef Escaped = escapeCStyle<EscapeChar::Single>(Val);
1042 if (!Escaped.empty()) {
1043 OS << "'" << Escaped << "'";
1044 } else {
1045 // A character literal might be sign-extended, which
1046 // would result in an invalid \U escape sequence.
1047 // FIXME: multicharacter literals such as '\xFF\xFF\xFF\xFF'
1048 // are not correctly handled.
1049 if ((Val & ~0xFFu) == ~0xFFu && Kind == CharacterLiteralKind::Ascii)
1050 Val &= 0xFFu;
1051 if (Val < 256 && isPrintable((unsigned char)Val))
1052 OS << "'" << (char)Val << "'";
1053 else if (Val < 256)
1054 OS << "'\\x" << llvm::format("%02x", Val) << "'";
1055 else if (Val <= 0xFFFF)
1056 OS << "'\\u" << llvm::format("%04x", Val) << "'";
1057 else
1058 OS << "'\\U" << llvm::format("%08x", Val) << "'";
1059 }
1060}
1061
1062FloatingLiteral::FloatingLiteral(const ASTContext &C, const llvm::APFloat &V,
1063 bool isexact, QualType Type, SourceLocation L)
1064 : Expr(FloatingLiteralClass, Type, VK_PRValue, OK_Ordinary), Loc(L) {
1065 setSemantics(V.getSemantics());
1066 FloatingLiteralBits.IsExact = isexact;
1067 setValue(C, V);
1068 setDependence(ExprDependence::None);
1069}
1070
1071FloatingLiteral::FloatingLiteral(const ASTContext &C, EmptyShell Empty)
1072 : Expr(FloatingLiteralClass, Empty) {
1073 setRawSemantics(llvm::APFloatBase::S_IEEEhalf);
1074 FloatingLiteralBits.IsExact = false;
1075}
1076
1078FloatingLiteral::Create(const ASTContext &C, const llvm::APFloat &V,
1079 bool isexact, QualType Type, SourceLocation L) {
1080 return new (C) FloatingLiteral(C, V, isexact, Type, L);
1081}
1082
1085 return new (C) FloatingLiteral(C, Empty);
1086}
1087
1088/// getValueAsApproximateDouble - This returns the value as an inaccurate
1089/// double. Note that this may cause loss of precision, but is useful for
1090/// debugging dumps, etc.
1092 llvm::APFloat V = getValue();
1093 bool ignored;
1094 V.convert(llvm::APFloat::IEEEdouble(), llvm::APFloat::rmNearestTiesToEven,
1095 &ignored);
1096 return V.convertToDouble();
1097}
1098
1099unsigned StringLiteral::mapCharByteWidth(TargetInfo const &Target,
1100 StringLiteralKind SK) {
1101 unsigned CharByteWidth = 0;
1102 switch (SK) {
1105 CharByteWidth = Target.getCharWidth();
1106 break;
1108 CharByteWidth = Target.getWCharWidth();
1109 break;
1111 CharByteWidth = Target.getChar16Width();
1112 break;
1114 CharByteWidth = Target.getChar32Width();
1115 break;
1117 return sizeof(char); // Host;
1118 }
1119 assert((CharByteWidth & 7) == 0 && "Assumes character size is byte multiple");
1120 CharByteWidth /= 8;
1121 assert((CharByteWidth == 1 || CharByteWidth == 2 || CharByteWidth == 4) &&
1122 "The only supported character byte widths are 1,2 and 4!");
1123 return CharByteWidth;
1124}
1125
1126StringLiteral::StringLiteral(const ASTContext &Ctx, StringRef Str,
1127 StringLiteralKind Kind, bool Pascal, QualType Ty,
1128 const SourceLocation *Loc,
1129 unsigned NumConcatenated)
1130 : Expr(StringLiteralClass, Ty, VK_LValue, OK_Ordinary) {
1131
1132 unsigned Length = Str.size();
1133
1134 StringLiteralBits.Kind = llvm::to_underlying(Kind);
1135 StringLiteralBits.NumConcatenated = NumConcatenated;
1136
1137 if (Kind != StringLiteralKind::Unevaluated) {
1138 assert(Ctx.getAsConstantArrayType(Ty) &&
1139 "StringLiteral must be of constant array type!");
1140 unsigned CharByteWidth = mapCharByteWidth(Ctx.getTargetInfo(), Kind);
1141 unsigned ByteLength = Str.size();
1142 assert((ByteLength % CharByteWidth == 0) &&
1143 "The size of the data must be a multiple of CharByteWidth!");
1144
1145 // Avoid the expensive division. The compiler should be able to figure it
1146 // out by itself. However as of clang 7, even with the appropriate
1147 // llvm_unreachable added just here, it is not able to do so.
1148 switch (CharByteWidth) {
1149 case 1:
1150 Length = ByteLength;
1151 break;
1152 case 2:
1153 Length = ByteLength / 2;
1154 break;
1155 case 4:
1156 Length = ByteLength / 4;
1157 break;
1158 default:
1159 llvm_unreachable("Unsupported character width!");
1160 }
1161
1162 StringLiteralBits.CharByteWidth = CharByteWidth;
1163 StringLiteralBits.IsPascal = Pascal;
1164 } else {
1165 assert(!Pascal && "Can't make an unevaluated Pascal string");
1166 StringLiteralBits.CharByteWidth = 1;
1167 StringLiteralBits.IsPascal = false;
1168 }
1169
1170 *getTrailingObjects<unsigned>() = Length;
1171
1172 // Initialize the trailing array of SourceLocation.
1173 // This is safe since SourceLocation is POD-like.
1174 std::memcpy(getTrailingObjects<SourceLocation>(), Loc,
1175 NumConcatenated * sizeof(SourceLocation));
1176
1177 // Initialize the trailing array of char holding the string data.
1178 std::memcpy(getTrailingObjects<char>(), Str.data(), Str.size());
1179
1180 setDependence(ExprDependence::None);
1181}
1182
1183StringLiteral::StringLiteral(EmptyShell Empty, unsigned NumConcatenated,
1184 unsigned Length, unsigned CharByteWidth)
1185 : Expr(StringLiteralClass, Empty) {
1186 StringLiteralBits.CharByteWidth = CharByteWidth;
1187 StringLiteralBits.NumConcatenated = NumConcatenated;
1188 *getTrailingObjects<unsigned>() = Length;
1189}
1190
1192 StringLiteralKind Kind, bool Pascal,
1193 QualType Ty, const SourceLocation *Loc,
1194 unsigned NumConcatenated) {
1195 void *Mem = Ctx.Allocate(totalSizeToAlloc<unsigned, SourceLocation, char>(
1196 1, NumConcatenated, Str.size()),
1197 alignof(StringLiteral));
1198 return new (Mem)
1199 StringLiteral(Ctx, Str, Kind, Pascal, Ty, Loc, NumConcatenated);
1200}
1201
1203 unsigned NumConcatenated,
1204 unsigned Length,
1205 unsigned CharByteWidth) {
1206 void *Mem = Ctx.Allocate(totalSizeToAlloc<unsigned, SourceLocation, char>(
1207 1, NumConcatenated, Length * CharByteWidth),
1208 alignof(StringLiteral));
1209 return new (Mem)
1210 StringLiteral(EmptyShell(), NumConcatenated, Length, CharByteWidth);
1211}
1212
1213void StringLiteral::outputString(raw_ostream &OS) const {
1214 switch (getKind()) {
1217 break; // no prefix.
1219 OS << 'L';
1220 break;
1222 OS << "u8";
1223 break;
1225 OS << 'u';
1226 break;
1228 OS << 'U';
1229 break;
1230 }
1231 OS << '"';
1232 static const char Hex[] = "0123456789ABCDEF";
1233
1234 unsigned LastSlashX = getLength();
1235 for (unsigned I = 0, N = getLength(); I != N; ++I) {
1236 uint32_t Char = getCodeUnit(I);
1237 StringRef Escaped = escapeCStyle<EscapeChar::Double>(Char);
1238 if (Escaped.empty()) {
1239 // FIXME: Convert UTF-8 back to codepoints before rendering.
1240
1241 // Convert UTF-16 surrogate pairs back to codepoints before rendering.
1242 // Leave invalid surrogates alone; we'll use \x for those.
1243 if (getKind() == StringLiteralKind::UTF16 && I != N - 1 &&
1244 Char >= 0xd800 && Char <= 0xdbff) {
1245 uint32_t Trail = getCodeUnit(I + 1);
1246 if (Trail >= 0xdc00 && Trail <= 0xdfff) {
1247 Char = 0x10000 + ((Char - 0xd800) << 10) + (Trail - 0xdc00);
1248 ++I;
1249 }
1250 }
1251
1252 if (Char > 0xff) {
1253 // If this is a wide string, output characters over 0xff using \x
1254 // escapes. Otherwise, this is a UTF-16 or UTF-32 string, and Char is a
1255 // codepoint: use \x escapes for invalid codepoints.
1257 (Char >= 0xd800 && Char <= 0xdfff) || Char >= 0x110000) {
1258 // FIXME: Is this the best way to print wchar_t?
1259 OS << "\\x";
1260 int Shift = 28;
1261 while ((Char >> Shift) == 0)
1262 Shift -= 4;
1263 for (/**/; Shift >= 0; Shift -= 4)
1264 OS << Hex[(Char >> Shift) & 15];
1265 LastSlashX = I;
1266 continue;
1267 }
1268
1269 if (Char > 0xffff)
1270 OS << "\\U00"
1271 << Hex[(Char >> 20) & 15]
1272 << Hex[(Char >> 16) & 15];
1273 else
1274 OS << "\\u";
1275 OS << Hex[(Char >> 12) & 15]
1276 << Hex[(Char >> 8) & 15]
1277 << Hex[(Char >> 4) & 15]
1278 << Hex[(Char >> 0) & 15];
1279 continue;
1280 }
1281
1282 // If we used \x... for the previous character, and this character is a
1283 // hexadecimal digit, prevent it being slurped as part of the \x.
1284 if (LastSlashX + 1 == I) {
1285 switch (Char) {
1286 case '0': case '1': case '2': case '3': case '4':
1287 case '5': case '6': case '7': case '8': case '9':
1288 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
1289 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
1290 OS << "\"\"";
1291 }
1292 }
1293
1294 assert(Char <= 0xff &&
1295 "Characters above 0xff should already have been handled.");
1296
1297 if (isPrintable(Char))
1298 OS << (char)Char;
1299 else // Output anything hard as an octal escape.
1300 OS << '\\'
1301 << (char)('0' + ((Char >> 6) & 7))
1302 << (char)('0' + ((Char >> 3) & 7))
1303 << (char)('0' + ((Char >> 0) & 7));
1304 } else {
1305 // Handle some common non-printable cases to make dumps prettier.
1306 OS << Escaped;
1307 }
1308 }
1309 OS << '"';
1310}
1311
1312/// getLocationOfByte - Return a source location that points to the specified
1313/// byte of this string literal.
1314///
1315/// Strings are amazingly complex. They can be formed from multiple tokens and
1316/// can have escape sequences in them in addition to the usual trigraph and
1317/// escaped newline business. This routine handles this complexity.
1318///
1319/// The *StartToken sets the first token to be searched in this function and
1320/// the *StartTokenByteOffset is the byte offset of the first token. Before
1321/// returning, it updates the *StartToken to the TokNo of the token being found
1322/// and sets *StartTokenByteOffset to the byte offset of the token in the
1323/// string.
1324/// Using these two parameters can reduce the time complexity from O(n^2) to
1325/// O(n) if one wants to get the location of byte for all the tokens in a
1326/// string.
1327///
1330 const LangOptions &Features,
1331 const TargetInfo &Target, unsigned *StartToken,
1332 unsigned *StartTokenByteOffset) const {
1333 assert((getKind() == StringLiteralKind::Ordinary ||
1336 "Only narrow string literals are currently supported");
1337
1338 // Loop over all of the tokens in this string until we find the one that
1339 // contains the byte we're looking for.
1340 unsigned TokNo = 0;
1341 unsigned StringOffset = 0;
1342 if (StartToken)
1343 TokNo = *StartToken;
1344 if (StartTokenByteOffset) {
1345 StringOffset = *StartTokenByteOffset;
1346 ByteNo -= StringOffset;
1347 }
1348 while (true) {
1349 assert(TokNo < getNumConcatenated() && "Invalid byte number!");
1350 SourceLocation StrTokLoc = getStrTokenLoc(TokNo);
1351
1352 // Get the spelling of the string so that we can get the data that makes up
1353 // the string literal, not the identifier for the macro it is potentially
1354 // expanded through.
1355 SourceLocation StrTokSpellingLoc = SM.getSpellingLoc(StrTokLoc);
1356
1357 // Re-lex the token to get its length and original spelling.
1358 std::pair<FileID, unsigned> LocInfo =
1359 SM.getDecomposedLoc(StrTokSpellingLoc);
1360 bool Invalid = false;
1361 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
1362 if (Invalid) {
1363 if (StartTokenByteOffset != nullptr)
1364 *StartTokenByteOffset = StringOffset;
1365 if (StartToken != nullptr)
1366 *StartToken = TokNo;
1367 return StrTokSpellingLoc;
1368 }
1369
1370 const char *StrData = Buffer.data()+LocInfo.second;
1371
1372 // Create a lexer starting at the beginning of this token.
1373 Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), Features,
1374 Buffer.begin(), StrData, Buffer.end());
1375 Token TheTok;
1376 TheLexer.LexFromRawLexer(TheTok);
1377
1378 // Use the StringLiteralParser to compute the length of the string in bytes.
1379 StringLiteralParser SLP(TheTok, SM, Features, Target);
1380 unsigned TokNumBytes = SLP.GetStringLength();
1381
1382 // If the byte is in this token, return the location of the byte.
1383 if (ByteNo < TokNumBytes ||
1384 (ByteNo == TokNumBytes && TokNo == getNumConcatenated() - 1)) {
1385 unsigned Offset = SLP.getOffsetOfStringByte(TheTok, ByteNo);
1386
1387 // Now that we know the offset of the token in the spelling, use the
1388 // preprocessor to get the offset in the original source.
1389 if (StartTokenByteOffset != nullptr)
1390 *StartTokenByteOffset = StringOffset;
1391 if (StartToken != nullptr)
1392 *StartToken = TokNo;
1393 return Lexer::AdvanceToTokenCharacter(StrTokLoc, Offset, SM, Features);
1394 }
1395
1396 // Move to the next string token.
1397 StringOffset += TokNumBytes;
1398 ++TokNo;
1399 ByteNo -= TokNumBytes;
1400 }
1401}
1402
1403/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1404/// corresponds to, e.g. "sizeof" or "[pre]++".
1406 switch (Op) {
1407#define UNARY_OPERATION(Name, Spelling) case UO_##Name: return Spelling;
1408#include "clang/AST/OperationKinds.def"
1409 }
1410 llvm_unreachable("Unknown unary operator");
1411}
1412
1415 switch (OO) {
1416 default: llvm_unreachable("No unary operator for overloaded function");
1417 case OO_PlusPlus: return Postfix ? UO_PostInc : UO_PreInc;
1418 case OO_MinusMinus: return Postfix ? UO_PostDec : UO_PreDec;
1419 case OO_Amp: return UO_AddrOf;
1420 case OO_Star: return UO_Deref;
1421 case OO_Plus: return UO_Plus;
1422 case OO_Minus: return UO_Minus;
1423 case OO_Tilde: return UO_Not;
1424 case OO_Exclaim: return UO_LNot;
1425 case OO_Coawait: return UO_Coawait;
1426 }
1427}
1428
1430 switch (Opc) {
1431 case UO_PostInc: case UO_PreInc: return OO_PlusPlus;
1432 case UO_PostDec: case UO_PreDec: return OO_MinusMinus;
1433 case UO_AddrOf: return OO_Amp;
1434 case UO_Deref: return OO_Star;
1435 case UO_Plus: return OO_Plus;
1436 case UO_Minus: return OO_Minus;
1437 case UO_Not: return OO_Tilde;
1438 case UO_LNot: return OO_Exclaim;
1439 case UO_Coawait: return OO_Coawait;
1440 default: return OO_None;
1441 }
1442}
1443
1444
1445//===----------------------------------------------------------------------===//
1446// Postfix Operators.
1447//===----------------------------------------------------------------------===//
1448
1451 SourceLocation RParenLoc, FPOptionsOverride FPFeatures,
1452 unsigned MinNumArgs, ADLCallKind UsesADL)
1453 : Expr(SC, Ty, VK, OK_Ordinary), RParenLoc(RParenLoc) {
1454 NumArgs = std::max<unsigned>(Args.size(), MinNumArgs);
1455 unsigned NumPreArgs = PreArgs.size();
1456 CallExprBits.NumPreArgs = NumPreArgs;
1457 assert((NumPreArgs == getNumPreArgs()) && "NumPreArgs overflow!");
1458
1459 unsigned OffsetToTrailingObjects = offsetToTrailingObjects(SC);
1460 CallExprBits.OffsetToTrailingObjects = OffsetToTrailingObjects;
1461 assert((CallExprBits.OffsetToTrailingObjects == OffsetToTrailingObjects) &&
1462 "OffsetToTrailingObjects overflow!");
1463
1464 CallExprBits.UsesADL = static_cast<bool>(UsesADL);
1465
1466 setCallee(Fn);
1467 for (unsigned I = 0; I != NumPreArgs; ++I)
1468 setPreArg(I, PreArgs[I]);
1469 for (unsigned I = 0; I != Args.size(); ++I)
1470 setArg(I, Args[I]);
1471 for (unsigned I = Args.size(); I != NumArgs; ++I)
1472 setArg(I, nullptr);
1473
1474 this->computeDependence();
1475
1476 CallExprBits.HasFPFeatures = FPFeatures.requiresTrailingStorage();
1477 if (hasStoredFPFeatures())
1478 setStoredFPFeatures(FPFeatures);
1479}
1480
1481CallExpr::CallExpr(StmtClass SC, unsigned NumPreArgs, unsigned NumArgs,
1482 bool HasFPFeatures, EmptyShell Empty)
1483 : Expr(SC, Empty), NumArgs(NumArgs) {
1484 CallExprBits.NumPreArgs = NumPreArgs;
1485 assert((NumPreArgs == getNumPreArgs()) && "NumPreArgs overflow!");
1486
1487 unsigned OffsetToTrailingObjects = offsetToTrailingObjects(SC);
1488 CallExprBits.OffsetToTrailingObjects = OffsetToTrailingObjects;
1489 assert((CallExprBits.OffsetToTrailingObjects == OffsetToTrailingObjects) &&
1490 "OffsetToTrailingObjects overflow!");
1491 CallExprBits.HasFPFeatures = HasFPFeatures;
1492}
1493
1496 SourceLocation RParenLoc,
1497 FPOptionsOverride FPFeatures, unsigned MinNumArgs,
1498 ADLCallKind UsesADL) {
1499 unsigned NumArgs = std::max<unsigned>(Args.size(), MinNumArgs);
1500 unsigned SizeOfTrailingObjects = CallExpr::sizeOfTrailingObjects(
1501 /*NumPreArgs=*/0, NumArgs, FPFeatures.requiresTrailingStorage());
1502 void *Mem =
1503 Ctx.Allocate(sizeof(CallExpr) + SizeOfTrailingObjects, alignof(CallExpr));
1504 return new (Mem) CallExpr(CallExprClass, Fn, /*PreArgs=*/{}, Args, Ty, VK,
1505 RParenLoc, FPFeatures, MinNumArgs, UsesADL);
1506}
1507
1509 ExprValueKind VK, SourceLocation RParenLoc,
1510 ADLCallKind UsesADL) {
1511 assert(!(reinterpret_cast<uintptr_t>(Mem) % alignof(CallExpr)) &&
1512 "Misaligned memory in CallExpr::CreateTemporary!");
1513 return new (Mem) CallExpr(CallExprClass, Fn, /*PreArgs=*/{}, /*Args=*/{}, Ty,
1514 VK, RParenLoc, FPOptionsOverride(),
1515 /*MinNumArgs=*/0, UsesADL);
1516}
1517
1518CallExpr *CallExpr::CreateEmpty(const ASTContext &Ctx, unsigned NumArgs,
1519 bool HasFPFeatures, EmptyShell Empty) {
1520 unsigned SizeOfTrailingObjects =
1521 CallExpr::sizeOfTrailingObjects(/*NumPreArgs=*/0, NumArgs, HasFPFeatures);
1522 void *Mem =
1523 Ctx.Allocate(sizeof(CallExpr) + SizeOfTrailingObjects, alignof(CallExpr));
1524 return new (Mem)
1525 CallExpr(CallExprClass, /*NumPreArgs=*/0, NumArgs, HasFPFeatures, Empty);
1526}
1527
1528unsigned CallExpr::offsetToTrailingObjects(StmtClass SC) {
1529 switch (SC) {
1530 case CallExprClass:
1531 return sizeof(CallExpr);
1532 case CXXOperatorCallExprClass:
1533 return sizeof(CXXOperatorCallExpr);
1534 case CXXMemberCallExprClass:
1535 return sizeof(CXXMemberCallExpr);
1536 case UserDefinedLiteralClass:
1537 return sizeof(UserDefinedLiteral);
1538 case CUDAKernelCallExprClass:
1539 return sizeof(CUDAKernelCallExpr);
1540 default:
1541 llvm_unreachable("unexpected class deriving from CallExpr!");
1542 }
1543}
1544
1546 Expr *CEE = IgnoreParenImpCasts();
1547
1548 while (auto *NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(CEE))
1549 CEE = NTTP->getReplacement()->IgnoreParenImpCasts();
1550
1551 // If we're calling a dereference, look at the pointer instead.
1552 while (true) {
1553 if (auto *BO = dyn_cast<BinaryOperator>(CEE)) {
1554 if (BO->isPtrMemOp()) {
1555 CEE = BO->getRHS()->IgnoreParenImpCasts();
1556 continue;
1557 }
1558 } else if (auto *UO = dyn_cast<UnaryOperator>(CEE)) {
1559 if (UO->getOpcode() == UO_Deref || UO->getOpcode() == UO_AddrOf ||
1560 UO->getOpcode() == UO_Plus) {
1561 CEE = UO->getSubExpr()->IgnoreParenImpCasts();
1562 continue;
1563 }
1564 }
1565 break;
1566 }
1567
1568 if (auto *DRE = dyn_cast<DeclRefExpr>(CEE))
1569 return DRE->getDecl();
1570 if (auto *ME = dyn_cast<MemberExpr>(CEE))
1571 return ME->getMemberDecl();
1572 if (auto *BE = dyn_cast<BlockExpr>(CEE))
1573 return BE->getBlockDecl();
1574
1575 return nullptr;
1576}
1577
1578/// If this is a call to a builtin, return the builtin ID. If not, return 0.
1580 const auto *FDecl = getDirectCallee();
1581 return FDecl ? FDecl->getBuiltinID() : 0;
1582}
1583
1585 if (unsigned BI = getBuiltinCallee())
1586 return Ctx.BuiltinInfo.isUnevaluated(BI);
1587 return false;
1588}
1589
1591 const Expr *Callee = getCallee();
1592 QualType CalleeType = Callee->getType();
1593 if (const auto *FnTypePtr = CalleeType->getAs<PointerType>()) {
1594 CalleeType = FnTypePtr->getPointeeType();
1595 } else if (const auto *BPT = CalleeType->getAs<BlockPointerType>()) {
1596 CalleeType = BPT->getPointeeType();
1597 } else if (CalleeType->isSpecificPlaceholderType(BuiltinType::BoundMember)) {
1598 if (isa<CXXPseudoDestructorExpr>(Callee->IgnoreParens()))
1599 return Ctx.VoidTy;
1600
1601 if (isa<UnresolvedMemberExpr>(Callee->IgnoreParens()))
1602 return Ctx.DependentTy;
1603
1604 // This should never be overloaded and so should never return null.
1605 CalleeType = Expr::findBoundMemberType(Callee);
1606 assert(!CalleeType.isNull());
1607 } else if (CalleeType->isRecordType()) {
1608 // If the Callee is a record type, then it is a not-yet-resolved
1609 // dependent call to the call operator of that type.
1610 return Ctx.DependentTy;
1611 } else if (CalleeType->isDependentType() ||
1612 CalleeType->isSpecificPlaceholderType(BuiltinType::Overload)) {
1613 return Ctx.DependentTy;
1614 }
1615
1616 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
1617 return FnType->getReturnType();
1618}
1619
1621 // If the return type is a struct, union, or enum that is marked nodiscard,
1622 // then return the return type attribute.
1623 if (const TagDecl *TD = getCallReturnType(Ctx)->getAsTagDecl())
1624 if (const auto *A = TD->getAttr<WarnUnusedResultAttr>())
1625 return A;
1626
1627 for (const auto *TD = getCallReturnType(Ctx)->getAs<TypedefType>(); TD;
1628 TD = TD->desugar()->getAs<TypedefType>())
1629 if (const auto *A = TD->getDecl()->getAttr<WarnUnusedResultAttr>())
1630 return A;
1631
1632 // Otherwise, see if the callee is marked nodiscard and return that attribute
1633 // instead.
1634 const Decl *D = getCalleeDecl();
1635 return D ? D->getAttr<WarnUnusedResultAttr>() : nullptr;
1636}
1637
1639 if (const auto *OCE = dyn_cast<CXXOperatorCallExpr>(this))
1640 return OCE->getBeginLoc();
1641
1643 if (begin.isInvalid() && getNumArgs() > 0 && getArg(0))
1644 begin = getArg(0)->getBeginLoc();
1645 return begin;
1646}
1648 if (const auto *OCE = dyn_cast<CXXOperatorCallExpr>(this))
1649 return OCE->getEndLoc();
1650
1652 if (end.isInvalid() && getNumArgs() > 0 && getArg(getNumArgs() - 1))
1653 end = getArg(getNumArgs() - 1)->getEndLoc();
1654 return end;
1655}
1656
1658 SourceLocation OperatorLoc,
1659 TypeSourceInfo *tsi,
1661 ArrayRef<Expr*> exprs,
1662 SourceLocation RParenLoc) {
1663 void *Mem = C.Allocate(
1664 totalSizeToAlloc<OffsetOfNode, Expr *>(comps.size(), exprs.size()));
1665
1666 return new (Mem) OffsetOfExpr(C, type, OperatorLoc, tsi, comps, exprs,
1667 RParenLoc);
1668}
1669
1671 unsigned numComps, unsigned numExprs) {
1672 void *Mem =
1673 C.Allocate(totalSizeToAlloc<OffsetOfNode, Expr *>(numComps, numExprs));
1674 return new (Mem) OffsetOfExpr(numComps, numExprs);
1675}
1676
1677OffsetOfExpr::OffsetOfExpr(const ASTContext &C, QualType type,
1678 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
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]);
1688
1690}
1691
1693 assert(getKind() == Field || getKind() == Identifier);
1694 if (getKind() == Field)
1695 return getField()->getIdentifier();
1696
1697 return reinterpret_cast<IdentifierInfo *> (Data & ~(uintptr_t)Mask);
1698}
1699
1701 UnaryExprOrTypeTrait ExprKind, Expr *E, QualType resultType,
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;
1712}
1713
1714MemberExpr::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,
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;
1736
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);
1750 }
1752}
1753
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,
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,
1767 HasQualifier, HasFoundDecl, HasTemplateKWAndArgsInfo,
1768 TemplateArgs ? TemplateArgs->size() : 0);
1769
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);
1774}
1775
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,
1785 HasQualifier, HasFoundDecl, HasTemplateKWAndArgsInfo,
1786 NumTemplateArgs);
1787 void *Mem = Context.Allocate(Size, alignof(MemberExpr));
1788 return new (Mem) MemberExpr(EmptyShell());
1789}
1790
1792 MemberDecl = NewD;
1793 if (getType()->isUndeducedType())
1794 setType(NewD->getType());
1796}
1797
1799 if (isImplicitAccess()) {
1800 if (hasQualifier())
1801 return getQualifierLoc().getBeginLoc();
1802 return MemberLoc;
1803 }
1804
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;
1811}
1815 EndLoc = getRAngleLoc();
1816 else if (EndLoc.isInvalid())
1817 EndLoc = getBase()->getEndLoc();
1818 return EndLoc;
1819}
1820
1821bool 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;
1830
1831 case CK_CPointerToObjCPointerCast:
1832 assert(getType()->isObjCObjectPointerType());
1833 assert(getSubExpr()->getType()->isPointerType());
1834 goto CheckNoBasePath;
1835
1836 case CK_BlockPointerToObjCPointerCast:
1837 assert(getType()->isObjCObjectPointerType());
1838 assert(getSubExpr()->getType()->isBlockPointerType());
1839 goto CheckNoBasePath;
1840
1841 case CK_ReinterpretMemberPointer:
1842 assert(getType()->isMemberPointerType());
1843 assert(getSubExpr()->getType()->isMemberPointerType());
1844 goto CheckNoBasePath;
1845
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());
1855 }
1856 goto CheckNoBasePath;
1857
1858 case CK_AnyPointerToBlockPointerCast:
1859 assert(getType()->isBlockPointerType());
1860 assert(getSubExpr()->getType()->isAnyPointerType() &&
1861 !getSubExpr()->getType()->isBlockPointerType());
1862 goto CheckNoBasePath;
1863
1864 case CK_CopyAndAutoreleaseBlockObject:
1865 assert(getType()->isBlockPointerType());
1866 assert(getSubExpr()->getType()->isBlockPointerType());
1867 goto CheckNoBasePath;
1868
1869 case CK_FunctionToPointerDecay:
1870 assert(getType()->isPointerType());
1871 assert(getSubExpr()->getType()->isFunctionType());
1872 goto CheckNoBasePath;
1873
1874 case CK_AddressSpaceConversion: {
1875 auto Ty = getType();
1876 auto SETy = getSubExpr()->getType();
1878 if (isPRValue() && !Ty->isDependentType() && !SETy->isDependentType()) {
1879 Ty = Ty->getPointeeType();
1880 SETy = SETy->getPointeeType();
1881 }
1882 assert((Ty->isDependentType() || SETy->isDependentType()) ||
1883 (!Ty.isNull() && !SETy.isNull() &&
1884 Ty.getAddressSpace() != SETy.getAddressSpace()));
1885 goto CheckNoBasePath;
1886 }
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 case CK_HLSLVectorTruncation:
1925 assert(!getType()->isBooleanType() && "unheralded conversion to bool");
1926 goto CheckNoBasePath;
1927
1928 case CK_Dependent:
1929 case CK_LValueToRValue:
1930 case CK_NoOp:
1931 case CK_AtomicToNonAtomic:
1932 case CK_NonAtomicToAtomic:
1933 case CK_PointerToBoolean:
1934 case CK_IntegralToBoolean:
1935 case CK_FloatingToBoolean:
1936 case CK_MemberPointerToBoolean:
1937 case CK_FloatingComplexToBoolean:
1938 case CK_IntegralComplexToBoolean:
1939 case CK_LValueBitCast: // -> bool&
1940 case CK_LValueToRValueBitCast:
1941 case CK_UserDefinedConversion: // operator bool()
1942 case CK_BuiltinFnToFnPtr:
1943 case CK_FixedPointToBoolean:
1944 case CK_HLSLArrayRValue:
1945 CheckNoBasePath:
1946 assert(path_empty() && "Cast kind should not have a base path!");
1947 break;
1948 }
1949 return true;
1950}
1951
1953 switch (CK) {
1954#define CAST_OPERATION(Name) case CK_##Name: return #Name;
1955#include "clang/AST/OperationKinds.def"
1956 }
1957 llvm_unreachable("Unhandled cast kind!");
1958}
1959
1960namespace {
1961// Skip over implicit nodes produced as part of semantic analysis.
1962// Designed for use with IgnoreExprNodes.
1963static Expr *ignoreImplicitSemaNodes(Expr *E) {
1964 if (auto *Materialize = dyn_cast<MaterializeTemporaryExpr>(E))
1965 return Materialize->getSubExpr();
1966
1967 if (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
1968 return Binder->getSubExpr();
1969
1970 if (auto *Full = dyn_cast<FullExpr>(E))
1971 return Full->getSubExpr();
1972
1973 if (auto *CPLIE = dyn_cast<CXXParenListInitExpr>(E);
1974 CPLIE && CPLIE->getInitExprs().size() == 1)
1975 return CPLIE->getInitExprs()[0];
1976
1977 return E;
1978}
1979} // namespace
1980
1982 const Expr *SubExpr = nullptr;
1983
1984 for (const CastExpr *E = this; E; E = dyn_cast<ImplicitCastExpr>(SubExpr)) {
1985 SubExpr = IgnoreExprNodes(E->getSubExpr(), ignoreImplicitSemaNodes);
1986
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<CXXMemberCallExpr>(SubExpr) || isa<BlockExpr>(SubExpr)) &&
1994 "Unexpected SubExpr for CK_UserDefinedConversion.");
1995 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SubExpr))
1996 SubExpr = MCE->getImplicitObjectArgument();
1997 }
1998 }
1999
2000 return const_cast<Expr *>(SubExpr);
2001}
2002
2004 const Expr *SubExpr = nullptr;
2005
2006 for (const CastExpr *E = this; E; E = dyn_cast<ImplicitCastExpr>(SubExpr)) {
2007 SubExpr = IgnoreExprNodes(E->getSubExpr(), ignoreImplicitSemaNodes);
2008
2009 if (E->getCastKind() == CK_ConstructorConversion)
2010 return cast<CXXConstructExpr>(SubExpr)->getConstructor();
2011
2012 if (E->getCastKind() == CK_UserDefinedConversion) {
2013 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SubExpr))
2014 return MCE->getMethodDecl();
2015 }
2016 }
2017
2018 return nullptr;
2019}
2020
2021CXXBaseSpecifier **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");
2031 }
2032}
2033
2035 QualType opType) {
2036 auto RD = unionType->castAs<RecordType>()->getDecl();
2037 return getTargetFieldForToUnionCast(RD, opType);
2038}
2039
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;
2049 }
2050 }
2051 return nullptr;
2052}
2053
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");
2071 }
2072}
2073
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;
2094}
2095
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);
2103}
2104
2106 ExprValueKind VK, CastKind K, Expr *Op,
2107 const CXXCastPath *BasePath,
2109 TypeSourceInfo *WrittenTy,
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;
2121}
2122
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);
2130}
2131
2132/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
2133/// corresponds to, e.g. "<<=".
2135 switch (Op) {
2136#define BINARY_OPERATION(Name, Spelling) case BO_##Name: return Spelling;
2137#include "clang/AST/OperationKinds.def"
2138 }
2139 llvm_unreachable("Invalid OpCode!");
2140}
2141
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;
2178 }
2179}
2180
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
2202 };
2203 return OverOps[Opc];
2204}
2205
2207 Opcode Opc,
2208 const Expr *LHS,
2209 const Expr *RHS) {
2210 if (Opc != BO_Add)
2211 return false;
2212
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;
2225 }
2226
2227 // Check that the pointer is a nullptr.
2228 if (!PExp->IgnoreParenCasts()
2230 return false;
2231
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;
2236
2237 return true;
2238}
2239
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);
2251}
2252
2254 switch (getIdentKind()) {
2256 return "__builtin_FILE";
2258 return "__builtin_FILE_NAME";
2260 return "__builtin_FUNCTION";
2262 return "__builtin_FUNCSIG";
2264 return "__builtin_LINE";
2266 return "__builtin_COLUMN";
2268 return "__builtin_source_location";
2269 }
2270 llvm_unreachable("unexpected IdentKind!");
2271}
2272
2274 const Expr *DefaultExpr) const {
2276 const DeclContext *Context;
2277
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();
2288 }
2289
2292
2293 auto MakeStringLiteral = [&](StringRef Tmp) {
2294 using LValuePathEntry = APValue::LValuePathEntry;
2296 // Decay the string to a pointer to the first character.
2297 LValuePathEntry Path[1] = {LValuePathEntry::ArrayIndex(0)};
2298 return APValue(Res, CharUnits::Zero(), Path, /*OnePastTheEnd=*/false);
2299 };
2300
2301 switch (getIdentKind()) {
2303 // __builtin_FILE_NAME() is a Clang-specific extension that expands to the
2304 // the last part of __builtin_FILE().
2307 FileName, PLoc, Ctx.getLangOpts(), Ctx.getTargetInfo());
2308 return MakeStringLiteral(FileName);
2309 }
2311 SmallString<256> Path(PLoc.getFilename());
2313 Ctx.getTargetInfo());
2314 return MakeStringLiteral(Path);
2315 }
2318 const auto *CurDecl = dyn_cast<Decl>(Context);
2319 const auto Kind = getIdentKind() == SourceLocIdentKind::Function
2322 return MakeStringLiteral(
2323 CurDecl ? PredefinedExpr::ComputeName(Kind, CurDecl) : std::string(""));
2324 }
2326 return APValue(Ctx.MakeIntValue(PLoc.getLine(), Ctx.UnsignedIntTy));
2328 return APValue(Ctx.MakeIntValue(PLoc.getColumn(), Ctx.UnsignedIntTy));
2330 // Fill in a std::source_location::__impl structure, by creating an
2331 // artificial file-scoped CompoundLiteralExpr, and returning a pointer to
2332 // that.
2333 const CXXRecordDecl *ImplDecl = getType()->getPointeeCXXRecordDecl();
2334 assert(ImplDecl);
2335
2336 // Construct an APValue for the __impl struct, and get or create a Decl
2337 // corresponding to that. Note that we've already verified that the shape of
2338 // the ImplDecl type is as expected.
2339
2341 for (const FieldDecl *F : ImplDecl->fields()) {
2342 StringRef Name = F->getName();
2343 if (Name == "_M_file_name") {
2344 SmallString<256> Path(PLoc.getFilename());
2346 Ctx.getTargetInfo());
2347 Value.getStructField(F->getFieldIndex()) = MakeStringLiteral(Path);
2348 } else if (Name == "_M_function_name") {
2349 // Note: this emits the PrettyFunction name -- different than what
2350 // __builtin_FUNCTION() above returns!
2351 const auto *CurDecl = dyn_cast<Decl>(Context);
2352 Value.getStructField(F->getFieldIndex()) = MakeStringLiteral(
2353 CurDecl && !isa<TranslationUnitDecl>(CurDecl)
2354 ? StringRef(PredefinedExpr::ComputeName(
2356 : "");
2357 } else if (Name == "_M_line") {
2358 llvm::APSInt IntVal = Ctx.MakeIntValue(PLoc.getLine(), F->getType());
2359 Value.getStructField(F->getFieldIndex()) = APValue(IntVal);
2360 } else if (Name == "_M_column") {
2361 llvm::APSInt IntVal = Ctx.MakeIntValue(PLoc.getColumn(), F->getType());
2362 Value.getStructField(F->getFieldIndex()) = APValue(IntVal);
2363 }
2364 }
2365
2368
2370 false);
2371 }
2372 }
2373 llvm_unreachable("unhandled case");
2374}
2375
2377 ArrayRef<Expr *> initExprs, SourceLocation rbraceloc)
2378 : Expr(InitListExprClass, QualType(), VK_PRValue, OK_Ordinary),
2379 InitExprs(C, initExprs.size()), LBraceLoc(lbraceloc),
2380 RBraceLoc(rbraceloc), AltForm(nullptr, true) {
2382 InitExprs.insert(C, InitExprs.end(), initExprs.begin(), initExprs.end());
2383
2385}
2386
2387void InitListExpr::reserveInits(const ASTContext &C, unsigned NumInits) {
2388 if (NumInits > InitExprs.size())
2389 InitExprs.reserve(C, NumInits);
2390}
2391
2392void InitListExpr::resizeInits(const ASTContext &C, unsigned NumInits) {
2393 InitExprs.resize(C, NumInits, nullptr);
2394}
2395
2397 if (Init >= InitExprs.size()) {
2398 InitExprs.insert(C, InitExprs.end(), Init - InitExprs.size() + 1, nullptr);
2399 setInit(Init, expr);
2400 return nullptr;
2401 }
2402
2403 Expr *Result = cast_or_null<Expr>(InitExprs[Init]);
2404 setInit(Init, expr);
2405 return Result;
2406}
2407
2409 assert(!hasArrayFiller() && "Filler already set!");
2410 ArrayFillerOrUnionFieldInit = filler;
2411 // Fill out any "holes" in the array due to designated initializers.
2412 Expr **inits = getInits();
2413 for (unsigned i = 0, e = getNumInits(); i != e; ++i)
2414 if (inits[i] == nullptr)
2415 inits[i] = filler;
2416}
2417
2419 if (getNumInits() != 1)
2420 return false;
2421 const ArrayType *AT = getType()->getAsArrayTypeUnsafe();
2422 if (!AT || !AT->getElementType()->isIntegerType())
2423 return false;
2424 // It is possible for getInit() to return null.
2425 const Expr *Init = getInit(0);
2426 if (!Init)
2427 return false;
2428 Init = Init->IgnoreParenImpCasts();
2429 return isa<StringLiteral>(Init) || isa<ObjCEncodeExpr>(Init);
2430}
2431
2433 assert(isSemanticForm() && "syntactic form never semantically transparent");
2434
2435 // A glvalue InitListExpr is always just sugar.
2436 if (isGLValue()) {
2437 assert(getNumInits() == 1 && "multiple inits in glvalue init list");
2438 return true;
2439 }
2440
2441 // Otherwise, we're sugar if and only if we have exactly one initializer that
2442 // is of the same type.
2443 if (getNumInits() != 1 || !getInit(0))
2444 return false;
2445
2446 // Don't confuse aggregate initialization of a struct X { X &x; }; with a
2447 // transparent struct copy.
2448 if (!getInit(0)->isPRValue() && getType()->isRecordType())
2449 return false;
2450
2451 return getType().getCanonicalType() ==
2453}
2454
2456 assert(isSyntacticForm() && "only test syntactic form as zero initializer");
2457
2458 if (LangOpts.CPlusPlus || getNumInits() != 1 || !getInit(0)) {
2459 return false;
2460 }
2461
2462 const IntegerLiteral *Lit = dyn_cast<IntegerLiteral>(getInit(0)->IgnoreImplicit());
2463 return Lit && Lit->getValue() == 0;
2464}
2465
2467 if (InitListExpr *SyntacticForm = getSyntacticForm())
2468 return SyntacticForm->getBeginLoc();
2469 SourceLocation Beg = LBraceLoc;
2470 if (Beg.isInvalid()) {
2471 // Find the first non-null initializer.
2472 for (InitExprsTy::const_iterator I = InitExprs.begin(),
2473 E = InitExprs.end();
2474 I != E; ++I) {
2475 if (Stmt *S = *I) {
2476 Beg = S->getBeginLoc();
2477 break;
2478 }
2479 }
2480 }
2481 return Beg;
2482}
2483
2485 if (InitListExpr *SyntacticForm = getSyntacticForm())
2486 return SyntacticForm->getEndLoc();
2487 SourceLocation End = RBraceLoc;
2488 if (End.isInvalid()) {
2489 // Find the first non-null initializer from the end.
2490 for (Stmt *S : llvm::reverse(InitExprs)) {
2491 if (S) {
2492 End = S->getEndLoc();
2493 break;
2494 }
2495 }
2496 }
2497 return End;
2498}
2499
2500/// getFunctionType - Return the underlying function type for this block.
2501///
2503 // The block pointer is never sugared, but the function type might be.
2504 return cast<BlockPointerType>(getType())
2506}
2507
2509 return TheBlock->getCaretLocation();
2510}
2511const Stmt *BlockExpr::getBody() const {
2512 return TheBlock->getBody();
2513}
2515 return TheBlock->getBody();
2516}
2517
2518
2519//===----------------------------------------------------------------------===//
2520// Generic Expression Routines
2521//===----------------------------------------------------------------------===//
2522
2524 // In C++11, discarded-value expressions of a certain form are special,
2525 // according to [expr]p10:
2526 // The lvalue-to-rvalue conversion (4.1) is applied only if the
2527 // expression is a glvalue of volatile-qualified type and it has
2528 // one of the following forms:
2529 if (!isGLValue() || !getType().isVolatileQualified())
2530 return false;
2531
2532 const Expr *E = IgnoreParens();
2533
2534 // - id-expression (5.1.1),
2535 if (isa<DeclRefExpr>(E))
2536 return true;
2537
2538 // - subscripting (5.2.1),
2539 if (isa<ArraySubscriptExpr>(E))
2540 return true;
2541
2542 // - class member access (5.2.5),
2543 if (isa<MemberExpr>(E))
2544 return true;
2545
2546 // - indirection (5.3.1),
2547 if (auto *UO = dyn_cast<UnaryOperator>(E))
2548 if (UO->getOpcode() == UO_Deref)
2549 return true;
2550
2551 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
2552 // - pointer-to-member operation (5.5),
2553 if (BO->isPtrMemOp())
2554 return true;
2555
2556 // - comma expression (5.18) where the right operand is one of the above.
2557 if (BO->getOpcode() == BO_Comma)
2558 return BO->getRHS()->isReadIfDiscardedInCPlusPlus11();
2559 }
2560
2561 // - conditional expression (5.16) where both the second and the third
2562 // operands are one of the above, or
2563 if (auto *CO = dyn_cast<ConditionalOperator>(E))
2564 return CO->getTrueExpr()->isReadIfDiscardedInCPlusPlus11() &&
2565 CO->getFalseExpr()->isReadIfDiscardedInCPlusPlus11();
2566 // The related edge case of "*x ?: *x".
2567 if (auto *BCO =
2568 dyn_cast<BinaryConditionalOperator>(E)) {
2569 if (auto *OVE = dyn_cast<OpaqueValueExpr>(BCO->getTrueExpr()))
2570 return OVE->getSourceExpr()->isReadIfDiscardedInCPlusPlus11() &&
2571 BCO->getFalseExpr()->isReadIfDiscardedInCPlusPlus11();
2572 }
2573
2574 // Objective-C++ extensions to the rule.
2575 if (isa<ObjCIvarRefExpr>(E))
2576 return true;
2577 if (const auto *POE = dyn_cast<PseudoObjectExpr>(E)) {
2578 if (isa<ObjCPropertyRefExpr, ObjCSubscriptRefExpr>(POE->getSyntacticForm()))
2579 return true;
2580 }
2581
2582 return false;
2583}
2584
2585/// isUnusedResultAWarning - Return true if this immediate expression should
2586/// be warned about if the result is unused. If so, fill in Loc and Ranges
2587/// with location to warn on and the source range[s] to report with the
2588/// warning.
2590 SourceRange &R1, SourceRange &R2,
2591 ASTContext &Ctx) const {
2592 // Don't warn if the expr is type dependent. The type could end up
2593 // instantiating to void.
2594 if (isTypeDependent())
2595 return false;
2596
2597 switch (getStmtClass()) {
2598 default:
2599 if (getType()->isVoidType())
2600 return false;
2601 WarnE = this;
2602 Loc = getExprLoc();
2603 R1 = getSourceRange();
2604 return true;
2605 case ParenExprClass:
2606 return cast<ParenExpr>(this)->getSubExpr()->
2607 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2608 case GenericSelectionExprClass:
2609 return cast<GenericSelectionExpr>(this)->getResultExpr()->
2610 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2611 case CoawaitExprClass:
2612 case CoyieldExprClass:
2613 return cast<CoroutineSuspendExpr>(this)->getResumeExpr()->
2614 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2615 case ChooseExprClass:
2616 return cast<ChooseExpr>(this)->getChosenSubExpr()->
2617 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2618 case UnaryOperatorClass: {
2619 const UnaryOperator *UO = cast<UnaryOperator>(this);
2620
2621 switch (UO->getOpcode()) {
2622 case UO_Plus:
2623 case UO_Minus:
2624 case UO_AddrOf:
2625 case UO_Not:
2626 case UO_LNot:
2627 case UO_Deref:
2628 break;
2629 case UO_Coawait:
2630 // This is just the 'operator co_await' call inside the guts of a
2631 // dependent co_await call.
2632 case UO_PostInc:
2633 case UO_PostDec:
2634 case UO_PreInc:
2635 case UO_PreDec: // ++/--
2636 return false; // Not a warning.
2637 case UO_Real:
2638 case UO_Imag:
2639 // accessing a piece of a volatile complex is a side-effect.
2640 if (Ctx.getCanonicalType(UO->getSubExpr()->getType())
2642 return false;
2643 break;
2644 case UO_Extension:
2645 return UO->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2646 }
2647 WarnE = this;
2648 Loc = UO->getOperatorLoc();
2649 R1 = UO->getSubExpr()->getSourceRange();
2650 return true;
2651 }
2652 case BinaryOperatorClass: {
2653 const BinaryOperator *BO = cast<BinaryOperator>(this);
2654 switch (BO->getOpcode()) {
2655 default:
2656 break;
2657 // Consider the RHS of comma for side effects. LHS was checked by
2658 // Sema::CheckCommaOperands.
2659 case BO_Comma:
2660 // ((foo = <blah>), 0) is an idiom for hiding the result (and
2661 // lvalue-ness) of an assignment written in a macro.
2662 if (IntegerLiteral *IE =
2663 dyn_cast<IntegerLiteral>(BO->getRHS()->IgnoreParens()))
2664 if (IE->getValue() == 0)
2665 return false;
2666 return BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2667 // Consider '||', '&&' to have side effects if the LHS or RHS does.
2668 case BO_LAnd:
2669 case BO_LOr:
2670 if (!BO->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx) ||
2671 !BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx))
2672 return false;
2673 break;
2674 }
2675 if (BO->isAssignmentOp())
2676 return false;
2677 WarnE = this;
2678 Loc = BO->getOperatorLoc();
2679 R1 = BO->getLHS()->getSourceRange();
2680 R2 = BO->getRHS()->getSourceRange();
2681 return true;
2682 }
2683 case CompoundAssignOperatorClass:
2684 case VAArgExprClass:
2685 case AtomicExprClass:
2686 return false;
2687
2688 case ConditionalOperatorClass: {
2689 // If only one of the LHS or RHS is a warning, the operator might
2690 // be being used for control flow. Only warn if both the LHS and
2691 // RHS are warnings.
2692 const auto *Exp = cast<ConditionalOperator>(this);
2693 return Exp->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx) &&
2694 Exp->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2695 }
2696 case BinaryConditionalOperatorClass: {
2697 const auto *Exp = cast<BinaryConditionalOperator>(this);
2698 return Exp->getFalseExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2699 }
2700
2701 case MemberExprClass:
2702 WarnE = this;
2703 Loc = cast<MemberExpr>(this)->getMemberLoc();
2704 R1 = SourceRange(Loc, Loc);
2705 R2 = cast<MemberExpr>(this)->getBase()->getSourceRange();
2706 return true;
2707
2708 case ArraySubscriptExprClass:
2709 WarnE = this;
2710 Loc = cast<ArraySubscriptExpr>(this)->getRBracketLoc();
2711 R1 = cast<ArraySubscriptExpr>(this)->getLHS()->getSourceRange();
2712 R2 = cast<ArraySubscriptExpr>(this)->getRHS()->getSourceRange();
2713 return true;
2714
2715 case CXXOperatorCallExprClass: {
2716 // Warn about operator ==,!=,<,>,<=, and >= even when user-defined operator
2717 // overloads as there is no reasonable way to define these such that they
2718 // have non-trivial, desirable side-effects. See the -Wunused-comparison
2719 // warning: operators == and != are commonly typo'ed, and so warning on them
2720 // provides additional value as well. If this list is updated,
2721 // DiagnoseUnusedComparison should be as well.
2722 const CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(this);
2723 switch (Op->getOperator()) {
2724 default:
2725 break;
2726 case OO_EqualEqual:
2727 case OO_ExclaimEqual:
2728 case OO_Less:
2729 case OO_Greater:
2730 case OO_GreaterEqual:
2731 case OO_LessEqual:
2732 if (Op->getCallReturnType(Ctx)->isReferenceType() ||
2733 Op->getCallReturnType(Ctx)->isVoidType())
2734 break;
2735 WarnE = this;
2736 Loc = Op->getOperatorLoc();
2737 R1 = Op->getSourceRange();
2738 return true;
2739 }
2740
2741 // Fallthrough for generic call handling.
2742 [[fallthrough]];
2743 }
2744 case CallExprClass:
2745 case CXXMemberCallExprClass:
2746 case UserDefinedLiteralClass: {
2747 // If this is a direct call, get the callee.
2748 const CallExpr *CE = cast<CallExpr>(this);
2749 if (const Decl *FD = CE->getCalleeDecl()) {
2750 // If the callee has attribute pure, const, or warn_unused_result, warn
2751 // about it. void foo() { strlen("bar"); } should warn.
2752 //
2753 // Note: If new cases are added here, DiagnoseUnusedExprResult should be
2754 // updated to match for QoI.
2755 if (CE->hasUnusedResultAttr(Ctx) ||
2756 FD->hasAttr<PureAttr>() || FD->hasAttr<ConstAttr>()) {
2757 WarnE = this;
2758 Loc = CE->getCallee()->getBeginLoc();
2759 R1 = CE->getCallee()->getSourceRange();
2760
2761 if (unsigned NumArgs = CE->getNumArgs())
2762 R2 = SourceRange(CE->getArg(0)->getBeginLoc(),
2763 CE->getArg(NumArgs - 1)->getEndLoc());
2764 return true;
2765 }
2766 }
2767 return false;
2768 }
2769
2770 // If we don't know precisely what we're looking at, let's not warn.
2771 case UnresolvedLookupExprClass:
2772 case CXXUnresolvedConstructExprClass:
2773 case RecoveryExprClass:
2774 return false;
2775
2776 case CXXTemporaryObjectExprClass:
2777 case CXXConstructExprClass: {
2778 if (const CXXRecordDecl *Type = getType()->getAsCXXRecordDecl()) {
2779 const auto *WarnURAttr = Type->getAttr<WarnUnusedResultAttr>();
2780 if (Type->hasAttr<WarnUnusedAttr>() ||
2781 (WarnURAttr && WarnURAttr->IsCXX11NoDiscard())) {
2782 WarnE = this;
2783 Loc = getBeginLoc();
2784 R1 = getSourceRange();
2785 return true;
2786 }
2787 }
2788
2789 const auto *CE = cast<CXXConstructExpr>(this);
2790 if (const CXXConstructorDecl *Ctor = CE->getConstructor()) {
2791 const auto *WarnURAttr = Ctor->getAttr<WarnUnusedResultAttr>();
2792 if (WarnURAttr && WarnURAttr->IsCXX11NoDiscard()) {
2793 WarnE = this;
2794 Loc = getBeginLoc();
2795 R1 = getSourceRange();
2796
2797 if (unsigned NumArgs = CE->getNumArgs())
2798 R2 = SourceRange(CE->getArg(0)->getBeginLoc(),
2799 CE->getArg(NumArgs - 1)->getEndLoc());
2800 return true;
2801 }
2802 }
2803
2804 return false;
2805 }
2806
2807 case ObjCMessageExprClass: {
2808 const ObjCMessageExpr *ME = cast<ObjCMessageExpr>(this);
2809 if (Ctx.getLangOpts().ObjCAutoRefCount &&
2810 ME->isInstanceMessage() &&
2811 !ME->getType()->isVoidType() &&
2812 ME->getMethodFamily() == OMF_init) {
2813 WarnE = this;
2814 Loc = getExprLoc();
2815 R1 = ME->getSourceRange();
2816 return true;
2817 }
2818
2819 if (const ObjCMethodDecl *MD = ME->getMethodDecl())
2820 if (MD->hasAttr<WarnUnusedResultAttr>()) {
2821 WarnE = this;
2822 Loc = getExprLoc();
2823 return true;
2824 }
2825
2826 return false;
2827 }
2828
2829 case ObjCPropertyRefExprClass:
2830 case ObjCSubscriptRefExprClass:
2831 WarnE = this;
2832 Loc = getExprLoc();
2833 R1 = getSourceRange();
2834 return true;
2835
2836 case PseudoObjectExprClass: {
2837 const auto *POE = cast<PseudoObjectExpr>(this);
2838
2839 // For some syntactic forms, we should always warn.
2840 if (isa<ObjCPropertyRefExpr, ObjCSubscriptRefExpr>(
2841 POE->getSyntacticForm())) {
2842 WarnE = this;
2843 Loc = getExprLoc();
2844 R1 = getSourceRange();
2845 return true;
2846 }
2847
2848 // For others, we should never warn.
2849 if (auto *BO = dyn_cast<BinaryOperator>(POE->getSyntacticForm()))
2850 if (BO->isAssignmentOp())
2851 return false;
2852 if (auto *UO = dyn_cast<UnaryOperator>(POE->getSyntacticForm()))
2853 if (UO->isIncrementDecrementOp())
2854 return false;
2855
2856 // Otherwise, warn if the result expression would warn.
2857 const Expr *Result = POE->getResultExpr();
2858 return Result && Result->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2859 }
2860
2861 case StmtExprClass: {
2862 // Statement exprs don't logically have side effects themselves, but are
2863 // sometimes used in macros in ways that give them a type that is unused.
2864 // For example ({ blah; foo(); }) will end up with a type if foo has a type.
2865 // however, if the result of the stmt expr is dead, we don't want to emit a
2866 // warning.
2867 const CompoundStmt *CS = cast<StmtExpr>(this)->getSubStmt();
2868 if (!CS->body_empty()) {
2869 if (const Expr *E = dyn_cast<Expr>(CS->body_back()))
2870 return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2871 if (const LabelStmt *Label = dyn_cast<LabelStmt>(CS->body_back()))
2872 if (const Expr *E = dyn_cast<Expr>(Label->getSubStmt()))
2873 return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2874 }
2875
2876 if (getType()->isVoidType())
2877 return false;
2878 WarnE = this;
2879 Loc = cast<StmtExpr>(this)->getLParenLoc();
2880 R1 = getSourceRange();
2881 return true;
2882 }
2883 case CXXFunctionalCastExprClass:
2884 case CStyleCastExprClass: {
2885 // Ignore an explicit cast to void, except in C++98 if the operand is a
2886 // volatile glvalue for which we would trigger an implicit read in any
2887 // other language mode. (Such an implicit read always happens as part of
2888 // the lvalue conversion in C, and happens in C++ for expressions of all
2889 // forms where it seems likely the user intended to trigger a volatile
2890 // load.)
2891 const CastExpr *CE = cast<CastExpr>(this);
2892 const Expr *SubE = CE->getSubExpr()->IgnoreParens();
2893 if (CE->getCastKind() == CK_ToVoid) {
2894 if (Ctx.getLangOpts().CPlusPlus && !Ctx.getLangOpts().CPlusPlus11 &&
2896 // Suppress the "unused value" warning for idiomatic usage of
2897 // '(void)var;' used to suppress "unused variable" warnings.
2898 if (auto *DRE = dyn_cast<DeclRefExpr>(SubE))
2899 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
2900 if (!VD->isExternallyVisible())
2901 return false;
2902
2903 // The lvalue-to-rvalue conversion would have no effect for an array.
2904 // It's implausible that the programmer expected this to result in a
2905 // volatile array load, so don't warn.
2906 if (SubE->getType()->isArrayType())
2907 return false;
2908
2909 return SubE->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2910 }
2911 return false;
2912 }
2913
2914 // If this is a cast to a constructor conversion, check the operand.
2915 // Otherwise, the result of the cast is unused.
2916 if (CE->getCastKind() == CK_ConstructorConversion)
2917 return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2918 if (CE->getCastKind() == CK_Dependent)
2919 return false;
2920
2921 WarnE = this;
2922 if (const CXXFunctionalCastExpr *CXXCE =
2923 dyn_cast<CXXFunctionalCastExpr>(this)) {
2924 Loc = CXXCE->getBeginLoc();
2925 R1 = CXXCE->getSubExpr()->getSourceRange();
2926 } else {
2927 const CStyleCastExpr *CStyleCE = cast<CStyleCastExpr>(this);
2928 Loc = CStyleCE->getLParenLoc();
2929 R1 = CStyleCE->getSubExpr()->getSourceRange();
2930 }
2931 return true;
2932 }
2933 case ImplicitCastExprClass: {
2934 const CastExpr *ICE = cast<ImplicitCastExpr>(this);
2935
2936 // lvalue-to-rvalue conversion on a volatile lvalue is a side-effect.
2937 if (ICE->getCastKind() == CK_LValueToRValue &&
2939 return false;
2940
2941 return ICE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2942 }
2943 case CXXDefaultArgExprClass:
2944 return (cast<CXXDefaultArgExpr>(this)
2945 ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
2946 case CXXDefaultInitExprClass:
2947 return (cast<CXXDefaultInitExpr>(this)
2948 ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
2949
2950 case CXXNewExprClass:
2951 // FIXME: In theory, there might be new expressions that don't have side
2952 // effects (e.g. a placement new with an uninitialized POD).
2953 case CXXDeleteExprClass:
2954 return false;
2955 case MaterializeTemporaryExprClass:
2956 return cast<MaterializeTemporaryExpr>(this)
2957 ->getSubExpr()
2958 ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2959 case CXXBindTemporaryExprClass:
2960 return cast<CXXBindTemporaryExpr>(this)->getSubExpr()
2961 ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2962 case ExprWithCleanupsClass:
2963 return cast<ExprWithCleanups>(this)->getSubExpr()
2964 ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2965 }
2966}
2967
2968/// isOBJCGCCandidate - Check if an expression is objc gc'able.
2969/// returns true, if it is; false otherwise.
2971 const Expr *E = IgnoreParens();
2972 switch (E->getStmtClass()) {
2973 default:
2974 return false;
2975 case ObjCIvarRefExprClass:
2976 return true;
2977 case Expr::UnaryOperatorClass:
2978 return cast<UnaryOperator>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
2979 case ImplicitCastExprClass:
2980 return cast<ImplicitCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
2981 case MaterializeTemporaryExprClass:
2982 return cast<MaterializeTemporaryExpr>(E)->getSubExpr()->isOBJCGCCandidate(
2983 Ctx);
2984 case CStyleCastExprClass:
2985 return cast<CStyleCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
2986 case DeclRefExprClass: {
2987 const Decl *D = cast<DeclRefExpr>(E)->getDecl();
2988
2989 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2990 if (VD->hasGlobalStorage())
2991 return true;
2992 QualType T = VD->getType();
2993 // dereferencing to a pointer is always a gc'able candidate,
2994 // unless it is __weak.
2995 return T->isPointerType() &&
2997 }
2998 return false;
2999 }
3000 case MemberExprClass: {
3001 const MemberExpr *M = cast<MemberExpr>(E);
3002 return M->getBase()->isOBJCGCCandidate(Ctx);
3003 }
3004 case ArraySubscriptExprClass:
3005 return cast<ArraySubscriptExpr>(E)->getBase()->isOBJCGCCandidate(Ctx);
3006 }
3007}
3008
3010 if (isTypeDependent())
3011 return false;
3013}
3014
3016 assert(expr->hasPlaceholderType(BuiltinType::BoundMember));
3017
3018 // Bound member expressions are always one of these possibilities:
3019 // x->m x.m x->*y x.*y
3020 // (possibly parenthesized)
3021
3022 expr = expr->IgnoreParens();
3023 if (const MemberExpr *mem = dyn_cast<MemberExpr>(expr)) {
3024 assert(isa<CXXMethodDecl>(mem->getMemberDecl()));
3025 return mem->getMemberDecl()->getType();
3026 }
3027
3028 if (const BinaryOperator *op = dyn_cast<BinaryOperator>(expr)) {
3029 QualType type = op->getRHS()->getType()->castAs<MemberPointerType>()
3030 ->getPointeeType();
3031 assert(type->isFunctionType());
3032 return type;
3033 }
3034
3035 assert(isa<UnresolvedMemberExpr>(expr) || isa<CXXPseudoDestructorExpr>(expr));
3036 return QualType();
3037}
3038
3041}
3042
3045}
3046
3049}
3050
3053}
3054
3057}
3058
3062}
3063
3066}
3067
3069 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(this)) {
3070 if (isa_and_nonnull<CXXConversionDecl>(MCE->getMethodDecl()))
3071 return MCE->getImplicitObjectArgument();
3072 }
3073 return this;
3074}
3075
3079}
3080
3084}
3085
3087 auto IgnoreNoopCastsSingleStep = [&Ctx](Expr *E) {
3088 if (auto *CE = dyn_cast<CastExpr>(E)) {
3089 // We ignore integer <-> casts that are of the same width, ptr<->ptr and
3090 // ptr<->int casts of the same width. We also ignore all identity casts.
3091 Expr *SubExpr = CE->getSubExpr();
3092 bool IsIdentityCast =
3093 Ctx.hasSameUnqualifiedType(E->getType(), SubExpr->getType());
3094 bool IsSameWidthCast = (E->getType()->isPointerType() ||
3095 E->getType()->isIntegralType(Ctx)) &&
3096 (SubExpr->getType()->isPointerType() ||
3097 SubExpr->getType()->isIntegralType(Ctx)) &&
3098 (Ctx.getTypeSize(E->getType()) ==
3099 Ctx.getTypeSize(SubExpr->getType()));
3100
3101 if (IsIdentityCast || IsSameWidthCast)
3102 return SubExpr;
3103 } else if (auto *NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E))
3104 return NTTP->getReplacement();
3105
3106 return E;
3107 };
3109 IgnoreNoopCastsSingleStep);
3110}
3111
3114 if (auto *Cast = dyn_cast<CXXFunctionalCastExpr>(E)) {
3115 auto *SE = Cast->getSubExpr();
3116 if (SE->getSourceRange() == E->getSourceRange())
3117 return SE;
3118 }
3119
3120 if (auto *C = dyn_cast<CXXConstructExpr>(E)) {
3121 auto NumArgs = C->getNumArgs();
3122 if (NumArgs == 1 ||
3123 (NumArgs > 1 && isa<CXXDefaultArgExpr>(C->getArg(1)))) {
3124 Expr *A = C->getArg(0);
3125 if (A->getSourceRange() == E->getSourceRange() || C->isElidable())
3126 return A;
3127 }
3128 }
3129 return E;
3130 };
3131 auto IgnoreImplicitMemberCallSingleStep = [](Expr *E) {
3132 if (auto *C = dyn_cast<CXXMemberCallExpr>(E)) {
3133 Expr *ExprNode = C->getImplicitObjectArgument();
3134 if (ExprNode->getSourceRange() == E->getSourceRange()) {
3135 return ExprNode;
3136 }
3137 if (auto *PE = dyn_cast<ParenExpr>(ExprNode)) {
3138 if (PE->getSourceRange() == C->getSourceRange()) {
3139 return cast<Expr>(PE);
3140 }
3141 }
3142 ExprNode = ExprNode->IgnoreParenImpCasts();
3143 if (ExprNode->getSourceRange() == E->getSourceRange())
3144 return ExprNode;
3145 }
3146 return E;
3147 };
3148 return IgnoreExprNodes(
3151 IgnoreImplicitMemberCallSingleStep);
3152}
3153
3155 const Expr *E = this;
3156 if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
3157 E = M->getSubExpr();
3158
3159 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3160 E = ICE->getSubExprAsWritten();
3161
3162 return isa<CXXDefaultArgExpr>(E);
3163}
3164
3165/// Skip over any no-op casts and any temporary-binding
3166/// expressions.
3168 if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
3169 E = M->getSubExpr();
3170
3171 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3172 if (ICE->getCastKind() == CK_NoOp)
3173 E = ICE->getSubExpr();
3174 else
3175 break;
3176 }
3177
3178 while (const CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
3179 E = BE->getSubExpr();
3180
3181 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3182 if (ICE->getCastKind() == CK_NoOp)
3183 E = ICE->getSubExpr();
3184 else
3185 break;
3186 }
3187
3188 return E->IgnoreParens();
3189}
3190
3191/// isTemporaryObject - Determines if this expression produces a
3192/// temporary of the given class type.
3194 if (!C.hasSameUnqualifiedType(getType(), C.getTypeDeclType(TempTy)))
3195 return false;
3196
3198
3199 // Temporaries are by definition pr-values of class type.
3200 if (!E->Classify(C).isPRValue()) {
3201 // In this context, property reference is a message call and is pr-value.
3202 if (!isa<ObjCPropertyRefExpr>(E))
3203 return false;
3204 }
3205
3206 // Black-list a few cases which yield pr-values of class type that don't
3207 // refer to temporaries of that type:
3208
3209 // - implicit derived-to-base conversions
3210 if (isa<ImplicitCastExpr>(E)) {
3211 switch (cast<ImplicitCastExpr>(E)->getCastKind()) {
3212 case CK_DerivedToBase:
3213 case CK_UncheckedDerivedToBase:
3214 return false;
3215 default:
3216 break;
3217 }
3218 }
3219
3220 // - member expressions (all)
3221 if (isa<MemberExpr>(E))
3222 return false;
3223
3224 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E))
3225 if (BO->isPtrMemOp())
3226 return false;
3227
3228 // - opaque values (all)
3229 if (isa<OpaqueValueExpr>(E))
3230 return false;
3231
3232 return true;
3233}
3234
3236 const Expr *E = this;
3237
3238 // Strip away parentheses and casts we don't care about.
3239 while (true) {
3240 if (const ParenExpr *Paren = dyn_cast<ParenExpr>(E)) {
3241 E = Paren->getSubExpr();
3242 continue;
3243 }
3244
3245 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3246 if (ICE->getCastKind() == CK_NoOp ||
3247 ICE->getCastKind() == CK_LValueToRValue ||
3248 ICE->getCastKind() == CK_DerivedToBase ||
3249 ICE->getCastKind() == CK_UncheckedDerivedToBase) {
3250 E = ICE->getSubExpr();
3251 continue;
3252 }
3253 }
3254
3255 if (const UnaryOperator* UnOp = dyn_cast<UnaryOperator>(E)) {
3256 if (UnOp->getOpcode() == UO_Extension) {
3257 E = UnOp->getSubExpr();
3258 continue;
3259 }
3260 }
3261
3262 if (const MaterializeTemporaryExpr *M
3263 = dyn_cast<MaterializeTemporaryExpr>(E)) {
3264 E = M->getSubExpr();
3265 continue;
3266 }
3267
3268 break;
3269 }
3270
3271 if (const CXXThisExpr *This = dyn_cast<CXXThisExpr>(E))
3272 return This->isImplicit();
3273
3274 return false;
3275}
3276
3277/// hasAnyTypeDependentArguments - Determines if any of the expressions
3278/// in Exprs is type-dependent.
3280 for (unsigned I = 0; I < Exprs.size(); ++I)
3281 if (Exprs[I]->isTypeDependent())
3282 return true;
3283
3284 return false;
3285}
3286
3288 const Expr **Culprit) const {
3289 assert(!isValueDependent() &&
3290 "Expression evaluator can't be called on a dependent expression.");
3291
3292 // This function is attempting whether an expression is an initializer
3293 // which can be evaluated at compile-time. It very closely parallels
3294 // ConstExprEmitter in CGExprConstant.cpp; if they don't match, it
3295 // will lead to unexpected results. Like ConstExprEmitter, it falls back
3296 // to isEvaluatable most of the time.
3297 //
3298 // If we ever capture reference-binding directly in the AST, we can
3299 // kill the second parameter.
3300
3301 if (IsForRef) {
3302 if (auto *EWC = dyn_cast<ExprWithCleanups>(this))
3303 return EWC->getSubExpr()->isConstantInitializer(Ctx, true, Culprit);
3304 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(this))
3305 return MTE->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
3307 if (EvaluateAsLValue(Result, Ctx) && !Result.HasSideEffects)
3308 return true;
3309 if (Culprit)
3310 *Culprit = this;
3311 return false;
3312 }
3313
3314 switch (getStmtClass()) {
3315 default: break;
3316 case Stmt::ExprWithCleanupsClass:
3317 return cast<ExprWithCleanups>(this)->getSubExpr()->isConstantInitializer(
3318 Ctx, IsForRef, Culprit);
3319 case StringLiteralClass:
3320 case ObjCEncodeExprClass:
3321 return true;
3322 case CXXTemporaryObjectExprClass:
3323 case CXXConstructExprClass: {
3324 const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
3325
3326 if (CE->getConstructor()->isTrivial() &&
3328 // Trivial default constructor
3329 if (!CE->getNumArgs()) return true;
3330
3331 // Trivial copy constructor
3332 assert(CE->getNumArgs() == 1 && "trivial ctor with > 1 argument");
3333 return CE->getArg(0)->isConstantInitializer(Ctx, false, Culprit);
3334 }
3335
3336 break;
3337 }
3338 case ConstantExprClass: {
3339 // FIXME: We should be able to return "true" here, but it can lead to extra
3340 // error messages. E.g. in Sema/array-init.c.
3341 const Expr *Exp = cast<ConstantExpr>(this)->getSubExpr();
3342 return Exp->isConstantInitializer(Ctx, false, Culprit);
3343 }
3344 case CompoundLiteralExprClass: {
3345 // This handles gcc's extension that allows global initializers like
3346 // "struct x {int x;} x = (struct x) {};".
3347 // FIXME: This accepts other cases it shouldn't!
3348 const Expr *Exp = cast<CompoundLiteralExpr>(this)->getInitializer();
3349 return Exp->isConstantInitializer(Ctx, false, Culprit);
3350 }
3351 case DesignatedInitUpdateExprClass: {
3352 const DesignatedInitUpdateExpr *DIUE = cast<DesignatedInitUpdateExpr>(this);
3353 return DIUE->getBase()->isConstantInitializer(Ctx, false, Culprit) &&
3354 DIUE->getUpdater()->isConstantInitializer(Ctx, false, Culprit);
3355 }
3356 case InitListExprClass: {
3357 // C++ [dcl.init.aggr]p2:
3358 // The elements of an aggregate are:
3359 // - for an array, the array elements in increasing subscript order, or
3360 // - for a class, the direct base classes in declaration order, followed
3361 // by the direct non-static data members (11.4) that are not members of
3362 // an anonymous union, in declaration order.
3363 const InitListExpr *ILE = cast<InitListExpr>(this);
3364 assert(ILE->isSemanticForm() && "InitListExpr must be in semantic form");
3365 if (ILE->getType()->isArrayType()) {
3366 unsigned numInits = ILE->getNumInits();
3367 for (unsigned i = 0; i < numInits; i++) {
3368 if (!ILE->getInit(i)->isConstantInitializer(Ctx, false, Culprit))
3369 return false;
3370 }
3371 return true;
3372 }
3373
3374 if (ILE->getType()->isRecordType()) {
3375 unsigned ElementNo = 0;
3376 RecordDecl *RD = ILE->getType()->castAs<RecordType>()->getDecl();
3377
3378 // In C++17, bases were added to the list of members used by aggregate
3379 // initialization.
3380 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3381 for (unsigned i = 0, e = CXXRD->getNumBases(); i < e; i++) {
3382 if (ElementNo < ILE->getNumInits()) {
3383 const Expr *Elt = ILE->getInit(ElementNo++);
3384 if (!Elt->isConstantInitializer(Ctx, false, Culprit))
3385 return false;
3386 }
3387 }
3388 }
3389
3390 for (const auto *Field : RD->fields()) {
3391 // If this is a union, skip all the fields that aren't being initialized.
3392 if (RD->isUnion() && ILE->getInitializedFieldInUnion() != Field)
3393 continue;
3394
3395 // Don't emit anonymous bitfields, they just affect layout.
3396 if (Field->isUnnamedBitField())
3397 continue;
3398
3399 if (ElementNo < ILE->getNumInits()) {
3400 const Expr *Elt = ILE->getInit(ElementNo++);
3401 if (Field->isBitField()) {
3402 // Bitfields have to evaluate to an integer.
3404 if (!Elt->EvaluateAsInt(Result, Ctx)) {
3405 if (Culprit)
3406 *Culprit = Elt;
3407 return false;
3408 }
3409 } else {
3410 bool RefType = Field->getType()->isReferenceType();
3411 if (!Elt->isConstantInitializer(Ctx, RefType, Culprit))
3412 return false;
3413 }
3414 }
3415 }
3416 return true;
3417 }
3418
3419 break;
3420 }
3421 case ImplicitValueInitExprClass:
3422 case NoInitExprClass:
3423 return true;
3424 case ParenExprClass:
3425 return cast<ParenExpr>(this)->getSubExpr()
3426 ->isConstantInitializer(Ctx, IsForRef, Culprit);
3427 case GenericSelectionExprClass:
3428 return cast<GenericSelectionExpr>(this)->getResultExpr()
3429 ->isConstantInitializer(Ctx, IsForRef, Culprit);
3430 case ChooseExprClass:
3431 if (cast<ChooseExpr>(this)->isConditionDependent()) {
3432 if (Culprit)
3433 *Culprit = this;
3434 return false;
3435 }
3436 return cast<ChooseExpr>(this)->getChosenSubExpr()
3437 ->isConstantInitializer(Ctx, IsForRef, Culprit);
3438 case UnaryOperatorClass: {
3439 const UnaryOperator* Exp = cast<UnaryOperator>(this);
3440 if (Exp->getOpcode() == UO_Extension)
3441 return Exp->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
3442 break;
3443 }
3444 case PackIndexingExprClass: {
3445 return cast<PackIndexingExpr>(this)
3446 ->getSelectedExpr()
3447 ->isConstantInitializer(Ctx, false, Culprit);
3448 }
3449 case CXXFunctionalCastExprClass:
3450 case CXXStaticCastExprClass:
3451 case ImplicitCastExprClass:
3452 case CStyleCastExprClass:
3453 case ObjCBridgedCastExprClass:
3454 case CXXDynamicCastExprClass:
3455 case CXXReinterpretCastExprClass:
3456 case CXXAddrspaceCastExprClass:
3457 case CXXConstCastExprClass: {
3458 const CastExpr *CE = cast<CastExpr>(this);
3459
3460 // Handle misc casts we want to ignore.
3461 if (CE->getCastKind() == CK_NoOp ||
3462 CE->getCastKind() == CK_LValueToRValue ||
3463 CE->getCastKind() == CK_ToUnion ||
3464 CE->getCastKind() == CK_ConstructorConversion ||
3465 CE->getCastKind() == CK_NonAtomicToAtomic ||
3466 CE->getCastKind() == CK_AtomicToNonAtomic ||
3467 CE->getCastKind() == CK_NullToPointer ||
3468 CE->getCastKind() == CK_IntToOCLSampler)
3469 return CE->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
3470
3471 break;
3472 }
3473 case MaterializeTemporaryExprClass:
3474 return cast<MaterializeTemporaryExpr>(this)
3475 ->getSubExpr()
3476 ->isConstantInitializer(Ctx, false, Culprit);
3477
3478 case SubstNonTypeTemplateParmExprClass:
3479 return cast<SubstNonTypeTemplateParmExpr>(this)->getReplacement()
3480 ->isConstantInitializer(Ctx, false, Culprit);
3481 case CXXDefaultArgExprClass:
3482 return cast<CXXDefaultArgExpr>(this)->getExpr()
3483 ->isConstantInitializer(Ctx, false, Culprit);
3484 case CXXDefaultInitExprClass:
3485 return cast<CXXDefaultInitExpr>(this)->getExpr()
3486 ->isConstantInitializer(Ctx, false, Culprit);
3487 }
3488 // Allow certain forms of UB in constant initializers: signed integer
3489 // overflow and floating-point division by zero. We'll give a warning on
3490 // these, but they're common enough that we have to accept them.
3492 return true;
3493 if (Culprit)
3494 *Culprit = this;
3495 return false;
3496}
3497
3499 unsigned BuiltinID = getBuiltinCallee();
3500 if (BuiltinID != Builtin::BI__assume &&
3501 BuiltinID != Builtin::BI__builtin_assume)
3502 return false;
3503
3504 const Expr* Arg = getArg(0);
3505 bool ArgVal;
3506 return !Arg->isValueDependent() &&
3507 Arg->EvaluateAsBooleanCondition(ArgVal, Ctx) && !ArgVal;
3508}
3509
3511 return getBuiltinCallee() == Builtin::BImove;
3512}
3513
3514namespace {
3515 /// Look for any side effects within a Stmt.
3516 class SideEffectFinder : public ConstEvaluatedExprVisitor<SideEffectFinder> {
3518 const bool IncludePossibleEffects;
3519 bool HasSideEffects;
3520
3521 public:
3522 explicit SideEffectFinder(const ASTContext &Context, bool IncludePossible)
3523 : Inherited(Context),
3524 IncludePossibleEffects(IncludePossible), HasSideEffects(false) { }
3525
3526 bool hasSideEffects() const { return HasSideEffects; }
3527
3528 void VisitDecl(const Decl *D) {
3529 if (!D)
3530 return;
3531
3532 // We assume the caller checks subexpressions (eg, the initializer, VLA
3533 // bounds) for side-effects on our behalf.
3534 if (auto *VD = dyn_cast<VarDecl>(D)) {
3535 // Registering a destructor is a side-effect.
3536 if (IncludePossibleEffects && VD->isThisDeclarationADefinition() &&
3537 VD->needsDestruction(Context))
3538 HasSideEffects = true;
3539 }
3540 }
3541
3542 void VisitDeclStmt(const DeclStmt *DS) {
3543 for (auto *D : DS->decls())
3544 VisitDecl(D);
3545 Inherited::VisitDeclStmt(DS);
3546 }
3547
3548 void VisitExpr(const Expr *E) {
3549 if (!HasSideEffects &&
3550 E->HasSideEffects(Context, IncludePossibleEffects))
3551 HasSideEffects = true;
3552 }
3553 };
3554}
3555
3557 bool IncludePossibleEffects) const {
3558 // In circumstances where we care about definite side effects instead of
3559 // potential side effects, we want to ignore expressions that are part of a
3560 // macro expansion as a potential side effect.
3561 if (!IncludePossibleEffects && getExprLoc().isMacroID())
3562 return false;
3563
3564 switch (getStmtClass()) {
3565 case NoStmtClass:
3566 #define ABSTRACT_STMT(Type)
3567 #define STMT(Type, Base) case Type##Class:
3568 #define EXPR(Type, Base)
3569 #include "clang/AST/StmtNodes.inc"
3570 llvm_unreachable("unexpected Expr kind");
3571
3572 case DependentScopeDeclRefExprClass:
3573 case CXXUnresolvedConstructExprClass:
3574 case CXXDependentScopeMemberExprClass:
3575 case UnresolvedLookupExprClass:
3576 case UnresolvedMemberExprClass:
3577 case PackExpansionExprClass:
3578 case SubstNonTypeTemplateParmPackExprClass:
3579 case FunctionParmPackExprClass:
3580 case TypoExprClass:
3581 case RecoveryExprClass:
3582 case CXXFoldExprClass:
3583 // Make a conservative assumption for dependent nodes.
3584 return IncludePossibleEffects;
3585
3586 case DeclRefExprClass:
3587 case ObjCIvarRefExprClass:
3588 case PredefinedExprClass:
3589 case IntegerLiteralClass:
3590 case FixedPointLiteralClass:
3591 case FloatingLiteralClass:
3592 case ImaginaryLiteralClass:
3593 case StringLiteralClass:
3594 case CharacterLiteralClass:
3595 case OffsetOfExprClass:
3596 case ImplicitValueInitExprClass:
3597 case UnaryExprOrTypeTraitExprClass:
3598 case AddrLabelExprClass:
3599 case GNUNullExprClass:
3600 case ArrayInitIndexExprClass:
3601 case NoInitExprClass:
3602 case CXXBoolLiteralExprClass:
3603 case CXXNullPtrLiteralExprClass:
3604 case CXXThisExprClass:
3605 case CXXScalarValueInitExprClass:
3606 case TypeTraitExprClass:
3607 case ArrayTypeTraitExprClass:
3608 case ExpressionTraitExprClass:
3609 case CXXNoexceptExprClass:
3610 case SizeOfPackExprClass:
3611 case ObjCStringLiteralClass:
3612 case ObjCEncodeExprClass:
3613 case ObjCBoolLiteralExprClass:
3614 case ObjCAvailabilityCheckExprClass:
3615 case CXXUuidofExprClass:
3616 case OpaqueValueExprClass:
3617 case SourceLocExprClass:
3618 case ConceptSpecializationExprClass:
3619 case RequiresExprClass:
3620 case SYCLUniqueStableNameExprClass:
3621 case PackIndexingExprClass:
3622 // These never have a side-effect.
3623 return false;
3624
3625 case ConstantExprClass:
3626 // FIXME: Move this into the "return false;" block above.
3627 return cast<ConstantExpr>(this)->getSubExpr()->HasSideEffects(
3628 Ctx, IncludePossibleEffects);
3629
3630 case CallExprClass:
3631 case CXXOperatorCallExprClass:
3632 case CXXMemberCallExprClass:
3633 case CUDAKernelCallExprClass:
3634 case UserDefinedLiteralClass: {
3635 // We don't know a call definitely has side effects, except for calls
3636 // to pure/const functions that definitely don't.
3637 // If the call itself is considered side-effect free, check the operands.
3638 const Decl *FD = cast<CallExpr>(this)->getCalleeDecl();
3639 bool IsPure = FD && (FD->hasAttr<ConstAttr>() || FD->hasAttr<PureAttr>());
3640 if (IsPure || !IncludePossibleEffects)
3641 break;
3642 return true;
3643 }
3644
3645 case BlockExprClass:
3646 case CXXBindTemporaryExprClass:
3647 if (!IncludePossibleEffects)
3648 break;
3649 return true;
3650
3651 case MSPropertyRefExprClass:
3652 case MSPropertySubscriptExprClass:
3653 case CompoundAssignOperatorClass:
3654 case VAArgExprClass:
3655 case AtomicExprClass:
3656 case CXXThrowExprClass:
3657 case CXXNewExprClass:
3658 case CXXDeleteExprClass:
3659 case CoawaitExprClass:
3660 case DependentCoawaitExprClass:
3661 case CoyieldExprClass:
3662 // These always have a side-effect.
3663 return true;
3664
3665 case StmtExprClass: {
3666 // StmtExprs have a side-effect if any substatement does.
3667 SideEffectFinder Finder(Ctx, IncludePossibleEffects);
3668 Finder.Visit(cast<StmtExpr>(this)->getSubStmt());
3669 return Finder.hasSideEffects();
3670 }
3671
3672 case ExprWithCleanupsClass:
3673 if (IncludePossibleEffects)
3674 if (cast<ExprWithCleanups>(this)->cleanupsHaveSideEffects())
3675 return true;
3676 break;
3677
3678 case ParenExprClass:
3679 case ArraySubscriptExprClass:
3680 case MatrixSubscriptExprClass:
3681 case ArraySectionExprClass:
3682 case OMPArrayShapingExprClass:
3683 case OMPIteratorExprClass:
3684 case MemberExprClass:
3685 case ConditionalOperatorClass:
3686 case BinaryConditionalOperatorClass:
3687 case CompoundLiteralExprClass:
3688 case ExtVectorElementExprClass:
3689 case DesignatedInitExprClass:
3690 case DesignatedInitUpdateExprClass:
3691 case ArrayInitLoopExprClass:
3692 case ParenListExprClass:
3693 case CXXPseudoDestructorExprClass:
3694 case CXXRewrittenBinaryOperatorClass:
3695 case CXXStdInitializerListExprClass:
3696 case SubstNonTypeTemplateParmExprClass:
3697 case MaterializeTemporaryExprClass:
3698 case ShuffleVectorExprClass:
3699 case ConvertVectorExprClass:
3700 case AsTypeExprClass:
3701 case CXXParenListInitExprClass:
3702 // These have a side-effect if any subexpression does.
3703 break;
3704
3705 case UnaryOperatorClass:
3706 if (cast<UnaryOperator>(this)->isIncrementDecrementOp())
3707 return true;
3708 break;
3709
3710 case BinaryOperatorClass:
3711 if (cast<BinaryOperator>(this)->isAssignmentOp())
3712 return true;
3713 break;
3714
3715 case InitListExprClass:
3716 // FIXME: The children for an InitListExpr doesn't include the array filler.
3717 if (const Expr *E = cast<InitListExpr>(this)->getArrayFiller())
3718 if (E->HasSideEffects(Ctx, IncludePossibleEffects))
3719 return true;
3720 break;
3721
3722 case GenericSelectionExprClass:
3723 return cast<GenericSelectionExpr>(this)->getResultExpr()->
3724 HasSideEffects(Ctx, IncludePossibleEffects);
3725
3726 case ChooseExprClass:
3727 return cast<ChooseExpr>(this)->getChosenSubExpr()->HasSideEffects(
3728 Ctx, IncludePossibleEffects);
3729
3730 case CXXDefaultArgExprClass:
3731 return cast<CXXDefaultArgExpr>(this)->getExpr()->HasSideEffects(
3732 Ctx, IncludePossibleEffects);
3733
3734 case CXXDefaultInitExprClass: {
3735 const FieldDecl *FD = cast<CXXDefaultInitExpr>(this)->getField();
3736 if (const Expr *E = FD->getInClassInitializer())
3737 return E->HasSideEffects(Ctx, IncludePossibleEffects);
3738 // If we've not yet parsed the initializer, assume it has side-effects.
3739 return true;
3740 }
3741
3742 case CXXDynamicCastExprClass: {
3743 // A dynamic_cast expression has side-effects if it can throw.
3744 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(this);
3745 if (DCE->getTypeAsWritten()->isReferenceType() &&
3746 DCE->getCastKind() == CK_Dynamic)
3747 return true;
3748 }
3749 [[fallthrough]];
3750 case ImplicitCastExprClass:
3751 case CStyleCastExprClass:
3752 case CXXStaticCastExprClass:
3753 case CXXReinterpretCastExprClass:
3754 case CXXConstCastExprClass:
3755 case CXXAddrspaceCastExprClass:
3756 case CXXFunctionalCastExprClass:
3757 case BuiltinBitCastExprClass: {
3758 // While volatile reads are side-effecting in both C and C++, we treat them
3759 // as having possible (not definite) side-effects. This allows idiomatic
3760 // code to behave without warning, such as sizeof(*v) for a volatile-
3761 // qualified pointer.
3762 if (!IncludePossibleEffects)
3763 break;
3764
3765 const CastExpr *CE = cast<CastExpr>(this);
3766 if (CE->getCastKind() == CK_LValueToRValue &&
3768 return true;
3769 break;
3770 }
3771
3772 case CXXTypeidExprClass:
3773 // typeid might throw if its subexpression is potentially-evaluated, so has
3774 // side-effects in that case whether or not its subexpression does.
3775 return cast<CXXTypeidExpr>(this)->isPotentiallyEvaluated();
3776
3777 case CXXConstructExprClass:
3778 case CXXTemporaryObjectExprClass: {
3779 const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
3780 if (!CE->getConstructor()->isTrivial() && IncludePossibleEffects)
3781 return true;
3782 // A trivial constructor does not add any side-effects of its own. Just look
3783 // at its arguments.
3784 break;
3785 }
3786
3787 case CXXInheritedCtorInitExprClass: {
3788 const auto *ICIE = cast<CXXInheritedCtorInitExpr>(this);
3789 if (!ICIE->getConstructor()->isTrivial() && IncludePossibleEffects)
3790 return true;
3791 break;
3792 }
3793
3794 case LambdaExprClass: {
3795 const LambdaExpr *LE = cast<LambdaExpr>(this);
3796 for (Expr *E : LE->capture_inits())
3797 if (E && E->HasSideEffects(Ctx, IncludePossibleEffects))
3798 return true;
3799 return false;
3800 }
3801
3802 case PseudoObjectExprClass: {
3803 // Only look for side-effects in the semantic form, and look past
3804 // OpaqueValueExpr bindings in that form.
3805 const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this);
3807 E = PO->semantics_end();
3808 I != E; ++I) {
3809 const Expr *Subexpr = *I;
3810 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Subexpr))
3811 Subexpr = OVE->getSourceExpr();
3812 if (Subexpr->HasSideEffects(Ctx, IncludePossibleEffects))
3813 return true;
3814 }
3815 return false;
3816 }
3817
3818 case ObjCBoxedExprClass:
3819 case ObjCArrayLiteralClass:
3820 case ObjCDictionaryLiteralClass:
3821 case ObjCSelectorExprClass:
3822 case ObjCProtocolExprClass:
3823 case ObjCIsaExprClass:
3824 case ObjCIndirectCopyRestoreExprClass:
3825 case ObjCSubscriptRefExprClass:
3826 case ObjCBridgedCastExprClass:
3827 case ObjCMessageExprClass:
3828 case ObjCPropertyRefExprClass:
3829 // FIXME: Classify these cases better.
3830 if (IncludePossibleEffects)
3831 return true;
3832 break;
3833 }
3834
3835 // Recurse to children.
3836 for (const Stmt *SubStmt : children())
3837 if (SubStmt &&
3838 cast<Expr>(SubStmt)->HasSideEffects(Ctx, IncludePossibleEffects))
3839 return true;
3840
3841 return false;
3842}
3843
3845 if (auto Call = dyn_cast<CallExpr>(this))
3846 return Call->getFPFeaturesInEffect(LO);
3847 if (auto UO = dyn_cast<UnaryOperator>(this))
3848 return UO->getFPFeaturesInEffect(LO);
3849 if (auto BO = dyn_cast<BinaryOperator>(this))
3850 return BO->getFPFeaturesInEffect(LO);
3851 if (auto Cast = dyn_cast<CastExpr>(this))
3852 return Cast->getFPFeaturesInEffect(LO);
3854}
3855
3856namespace {
3857 /// Look for a call to a non-trivial function within an expression.
3858 class NonTrivialCallFinder : public ConstEvaluatedExprVisitor<NonTrivialCallFinder>
3859 {
3861
3862 bool NonTrivial;
3863
3864 public:
3865 explicit NonTrivialCallFinder(const ASTContext &Context)
3866 : Inherited(Context), NonTrivial(false) { }
3867
3868 bool hasNonTrivialCall() const { return NonTrivial; }
3869
3870 void VisitCallExpr(const CallExpr *E) {
3871 if (const CXXMethodDecl *Method
3872 = dyn_cast_or_null<const CXXMethodDecl>(E->getCalleeDecl())) {
3873 if (Method->isTrivial()) {
3874 // Recurse to children of the call.
3875 Inherited::VisitStmt(E);
3876 return;
3877 }
3878 }
3879
3880 NonTrivial = true;
3881 }
3882
3883 void VisitCXXConstructExpr(const CXXConstructExpr *E) {
3884 if (E->getConstructor()->isTrivial()) {
3885 // Recurse to children of the call.
3886 Inherited::VisitStmt(E);
3887 return;
3888 }
3889
3890 NonTrivial = true;
3891 }
3892
3893 void VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
3894 // Destructor of the temporary might be null if destructor declaration
3895 // is not valid.
3896 if (const CXXDestructorDecl *DtorDecl =
3897 E->getTemporary()->getDestructor()) {
3898 if (DtorDecl->isTrivial()) {
3899 Inherited::VisitStmt(E);
3900 return;
3901 }
3902 }
3903
3904 NonTrivial = true;
3905 }
3906 };
3907}
3908
3909bool Expr::hasNonTrivialCall(const ASTContext &Ctx) const {
3910 NonTrivialCallFinder Finder(Ctx);
3911 Finder.Visit(this);
3912 return Finder.hasNonTrivialCall();
3913}
3914
3915/// isNullPointerConstant - C99 6.3.2.3p3 - Return whether this is a null
3916/// pointer constant or not, as well as the specific kind of constant detected.
3917/// Null pointer constants can be integer constant expressions with the
3918/// value zero, casts of zero to void*, nullptr (C++0X), or __null
3919/// (a GNU extension).
3923 if (isValueDependent() &&
3924 (!Ctx.getLangOpts().CPlusPlus11 || Ctx.getLangOpts().MSVCCompat)) {
3925 // Error-dependent expr should never be a null pointer.
3926 if (containsErrors())
3927 return NPCK_NotNull;
3928 switch (NPC) {
3930 llvm_unreachable("Unexpected value dependent expression!");
3932 if (isTypeDependent() || getType()->isIntegralType(Ctx))
3933 return NPCK_ZeroExpression;
3934 else
3935 return NPCK_NotNull;
3936
3938 return NPCK_NotNull;
3939 }
3940 }
3941
3942 // Strip off a cast to void*, if it exists. Except in C++.
3943 if (const ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(this)) {
3944 if (!Ctx.getLangOpts().CPlusPlus) {
3945 // Check that it is a cast to void*.
3946 if (const PointerType *PT = CE->getType()->getAs<PointerType>()) {
3947 QualType Pointee = PT->getPointeeType();
3948 Qualifiers Qs = Pointee.getQualifiers();
3949 // Only (void*)0 or equivalent are treated as nullptr. If pointee type
3950 // has non-default address space it is not treated as nullptr.
3951 // (__generic void*)0 in OpenCL 2.0 should not be treated as nullptr
3952 // since it cannot be assigned to a pointer to constant address space.
3953 if (Ctx.getLangOpts().OpenCL &&
3955 Qs.removeAddressSpace();
3956
3957 if (Pointee->isVoidType() && Qs.empty() && // to void*
3958 CE->getSubExpr()->getType()->isIntegerType()) // from int
3959 return CE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
3960 }
3961 }
3962 } else if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(this)) {
3963 // Ignore the ImplicitCastExpr type entirely.
3964 return ICE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
3965 } else if (const ParenExpr *PE = dyn_cast<ParenExpr>(this)) {
3966 // Accept ((void*)0) as a null pointer constant, as many other
3967 // implementations do.
3968 return PE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
3969 } else if (const GenericSelectionExpr *GE =
3970 dyn_cast<GenericSelectionExpr>(this)) {
3971 if (GE->isResultDependent())
3972 return NPCK_NotNull;
3973 return GE->getResultExpr()->isNullPointerConstant(Ctx, NPC);
3974 } else if (const ChooseExpr *CE = dyn_cast<ChooseExpr>(this)) {
3975 if (CE->isConditionDependent())
3976 return NPCK_NotNull;
3977 return CE->getChosenSubExpr()->isNullPointerConstant(Ctx, NPC);
3978 } else if (const CXXDefaultArgExpr *DefaultArg
3979 = dyn_cast<CXXDefaultArgExpr>(this)) {
3980 // See through default argument expressions.
3981 return DefaultArg->getExpr()->isNullPointerConstant(Ctx, NPC);
3982 } else if (const CXXDefaultInitExpr *DefaultInit
3983 = dyn_cast<CXXDefaultInitExpr>(this)) {
3984 // See through default initializer expressions.
3985 return DefaultInit->getExpr()->isNullPointerConstant(Ctx, NPC);
3986 } else if (isa<GNUNullExpr>(this)) {
3987 // The GNU __null extension is always a null pointer constant.
3988 return NPCK_GNUNull;
3989 } else if (const MaterializeTemporaryExpr *M
3990 = dyn_cast<MaterializeTemporaryExpr>(this)) {
3991 return M->getSubExpr()->isNullPointerConstant(Ctx, NPC);
3992 } else if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(this)) {
3993 if (const Expr *Source = OVE->getSourceExpr())
3994 return Source->isNullPointerConstant(Ctx, NPC);
3995 }
3996
3997 // If the expression has no type information, it cannot be a null pointer
3998 // constant.
3999 if (getType().isNull())
4000 return NPCK_NotNull;
4001
4002 // C++11/C23 nullptr_t is always a null pointer constant.
4003 if (getType()->isNullPtrType())
4004 return NPCK_CXX11_nullptr;
4005
4006 if (const RecordType *UT = getType()->getAsUnionType())
4007 if (!Ctx.getLangOpts().CPlusPlus11 &&
4008 UT && UT->getDecl()->hasAttr<TransparentUnionAttr>())
4009 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(this)){
4010 const Expr *InitExpr = CLE->getInitializer();
4011 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(InitExpr))
4012 return ILE->getInit(0)->isNullPointerConstant(Ctx, NPC);
4013 }
4014 // This expression must be an integer type.
4015 if (!getType()->isIntegerType() ||
4016 (Ctx.getLangOpts().CPlusPlus && getType()->isEnumeralType()))
4017 return NPCK_NotNull;
4018
4019 if (Ctx.getLangOpts().CPlusPlus11) {
4020 // C++11 [conv.ptr]p1: A null pointer constant is an integer literal with
4021 // value zero or a prvalue of type std::nullptr_t.
4022 // Microsoft mode permits C++98 rules reflecting MSVC behavior.
4023 const IntegerLiteral *Lit = dyn_cast<IntegerLiteral>(this);
4024 if (Lit && !Lit->getValue())
4025 return NPCK_ZeroLiteral;
4026 if (!Ctx.getLangOpts().MSVCCompat || !isCXX98IntegralConstantExpr(Ctx))
4027 return NPCK_NotNull;
4028 } else {
4029 // If we have an integer constant expression, we need to *evaluate* it and
4030 // test for the value 0.
4031 if (!isIntegerConstantExpr(Ctx))
4032 return NPCK_NotNull;
4033 }
4034
4035 if (EvaluateKnownConstInt(Ctx) != 0)
4036 return NPCK_NotNull;
4037
4038 if (isa<IntegerLiteral>(this))
4039 return NPCK_ZeroLiteral;
4040 return NPCK_ZeroExpression;
4041}
4042
4043/// If this expression is an l-value for an Objective C
4044/// property, find the underlying property reference expression.
4046 const Expr *E = this;
4047 while (true) {
4048 assert((E->isLValue() && E->getObjectKind() == OK_ObjCProperty) &&
4049 "expression is not a property reference");
4050 E = E->IgnoreParenCasts();
4051 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
4052 if (BO->getOpcode() == BO_Comma) {
4053 E = BO->getRHS();
4054 continue;
4055 }
4056 }
4057
4058 break;
4059 }
4060
4061 return cast<ObjCPropertyRefExpr>(E);
4062}
4063
4065 const Expr *E = IgnoreParenImpCasts();
4066
4067 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
4068 if (!DRE)
4069 return false;
4070
4071 const ImplicitParamDecl *Param = dyn_cast<ImplicitParamDecl>(DRE->getDecl());
4072 if (!Param)
4073 return false;
4074
4075 const ObjCMethodDecl *M = dyn_cast<ObjCMethodDecl>(Param->getDeclContext());
4076 if (!M)
4077 return false;
4078
4079 return M->getSelfDecl() == Param;
4080}
4081
4083 Expr *E = this->IgnoreParens();
4084
4085 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
4086 if (ICE->getCastKind() == CK_LValueToRValue ||
4087 (ICE->isGLValue() && ICE->getCastKind() == CK_NoOp))
4088 E = ICE->getSubExpr()->IgnoreParens();
4089 else
4090 break;
4091 }
4092
4093 if (MemberExpr *MemRef = dyn_cast<MemberExpr>(E))
4094 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemRef->getMemberDecl()))
4095 if (Field->isBitField())
4096 return Field;
4097
4098 if (ObjCIvarRefExpr *IvarRef = dyn_cast<ObjCIvarRefExpr>(E)) {
4099 FieldDecl *Ivar = IvarRef->getDecl();
4100 if (Ivar->isBitField())
4101 return Ivar;
4102 }
4103
4104 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E)) {
4105 if (FieldDecl *Field = dyn_cast<FieldDecl>(DeclRef->getDecl()))
4106 if (Field->isBitField())
4107 return Field;
4108
4109 if (BindingDecl *BD = dyn_cast<BindingDecl>(DeclRef->getDecl()))
4110 if (Expr *E = BD->getBinding())
4111 return E->getSourceBitField();
4112 }
4113
4114 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(E)) {
4115 if (BinOp->isAssignmentOp() && BinOp->getLHS())
4116 return BinOp->getLHS()->getSourceBitField();
4117
4118 if (BinOp->getOpcode() == BO_Comma && BinOp->getRHS())
4119 return BinOp->getRHS()->getSourceBitField();
4120 }
4121
4122 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E))
4123 if (UnOp->isPrefix() && UnOp->isIncrementDecrementOp())
4124 return UnOp->getSubExpr()->getSourceBitField();
4125
4126 return nullptr;
4127}
4128
4130 Expr *E = this->IgnoreParenImpCasts();
4131 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
4132 return dyn_cast<EnumConstantDecl>(DRE->getDecl());
4133 return nullptr;
4134}
4135
4137 // FIXME: Why do we not just look at the ObjectKind here?
4138 const Expr *E = this->IgnoreParens();
4139
4140 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
4141 if (ICE->isGLValue() && ICE->getCastKind() == CK_NoOp)
4142 E = ICE->getSubExpr()->IgnoreParens();
4143 else
4144 break;
4145 }
4146
4147 if (const ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(E))
4148 return ASE->getBase()->getType()->isVectorType();
4149
4150 if (isa<ExtVectorElementExpr>(E))
4151 return true;
4152
4153 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
4154 if (auto *BD = dyn_cast<BindingDecl>(DRE->getDecl()))
4155 if (auto *E = BD->getBinding())
4156 return E->refersToVectorElement();
4157
4158 return false;
4159}
4160
4162 const Expr *E = this->IgnoreParenImpCasts();
4163
4164 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
4165 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
4166 if (VD->getStorageClass() == SC_Register &&
4167 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
4168 return true;
4169
4170 return false;
4171}
4172
4173bool Expr::isSameComparisonOperand(const Expr* E1, const Expr* E2) {
4174 E1 = E1->IgnoreParens();
4175 E2 = E2->IgnoreParens();
4176
4177 if (E1->getStmtClass() != E2->getStmtClass())
4178 return false;
4179
4180 switch (E1->getStmtClass()) {
4181 default:
4182 return false;
4183 case CXXThisExprClass:
4184 return true;
4185 case DeclRefExprClass: {
4186 // DeclRefExpr without an ImplicitCastExpr can happen for integral
4187 // template parameters.
4188 const auto *DRE1 = cast<DeclRefExpr>(E1);
4189 const auto *DRE2 = cast<DeclRefExpr>(E2);
4190 return DRE1->isPRValue() && DRE2->isPRValue() &&
4191 DRE1->getDecl() == DRE2->getDecl();
4192 }
4193 case ImplicitCastExprClass: {
4194 // Peel off implicit casts.
4195 while (true) {
4196 const auto *ICE1 = dyn_cast<ImplicitCastExpr>(E1);
4197 const auto *ICE2 = dyn_cast<ImplicitCastExpr>(E2);
4198 if (!ICE1 || !ICE2)
4199 return false;
4200 if (ICE1->getCastKind() != ICE2->getCastKind())
4201 return false;
4202 E1 = ICE1->getSubExpr()->IgnoreParens();
4203 E2 = ICE2->getSubExpr()->IgnoreParens();
4204 // The final cast must be one of these types.
4205 if (ICE1->getCastKind() == CK_LValueToRValue ||
4206 ICE1->getCastKind() == CK_ArrayToPointerDecay ||
4207 ICE1->getCastKind() == CK_FunctionToPointerDecay) {
4208 break;
4209 }
4210 }
4211
4212 const auto *DRE1 = dyn_cast<DeclRefExpr>(E1);
4213 const auto *DRE2 = dyn_cast<DeclRefExpr>(E2);
4214 if (DRE1 && DRE2)
4215 return declaresSameEntity(DRE1->getDecl(), DRE2->getDecl());
4216
4217 const auto *Ivar1 = dyn_cast<ObjCIvarRefExpr>(E1);
4218 const auto *Ivar2 = dyn_cast<ObjCIvarRefExpr>(E2);
4219 if (Ivar1 && Ivar2) {
4220 return Ivar1->isFreeIvar() && Ivar2->isFreeIvar() &&
4221 declaresSameEntity(Ivar1->getDecl(), Ivar2->getDecl());
4222 }
4223
4224 const auto *Array1 = dyn_cast<ArraySubscriptExpr>(E1);
4225 const auto *Array2 = dyn_cast<ArraySubscriptExpr>(E2);
4226 if (Array1 && Array2) {
4227 if (!isSameComparisonOperand(Array1->getBase(), Array2->getBase()))
4228 return false;
4229
4230 auto Idx1 = Array1->getIdx();
4231 auto Idx2 = Array2->getIdx();
4232 const auto Integer1 = dyn_cast<IntegerLiteral>(Idx1);
4233 const auto Integer2 = dyn_cast<IntegerLiteral>(Idx2);
4234 if (Integer1 && Integer2) {
4235 if (!llvm::APInt::isSameValue(Integer1->getValue(),
4236 Integer2->getValue()))
4237 return false;
4238 } else {
4239 if (!isSameComparisonOperand(Idx1, Idx2))
4240 return false;
4241 }
4242
4243 return true;
4244 }
4245
4246 // Walk the MemberExpr chain.
4247 while (isa<MemberExpr>(E1) && isa<MemberExpr>(E2)) {
4248 const auto *ME1 = cast<MemberExpr>(E1);
4249 const auto *ME2 = cast<MemberExpr>(E2);
4250 if (!declaresSameEntity(ME1->getMemberDecl(), ME2->getMemberDecl()))
4251 return false;
4252 if (const auto *D = dyn_cast<VarDecl>(ME1->getMemberDecl()))
4253 if (D->isStaticDataMember())
4254 return true;
4255 E1 = ME1->getBase()->IgnoreParenImpCasts();
4256 E2 = ME2->getBase()->IgnoreParenImpCasts();
4257 }
4258
4259 if (isa<CXXThisExpr>(E1) && isa<CXXThisExpr>(E2))
4260 return true;
4261
4262 // A static member variable can end the MemberExpr chain with either
4263 // a MemberExpr or a DeclRefExpr.
4264 auto getAnyDecl = [](const Expr *E) -> const ValueDecl * {
4265 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
4266 return DRE->getDecl();
4267 if (const auto *ME = dyn_cast<MemberExpr>(E))
4268 return ME->getMemberDecl();
4269 return nullptr;
4270 };
4271
4272 const ValueDecl *VD1 = getAnyDecl(E1);
4273 const ValueDecl *VD2 = getAnyDecl(E2);
4274 return declaresSameEntity(VD1, VD2);
4275 }
4276 }
4277}
4278
4279/// isArrow - Return true if the base expression is a pointer to vector,
4280/// return false if the base expression is a vector.
4282 return getBase()->getType()->isPointerType();
4283}
4284
4286 if (const VectorType *VT = getType()->getAs<VectorType>())
4287 return VT->getNumElements();
4288 return 1;
4289}
4290
4291/// containsDuplicateElements - Return true if any element access is repeated.
4293 // FIXME: Refactor this code to an accessor on the AST node which returns the
4294 // "type" of component access, and share with code below and in Sema.
4295 StringRef Comp = Accessor->getName();
4296
4297 // Halving swizzles do not contain duplicate elements.
4298 if (Comp == "hi" || Comp == "lo" || Comp == "even" || Comp == "odd")
4299 return false;
4300
4301 // Advance past s-char prefix on hex swizzles.
4302 if (Comp[0] == 's' || Comp[0] == 'S')
4303 Comp = Comp.substr(1);
4304
4305 for (unsigned i = 0, e = Comp.size(); i != e; ++i)
4306 if (Comp.substr(i + 1).contains(Comp[i]))
4307 return true;
4308
4309 return false;
4310}
4311
4312/// getEncodedElementAccess - We encode the fields as a llvm ConstantArray.
4314 SmallVectorImpl<uint32_t> &Elts) const {
4315 StringRef Comp = Accessor->getName();
4316 bool isNumericAccessor = false;
4317 if (Comp[0] == 's' || Comp[0] == 'S') {
4318 Comp = Comp.substr(1);
4319 isNumericAccessor = true;
4320 }
4321
4322 bool isHi = Comp == "hi";
4323 bool isLo = Comp == "lo";
4324 bool isEven = Comp == "even";
4325 bool isOdd = Comp == "odd";
4326
4327 for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
4328 uint64_t Index;
4329
4330 if (isHi)
4331 Index = e + i;
4332 else if (isLo)
4333 Index = i;
4334 else if (isEven)
4335 Index = 2 * i;
4336 else if (isOdd)
4337 Index = 2 * i + 1;
4338 else
4339 Index = ExtVectorType::getAccessorIdx(Comp[i], isNumericAccessor);
4340
4341 Elts.push_back(Index);
4342 }
4343}
4344
4347 SourceLocation RP)
4348 : Expr(ShuffleVectorExprClass, Type, VK_PRValue, OK_Ordinary),
4349 BuiltinLoc(BLoc), RParenLoc(RP), NumExprs(args.size()) {
4350 SubExprs = new (C) Stmt*[args.size()];
4351 for (unsigned i = 0; i != args.size(); i++)
4352 SubExprs[i] = args[i];
4353
4355}
4356
4358 if (SubExprs) C.Deallocate(SubExprs);
4359
4360 this->NumExprs = Exprs.size();
4361 SubExprs = new (C) Stmt*[NumExprs];
4362 memcpy(SubExprs, Exprs.data(), sizeof(Expr *) * Exprs.size());
4363}
4364
4365GenericSelectionExpr::GenericSelectionExpr(
4366 const ASTContext &, SourceLocation GenericLoc, Expr *ControllingExpr,
4367 ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
4368 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4369 bool ContainsUnexpandedParameterPack, unsigned ResultIndex)
4370 : Expr(GenericSelectionExprClass, AssocExprs[ResultIndex]->getType(),
4371 AssocExprs[ResultIndex]->getValueKind(),
4372 AssocExprs[ResultIndex]->getObjectKind()),
4373 NumAssocs(AssocExprs.size()), ResultIndex(ResultIndex),
4374 IsExprPredicate(true), DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
4375 assert(AssocTypes.size() == AssocExprs.size() &&
4376 "Must have the same number of association expressions"
4377 " and TypeSourceInfo!");
4378 assert(ResultIndex < NumAssocs && "ResultIndex is out-of-bounds!");
4379
4380 GenericSelectionExprBits.GenericLoc = GenericLoc;
4381 getTrailingObjects<Stmt *>()[getIndexOfControllingExpression()] =
4382 ControllingExpr;
4383 std::copy(AssocExprs.begin(), AssocExprs.end(),
4384 getTrailingObjects<Stmt *>() + getIndexOfStartOfAssociatedExprs());
4385 std::copy(AssocTypes.begin(), AssocTypes.end(),
4386 getTrailingObjects<TypeSourceInfo *>() +
4387 getIndexOfStartOfAssociatedTypes());
4388
4389 setDependence(computeDependence(this, ContainsUnexpandedParameterPack));
4390}
4391
4392GenericSelectionExpr::GenericSelectionExpr(
4393 const ASTContext &, SourceLocation GenericLoc,
4394 TypeSourceInfo *ControllingType, ArrayRef<TypeSourceInfo *> AssocTypes,
4395 ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,
4396 SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack,
4397 unsigned ResultIndex)
4398 : Expr(GenericSelectionExprClass, AssocExprs[ResultIndex]->getType(),
4399 AssocExprs[ResultIndex]->getValueKind(),
4400 AssocExprs[ResultIndex]->getObjectKind()),
4401 NumAssocs(AssocExprs.size()), ResultIndex(ResultIndex),
4402 IsExprPredicate(false), DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
4403 assert(AssocTypes.size() == AssocExprs.size() &&
4404 "Must have the same number of association expressions"
4405 " and TypeSourceInfo!");
4406 assert(ResultIndex < NumAssocs && "ResultIndex is out-of-bounds!");
4407
4408 GenericSelectionExprBits.GenericLoc = GenericLoc;
4409 getTrailingObjects<TypeSourceInfo *>()[getIndexOfControllingType()] =
4410 ControllingType;
4411 std::copy(AssocExprs.begin(), AssocExprs.end(),
4412 getTrailingObjects<Stmt *>() + getIndexOfStartOfAssociatedExprs());
4413 std::copy(AssocTypes.begin(), AssocTypes.end(),
4414 getTrailingObjects<TypeSourceInfo *>() +
4415 getIndexOfStartOfAssociatedTypes());
4416
4417 setDependence(computeDependence(this, ContainsUnexpandedParameterPack));
4418}
4419
4420GenericSelectionExpr::GenericSelectionExpr(
4421 const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,
4422 ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
4423 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4424 bool ContainsUnexpandedParameterPack)
4425 : Expr(GenericSelectionExprClass, Context.DependentTy, VK_PRValue,
4426 OK_Ordinary),
4427 NumAssocs(AssocExprs.size()), ResultIndex(ResultDependentIndex),
4428 IsExprPredicate(true), DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
4429 assert(AssocTypes.size() == AssocExprs.size() &&
4430 "Must have the same number of association expressions"
4431 " and TypeSourceInfo!");
4432
4433 GenericSelectionExprBits.GenericLoc = GenericLoc;
4434 getTrailingObjects<Stmt *>()[getIndexOfControllingExpression()] =
4435 ControllingExpr;
4436 std::copy(AssocExprs.begin(), AssocExprs.end(),
4437 getTrailingObjects<Stmt *>() + getIndexOfStartOfAssociatedExprs());
4438 std::copy(AssocTypes.begin(), AssocTypes.end(),
4439 getTrailingObjects<TypeSourceInfo *>() +
4440 getIndexOfStartOfAssociatedTypes());
4441
4442 setDependence(computeDependence(this, ContainsUnexpandedParameterPack));
4443}
4444
4445GenericSelectionExpr::GenericSelectionExpr(
4446 const ASTContext &Context, SourceLocation GenericLoc,
4447 TypeSourceInfo *ControllingType, ArrayRef<TypeSourceInfo *> AssocTypes,
4448 ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,
4449 SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack)
4450 : Expr(GenericSelectionExprClass, Context.DependentTy, VK_PRValue,
4451 OK_Ordinary),
4452 NumAssocs(AssocExprs.size()), ResultIndex(ResultDependentIndex),
4453 IsExprPredicate(false), DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
4454 assert(AssocTypes.size() == AssocExprs.size() &&
4455 "Must have the same number of association expressions"
4456 " and TypeSourceInfo!");
4457
4458 GenericSelectionExprBits.GenericLoc = GenericLoc;
4459 getTrailingObjects<TypeSourceInfo *>()[getIndexOfControllingType()] =
4460 ControllingType;
4461 std::copy(AssocExprs.begin(), AssocExprs.end(),
4462 getTrailingObjects<Stmt *>() + getIndexOfStartOfAssociatedExprs());
4463 std::copy(AssocTypes.begin(), AssocTypes.end(),
4464 getTrailingObjects<TypeSourceInfo *>() +
4465 getIndexOfStartOfAssociatedTypes());
4466
4467 setDependence(computeDependence(this, ContainsUnexpandedParameterPack));
4468}
4469
4470GenericSelectionExpr::GenericSelectionExpr(EmptyShell Empty, unsigned NumAssocs)
4471 : Expr(GenericSelectionExprClass, Empty), NumAssocs(NumAssocs) {}
4472
4474 const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,
4475 ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
4476 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4477 bool ContainsUnexpandedParameterPack, unsigned ResultIndex) {
4478 unsigned NumAssocs = AssocExprs.size();
4479 void *Mem = Context.Allocate(
4480 totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
4481 alignof(GenericSelectionExpr));
4482 return new (Mem) GenericSelectionExpr(
4483 Context, GenericLoc, ControllingExpr, AssocTypes, AssocExprs, DefaultLoc,
4484 RParenLoc, ContainsUnexpandedParameterPack, ResultIndex);
4485}
4486
4488 const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,
4489 ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
4490 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4491 bool ContainsUnexpandedParameterPack) {
4492 unsigned NumAssocs = AssocExprs.size();
4493 void *Mem = Context.Allocate(
4494 totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
4495 alignof(GenericSelectionExpr));
4496 return new (Mem) GenericSelectionExpr(
4497 Context, GenericLoc, ControllingExpr, AssocTypes, AssocExprs, DefaultLoc,
4498 RParenLoc, ContainsUnexpandedParameterPack);
4499}
4500
4502 const ASTContext &Context, SourceLocation GenericLoc,
4503 TypeSourceInfo *ControllingType, ArrayRef<TypeSourceInfo *> AssocTypes,
4504 ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,
4505 SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack,
4506 unsigned ResultIndex) {
4507 unsigned NumAssocs = AssocExprs.size();
4508 void *Mem = Context.Allocate(
4509 totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
4510 alignof(GenericSelectionExpr));
4511 return new (Mem) GenericSelectionExpr(
4512 Context, GenericLoc, ControllingType, AssocTypes, AssocExprs, DefaultLoc,
4513 RParenLoc, ContainsUnexpandedParameterPack, ResultIndex);
4514}
4515
4517 const ASTContext &Context, SourceLocation GenericLoc,
4518 TypeSourceInfo *ControllingType, ArrayRef<TypeSourceInfo *> AssocTypes,
4519 ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,
4520 SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack) {
4521 unsigned NumAssocs = AssocExprs.size();
4522 void *Mem = Context.Allocate(
4523 totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
4524 alignof(GenericSelectionExpr));
4525 return new (Mem) GenericSelectionExpr(
4526 Context, GenericLoc, ControllingType, AssocTypes, AssocExprs, DefaultLoc,
4527 RParenLoc, ContainsUnexpandedParameterPack);
4528}
4529
4532 unsigned NumAssocs) {
4533 void *Mem = Context.Allocate(
4534 totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
4535 alignof(GenericSelectionExpr));
4536 return new (Mem) GenericSelectionExpr(EmptyShell(), NumAssocs);
4537}
4538
4539//===----------------------------------------------------------------------===//
4540// DesignatedInitExpr
4541//===----------------------------------------------------------------------===//
4542
4544 assert(isFieldDesignator() && "Only valid on a field designator");
4545 if (FieldInfo.NameOrField & 0x01)
4546 return reinterpret_cast<IdentifierInfo *>(FieldInfo.NameOrField & ~0x01);
4547 return getFieldDecl()->getIdentifier();
4548}
4549
4550DesignatedInitExpr::DesignatedInitExpr(const ASTContext &C, QualType Ty,
4551 llvm::ArrayRef<Designator> Designators,
4552 SourceLocation EqualOrColonLoc,
4553 bool GNUSyntax,
4554 ArrayRef<Expr *> IndexExprs, Expr *Init)
4555 : Expr(DesignatedInitExprClass, Ty, Init->getValueKind(),
4556 Init->getObjectKind()),
4557 EqualOrColonLoc(EqualOrColonLoc), GNUSyntax(GNUSyntax),
4558 NumDesignators(Designators.size()), NumSubExprs(IndexExprs.size() + 1) {
4559 this->Designators = new (C) Designator[NumDesignators];
4560
4561 // Record the initializer itself.
4562 child_iterator Child = child_begin();
4563 *Child++ = Init;
4564
4565 // Copy the designators and their subexpressions, computing
4566 // value-dependence along the way.
4567 unsigned IndexIdx = 0;
4568 for (unsigned I = 0; I != NumDesignators; ++I) {
4569 this->Designators[I] = Designators[I];
4570 if (this->Designators[I].isArrayDesignator()) {
4571 // Copy the index expressions into permanent storage.
4572 *Child++ = IndexExprs[IndexIdx++];
4573 } else if (this->Designators[I].isArrayRangeDesignator()) {
4574 // Copy the start/end expressions into permanent storage.
4575 *Child++ = IndexExprs[IndexIdx++];
4576 *Child++ = IndexExprs[IndexIdx++];
4577 }
4578 }
4579
4580 assert(IndexIdx == IndexExprs.size() && "Wrong number of index expressions");
4582}
4583
4586 llvm::ArrayRef<Designator> Designators,
4587 ArrayRef<Expr*> IndexExprs,
4588 SourceLocation ColonOrEqualLoc,
4589 bool UsesColonSyntax, Expr *Init) {
4590 void *Mem = C.Allocate(totalSizeToAlloc<Stmt *>(IndexExprs.size() + 1),
4591 alignof(DesignatedInitExpr));
4592 return new (Mem) DesignatedInitExpr(C, C.VoidTy, Designators,
4593 ColonOrEqualLoc, UsesColonSyntax,
4594 IndexExprs, Init);
4595}
4596
4598 unsigned NumIndexExprs) {
4599 void *Mem = C.Allocate(totalSizeToAlloc<Stmt *>(NumIndexExprs + 1),
4600 alignof(DesignatedInitExpr));
4601 return new (Mem) DesignatedInitExpr(NumIndexExprs + 1);
4602}
4603
4605 const Designator *Desigs,
4606 unsigned NumDesigs) {
4607 Designators = new (C) Designator[NumDesigs];
4608 NumDesignators = NumDesigs;
4609 for (unsigned I = 0; I != NumDesigs; ++I)
4610 Designators[I] = Desigs[I];
4611}
4612
4614 DesignatedInitExpr *DIE = const_cast<DesignatedInitExpr*>(this);
4615 if (size() == 1)
4616 return DIE->getDesignator(0)->getSourceRange();
4617 return SourceRange(DIE->getDesignator(0)->getBeginLoc(),
4618 DIE->getDesignator(size() - 1)->getEndLoc());
4619}
4620
4622 auto *DIE = const_cast<DesignatedInitExpr *>(this);
4623 Designator &First = *DIE->getDesignator(0);
4624 if (First.isFieldDesignator()) {
4625 // Skip past implicit designators for anonymous structs/unions, since
4626 // these do not have valid source locations.
4627 for (unsigned int i = 0; i < DIE->size(); i++) {
4628 Designator &Des = *DIE->getDesignator(i);
4629 SourceLocation retval = GNUSyntax ? Des.getFieldLoc() : Des.getDotLoc();
4630 if (!retval.isValid())
4631 continue;
4632 return retval;
4633 }
4634 }
4635 return First.getLBracketLoc();
4636}
4637
4639 return getInit()->getEndLoc();
4640}
4641
4643 assert(D.isArrayDesignator() && "Requires array designator");
4644 return getSubExpr(D.getArrayIndex() + 1);
4645}
4646
4648 assert(D.isArrayRangeDesignator() && "Requires array range designator");
4649 return getSubExpr(D.getArrayIndex() + 1);
4650}
4651
4653 assert(D.isArrayRangeDesignator() && "Requires array range designator");
4654 return getSubExpr(D.getArrayIndex() + 2);
4655}
4656
4657/// Replaces the designator at index @p Idx with the series
4658/// of designators in [First, Last).
4660 const Designator *First,
4661 const Designator *Last) {
4662 unsigned NumNewDesignators = Last - First;
4663 if (NumNewDesignators == 0) {
4664 std::copy_backward(Designators + Idx + 1,
4665 Designators + NumDesignators,
4666 Designators + Idx);
4667 --NumNewDesignators;
4668 return;
4669 }
4670 if (NumNewDesignators == 1) {
4671 Designators[Idx] = *First;
4672 return;
4673 }
4674
4675 Designator *NewDesignators
4676 = new (C) Designator[NumDesignators - 1 + NumNewDesignators];
4677 std::copy(Designators, Designators + Idx, NewDesignators);
4678 std::copy(First, Last, NewDesignators + Idx);
4679 std::copy(Designators + Idx + 1, Designators + NumDesignators,
4680 NewDesignators + Idx + NumNewDesignators);
4681 Designators = NewDesignators;
4682 NumDesignators = NumDesignators - 1 + NumNewDesignators;
4683}
4684
4686 SourceLocation lBraceLoc,
4687 Expr *baseExpr,
4688 SourceLocation rBraceLoc)
4689 : Expr(DesignatedInitUpdateExprClass, baseExpr->getType(), VK_PRValue,
4690 OK_Ordinary) {
4691 BaseAndUpdaterExprs[0] = baseExpr;
4692
4693 InitListExpr *ILE =
4694 new (C) InitListExpr(C, lBraceLoc, std::nullopt, rBraceLoc);
4695 ILE->setType(baseExpr->getType());
4696 BaseAndUpdaterExprs[1] = ILE;
4697
4698 // FIXME: this is wrong, set it correctly.
4699 setDependence(ExprDependence::None);
4700}
4701
4703 return getBase()->getBeginLoc();
4704}
4705
4707 return getBase()->getEndLoc();
4708}
4709
4710ParenListExpr::ParenListExpr(SourceLocation LParenLoc, ArrayRef<Expr *> Exprs,
4711 SourceLocation RParenLoc)
4712 : Expr(ParenListExprClass, QualType(), VK_PRValue, OK_Ordinary),
4713 LParenLoc(LParenLoc), RParenLoc(RParenLoc) {
4714 ParenListExprBits.NumExprs = Exprs.size();
4715
4716 for (unsigned I = 0, N = Exprs.size(); I != N; ++I)
4717 getTrailingObjects<Stmt *>()[I] = Exprs[I];
4719}
4720
4721ParenListExpr::ParenListExpr(EmptyShell Empty, unsigned NumExprs)
4722 : Expr(ParenListExprClass, Empty) {
4723 ParenListExprBits.NumExprs = NumExprs;
4724}
4725
4727 SourceLocation LParenLoc,
4728 ArrayRef<Expr *> Exprs,
4729 SourceLocation RParenLoc) {
4730 void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *>(Exprs.size()),
4731 alignof(ParenListExpr));
4732 return new (Mem) ParenListExpr(LParenLoc, Exprs, RParenLoc);
4733}
4734
4736 unsigned NumExprs) {
4737 void *Mem =
4738 Ctx.Allocate(totalSizeToAlloc<Stmt *>(NumExprs), alignof(ParenListExpr));
4739 return new (Mem) ParenListExpr(EmptyShell(), NumExprs);
4740}
4741
4743 Opcode opc, QualType ResTy, ExprValueKind VK,
4745 FPOptionsOverride FPFeatures)
4746 : Expr(BinaryOperatorClass, ResTy, VK, OK) {
4747 BinaryOperatorBits.Opc = opc;
4748 assert(!isCompoundAssignmentOp() &&
4749 "Use CompoundAssignOperator for compound assignments");
4750 BinaryOperatorBits.OpLoc = opLoc;
4751 SubExprs[LHS] = lhs;
4752 SubExprs[RHS] = rhs;
4753 BinaryOperatorBits.HasFPFeatures = FPFeatures.requiresTrailingStorage();
4754 if (hasStoredFPFeatures())
4755 setStoredFPFeatures(FPFeatures);
4757}
4758
4760 Opcode opc, QualType ResTy, ExprValueKind VK,
4762 FPOptionsOverride FPFeatures, bool dead2)
4763 : Expr(CompoundAssignOperatorClass, ResTy, VK, OK) {
4764 BinaryOperatorBits.Opc = opc;
4765 assert(isCompoundAssignmentOp() &&
4766 "Use CompoundAssignOperator for compound assignments");
4767 BinaryOperatorBits.OpLoc = opLoc;
4768 SubExprs[LHS] = lhs;
4769 SubExprs[RHS] = rhs;
4770 BinaryOperatorBits.HasFPFeatures = FPFeatures.requiresTrailingStorage();
4771 if (hasStoredFPFeatures())
4772 setStoredFPFeatures(FPFeatures);
4774}
4775
4777 bool HasFPFeatures) {
4778 unsigned Extra = sizeOfTrailingObjects(HasFPFeatures);
4779 void *Mem =
4780 C.Allocate(sizeof(BinaryOperator) + Extra, alignof(BinaryOperator));
4781 return new (Mem) BinaryOperator(EmptyShell());
4782}
4783
4785 Expr *rhs, Opcode opc, QualType ResTy,
4787 SourceLocation opLoc,
4788 FPOptionsOverride FPFeatures) {
4789 bool HasFPFeatures = FPFeatures.requiresTrailingStorage();
4790 unsigned Extra = sizeOfTrailingObjects(HasFPFeatures);
4791 void *Mem =
4792 C.Allocate(sizeof(BinaryOperator) + Extra, alignof(BinaryOperator));
4793 return new (Mem)
4794 BinaryOperator(C, lhs, rhs, opc, ResTy, VK, OK, opLoc, FPFeatures);
4795}
4796
4799 unsigned Extra = sizeOfTrailingObjects(HasFPFeatures);
4800 void *Mem = C.Allocate(sizeof(CompoundAssignOperator) + Extra,
4801 alignof(CompoundAssignOperator));
4802 return new (Mem) CompoundAssignOperator(C, EmptyShell(), HasFPFeatures);
4803}
4804
4807 Opcode opc, QualType ResTy, ExprValueKind VK,
4809 FPOptionsOverride FPFeatures,
4810 QualType CompLHSType, QualType CompResultType) {
4811 bool HasFPFeatures = FPFeatures.requiresTrailingStorage();
4812 unsigned Extra = sizeOfTrailingObjects(HasFPFeatures);
4813 void *Mem = C.Allocate(sizeof(CompoundAssignOperator) + Extra,
4814 alignof(CompoundAssignOperator));
4815 return new (Mem)
4816 CompoundAssignOperator(C, lhs, rhs, opc, ResTy, VK, OK, opLoc, FPFeatures,
4817 CompLHSType, CompResultType);
4818}
4819
4821 bool hasFPFeatures) {
4822 void *Mem = C.Allocate(totalSizeToAlloc<FPOptionsOverride>(hasFPFeatures),
4823 alignof(UnaryOperator));
4824 return new (Mem) UnaryOperator(hasFPFeatures, EmptyShell());
4825}
4826
4829 SourceLocation l, bool CanOverflow,
4830 FPOptionsOverride FPFeatures)
4831 : Expr(UnaryOperatorClass, type, VK, OK), Val(input) {
4832 UnaryOperatorBits.Opc = opc;
4833 UnaryOperatorBits.CanOverflow = CanOverflow;
4834 UnaryOperatorBits.Loc = l;
4835 UnaryOperatorBits.HasFPFeatures = FPFeatures.requiresTrailingStorage();
4836 if (hasStoredFPFeatures())
4837 setStoredFPFeatures(FPFeatures);
4838 setDependence(computeDependence(this, Ctx));
4839}
4840
4842 Opcode opc, QualType type,
4844 SourceLocation l, bool CanOverflow,
4845 FPOptionsOverride FPFeatures) {
4846 bool HasFPFeatures = FPFeatures.requiresTrailingStorage();
4847 unsigned Size = totalSizeToAlloc<FPOptionsOverride>(HasFPFeatures);
4848 void *Mem = C.Allocate(Size, alignof(UnaryOperator));
4849 return new (Mem)
4850 UnaryOperator(C, input, opc, type, VK, OK, l, CanOverflow, FPFeatures);
4851}
4852
4854 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(e))
4855 e = ewc->getSubExpr();
4856 if (const MaterializeTemporaryExpr *m = dyn_cast<MaterializeTemporaryExpr>(e))
4857 e = m->getSubExpr();
4858 e = cast<CXXConstructExpr>(e)->getArg(0);
4859 while (const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
4860 e = ice->getSubExpr();
4861 return cast<OpaqueValueExpr>(e);
4862}
4863
4865 EmptyShell sh,
4866 unsigned numSemanticExprs) {
4867 void *buffer =
4868 Context.Allocate(totalSizeToAlloc<Expr *>(1 + numSemanticExprs),
4869 alignof(PseudoObjectExpr));
4870 return new(buffer) PseudoObjectExpr(sh, numSemanticExprs);
4871}
4872
4873PseudoObjectExpr::PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs)
4874 : Expr(PseudoObjectExprClass, shell) {
4875 PseudoObjectExprBits.NumSubExprs = numSemanticExprs + 1;
4876}
4877
4879 ArrayRef<Expr*> semantics,
4880 unsigned resultIndex) {
4881 assert(syntax && "no syntactic expression!");
4882 assert(semantics.size() && "no semantic expressions!");
4883
4884 QualType type;
4885 ExprValueKind VK;
4886 if (resultIndex == NoResult) {
4887 type = C.VoidTy;
4888 VK = VK_PRValue;
4889 } else {
4890 assert(resultIndex < semantics.size());
4891 type = semantics[resultIndex]->getType();
4892 VK = semantics[resultIndex]->getValueKind();
4893 assert(semantics[resultIndex]->getObjectKind() == OK_Ordinary);
4894 }
4895
4896 void *buffer = C.Allocate(totalSizeToAlloc<Expr *>(semantics.size() + 1),
4897 alignof(PseudoObjectExpr));
4898 return new(buffer) PseudoObjectExpr(type, VK, syntax, semantics,
4899 resultIndex);
4900}
4901
4902PseudoObjectExpr::PseudoObjectExpr(QualType type, ExprValueKind VK,
4903 Expr *syntax, ArrayRef<Expr *> semantics,
4904 unsigned resultIndex)
4905 : Expr(PseudoObjectExprClass, type, VK, OK_Ordinary) {
4906 PseudoObjectExprBits.NumSubExprs = semantics.size() + 1;
4907 PseudoObjectExprBits.ResultIndex = resultIndex + 1;
4908
4909 for (unsigned i = 0, e = semantics.size() + 1; i != e; ++i) {
4910 Expr *E = (i == 0 ? syntax : semantics[i-1]);
4911 getSubExprsBuffer()[i] = E;
4912
4913 if (isa<OpaqueValueExpr>(E))
4914 assert(cast<OpaqueValueExpr>(E)->getSourceExpr() != nullptr &&
4915 "opaque-value semantic expressions for pseudo-object "
4916 "operations must have sources");
4917 }
4918
4920}
4921
4922//===----------------------------------------------------------------------===//
4923// Child Iterators for iterating over subexpressions/substatements
4924//===----------------------------------------------------------------------===//
4925
4926// UnaryExprOrTypeTraitExpr
4928 const_child_range CCR =
4929 const_cast<const UnaryExprOrTypeTraitExpr *>(this)->children();
4930 return child_range(cast_away_const(CCR.begin()), cast_away_const(CCR.end()));
4931}
4932
4934 // If this is of a type and the type is a VLA type (and not a typedef), the
4935 // size expression of the VLA needs to be treated as an executable expression.
4936 // Why isn't this weirdness documented better in StmtIterator?
4937 if (isArgumentType()) {
4938 if (const VariableArrayType *T =
4939 dyn_cast<VariableArrayType>(getArgumentType().getTypePtr()))
4942 }
4943 return const_child_range(&Argument.Ex, &Argument.Ex + 1);
4944}
4945
4947 AtomicOp op, SourceLocation RP)
4948 : Expr(AtomicExprClass, t, VK_PRValue, OK_Ordinary),
4949 NumSubExprs(args.size()), BuiltinLoc(BLoc), RParenLoc(RP), Op(op) {
4950 assert(args.size() == getNumSubExprs(op) && "wrong number of subexpressions");
4951 for (unsigned i = 0; i != args.size(); i++)
4952 SubExprs[i] = args[i];
4954}
4955
4957 switch (Op) {
4958 case AO__c11_atomic_init:
4959 case AO__opencl_atomic_init:
4960 case AO__c11_atomic_load:
4961 case AO__atomic_load_n:
4962 return 2;
4963
4964 case AO__scoped_atomic_load_n:
4965 case AO__opencl_atomic_load:
4966 case AO__hip_atomic_load:
4967 case AO__c11_atomic_store:
4968 case AO__c11_atomic_exchange:
4969 case AO__atomic_load:
4970 case AO__atomic_store:
4971 case AO__atomic_store_n:
4972 case AO__atomic_exchange_n:
4973 case AO__c11_atomic_fetch_add:
4974 case AO__c11_atomic_fetch_sub:
4975 case AO__c11_atomic_fetch_and:
4976 case AO__c11_atomic_fetch_or:
4977 case AO__c11_atomic_fetch_xor:
4978 case AO__c11_atomic_fetch_nand:
4979 case AO__c11_atomic_fetch_max:
4980 case AO__c11_atomic_fetch_min:
4981 case AO__atomic_fetch_add:
4982 case AO__atomic_fetch_sub:
4983 case AO__atomic_fetch_and:
4984 case AO__atomic_fetch_or:
4985 case AO__atomic_fetch_xor:
4986 case AO__atomic_fetch_nand:
4987 case AO__atomic_add_fetch:
4988 case AO__atomic_sub_fetch:
4989 case AO__atomic_and_fetch:
4990 case AO__atomic_or_fetch:
4991 case AO__atomic_xor_fetch:
4992 case AO__atomic_nand_fetch:
4993 case AO__atomic_min_fetch:
4994 case AO__atomic_max_fetch:
4995 case AO__atomic_fetch_min:
4996 case AO__atomic_fetch_max:
4997 return 3;
4998
4999 case AO__scoped_atomic_load:
5000 case AO__scoped_atomic_store:
5001 case AO__scoped_atomic_store_n:
5002 case AO__scoped_atomic_fetch_add:
5003 case AO__scoped_atomic_fetch_sub:
5004 case AO__scoped_atomic_fetch_and:
5005 case AO__scoped_atomic_fetch_or:
5006 case AO__scoped_atomic_fetch_xor:
5007 case AO__scoped_atomic_fetch_nand:
5008 case AO__scoped_atomic_add_fetch:
5009 case AO__scoped_atomic_sub_fetch:
5010 case AO__scoped_atomic_and_fetch:
5011 case AO__scoped_atomic_or_fetch:
5012 case AO__scoped_atomic_xor_fetch:
5013 case AO__scoped_atomic_nand_fetch:
5014 case AO__scoped_atomic_min_fetch:
5015 case AO__scoped_atomic_max_fetch:
5016 case AO__scoped_atomic_fetch_min:
5017 case AO__scoped_atomic_fetch_max:
5018 case AO__scoped_atomic_exchange_n:
5019 case AO__hip_atomic_exchange:
5020 case AO__hip_atomic_fetch_add:
5021 case AO__hip_atomic_fetch_sub:
5022 case AO__hip_atomic_fetch_and:
5023 case AO__hip_atomic_fetch_or:
5024 case AO__hip_atomic_fetch_xor:
5025 case AO__hip_atomic_fetch_min:
5026 case AO__hip_atomic_fetch_max:
5027 case AO__opencl_atomic_store:
5028 case AO__hip_atomic_store:
5029 case AO__opencl_atomic_exchange: