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()->isRecordType());
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 switch (getStmtClass()) {
268 case Stmt::NoStmtClass: llvm_unreachable("statement without class");
269#define ABSTRACT_STMT(type)
270#define STMT(type, base) \
271 case Stmt::type##Class: break;
272#define EXPR(type, base) \
273 case Stmt::type##Class: return getExprLocImpl<type>(this, &type::getExprLoc);
274#include "clang/AST/StmtNodes.inc"
275 }
276 llvm_unreachable("unknown expression kind");
277}
278
279//===----------------------------------------------------------------------===//
280// Primary Expressions.
281//===----------------------------------------------------------------------===//
282
284 assert((Kind == ConstantResultStorageKind::APValue ||
287 "Invalid StorageKind Value");
288 (void)Kind;
289}
290
292 switch (Value.getKind()) {
293 case APValue::None:
296 case APValue::Int:
297 if (!Value.getInt().needsCleanup())
299 [[fallthrough]];
300 default:
302 }
303}
304
307 if (T->isIntegralOrEnumerationType() && Context.getTypeInfo(T).Width <= 64)
310}
311
312ConstantExpr::ConstantExpr(Expr *SubExpr, ConstantResultStorageKind StorageKind,
313 bool IsImmediateInvocation)
314 : FullExpr(ConstantExprClass, SubExpr) {
315 ConstantExprBits.ResultKind = llvm::to_underlying(StorageKind);
316 ConstantExprBits.APValueKind = APValue::None;
317 ConstantExprBits.IsUnsigned = false;
318 ConstantExprBits.BitWidth = 0;
319 ConstantExprBits.HasCleanup = false;
320 ConstantExprBits.IsImmediateInvocation = IsImmediateInvocation;
321
322 if (StorageKind == ConstantResultStorageKind::APValue)
323 ::new (getTrailingObjects<APValue>()) APValue();
324}
325
327 ConstantResultStorageKind StorageKind,
328 bool IsImmediateInvocation) {
329 assert(!isa<ConstantExpr>(E));
330 AssertResultStorageKind(StorageKind);
331
332 unsigned Size = totalSizeToAlloc<APValue, uint64_t>(
334 StorageKind == ConstantResultStorageKind::Int64);
335 void *Mem = Context.Allocate(Size, alignof(ConstantExpr));
336 return new (Mem) ConstantExpr(E, StorageKind, IsImmediateInvocation);
337}
338
340 const APValue &Result) {
342 ConstantExpr *Self = Create(Context, E, StorageKind);
343 Self->SetResult(Result, Context);
344 return Self;
345}
346
347ConstantExpr::ConstantExpr(EmptyShell Empty,
348 ConstantResultStorageKind StorageKind)
349 : FullExpr(ConstantExprClass, Empty) {
350 ConstantExprBits.ResultKind = llvm::to_underlying(StorageKind);
351
352 if (StorageKind == ConstantResultStorageKind::APValue)
353 ::new (getTrailingObjects<APValue>()) APValue();
354}
355
357 ConstantResultStorageKind StorageKind) {
358 AssertResultStorageKind(StorageKind);
359
360 unsigned Size = totalSizeToAlloc<APValue, uint64_t>(
362 StorageKind == ConstantResultStorageKind::Int64);
363 void *Mem = Context.Allocate(Size, alignof(ConstantExpr));
364 return new (Mem) ConstantExpr(EmptyShell(), StorageKind);
365}
366
368 assert((unsigned)getStorageKind(Value) <= ConstantExprBits.ResultKind &&
369 "Invalid storage for this value kind");
370 ConstantExprBits.APValueKind = Value.getKind();
371 switch (getResultStorageKind()) {
373 return;
375 Int64Result() = *Value.getInt().getRawData();
376 ConstantExprBits.BitWidth = Value.getInt().getBitWidth();
377 ConstantExprBits.IsUnsigned = Value.getInt().isUnsigned();
378 return;
380 if (!ConstantExprBits.HasCleanup && Value.needsCleanup()) {
381 ConstantExprBits.HasCleanup = true;
382 Context.addDestruction(&APValueResult());
383 }
384 APValueResult() = std::move(Value);
385 return;
386 }
387 llvm_unreachable("Invalid ResultKind Bits");
388}
389
391 switch (getResultStorageKind()) {
393 return APValueResult().getInt();
395 return llvm::APSInt(llvm::APInt(ConstantExprBits.BitWidth, Int64Result()),
396 ConstantExprBits.IsUnsigned);
397 default:
398 llvm_unreachable("invalid Accessor");
399 }
400}
401
403
404 switch (getResultStorageKind()) {
406 return APValueResult();
408 return APValue(
409 llvm::APSInt(llvm::APInt(ConstantExprBits.BitWidth, Int64Result()),
410 ConstantExprBits.IsUnsigned));
412 if (ConstantExprBits.APValueKind == APValue::Indeterminate)
414 return APValue();
415 }
416 llvm_unreachable("invalid ResultKind");
417}
418
419DeclRefExpr::DeclRefExpr(const ASTContext &Ctx, ValueDecl *D,
420 bool RefersToEnclosingVariableOrCapture, QualType T,
422 const DeclarationNameLoc &LocInfo,
423 NonOdrUseReason NOUR)
424 : Expr(DeclRefExprClass, T, VK, OK_Ordinary), D(D), DNLoc(LocInfo) {
425 DeclRefExprBits.HasQualifier = false;
426 DeclRefExprBits.HasTemplateKWAndArgsInfo = false;
427 DeclRefExprBits.HasFoundDecl = false;
428 DeclRefExprBits.HadMultipleCandidates = false;
429 DeclRefExprBits.RefersToEnclosingVariableOrCapture =
430 RefersToEnclosingVariableOrCapture;
431 DeclRefExprBits.CapturedByCopyInLambdaWithExplicitObjectParameter = false;
432 DeclRefExprBits.NonOdrUseReason = NOUR;
433 DeclRefExprBits.IsImmediateEscalating = false;
434 DeclRefExprBits.Loc = L;
436}
437
438DeclRefExpr::DeclRefExpr(const ASTContext &Ctx,
439 NestedNameSpecifierLoc QualifierLoc,
440 SourceLocation TemplateKWLoc, ValueDecl *D,
441 bool RefersToEnclosingVariableOrCapture,
442 const DeclarationNameInfo &NameInfo, NamedDecl *FoundD,
443 const TemplateArgumentListInfo *TemplateArgs,
445 : Expr(DeclRefExprClass, T, VK, OK_Ordinary), D(D),
446 DNLoc(NameInfo.getInfo()) {
447 DeclRefExprBits.Loc = NameInfo.getLoc();
448 DeclRefExprBits.HasQualifier = QualifierLoc ? 1 : 0;
449 if (QualifierLoc)
450 new (getTrailingObjects<NestedNameSpecifierLoc>())
451 NestedNameSpecifierLoc(QualifierLoc);
452 DeclRefExprBits.HasFoundDecl = FoundD ? 1 : 0;
453 if (FoundD)
454 *getTrailingObjects<NamedDecl *>() = FoundD;
455 DeclRefExprBits.HasTemplateKWAndArgsInfo
456 = (TemplateArgs || TemplateKWLoc.isValid()) ? 1 : 0;
457 DeclRefExprBits.RefersToEnclosingVariableOrCapture =
458 RefersToEnclosingVariableOrCapture;
459 DeclRefExprBits.CapturedByCopyInLambdaWithExplicitObjectParameter = false;
460 DeclRefExprBits.NonOdrUseReason = NOUR;
461 if (TemplateArgs) {
462 auto Deps = TemplateArgumentDependence::None;
463 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
464 TemplateKWLoc, *TemplateArgs, getTrailingObjects<TemplateArgumentLoc>(),
465 Deps);
466 assert(!(Deps & TemplateArgumentDependence::Dependent) &&
467 "built a DeclRefExpr with dependent template args");
468 } else if (TemplateKWLoc.isValid()) {
469 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
470 TemplateKWLoc);
471 }
472 DeclRefExprBits.IsImmediateEscalating = false;
473 DeclRefExprBits.HadMultipleCandidates = 0;
475}
476
478 NestedNameSpecifierLoc QualifierLoc,
479 SourceLocation TemplateKWLoc, ValueDecl *D,
480 bool RefersToEnclosingVariableOrCapture,
481 SourceLocation NameLoc, QualType T,
482 ExprValueKind VK, NamedDecl *FoundD,
483 const TemplateArgumentListInfo *TemplateArgs,
484 NonOdrUseReason NOUR) {
485 return Create(Context, QualifierLoc, TemplateKWLoc, D,
486 RefersToEnclosingVariableOrCapture,
487 DeclarationNameInfo(D->getDeclName(), NameLoc),
488 T, VK, FoundD, TemplateArgs, NOUR);
489}
490
492 NestedNameSpecifierLoc QualifierLoc,
493 SourceLocation TemplateKWLoc, ValueDecl *D,
494 bool RefersToEnclosingVariableOrCapture,
495 const DeclarationNameInfo &NameInfo,
497 NamedDecl *FoundD,
498 const TemplateArgumentListInfo *TemplateArgs,
499 NonOdrUseReason NOUR) {
500 // Filter out cases where the found Decl is the same as the value refenenced.
501 if (D == FoundD)
502 FoundD = nullptr;
503
504 bool HasTemplateKWAndArgsInfo = TemplateArgs || TemplateKWLoc.isValid();
505 std::size_t Size =
506 totalSizeToAlloc<NestedNameSpecifierLoc, NamedDecl *,
508 QualifierLoc ? 1 : 0, FoundD ? 1 : 0,
509 HasTemplateKWAndArgsInfo ? 1 : 0,
510 TemplateArgs ? TemplateArgs->size() : 0);
511
512 void *Mem = Context.Allocate(Size, alignof(DeclRefExpr));
513 return new (Mem) DeclRefExpr(Context, QualifierLoc, TemplateKWLoc, D,
514 RefersToEnclosingVariableOrCapture, NameInfo,
515 FoundD, TemplateArgs, T, VK, NOUR);
516}
517
519 bool HasQualifier,
520 bool HasFoundDecl,
521 bool HasTemplateKWAndArgsInfo,
522 unsigned NumTemplateArgs) {
523 assert(NumTemplateArgs == 0 || HasTemplateKWAndArgsInfo);
524 std::size_t Size =
525 totalSizeToAlloc<NestedNameSpecifierLoc, NamedDecl *,
527 HasQualifier ? 1 : 0, HasFoundDecl ? 1 : 0, HasTemplateKWAndArgsInfo,
528 NumTemplateArgs);
529 void *Mem = Context.Allocate(Size, alignof(DeclRefExpr));
530 return new (Mem) DeclRefExpr(EmptyShell());
531}
532
534 D = NewD;
535 if (getType()->isUndeducedType())
536 setType(NewD->getType());
538}
539
541 if (hasQualifier())
542 return getQualifierLoc().getBeginLoc();
543 return getNameInfo().getBeginLoc();
544}
547 return getRAngleLoc();
548 return getNameInfo().getEndLoc();
549}
550
551SYCLUniqueStableNameExpr::SYCLUniqueStableNameExpr(SourceLocation OpLoc,
552 SourceLocation LParen,
553 SourceLocation RParen,
554 QualType ResultTy,
555 TypeSourceInfo *TSI)
556 : Expr(SYCLUniqueStableNameExprClass, ResultTy, VK_PRValue, OK_Ordinary),
557 OpLoc(OpLoc), LParen(LParen), RParen(RParen) {
558 setTypeSourceInfo(TSI);
560}
561
562SYCLUniqueStableNameExpr::SYCLUniqueStableNameExpr(EmptyShell Empty,
563 QualType ResultTy)
564 : Expr(SYCLUniqueStableNameExprClass, ResultTy, VK_PRValue, OK_Ordinary) {}
565
568 SourceLocation LParen, SourceLocation RParen,
569 TypeSourceInfo *TSI) {
570 QualType ResultTy = Ctx.getPointerType(Ctx.CharTy.withConst());
571 return new (Ctx)
572 SYCLUniqueStableNameExpr(OpLoc, LParen, RParen, ResultTy, TSI);
573}
574
577 QualType ResultTy = Ctx.getPointerType(Ctx.CharTy.withConst());
578 return new (Ctx) SYCLUniqueStableNameExpr(EmptyShell(), ResultTy);
579}
580
584}
585
587 QualType Ty) {
588 auto MangleCallback = [](ASTContext &Ctx,
589 const NamedDecl *ND) -> std::optional<unsigned> {
590 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND))
591 return RD->getDeviceLambdaManglingNumber();
592 return std::nullopt;
593 };
594
595 std::unique_ptr<MangleContext> Ctx{ItaniumMangleContext::create(
596 Context, Context.getDiagnostics(), MangleCallback)};
597
598 std::string Buffer;
599 Buffer.reserve(128);
600 llvm::raw_string_ostream Out(Buffer);
601 Ctx->mangleCanonicalTypeName(Ty, Out);
602
603 return Out.str();
604}
605
606PredefinedExpr::PredefinedExpr(SourceLocation L, QualType FNTy,
607 PredefinedIdentKind IK, bool IsTransparent,
608 StringLiteral *SL)
609 : Expr(PredefinedExprClass, FNTy, VK_LValue, OK_Ordinary) {
610 PredefinedExprBits.Kind = llvm::to_underlying(IK);
611 assert((getIdentKind() == IK) &&
612 "IdentKind do not fit in PredefinedExprBitfields!");
613 bool HasFunctionName = SL != nullptr;
614 PredefinedExprBits.HasFunctionName = HasFunctionName;
615 PredefinedExprBits.IsTransparent = IsTransparent;
616 PredefinedExprBits.Loc = L;
617 if (HasFunctionName)
618 setFunctionName(SL);
620}
621
622PredefinedExpr::PredefinedExpr(EmptyShell Empty, bool HasFunctionName)
623 : Expr(PredefinedExprClass, Empty) {
624 PredefinedExprBits.HasFunctionName = HasFunctionName;
625}
626
629 bool IsTransparent, StringLiteral *SL) {
630 bool HasFunctionName = SL != nullptr;
631 void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *>(HasFunctionName),
632 alignof(PredefinedExpr));
633 return new (Mem) PredefinedExpr(L, FNTy, IK, IsTransparent, SL);
634}
635
637 bool HasFunctionName) {
638 void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *>(HasFunctionName),
639 alignof(PredefinedExpr));
640 return new (Mem) PredefinedExpr(EmptyShell(), HasFunctionName);
641}
642
644 switch (IK) {
646 return "__func__";
648 return "__FUNCTION__";
650 return "__FUNCDNAME__";
652 return "L__FUNCTION__";
654 return "__PRETTY_FUNCTION__";
656 return "__FUNCSIG__";
658 return "L__FUNCSIG__";
660 break;
661 }
662 llvm_unreachable("Unknown ident kind for PredefinedExpr");
663}
664
665// FIXME: Maybe this should use DeclPrinter with a special "print predefined
666// expr" policy instead.
668 const Decl *CurrentDecl) {
669 ASTContext &Context = CurrentDecl->getASTContext();
670
672 if (const NamedDecl *ND = dyn_cast<NamedDecl>(CurrentDecl)) {
673 std::unique_ptr<MangleContext> MC;
674 MC.reset(Context.createMangleContext());
675
676 if (MC->shouldMangleDeclName(ND)) {
677 SmallString<256> Buffer;
678 llvm::raw_svector_ostream Out(Buffer);
679 GlobalDecl GD;
680 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(ND))
681 GD = GlobalDecl(CD, Ctor_Base);
682 else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(ND))
683 GD = GlobalDecl(DD, Dtor_Base);
684 else if (ND->hasAttr<CUDAGlobalAttr>())
685 GD = GlobalDecl(cast<FunctionDecl>(ND));
686 else
687 GD = GlobalDecl(ND);
688 MC->mangleName(GD, Out);
689
690 if (!Buffer.empty() && Buffer.front() == '\01')
691 return std::string(Buffer.substr(1));
692 return std::string(Buffer);
693 }
694 return std::string(ND->getIdentifier()->getName());
695 }
696 return "";
697 }
698 if (isa<BlockDecl>(CurrentDecl)) {
699 // For blocks we only emit something if it is enclosed in a function
700 // For top-level block we'd like to include the name of variable, but we
701 // don't have it at this point.
702 auto DC = CurrentDecl->getDeclContext();
703 if (DC->isFileContext())
704 return "";
705
706 SmallString<256> Buffer;
707 llvm::raw_svector_ostream Out(Buffer);
708 if (auto *DCBlock = dyn_cast<BlockDecl>(DC))
709 // For nested blocks, propagate up to the parent.
710 Out << ComputeName(IK, DCBlock);
711 else if (auto *DCDecl = dyn_cast<Decl>(DC))
712 Out << ComputeName(IK, DCDecl) << "_block_invoke";
713 return std::string(Out.str());
714 }
715 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CurrentDecl)) {
720 return FD->getNameAsString();
721
722 SmallString<256> Name;
723 llvm::raw_svector_ostream Out(Name);
724
725 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
726 if (MD->isVirtual() && IK != PredefinedIdentKind::PrettyFunctionNoVirtual)
727 Out << "virtual ";
728 if (MD->isStatic())
729 Out << "static ";
730 }
731
732 class PrettyCallbacks final : public PrintingCallbacks {
733 public:
734 PrettyCallbacks(const LangOptions &LO) : LO(LO) {}
735 std::string remapPath(StringRef Path) const override {
736 SmallString<128> p(Path);
737 LO.remapPathPrefix(p);
738 return std::string(p);
739 }
740
741 private:
742 const LangOptions &LO;
743 };
744 PrintingPolicy Policy(Context.getLangOpts());
745 PrettyCallbacks PrettyCB(Context.getLangOpts());
746 Policy.Callbacks = &PrettyCB;
747 std::string Proto;
748 llvm::raw_string_ostream POut(Proto);
749
750 const FunctionDecl *Decl = FD;
751 if (const FunctionDecl* Pattern = FD->getTemplateInstantiationPattern())
752 Decl = Pattern;
753 const FunctionType *AFT = Decl->getType()->getAs<FunctionType>();
754 const FunctionProtoType *FT = nullptr;
755 if (FD->hasWrittenPrototype())
756 FT = dyn_cast<FunctionProtoType>(AFT);
757
760 switch (AFT->getCallConv()) {
761 case CC_C: POut << "__cdecl "; break;
762 case CC_X86StdCall: POut << "__stdcall "; break;
763 case CC_X86FastCall: POut << "__fastcall "; break;
764 case CC_X86ThisCall: POut << "__thiscall "; break;
765 case CC_X86VectorCall: POut << "__vectorcall "; break;
766 case CC_X86RegCall: POut << "__regcall "; break;
767 // Only bother printing the conventions that MSVC knows about.
768 default: break;
769 }
770 }
771
772 FD->printQualifiedName(POut, Policy);
773
774 POut << "(";
775 if (FT) {
776 for (unsigned i = 0, e = Decl->getNumParams(); i != e; ++i) {
777 if (i) POut << ", ";
778 POut << Decl->getParamDecl(i)->getType().stream(Policy);
779 }
780
781 if (FT->isVariadic()) {
782 if (FD->getNumParams()) POut << ", ";
783 POut << "...";
784 } else if ((IK == PredefinedIdentKind::FuncSig ||
786 !Context.getLangOpts().CPlusPlus) &&
787 !Decl->getNumParams()) {
788 POut << "void";
789 }
790 }
791 POut << ")";
792
793 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
794 assert(FT && "We must have a written prototype in this case.");
795 if (FT->isConst())
796 POut << " const";
797 if (FT->isVolatile())
798 POut << " volatile";
799 RefQualifierKind Ref = MD->getRefQualifier();
800 if (Ref == RQ_LValue)
801 POut << " &";
802 else if (Ref == RQ_RValue)
803 POut << " &&";
804 }
805
807 SpecsTy Specs;
808 const DeclContext *Ctx = FD->getDeclContext();
809 while (Ctx && isa<NamedDecl>(Ctx)) {
811 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx);
812 if (Spec && !Spec->isExplicitSpecialization())
813 Specs.push_back(Spec);
814 Ctx = Ctx->getParent();
815 }
816
817 std::string TemplateParams;
818 llvm::raw_string_ostream TOut(TemplateParams);
819 for (const ClassTemplateSpecializationDecl *D : llvm::reverse(Specs)) {
820 const TemplateParameterList *Params =
821 D->getSpecializedTemplate()->getTemplateParameters();
822 const TemplateArgumentList &Args = D->getTemplateArgs();
823 assert(Params->size() == Args.size());
824 for (unsigned i = 0, numParams = Params->size(); i != numParams; ++i) {
825 StringRef Param = Params->getParam(i)->getName();
826 if (Param.empty()) continue;
827 TOut << Param << " = ";
828 Args.get(i).print(Policy, TOut,
830 Policy, Params, i));
831 TOut << ", ";
832 }
833 }
834
836 = FD->getTemplateSpecializationInfo();
837 if (FSI && !FSI->isExplicitSpecialization()) {
838 const TemplateParameterList* Params
840 const TemplateArgumentList* Args = FSI->TemplateArguments;
841 assert(Params->size() == Args->size());
842 for (unsigned i = 0, e = Params->size(); i != e; ++i) {
843 StringRef Param = Params->getParam(i)->getName();
844 if (Param.empty()) continue;
845 TOut << Param << " = ";
846 Args->get(i).print(Policy, TOut, /*IncludeType*/ true);
847 TOut << ", ";
848 }
849 }
850
851 TOut.flush();
852 if (!TemplateParams.empty()) {
853 // remove the trailing comma and space
854 TemplateParams.resize(TemplateParams.size() - 2);
855 POut << " [" << TemplateParams << "]";
856 }
857
858 POut.flush();
859
860 // Print "auto" for all deduced return types. This includes C++1y return
861 // type deduction and lambdas. For trailing return types resolve the
862 // decltype expression. Otherwise print the real type when this is
863 // not a constructor or destructor.
864 if (isa<CXXMethodDecl>(FD) &&
865 cast<CXXMethodDecl>(FD)->getParent()->isLambda())
866 Proto = "auto " + Proto;
867 else if (FT && FT->getReturnType()->getAs<DecltypeType>())
868 FT->getReturnType()
869 ->getAs<DecltypeType>()
871 .getAsStringInternal(Proto, Policy);
872 else if (!isa<CXXConstructorDecl>(FD) && !isa<CXXDestructorDecl>(FD))
873 AFT->getReturnType().getAsStringInternal(Proto, Policy);
874
875 Out << Proto;
876
877 return std::string(Name);
878 }
879 if (const CapturedDecl *CD = dyn_cast<CapturedDecl>(CurrentDecl)) {
880 for (const DeclContext *DC = CD->getParent(); DC; DC = DC->getParent())
881 // Skip to its enclosing function or method, but not its enclosing
882 // CapturedDecl.
883 if (DC->isFunctionOrMethod() && (DC->getDeclKind() != Decl::Captured)) {
884 const Decl *D = Decl::castFromDeclContext(DC);
885 return ComputeName(IK, D);
886 }
887 llvm_unreachable("CapturedDecl not inside a function or method");
888 }
889 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurrentDecl)) {
890 SmallString<256> Name;
891 llvm::raw_svector_ostream Out(Name);
892 Out << (MD->isInstanceMethod() ? '-' : '+');
893 Out << '[';
894
895 // For incorrect code, there might not be an ObjCInterfaceDecl. Do
896 // a null check to avoid a crash.
897 if (const ObjCInterfaceDecl *ID = MD->getClassInterface())
898 Out << *ID;
899
900 if (const ObjCCategoryImplDecl *CID =
901 dyn_cast<ObjCCategoryImplDecl>(MD->getDeclContext()))
902 Out << '(' << *CID << ')';
903
904 Out << ' ';
905 MD->getSelector().print(Out);
906 Out << ']';
907
908 return std::string(Name);
909 }
910 if (isa<TranslationUnitDecl>(CurrentDecl) &&
912 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
913 return "top level";
914 }
915 return "";
916}
917
919 const llvm::APInt &Val) {
920 if (hasAllocation())
921 C.Deallocate(pVal);
922
923 BitWidth = Val.getBitWidth();
924 unsigned NumWords = Val.getNumWords();
925 const uint64_t* Words = Val.getRawData();
926 if (NumWords > 1) {
927 pVal = new (C) uint64_t[NumWords];
928 std::copy(Words, Words + NumWords, pVal);
929 } else if (NumWords == 1)
930 VAL = Words[0];
931 else
932 VAL = 0;
933}
934
935IntegerLiteral::IntegerLiteral(const ASTContext &C, const llvm::APInt &V,
937 : Expr(IntegerLiteralClass, type, VK_PRValue, OK_Ordinary), Loc(l) {
938 assert(type->isIntegerType() && "Illegal type in IntegerLiteral");
939 assert(V.getBitWidth() == C.getIntWidth(type) &&
940 "Integer type is not the correct size for constant.");
941 setValue(C, V);
942 setDependence(ExprDependence::None);
943}
944
946IntegerLiteral::Create(const ASTContext &C, const llvm::APInt &V,
948 return new (C) IntegerLiteral(C, V, type, l);
949}
950
953 return new (C) IntegerLiteral(Empty);
954}
955
956FixedPointLiteral::FixedPointLiteral(const ASTContext &C, const llvm::APInt &V,
958 unsigned Scale)
959 : Expr(FixedPointLiteralClass, type, VK_PRValue, OK_Ordinary), Loc(l),
960 Scale(Scale) {
961 assert(type->isFixedPointType() && "Illegal type in FixedPointLiteral");
962 assert(V.getBitWidth() == C.getTypeInfo(type).Width &&
963 "Fixed point type is not the correct size for constant.");
964 setValue(C, V);
965 setDependence(ExprDependence::None);
966}
967
969 const llvm::APInt &V,
972 unsigned Scale) {
973 return new (C) FixedPointLiteral(C, V, type, l, Scale);
974}
975
977 EmptyShell Empty) {
978 return new (C) FixedPointLiteral(Empty);
979}
980
981std::string FixedPointLiteral::getValueAsString(unsigned Radix) const {
982 // Currently the longest decimal number that can be printed is the max for an
983 // unsigned long _Accum: 4294967295.99999999976716935634613037109375
984 // which is 43 characters.
987 S, llvm::APSInt::getUnsigned(getValue().getZExtValue()), Scale);
988 return std::string(S);
989}
990
992 raw_ostream &OS) {
993 switch (Kind) {
995 break; // no prefix.
997 OS << 'L';
998 break;
1000 OS << "u8";
1001 break;
1003 OS << 'u';
1004 break;
1006 OS << 'U';
1007 break;
1008 }
1009
1010 StringRef Escaped = escapeCStyle<EscapeChar::Single>(Val);
1011 if (!Escaped.empty()) {
1012 OS << "'" << Escaped << "'";
1013 } else {
1014 // A character literal might be sign-extended, which
1015 // would result in an invalid \U escape sequence.
1016 // FIXME: multicharacter literals such as '\xFF\xFF\xFF\xFF'
1017 // are not correctly handled.
1018 if ((Val & ~0xFFu) == ~0xFFu && Kind == CharacterLiteralKind::Ascii)
1019 Val &= 0xFFu;
1020 if (Val < 256 && isPrintable((unsigned char)Val))
1021 OS << "'" << (char)Val << "'";
1022 else if (Val < 256)
1023 OS << "'\\x" << llvm::format("%02x", Val) << "'";
1024 else if (Val <= 0xFFFF)
1025 OS << "'\\u" << llvm::format("%04x", Val) << "'";
1026 else
1027 OS << "'\\U" << llvm::format("%08x", Val) << "'";
1028 }
1029}
1030
1031FloatingLiteral::FloatingLiteral(const ASTContext &C, const llvm::APFloat &V,
1032 bool isexact, QualType Type, SourceLocation L)
1033 : Expr(FloatingLiteralClass, Type, VK_PRValue, OK_Ordinary), Loc(L) {
1034 setSemantics(V.getSemantics());
1035 FloatingLiteralBits.IsExact = isexact;
1036 setValue(C, V);
1037 setDependence(ExprDependence::None);
1038}
1039
1040FloatingLiteral::FloatingLiteral(const ASTContext &C, EmptyShell Empty)
1041 : Expr(FloatingLiteralClass, Empty) {
1042 setRawSemantics(llvm::APFloatBase::S_IEEEhalf);
1043 FloatingLiteralBits.IsExact = false;
1044}
1045
1047FloatingLiteral::Create(const ASTContext &C, const llvm::APFloat &V,
1048 bool isexact, QualType Type, SourceLocation L) {
1049 return new (C) FloatingLiteral(C, V, isexact, Type, L);
1050}
1051
1054 return new (C) FloatingLiteral(C, Empty);
1055}
1056
1057/// getValueAsApproximateDouble - This returns the value as an inaccurate
1058/// double. Note that this may cause loss of precision, but is useful for
1059/// debugging dumps, etc.
1061 llvm::APFloat V = getValue();
1062 bool ignored;
1063 V.convert(llvm::APFloat::IEEEdouble(), llvm::APFloat::rmNearestTiesToEven,
1064 &ignored);
1065 return V.convertToDouble();
1066}
1067
1068unsigned StringLiteral::mapCharByteWidth(TargetInfo const &Target,
1069 StringLiteralKind SK) {
1070 unsigned CharByteWidth = 0;
1071 switch (SK) {
1074 CharByteWidth = Target.getCharWidth();
1075 break;
1077 CharByteWidth = Target.getWCharWidth();
1078 break;
1080 CharByteWidth = Target.getChar16Width();
1081 break;
1083 CharByteWidth = Target.getChar32Width();
1084 break;
1086 return sizeof(char); // Host;
1087 }
1088 assert((CharByteWidth & 7) == 0 && "Assumes character size is byte multiple");
1089 CharByteWidth /= 8;
1090 assert((CharByteWidth == 1 || CharByteWidth == 2 || CharByteWidth == 4) &&
1091 "The only supported character byte widths are 1,2 and 4!");
1092 return CharByteWidth;
1093}
1094
1095StringLiteral::StringLiteral(const ASTContext &Ctx, StringRef Str,
1096 StringLiteralKind Kind, bool Pascal, QualType Ty,
1097 const SourceLocation *Loc,
1098 unsigned NumConcatenated)
1099 : Expr(StringLiteralClass, Ty, VK_LValue, OK_Ordinary) {
1100
1101 unsigned Length = Str.size();
1102
1103 StringLiteralBits.Kind = llvm::to_underlying(Kind);
1104 StringLiteralBits.NumConcatenated = NumConcatenated;
1105
1106 if (Kind != StringLiteralKind::Unevaluated) {
1107 assert(Ctx.getAsConstantArrayType(Ty) &&
1108 "StringLiteral must be of constant array type!");
1109 unsigned CharByteWidth = mapCharByteWidth(Ctx.getTargetInfo(), Kind);
1110 unsigned ByteLength = Str.size();
1111 assert((ByteLength % CharByteWidth == 0) &&
1112 "The size of the data must be a multiple of CharByteWidth!");
1113
1114 // Avoid the expensive division. The compiler should be able to figure it
1115 // out by itself. However as of clang 7, even with the appropriate
1116 // llvm_unreachable added just here, it is not able to do so.
1117 switch (CharByteWidth) {
1118 case 1:
1119 Length = ByteLength;
1120 break;
1121 case 2:
1122 Length = ByteLength / 2;
1123 break;
1124 case 4:
1125 Length = ByteLength / 4;
1126 break;
1127 default:
1128 llvm_unreachable("Unsupported character width!");
1129 }
1130
1131 StringLiteralBits.CharByteWidth = CharByteWidth;
1132 StringLiteralBits.IsPascal = Pascal;
1133 } else {
1134 assert(!Pascal && "Can't make an unevaluated Pascal string");
1135 StringLiteralBits.CharByteWidth = 1;
1136 StringLiteralBits.IsPascal = false;
1137 }
1138
1139 *getTrailingObjects<unsigned>() = Length;
1140
1141 // Initialize the trailing array of SourceLocation.
1142 // This is safe since SourceLocation is POD-like.
1143 std::memcpy(getTrailingObjects<SourceLocation>(), Loc,
1144 NumConcatenated * sizeof(SourceLocation));
1145
1146 // Initialize the trailing array of char holding the string data.
1147 std::memcpy(getTrailingObjects<char>(), Str.data(), Str.size());
1148
1149 setDependence(ExprDependence::None);
1150}
1151
1152StringLiteral::StringLiteral(EmptyShell Empty, unsigned NumConcatenated,
1153 unsigned Length, unsigned CharByteWidth)
1154 : Expr(StringLiteralClass, Empty) {
1155 StringLiteralBits.CharByteWidth = CharByteWidth;
1156 StringLiteralBits.NumConcatenated = NumConcatenated;
1157 *getTrailingObjects<unsigned>() = Length;
1158}
1159
1161 StringLiteralKind Kind, bool Pascal,
1162 QualType Ty, const SourceLocation *Loc,
1163 unsigned NumConcatenated) {
1164 void *Mem = Ctx.Allocate(totalSizeToAlloc<unsigned, SourceLocation, char>(
1165 1, NumConcatenated, Str.size()),
1166 alignof(StringLiteral));
1167 return new (Mem)
1168 StringLiteral(Ctx, Str, Kind, Pascal, Ty, Loc, NumConcatenated);
1169}
1170
1172 unsigned NumConcatenated,
1173 unsigned Length,
1174 unsigned CharByteWidth) {
1175 void *Mem = Ctx.Allocate(totalSizeToAlloc<unsigned, SourceLocation, char>(
1176 1, NumConcatenated, Length * CharByteWidth),
1177 alignof(StringLiteral));
1178 return new (Mem)
1179 StringLiteral(EmptyShell(), NumConcatenated, Length, CharByteWidth);
1180}
1181
1182void StringLiteral::outputString(raw_ostream &OS) const {
1183 switch (getKind()) {
1186 break; // no prefix.
1188 OS << 'L';
1189 break;
1191 OS << "u8";
1192 break;
1194 OS << 'u';
1195 break;
1197 OS << 'U';
1198 break;
1199 }
1200 OS << '"';
1201 static const char Hex[] = "0123456789ABCDEF";
1202
1203 unsigned LastSlashX = getLength();
1204 for (unsigned I = 0, N = getLength(); I != N; ++I) {
1205 uint32_t Char = getCodeUnit(I);
1206 StringRef Escaped = escapeCStyle<EscapeChar::Double>(Char);
1207 if (Escaped.empty()) {
1208 // FIXME: Convert UTF-8 back to codepoints before rendering.
1209
1210 // Convert UTF-16 surrogate pairs back to codepoints before rendering.
1211 // Leave invalid surrogates alone; we'll use \x for those.
1212 if (getKind() == StringLiteralKind::UTF16 && I != N - 1 &&
1213 Char >= 0xd800 && Char <= 0xdbff) {
1214 uint32_t Trail = getCodeUnit(I + 1);
1215 if (Trail >= 0xdc00 && Trail <= 0xdfff) {
1216 Char = 0x10000 + ((Char - 0xd800) << 10) + (Trail - 0xdc00);
1217 ++I;
1218 }
1219 }
1220
1221 if (Char > 0xff) {
1222 // If this is a wide string, output characters over 0xff using \x
1223 // escapes. Otherwise, this is a UTF-16 or UTF-32 string, and Char is a
1224 // codepoint: use \x escapes for invalid codepoints.
1226 (Char >= 0xd800 && Char <= 0xdfff) || Char >= 0x110000) {
1227 // FIXME: Is this the best way to print wchar_t?
1228 OS << "\\x";
1229 int Shift = 28;
1230 while ((Char >> Shift) == 0)
1231 Shift -= 4;
1232 for (/**/; Shift >= 0; Shift -= 4)
1233 OS << Hex[(Char >> Shift) & 15];
1234 LastSlashX = I;
1235 continue;
1236 }
1237
1238 if (Char > 0xffff)
1239 OS << "\\U00"
1240 << Hex[(Char >> 20) & 15]
1241 << Hex[(Char >> 16) & 15];
1242 else
1243 OS << "\\u";
1244 OS << Hex[(Char >> 12) & 15]
1245 << Hex[(Char >> 8) & 15]
1246 << Hex[(Char >> 4) & 15]
1247 << Hex[(Char >> 0) & 15];
1248 continue;
1249 }
1250
1251 // If we used \x... for the previous character, and this character is a
1252 // hexadecimal digit, prevent it being slurped as part of the \x.
1253 if (LastSlashX + 1 == I) {
1254 switch (Char) {
1255 case '0': case '1': case '2': case '3': case '4':
1256 case '5': case '6': case '7': case '8': case '9':
1257 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
1258 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
1259 OS << "\"\"";
1260 }
1261 }
1262
1263 assert(Char <= 0xff &&
1264 "Characters above 0xff should already have been handled.");
1265
1266 if (isPrintable(Char))
1267 OS << (char)Char;
1268 else // Output anything hard as an octal escape.
1269 OS << '\\'
1270 << (char)('0' + ((Char >> 6) & 7))
1271 << (char)('0' + ((Char >> 3) & 7))
1272 << (char)('0' + ((Char >> 0) & 7));
1273 } else {
1274 // Handle some common non-printable cases to make dumps prettier.
1275 OS << Escaped;
1276 }
1277 }
1278 OS << '"';
1279}
1280
1281/// getLocationOfByte - Return a source location that points to the specified
1282/// byte of this string literal.
1283///
1284/// Strings are amazingly complex. They can be formed from multiple tokens and
1285/// can have escape sequences in them in addition to the usual trigraph and
1286/// escaped newline business. This routine handles this complexity.
1287///
1288/// The *StartToken sets the first token to be searched in this function and
1289/// the *StartTokenByteOffset is the byte offset of the first token. Before
1290/// returning, it updates the *StartToken to the TokNo of the token being found
1291/// and sets *StartTokenByteOffset to the byte offset of the token in the
1292/// string.
1293/// Using these two parameters can reduce the time complexity from O(n^2) to
1294/// O(n) if one wants to get the location of byte for all the tokens in a
1295/// string.
1296///
1299 const LangOptions &Features,
1300 const TargetInfo &Target, unsigned *StartToken,
1301 unsigned *StartTokenByteOffset) const {
1302 assert((getKind() == StringLiteralKind::Ordinary ||
1305 "Only narrow string literals are currently supported");
1306
1307 // Loop over all of the tokens in this string until we find the one that
1308 // contains the byte we're looking for.
1309 unsigned TokNo = 0;
1310 unsigned StringOffset = 0;
1311 if (StartToken)
1312 TokNo = *StartToken;
1313 if (StartTokenByteOffset) {
1314 StringOffset = *StartTokenByteOffset;
1315 ByteNo -= StringOffset;
1316 }
1317 while (true) {
1318 assert(TokNo < getNumConcatenated() && "Invalid byte number!");
1319 SourceLocation StrTokLoc = getStrTokenLoc(TokNo);
1320
1321 // Get the spelling of the string so that we can get the data that makes up
1322 // the string literal, not the identifier for the macro it is potentially
1323 // expanded through.
1324 SourceLocation StrTokSpellingLoc = SM.getSpellingLoc(StrTokLoc);
1325
1326 // Re-lex the token to get its length and original spelling.
1327 std::pair<FileID, unsigned> LocInfo =
1328 SM.getDecomposedLoc(StrTokSpellingLoc);
1329 bool Invalid = false;
1330 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
1331 if (Invalid) {
1332 if (StartTokenByteOffset != nullptr)
1333 *StartTokenByteOffset = StringOffset;
1334 if (StartToken != nullptr)
1335 *StartToken = TokNo;
1336 return StrTokSpellingLoc;
1337 }
1338
1339 const char *StrData = Buffer.data()+LocInfo.second;
1340
1341 // Create a lexer starting at the beginning of this token.
1342 Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), Features,
1343 Buffer.begin(), StrData, Buffer.end());
1344 Token TheTok;
1345 TheLexer.LexFromRawLexer(TheTok);
1346
1347 // Use the StringLiteralParser to compute the length of the string in bytes.
1348 StringLiteralParser SLP(TheTok, SM, Features, Target);
1349 unsigned TokNumBytes = SLP.GetStringLength();
1350
1351 // If the byte is in this token, return the location of the byte.
1352 if (ByteNo < TokNumBytes ||
1353 (ByteNo == TokNumBytes && TokNo == getNumConcatenated() - 1)) {
1354 unsigned Offset = SLP.getOffsetOfStringByte(TheTok, ByteNo);
1355
1356 // Now that we know the offset of the token in the spelling, use the
1357 // preprocessor to get the offset in the original source.
1358 if (StartTokenByteOffset != nullptr)
1359 *StartTokenByteOffset = StringOffset;
1360 if (StartToken != nullptr)
1361 *StartToken = TokNo;
1362 return Lexer::AdvanceToTokenCharacter(StrTokLoc, Offset, SM, Features);
1363 }
1364
1365 // Move to the next string token.
1366 StringOffset += TokNumBytes;
1367 ++TokNo;
1368 ByteNo -= TokNumBytes;
1369 }
1370}
1371
1372/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1373/// corresponds to, e.g. "sizeof" or "[pre]++".
1375 switch (Op) {
1376#define UNARY_OPERATION(Name, Spelling) case UO_##Name: return Spelling;
1377#include "clang/AST/OperationKinds.def"
1378 }
1379 llvm_unreachable("Unknown unary operator");
1380}
1381
1384 switch (OO) {
1385 default: llvm_unreachable("No unary operator for overloaded function");
1386 case OO_PlusPlus: return Postfix ? UO_PostInc : UO_PreInc;
1387 case OO_MinusMinus: return Postfix ? UO_PostDec : UO_PreDec;
1388 case OO_Amp: return UO_AddrOf;
1389 case OO_Star: return UO_Deref;
1390 case OO_Plus: return UO_Plus;
1391 case OO_Minus: return UO_Minus;
1392 case OO_Tilde: return UO_Not;
1393 case OO_Exclaim: return UO_LNot;
1394 case OO_Coawait: return UO_Coawait;
1395 }
1396}
1397
1399 switch (Opc) {
1400 case UO_PostInc: case UO_PreInc: return OO_PlusPlus;
1401 case UO_PostDec: case UO_PreDec: return OO_MinusMinus;
1402 case UO_AddrOf: return OO_Amp;
1403 case UO_Deref: return OO_Star;
1404 case UO_Plus: return OO_Plus;
1405 case UO_Minus: return OO_Minus;
1406 case UO_Not: return OO_Tilde;
1407 case UO_LNot: return OO_Exclaim;
1408 case UO_Coawait: return OO_Coawait;
1409 default: return OO_None;
1410 }
1411}
1412
1413
1414//===----------------------------------------------------------------------===//
1415// Postfix Operators.
1416//===----------------------------------------------------------------------===//
1417
1420 SourceLocation RParenLoc, FPOptionsOverride FPFeatures,
1421 unsigned MinNumArgs, ADLCallKind UsesADL)
1422 : Expr(SC, Ty, VK, OK_Ordinary), RParenLoc(RParenLoc) {
1423 NumArgs = std::max<unsigned>(Args.size(), MinNumArgs);
1424 unsigned NumPreArgs = PreArgs.size();
1425 CallExprBits.NumPreArgs = NumPreArgs;
1426 assert((NumPreArgs == getNumPreArgs()) && "NumPreArgs overflow!");
1427
1428 unsigned OffsetToTrailingObjects = offsetToTrailingObjects(SC);
1429 CallExprBits.OffsetToTrailingObjects = OffsetToTrailingObjects;
1430 assert((CallExprBits.OffsetToTrailingObjects == OffsetToTrailingObjects) &&
1431 "OffsetToTrailingObjects overflow!");
1432
1433 CallExprBits.UsesADL = static_cast<bool>(UsesADL);
1434
1435 setCallee(Fn);
1436 for (unsigned I = 0; I != NumPreArgs; ++I)
1437 setPreArg(I, PreArgs[I]);
1438 for (unsigned I = 0; I != Args.size(); ++I)
1439 setArg(I, Args[I]);
1440 for (unsigned I = Args.size(); I != NumArgs; ++I)
1441 setArg(I, nullptr);
1442
1443 this->computeDependence();
1444
1445 CallExprBits.HasFPFeatures = FPFeatures.requiresTrailingStorage();
1446 if (hasStoredFPFeatures())
1447 setStoredFPFeatures(FPFeatures);
1448}
1449
1450CallExpr::CallExpr(StmtClass SC, unsigned NumPreArgs, unsigned NumArgs,
1451 bool HasFPFeatures, EmptyShell Empty)
1452 : Expr(SC, Empty), NumArgs(NumArgs) {
1453 CallExprBits.NumPreArgs = NumPreArgs;
1454 assert((NumPreArgs == getNumPreArgs()) && "NumPreArgs overflow!");
1455
1456 unsigned OffsetToTrailingObjects = offsetToTrailingObjects(SC);
1457 CallExprBits.OffsetToTrailingObjects = OffsetToTrailingObjects;
1458 assert((CallExprBits.OffsetToTrailingObjects == OffsetToTrailingObjects) &&
1459 "OffsetToTrailingObjects overflow!");
1460 CallExprBits.HasFPFeatures = HasFPFeatures;
1461}
1462
1465 SourceLocation RParenLoc,
1466 FPOptionsOverride FPFeatures, unsigned MinNumArgs,
1467 ADLCallKind UsesADL) {
1468 unsigned NumArgs = std::max<unsigned>(Args.size(), MinNumArgs);
1469 unsigned SizeOfTrailingObjects = CallExpr::sizeOfTrailingObjects(
1470 /*NumPreArgs=*/0, NumArgs, FPFeatures.requiresTrailingStorage());
1471 void *Mem =
1472 Ctx.Allocate(sizeof(CallExpr) + SizeOfTrailingObjects, alignof(CallExpr));
1473 return new (Mem) CallExpr(CallExprClass, Fn, /*PreArgs=*/{}, Args, Ty, VK,
1474 RParenLoc, FPFeatures, MinNumArgs, UsesADL);
1475}
1476
1478 ExprValueKind VK, SourceLocation RParenLoc,
1479 ADLCallKind UsesADL) {
1480 assert(!(reinterpret_cast<uintptr_t>(Mem) % alignof(CallExpr)) &&
1481 "Misaligned memory in CallExpr::CreateTemporary!");
1482 return new (Mem) CallExpr(CallExprClass, Fn, /*PreArgs=*/{}, /*Args=*/{}, Ty,
1483 VK, RParenLoc, FPOptionsOverride(),
1484 /*MinNumArgs=*/0, UsesADL);
1485}
1486
1487CallExpr *CallExpr::CreateEmpty(const ASTContext &Ctx, unsigned NumArgs,
1488 bool HasFPFeatures, EmptyShell Empty) {
1489 unsigned SizeOfTrailingObjects =
1490 CallExpr::sizeOfTrailingObjects(/*NumPreArgs=*/0, NumArgs, HasFPFeatures);
1491 void *Mem =
1492 Ctx.Allocate(sizeof(CallExpr) + SizeOfTrailingObjects, alignof(CallExpr));
1493 return new (Mem)
1494 CallExpr(CallExprClass, /*NumPreArgs=*/0, NumArgs, HasFPFeatures, Empty);
1495}
1496
1497unsigned CallExpr::offsetToTrailingObjects(StmtClass SC) {
1498 switch (SC) {
1499 case CallExprClass:
1500 return sizeof(CallExpr);
1501 case CXXOperatorCallExprClass:
1502 return sizeof(CXXOperatorCallExpr);
1503 case CXXMemberCallExprClass:
1504 return sizeof(CXXMemberCallExpr);
1505 case UserDefinedLiteralClass:
1506 return sizeof(UserDefinedLiteral);
1507 case CUDAKernelCallExprClass:
1508 return sizeof(CUDAKernelCallExpr);
1509 default:
1510 llvm_unreachable("unexpected class deriving from CallExpr!");
1511 }
1512}
1513
1515 Expr *CEE = IgnoreParenImpCasts();
1516
1517 while (auto *NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(CEE))
1518 CEE = NTTP->getReplacement()->IgnoreParenImpCasts();
1519
1520 // If we're calling a dereference, look at the pointer instead.
1521 while (true) {
1522 if (auto *BO = dyn_cast<BinaryOperator>(CEE)) {
1523 if (BO->isPtrMemOp()) {
1524 CEE = BO->getRHS()->IgnoreParenImpCasts();
1525 continue;
1526 }
1527 } else if (auto *UO = dyn_cast<UnaryOperator>(CEE)) {
1528 if (UO->getOpcode() == UO_Deref || UO->getOpcode() == UO_AddrOf ||
1529 UO->getOpcode() == UO_Plus) {
1530 CEE = UO->getSubExpr()->IgnoreParenImpCasts();
1531 continue;
1532 }
1533 }
1534 break;
1535 }
1536
1537 if (auto *DRE = dyn_cast<DeclRefExpr>(CEE))
1538 return DRE->getDecl();
1539 if (auto *ME = dyn_cast<MemberExpr>(CEE))
1540 return ME->getMemberDecl();
1541 if (auto *BE = dyn_cast<BlockExpr>(CEE))
1542 return BE->getBlockDecl();
1543
1544 return nullptr;
1545}
1546
1547/// If this is a call to a builtin, return the builtin ID. If not, return 0.
1549 const auto *FDecl = getDirectCallee();
1550 return FDecl ? FDecl->getBuiltinID() : 0;
1551}
1552
1554 if (unsigned BI = getBuiltinCallee())
1555 return Ctx.BuiltinInfo.isUnevaluated(BI);
1556 return false;
1557}
1558
1560 const Expr *Callee = getCallee();
1561 QualType CalleeType = Callee->getType();
1562 if (const auto *FnTypePtr = CalleeType->getAs<PointerType>()) {
1563 CalleeType = FnTypePtr->getPointeeType();
1564 } else if (const auto *BPT = CalleeType->getAs<BlockPointerType>()) {
1565 CalleeType = BPT->getPointeeType();
1566 } else if (CalleeType->isSpecificPlaceholderType(BuiltinType::BoundMember)) {
1567 if (isa<CXXPseudoDestructorExpr>(Callee->IgnoreParens()))
1568 return Ctx.VoidTy;
1569
1570 if (isa<UnresolvedMemberExpr>(Callee->IgnoreParens()))
1571 return Ctx.DependentTy;
1572
1573 // This should never be overloaded and so should never return null.
1574 CalleeType = Expr::findBoundMemberType(Callee);
1575 assert(!CalleeType.isNull());
1576 } else if (CalleeType->isRecordType()) {
1577 // If the Callee is a record type, then it is a not-yet-resolved
1578 // dependent call to the call operator of that type.
1579 return Ctx.DependentTy;
1580 } else if (CalleeType->isDependentType() ||
1581 CalleeType->isSpecificPlaceholderType(BuiltinType::Overload)) {
1582 return Ctx.DependentTy;
1583 }
1584
1585 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
1586 return FnType->getReturnType();
1587}
1588
1590 // If the return type is a struct, union, or enum that is marked nodiscard,
1591 // then return the return type attribute.
1592 if (const TagDecl *TD = getCallReturnType(Ctx)->getAsTagDecl())
1593 if (const auto *A = TD->getAttr<WarnUnusedResultAttr>())
1594 return A;
1595
1596 for (const auto *TD = getCallReturnType(Ctx)->getAs<TypedefType>(); TD;
1597 TD = TD->desugar()->getAs<TypedefType>())
1598 if (const auto *A = TD->getDecl()->getAttr<WarnUnusedResultAttr>())
1599 return A;
1600
1601 // Otherwise, see if the callee is marked nodiscard and return that attribute
1602 // instead.
1603 const Decl *D = getCalleeDecl();
1604 return D ? D->getAttr<WarnUnusedResultAttr>() : nullptr;
1605}
1606
1608 if (const auto *OCE = dyn_cast<CXXOperatorCallExpr>(this))
1609 return OCE->getBeginLoc();
1610
1612 if (begin.isInvalid() && getNumArgs() > 0 && getArg(0))
1613 begin = getArg(0)->getBeginLoc();
1614 return begin;
1615}
1617 if (const auto *OCE = dyn_cast<CXXOperatorCallExpr>(this))
1618 return OCE->getEndLoc();
1619
1621 if (end.isInvalid() && getNumArgs() > 0 && getArg(getNumArgs() - 1))
1622 end = getArg(getNumArgs() - 1)->getEndLoc();
1623 return end;
1624}
1625
1627 SourceLocation OperatorLoc,
1628 TypeSourceInfo *tsi,
1630 ArrayRef<Expr*> exprs,
1631 SourceLocation RParenLoc) {
1632 void *Mem = C.Allocate(
1633 totalSizeToAlloc<OffsetOfNode, Expr *>(comps.size(), exprs.size()));
1634
1635 return new (Mem) OffsetOfExpr(C, type, OperatorLoc, tsi, comps, exprs,
1636 RParenLoc);
1637}
1638
1640 unsigned numComps, unsigned numExprs) {
1641 void *Mem =
1642 C.Allocate(totalSizeToAlloc<OffsetOfNode, Expr *>(numComps, numExprs));
1643 return new (Mem) OffsetOfExpr(numComps, numExprs);
1644}
1645
1646OffsetOfExpr::OffsetOfExpr(const ASTContext &C, QualType type,
1647 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
1649 SourceLocation RParenLoc)
1650 : Expr(OffsetOfExprClass, type, VK_PRValue, OK_Ordinary),
1651 OperatorLoc(OperatorLoc), RParenLoc(RParenLoc), TSInfo(tsi),
1652 NumComps(comps.size()), NumExprs(exprs.size()) {
1653 for (unsigned i = 0; i != comps.size(); ++i)
1654 setComponent(i, comps[i]);
1655 for (unsigned i = 0; i != exprs.size(); ++i)
1656 setIndexExpr(i, exprs[i]);
1657
1659}
1660
1662 assert(getKind() == Field || getKind() == Identifier);
1663 if (getKind() == Field)
1664 return getField()->getIdentifier();
1665
1666 return reinterpret_cast<IdentifierInfo *> (Data & ~(uintptr_t)Mask);
1667}
1668
1670 UnaryExprOrTypeTrait ExprKind, Expr *E, QualType resultType,
1672 : Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_PRValue, OK_Ordinary),
1673 OpLoc(op), RParenLoc(rp) {
1674 assert(ExprKind <= UETT_Last && "invalid enum value!");
1675 UnaryExprOrTypeTraitExprBits.Kind = ExprKind;
1676 assert(static_cast<unsigned>(ExprKind) == UnaryExprOrTypeTraitExprBits.Kind &&
1677 "UnaryExprOrTypeTraitExprBits.Kind overflow!");
1678 UnaryExprOrTypeTraitExprBits.IsType = false;
1679 Argument.Ex = E;
1681}
1682
1683MemberExpr::MemberExpr(Expr *Base, bool IsArrow, SourceLocation OperatorLoc,
1684 ValueDecl *MemberDecl,
1685 const DeclarationNameInfo &NameInfo, QualType T,
1687 NonOdrUseReason NOUR)
1688 : Expr(MemberExprClass, T, VK, OK), Base(Base), MemberDecl(MemberDecl),
1689 MemberDNLoc(NameInfo.getInfo()), MemberLoc(NameInfo.getLoc()) {
1690 assert(!NameInfo.getName() ||
1691 MemberDecl->getDeclName() == NameInfo.getName());
1692 MemberExprBits.IsArrow = IsArrow;
1693 MemberExprBits.HasQualifierOrFoundDecl = false;
1694 MemberExprBits.HasTemplateKWAndArgsInfo = false;
1695 MemberExprBits.HadMultipleCandidates = false;
1696 MemberExprBits.NonOdrUseReason = NOUR;
1697 MemberExprBits.OperatorLoc = OperatorLoc;
1699}
1700
1702 const ASTContext &C, Expr *Base, bool IsArrow, SourceLocation OperatorLoc,
1703 NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,
1704 ValueDecl *MemberDecl, DeclAccessPair FoundDecl,
1705 DeclarationNameInfo NameInfo, const TemplateArgumentListInfo *TemplateArgs,
1707 bool HasQualOrFound = QualifierLoc || FoundDecl.getDecl() != MemberDecl ||
1708 FoundDecl.getAccess() != MemberDecl->getAccess();
1709 bool HasTemplateKWAndArgsInfo = TemplateArgs || TemplateKWLoc.isValid();
1710 std::size_t Size =
1713 HasQualOrFound ? 1 : 0, HasTemplateKWAndArgsInfo ? 1 : 0,
1714 TemplateArgs ? TemplateArgs->size() : 0);
1715
1716 void *Mem = C.Allocate(Size, alignof(MemberExpr));
1717 MemberExpr *E = new (Mem) MemberExpr(Base, IsArrow, OperatorLoc, MemberDecl,
1718 NameInfo, T, VK, OK, NOUR);
1719
1720 if (HasQualOrFound) {
1721 E->MemberExprBits.HasQualifierOrFoundDecl = true;
1722
1724 E->getTrailingObjects<MemberExprNameQualifier>();
1725 NQ->QualifierLoc = QualifierLoc;
1726 NQ->FoundDecl = FoundDecl;
1727 }
1728
1729 E->MemberExprBits.HasTemplateKWAndArgsInfo =
1730 TemplateArgs || TemplateKWLoc.isValid();
1731
1732 // FIXME: remove remaining dependence computation to computeDependence().
1733 auto Deps = E->getDependence();
1734 if (TemplateArgs) {
1735 auto TemplateArgDeps = TemplateArgumentDependence::None;
1736 E->getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
1737 TemplateKWLoc, *TemplateArgs,
1738 E->getTrailingObjects<TemplateArgumentLoc>(), TemplateArgDeps);
1739 for (const TemplateArgumentLoc &ArgLoc : TemplateArgs->arguments()) {
1740 Deps |= toExprDependence(ArgLoc.getArgument().getDependence());
1741 }
1742 } else if (TemplateKWLoc.isValid()) {
1743 E->getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
1744 TemplateKWLoc);
1745 }
1746 E->setDependence(Deps);
1747
1748 return E;
1749}
1750
1752 bool HasQualifier, bool HasFoundDecl,
1753 bool HasTemplateKWAndArgsInfo,
1754 unsigned NumTemplateArgs) {
1755 assert((!NumTemplateArgs || HasTemplateKWAndArgsInfo) &&
1756 "template args but no template arg info?");
1757 bool HasQualOrFound = HasQualifier || HasFoundDecl;
1758 std::size_t Size =
1760 TemplateArgumentLoc>(HasQualOrFound ? 1 : 0,
1761 HasTemplateKWAndArgsInfo ? 1 : 0,
1762 NumTemplateArgs);
1763 void *Mem = Context.Allocate(Size, alignof(MemberExpr));
1764 return new (Mem) MemberExpr(EmptyShell());
1765}
1766
1768 MemberDecl = NewD;
1769 if (getType()->isUndeducedType())
1770 setType(NewD->getType());
1772}
1773
1775 if (isImplicitAccess()) {
1776 if (hasQualifier())
1777 return getQualifierLoc().getBeginLoc();
1778 return MemberLoc;
1779 }
1780
1781 // FIXME: We don't want this to happen. Rather, we should be able to
1782 // detect all kinds of implicit accesses more cleanly.
1783 SourceLocation BaseStartLoc = getBase()->getBeginLoc();
1784 if (BaseStartLoc.isValid())
1785 return BaseStartLoc;
1786 return MemberLoc;
1787}
1791 EndLoc = getRAngleLoc();
1792 else if (EndLoc.isInvalid())
1793 EndLoc = getBase()->getEndLoc();
1794 return EndLoc;
1795}
1796
1797bool CastExpr::CastConsistency() const {
1798 switch (getCastKind()) {
1799 case CK_DerivedToBase:
1800 case CK_UncheckedDerivedToBase:
1801 case CK_DerivedToBaseMemberPointer:
1802 case CK_BaseToDerived:
1803 case CK_BaseToDerivedMemberPointer:
1804 assert(!path_empty() && "Cast kind should have a base path!");
1805 break;
1806
1807 case CK_CPointerToObjCPointerCast:
1808 assert(getType()->isObjCObjectPointerType());
1809 assert(getSubExpr()->getType()->isPointerType());
1810 goto CheckNoBasePath;
1811
1812 case CK_BlockPointerToObjCPointerCast:
1813 assert(getType()->isObjCObjectPointerType());
1814 assert(getSubExpr()->getType()->isBlockPointerType());
1815 goto CheckNoBasePath;
1816
1817 case CK_ReinterpretMemberPointer:
1818 assert(getType()->isMemberPointerType());
1819 assert(getSubExpr()->getType()->isMemberPointerType());
1820 goto CheckNoBasePath;
1821
1822 case CK_BitCast:
1823 // Arbitrary casts to C pointer types count as bitcasts.
1824 // Otherwise, we should only have block and ObjC pointer casts
1825 // here if they stay within the type kind.
1826 if (!getType()->isPointerType()) {
1827 assert(getType()->isObjCObjectPointerType() ==
1828 getSubExpr()->getType()->isObjCObjectPointerType());
1829 assert(getType()->isBlockPointerType() ==
1830 getSubExpr()->getType()->isBlockPointerType());
1831 }
1832 goto CheckNoBasePath;
1833
1834 case CK_AnyPointerToBlockPointerCast:
1835 assert(getType()->isBlockPointerType());
1836 assert(getSubExpr()->getType()->isAnyPointerType() &&
1837 !getSubExpr()->getType()->isBlockPointerType());
1838 goto CheckNoBasePath;
1839
1840 case CK_CopyAndAutoreleaseBlockObject:
1841 assert(getType()->isBlockPointerType());
1842 assert(getSubExpr()->getType()->isBlockPointerType());
1843 goto CheckNoBasePath;
1844
1845 case CK_FunctionToPointerDecay:
1846 assert(getType()->isPointerType());
1847 assert(getSubExpr()->getType()->isFunctionType());
1848 goto CheckNoBasePath;
1849
1850 case CK_AddressSpaceConversion: {
1851 auto Ty = getType();
1852 auto SETy = getSubExpr()->getType();
1854 if (isPRValue() && !Ty->isDependentType() && !SETy->isDependentType()) {
1855 Ty = Ty->getPointeeType();
1856 SETy = SETy->getPointeeType();
1857 }
1858 assert((Ty->isDependentType() || SETy->isDependentType()) ||
1859 (!Ty.isNull() && !SETy.isNull() &&
1860 Ty.getAddressSpace() != SETy.getAddressSpace()));
1861 goto CheckNoBasePath;
1862 }
1863 // These should not have an inheritance path.
1864 case CK_Dynamic:
1865 case CK_ToUnion:
1866 case CK_ArrayToPointerDecay:
1867 case CK_NullToMemberPointer:
1868 case CK_NullToPointer:
1869 case CK_ConstructorConversion:
1870 case CK_IntegralToPointer:
1871 case CK_PointerToIntegral:
1872 case CK_ToVoid:
1873 case CK_VectorSplat:
1874 case CK_IntegralCast:
1875 case CK_BooleanToSignedIntegral:
1876 case CK_IntegralToFloating:
1877 case CK_FloatingToIntegral:
1878 case CK_FloatingCast:
1879 case CK_ObjCObjectLValueCast:
1880 case CK_FloatingRealToComplex:
1881 case CK_FloatingComplexToReal:
1882 case CK_FloatingComplexCast:
1883 case CK_FloatingComplexToIntegralComplex:
1884 case CK_IntegralRealToComplex:
1885 case CK_IntegralComplexToReal:
1886 case CK_IntegralComplexCast:
1887 case CK_IntegralComplexToFloatingComplex:
1888 case CK_ARCProduceObject:
1889 case CK_ARCConsumeObject:
1890 case CK_ARCReclaimReturnedObject:
1891 case CK_ARCExtendBlockObject:
1892 case CK_ZeroToOCLOpaqueType:
1893 case CK_IntToOCLSampler:
1894 case CK_FloatingToFixedPoint:
1895 case CK_FixedPointToFloating:
1896 case CK_FixedPointCast:
1897 case CK_FixedPointToIntegral:
1898 case CK_IntegralToFixedPoint:
1899 case CK_MatrixCast:
1900 case CK_HLSLVectorTruncation:
1901 assert(!getType()->isBooleanType() && "unheralded conversion to bool");
1902 goto CheckNoBasePath;
1903
1904 case CK_Dependent:
1905 case CK_LValueToRValue:
1906 case CK_NoOp:
1907 case CK_AtomicToNonAtomic:
1908 case CK_NonAtomicToAtomic:
1909 case CK_PointerToBoolean:
1910 case CK_IntegralToBoolean:
1911 case CK_FloatingToBoolean:
1912 case CK_MemberPointerToBoolean:
1913 case CK_FloatingComplexToBoolean:
1914 case CK_IntegralComplexToBoolean:
1915 case CK_LValueBitCast: // -> bool&
1916 case CK_LValueToRValueBitCast:
1917 case CK_UserDefinedConversion: // operator bool()
1918 case CK_BuiltinFnToFnPtr:
1919 case CK_FixedPointToBoolean:
1920 CheckNoBasePath:
1921 assert(path_empty() && "Cast kind should not have a base path!");
1922 break;
1923 }
1924 return true;
1925}
1926
1928 switch (CK) {
1929#define CAST_OPERATION(Name) case CK_##Name: return #Name;
1930#include "clang/AST/OperationKinds.def"
1931 }
1932 llvm_unreachable("Unhandled cast kind!");
1933}
1934
1935namespace {
1936// Skip over implicit nodes produced as part of semantic analysis.
1937// Designed for use with IgnoreExprNodes.
1938static Expr *ignoreImplicitSemaNodes(Expr *E) {
1939 if (auto *Materialize = dyn_cast<MaterializeTemporaryExpr>(E))
1940 return Materialize->getSubExpr();
1941
1942 if (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
1943 return Binder->getSubExpr();
1944
1945 if (auto *Full = dyn_cast<FullExpr>(E))
1946 return Full->getSubExpr();
1947
1948 if (auto *CPLIE = dyn_cast<CXXParenListInitExpr>(E);
1949 CPLIE && CPLIE->getInitExprs().size() == 1)
1950 return CPLIE->getInitExprs()[0];
1951
1952 return E;
1953}
1954} // namespace
1955
1957 const Expr *SubExpr = nullptr;
1958
1959 for (const CastExpr *E = this; E; E = dyn_cast<ImplicitCastExpr>(SubExpr)) {
1960 SubExpr = IgnoreExprNodes(E->getSubExpr(), ignoreImplicitSemaNodes);
1961
1962 // Conversions by constructor and conversion functions have a
1963 // subexpression describing the call; strip it off.
1964 if (E->getCastKind() == CK_ConstructorConversion) {
1965 SubExpr = IgnoreExprNodes(cast<CXXConstructExpr>(SubExpr)->getArg(0),
1966 ignoreImplicitSemaNodes);
1967 } else if (E->getCastKind() == CK_UserDefinedConversion) {
1968 assert((isa<CXXMemberCallExpr>(SubExpr) || isa<BlockExpr>(SubExpr)) &&
1969 "Unexpected SubExpr for CK_UserDefinedConversion.");
1970 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SubExpr))
1971 SubExpr = MCE->getImplicitObjectArgument();
1972 }
1973 }
1974
1975 return const_cast<Expr *>(SubExpr);
1976}
1977
1979 const Expr *SubExpr = nullptr;
1980
1981 for (const CastExpr *E = this; E; E = dyn_cast<ImplicitCastExpr>(SubExpr)) {
1982 SubExpr = IgnoreExprNodes(E->getSubExpr(), ignoreImplicitSemaNodes);
1983
1984 if (E->getCastKind() == CK_ConstructorConversion)
1985 return cast<CXXConstructExpr>(SubExpr)->getConstructor();
1986
1987 if (E->getCastKind() == CK_UserDefinedConversion) {
1988 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SubExpr))
1989 return MCE->getMethodDecl();
1990 }
1991 }
1992
1993 return nullptr;
1994}
1995
1996CXXBaseSpecifier **CastExpr::path_buffer() {
1997 switch (getStmtClass()) {
1998#define ABSTRACT_STMT(x)
1999#define CASTEXPR(Type, Base) \
2000 case Stmt::Type##Class: \
2001 return static_cast<Type *>(this)->getTrailingObjects<CXXBaseSpecifier *>();
2002#define STMT(Type, Base)
2003#include "clang/AST/StmtNodes.inc"
2004 default:
2005 llvm_unreachable("non-cast expressions not possible here");
2006 }
2007}
2008
2010 QualType opType) {
2011 auto RD = unionType->castAs<RecordType>()->getDecl();
2012 return getTargetFieldForToUnionCast(RD, opType);
2013}
2014
2016 QualType OpType) {
2017 auto &Ctx = RD->getASTContext();
2018 RecordDecl::field_iterator Field, FieldEnd;
2019 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
2020 Field != FieldEnd; ++Field) {
2021 if (Ctx.hasSameUnqualifiedType(Field->getType(), OpType) &&
2022 !Field->isUnnamedBitfield()) {
2023 return *Field;
2024 }
2025 }
2026 return nullptr;
2027}
2028
2030 assert(hasStoredFPFeatures());
2031 switch (getStmtClass()) {
2032 case ImplicitCastExprClass:
2033 return static_cast<ImplicitCastExpr *>(this)
2034 ->getTrailingObjects<FPOptionsOverride>();
2035 case CStyleCastExprClass:
2036 return static_cast<CStyleCastExpr *>(this)
2037 ->getTrailingObjects<FPOptionsOverride>();
2038 case CXXFunctionalCastExprClass:
2039 return static_cast<CXXFunctionalCastExpr *>(this)
2040 ->getTrailingObjects<FPOptionsOverride>();
2041 case CXXStaticCastExprClass:
2042 return static_cast<CXXStaticCastExpr *>(this)
2043 ->getTrailingObjects<FPOptionsOverride>();
2044 default:
2045 llvm_unreachable("Cast does not have FPFeatures");
2046 }
2047}
2048
2050 CastKind Kind, Expr *Operand,
2051 const CXXCastPath *BasePath,
2052 ExprValueKind VK,
2053 FPOptionsOverride FPO) {
2054 unsigned PathSize = (BasePath ? BasePath->size() : 0);
2055 void *Buffer =
2056 C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *, FPOptionsOverride>(
2057 PathSize, FPO.requiresTrailingStorage()));
2058 // Per C++ [conv.lval]p3, lvalue-to-rvalue conversions on class and
2059 // std::nullptr_t have special semantics not captured by CK_LValueToRValue.
2060 assert((Kind != CK_LValueToRValue ||
2061 !(T->isNullPtrType() || T->getAsCXXRecordDecl())) &&
2062 "invalid type for lvalue-to-rvalue conversion");
2063 ImplicitCastExpr *E =
2064 new (Buffer) ImplicitCastExpr(T, Kind, Operand, PathSize, FPO, VK);
2065 if (PathSize)
2066 std::uninitialized_copy_n(BasePath->data(), BasePath->size(),
2067 E->getTrailingObjects<CXXBaseSpecifier *>());
2068 return E;
2069}
2070
2072 unsigned PathSize,
2073 bool HasFPFeatures) {
2074 void *Buffer =
2075 C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *, FPOptionsOverride>(
2076 PathSize, HasFPFeatures));
2077 return new (Buffer) ImplicitCastExpr(EmptyShell(), PathSize, HasFPFeatures);
2078}
2079
2081 ExprValueKind VK, CastKind K, Expr *Op,
2082 const CXXCastPath *BasePath,
2084 TypeSourceInfo *WrittenTy,
2086 unsigned PathSize = (BasePath ? BasePath->size() : 0);
2087 void *Buffer =
2088 C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *, FPOptionsOverride>(
2089 PathSize, FPO.requiresTrailingStorage()));
2090 CStyleCastExpr *E =
2091 new (Buffer) CStyleCastExpr(T, VK, K, Op, PathSize, FPO, WrittenTy, L, R);
2092 if (PathSize)
2093 std::uninitialized_copy_n(BasePath->data(), BasePath->size(),
2094 E->getTrailingObjects<CXXBaseSpecifier *>());
2095 return E;
2096}
2097
2099 unsigned PathSize,
2100 bool HasFPFeatures) {
2101 void *Buffer =
2102 C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *, FPOptionsOverride>(
2103 PathSize, HasFPFeatures));
2104 return new (Buffer) CStyleCastExpr(EmptyShell(), PathSize, HasFPFeatures);
2105}
2106
2107/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
2108/// corresponds to, e.g. "<<=".
2110 switch (Op) {
2111#define BINARY_OPERATION(Name, Spelling) case BO_##Name: return Spelling;
2112#include "clang/AST/OperationKinds.def"
2113 }
2114 llvm_unreachable("Invalid OpCode!");
2115}
2116
2119 switch (OO) {
2120 default: llvm_unreachable("Not an overloadable binary operator");
2121 case OO_Plus: return BO_Add;
2122 case OO_Minus: return BO_Sub;
2123 case OO_Star: return BO_Mul;
2124 case OO_Slash: return BO_Div;
2125 case OO_Percent: return BO_Rem;
2126 case OO_Caret: return BO_Xor;
2127 case OO_Amp: return BO_And;
2128 case OO_Pipe: return BO_Or;
2129 case OO_Equal: return BO_Assign;
2130 case OO_Spaceship: return BO_Cmp;
2131 case OO_Less: return BO_LT;
2132 case OO_Greater: return BO_GT;
2133 case OO_PlusEqual: return BO_AddAssign;
2134 case OO_MinusEqual: return BO_SubAssign;
2135 case OO_StarEqual: return BO_MulAssign;
2136 case OO_SlashEqual: return BO_DivAssign;
2137 case OO_PercentEqual: return BO_RemAssign;
2138 case OO_CaretEqual: return BO_XorAssign;
2139 case OO_AmpEqual: return BO_AndAssign;
2140 case OO_PipeEqual: return BO_OrAssign;
2141 case OO_LessLess: return BO_Shl;
2142 case OO_GreaterGreater: return BO_Shr;
2143 case OO_LessLessEqual: return BO_ShlAssign;
2144 case OO_GreaterGreaterEqual: return BO_ShrAssign;
2145 case OO_EqualEqual: return BO_EQ;
2146 case OO_ExclaimEqual: return BO_NE;
2147 case OO_LessEqual: return BO_LE;
2148 case OO_GreaterEqual: return BO_GE;
2149 case OO_AmpAmp: return BO_LAnd;
2150 case OO_PipePipe: return BO_LOr;
2151 case OO_Comma: return BO_Comma;
2152 case OO_ArrowStar: return BO_PtrMemI;
2153 }
2154}
2155
2157 static const OverloadedOperatorKind OverOps[] = {
2158 /* .* Cannot be overloaded */OO_None, OO_ArrowStar,
2159 OO_Star, OO_Slash, OO_Percent,
2160 OO_Plus, OO_Minus,
2161 OO_LessLess, OO_GreaterGreater,
2162 OO_Spaceship,
2163 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
2164 OO_EqualEqual, OO_ExclaimEqual,
2165 OO_Amp,
2166 OO_Caret,
2167 OO_Pipe,
2168 OO_AmpAmp,
2169 OO_PipePipe,
2170 OO_Equal, OO_StarEqual,
2171 OO_SlashEqual, OO_PercentEqual,
2172 OO_PlusEqual, OO_MinusEqual,
2173 OO_LessLessEqual, OO_GreaterGreaterEqual,
2174 OO_AmpEqual, OO_CaretEqual,
2175 OO_PipeEqual,
2176 OO_Comma
2177 };
2178 return OverOps[Opc];
2179}
2180
2182 Opcode Opc,
2183 const Expr *LHS,
2184 const Expr *RHS) {
2185 if (Opc != BO_Add)
2186 return false;
2187
2188 // Check that we have one pointer and one integer operand.
2189 const Expr *PExp;
2190 if (LHS->getType()->isPointerType()) {
2191 if (!RHS->getType()->isIntegerType())
2192 return false;
2193 PExp = LHS;
2194 } else if (RHS->getType()->isPointerType()) {
2195 if (!LHS->getType()->isIntegerType())
2196 return false;
2197 PExp = RHS;
2198 } else {
2199 return false;
2200 }
2201
2202 // Check that the pointer is a nullptr.
2203 if (!PExp->IgnoreParenCasts()
2205 return false;
2206
2207 // Check that the pointee type is char-sized.
2208 const PointerType *PTy = PExp->getType()->getAs<PointerType>();
2209 if (!PTy || !PTy->getPointeeType()->isCharType())
2210 return false;
2211
2212 return true;
2213}
2214
2216 QualType ResultTy, SourceLocation BLoc,
2217 SourceLocation RParenLoc,
2218 DeclContext *ParentContext)
2219 : Expr(SourceLocExprClass, ResultTy, VK_PRValue, OK_Ordinary),
2220 BuiltinLoc(BLoc), RParenLoc(RParenLoc), ParentContext(ParentContext) {
2221 SourceLocExprBits.Kind = llvm::to_underlying(Kind);
2222 // In dependent contexts, function names may change.
2223 setDependence(MayBeDependent(Kind) && ParentContext->isDependentContext()
2224 ? ExprDependence::Value
2225 : ExprDependence::None);
2226}
2227
2229 switch (getIdentKind()) {
2231 return "__builtin_FILE";
2233 return "__builtin_FILE_NAME";
2235 return "__builtin_FUNCTION";
2237 return "__builtin_FUNCSIG";
2239 return "__builtin_LINE";
2241 return "__builtin_COLUMN";
2243 return "__builtin_source_location";
2244 }
2245 llvm_unreachable("unexpected IdentKind!");
2246}
2247
2249 const Expr *DefaultExpr) const {
2250 SourceLocation Loc;
2251 const DeclContext *Context;
2252
2253 if (const auto *DIE = dyn_cast_if_present<CXXDefaultInitExpr>(DefaultExpr)) {
2254 Loc = DIE->getUsedLocation();
2255 Context = DIE->getUsedContext();
2256 } else if (const auto *DAE =
2257 dyn_cast_if_present<CXXDefaultArgExpr>(DefaultExpr)) {
2258 Loc = DAE->getUsedLocation();
2259 Context = DAE->getUsedContext();
2260 } else {
2261 Loc = getLocation();
2262 Context = getParentContext();
2263 }
2264
2267
2268 auto MakeStringLiteral = [&](StringRef Tmp) {
2269 using LValuePathEntry = APValue::LValuePathEntry;
2271 // Decay the string to a pointer to the first character.
2272 LValuePathEntry Path[1] = {LValuePathEntry::ArrayIndex(0)};
2273 return APValue(Res, CharUnits::Zero(), Path, /*OnePastTheEnd=*/false);
2274 };
2275
2276 switch (getIdentKind()) {
2278 // __builtin_FILE_NAME() is a Clang-specific extension that expands to the
2279 // the last part of __builtin_FILE().
2282 FileName, PLoc, Ctx.getLangOpts(), Ctx.getTargetInfo());
2283 return MakeStringLiteral(FileName);
2284 }
2286 SmallString<256> Path(PLoc.getFilename());
2288 Ctx.getTargetInfo());
2289 return MakeStringLiteral(Path);
2290 }
2293 const auto *CurDecl = dyn_cast<Decl>(Context);
2294 const auto Kind = getIdentKind() == SourceLocIdentKind::Function
2297 return MakeStringLiteral(
2298 CurDecl ? PredefinedExpr::ComputeName(Kind, CurDecl) : std::string(""));
2299 }
2301 return APValue(Ctx.MakeIntValue(PLoc.getLine(), Ctx.UnsignedIntTy));
2303 return APValue(Ctx.MakeIntValue(PLoc.getColumn(), Ctx.UnsignedIntTy));
2305 // Fill in a std::source_location::__impl structure, by creating an
2306 // artificial file-scoped CompoundLiteralExpr, and returning a pointer to
2307 // that.
2308 const CXXRecordDecl *ImplDecl = getType()->getPointeeCXXRecordDecl();
2309 assert(ImplDecl);
2310
2311 // Construct an APValue for the __impl struct, and get or create a Decl
2312 // corresponding to that. Note that we've already verified that the shape of
2313 // the ImplDecl type is as expected.
2314
2316 for (const FieldDecl *F : ImplDecl->fields()) {
2317 StringRef Name = F->getName();
2318 if (Name == "_M_file_name") {
2319 SmallString<256> Path(PLoc.getFilename());
2321 Ctx.getTargetInfo());
2322 Value.getStructField(F->getFieldIndex()) = MakeStringLiteral(Path);
2323 } else if (Name == "_M_function_name") {
2324 // Note: this emits the PrettyFunction name -- different than what
2325 // __builtin_FUNCTION() above returns!
2326 const auto *CurDecl = dyn_cast<Decl>(Context);
2327 Value.getStructField(F->getFieldIndex()) = MakeStringLiteral(
2328 CurDecl && !isa<TranslationUnitDecl>(CurDecl)
2329 ? StringRef(PredefinedExpr::ComputeName(
2331 : "");
2332 } else if (Name == "_M_line") {
2333 llvm::APSInt IntVal = Ctx.MakeIntValue(PLoc.getLine(), F->getType());
2334 Value.getStructField(F->getFieldIndex()) = APValue(IntVal);
2335 } else if (Name == "_M_column") {
2336 llvm::APSInt IntVal = Ctx.MakeIntValue(PLoc.getColumn(), F->getType());
2337 Value.getStructField(F->getFieldIndex()) = APValue(IntVal);
2338 }
2339 }
2340
2342 Ctx.getUnnamedGlobalConstantDecl(getType()->getPointeeType(), Value);
2343
2345 false);
2346 }
2347 }
2348 llvm_unreachable("unhandled case");
2349}
2350
2352 ArrayRef<Expr *> initExprs, SourceLocation rbraceloc)
2353 : Expr(InitListExprClass, QualType(), VK_PRValue, OK_Ordinary),
2354 InitExprs(C, initExprs.size()), LBraceLoc(lbraceloc),
2355 RBraceLoc(rbraceloc), AltForm(nullptr, true) {
2357 InitExprs.insert(C, InitExprs.end(), initExprs.begin(), initExprs.end());
2358
2360}
2361
2362void InitListExpr::reserveInits(const ASTContext &C, unsigned NumInits) {
2363 if (NumInits > InitExprs.size())
2364 InitExprs.reserve(C, NumInits);
2365}
2366
2367void InitListExpr::resizeInits(const ASTContext &C, unsigned NumInits) {
2368 InitExprs.resize(C, NumInits, nullptr);
2369}
2370
2372 if (Init >= InitExprs.size()) {
2373 InitExprs.insert(C, InitExprs.end(), Init - InitExprs.size() + 1, nullptr);
2374 setInit(Init, expr);
2375 return nullptr;
2376 }
2377
2378 Expr *Result = cast_or_null<Expr>(InitExprs[Init]);
2379 setInit(Init, expr);
2380 return Result;
2381}
2382
2384 assert(!hasArrayFiller() && "Filler already set!");
2385 ArrayFillerOrUnionFieldInit = filler;
2386 // Fill out any "holes" in the array due to designated initializers.
2387 Expr **inits = getInits();
2388 for (unsigned i = 0, e = getNumInits(); i != e; ++i)
2389 if (inits[i] == nullptr)
2390 inits[i] = filler;
2391}
2392
2394 if (getNumInits() != 1)
2395 return false;
2396 const ArrayType *AT = getType()->getAsArrayTypeUnsafe();
2397 if (!AT || !AT->getElementType()->isIntegerType())
2398 return false;
2399 // It is possible for getInit() to return null.
2400 const Expr *Init = getInit(0);
2401 if (!Init)
2402 return false;
2403 Init = Init->IgnoreParenImpCasts();
2404 return isa<StringLiteral>(Init) || isa<ObjCEncodeExpr>(Init);
2405}
2406
2408 assert(isSemanticForm() && "syntactic form never semantically transparent");
2409
2410 // A glvalue InitListExpr is always just sugar.
2411 if (isGLValue()) {
2412 assert(getNumInits() == 1 && "multiple inits in glvalue init list");
2413 return true;
2414 }
2415
2416 // Otherwise, we're sugar if and only if we have exactly one initializer that
2417 // is of the same type.
2418 if (getNumInits() != 1 || !getInit(0))
2419 return false;
2420
2421 // Don't confuse aggregate initialization of a struct X { X &x; }; with a
2422 // transparent struct copy.
2423 if (!getInit(0)->isPRValue() && getType()->isRecordType())
2424 return false;
2425
2426 return getType().getCanonicalType() ==
2428}
2429
2431 assert(isSyntacticForm() && "only test syntactic form as zero initializer");
2432
2433 if (LangOpts.CPlusPlus || getNumInits() != 1 || !getInit(0)) {
2434 return false;
2435 }
2436
2437 const IntegerLiteral *Lit = dyn_cast<IntegerLiteral>(getInit(0)->IgnoreImplicit());
2438 return Lit && Lit->getValue() == 0;
2439}
2440
2442 if (InitListExpr *SyntacticForm = getSyntacticForm())
2443 return SyntacticForm->getBeginLoc();
2444 SourceLocation Beg = LBraceLoc;
2445 if (Beg.isInvalid()) {
2446 // Find the first non-null initializer.
2447 for (InitExprsTy::const_iterator I = InitExprs.begin(),
2448 E = InitExprs.end();
2449 I != E; ++I) {
2450 if (Stmt *S = *I) {
2451 Beg = S->getBeginLoc();
2452 break;
2453 }
2454 }
2455 }
2456 return Beg;
2457}
2458
2460 if (InitListExpr *SyntacticForm = getSyntacticForm())
2461 return SyntacticForm->getEndLoc();
2462 SourceLocation End = RBraceLoc;
2463 if (End.isInvalid()) {
2464 // Find the first non-null initializer from the end.
2465 for (Stmt *S : llvm::reverse(InitExprs)) {
2466 if (S) {
2467 End = S->getEndLoc();
2468 break;
2469 }
2470 }
2471 }
2472 return End;
2473}
2474
2475/// getFunctionType - Return the underlying function type for this block.
2476///
2478 // The block pointer is never sugared, but the function type might be.
2479 return cast<BlockPointerType>(getType())
2481}
2482
2484 return TheBlock->getCaretLocation();
2485}
2486const Stmt *BlockExpr::getBody() const {
2487 return TheBlock->getBody();
2488}
2490 return TheBlock->getBody();
2491}
2492
2493
2494//===----------------------------------------------------------------------===//
2495// Generic Expression Routines
2496//===----------------------------------------------------------------------===//
2497
2499 // In C++11, discarded-value expressions of a certain form are special,
2500 // according to [expr]p10:
2501 // The lvalue-to-rvalue conversion (4.1) is applied only if the
2502 // expression is a glvalue of volatile-qualified type and it has
2503 // one of the following forms:
2504 if (!isGLValue() || !getType().isVolatileQualified())
2505 return false;
2506
2507 const Expr *E = IgnoreParens();
2508
2509 // - id-expression (5.1.1),
2510 if (isa<DeclRefExpr>(E))
2511 return true;
2512
2513 // - subscripting (5.2.1),
2514 if (isa<ArraySubscriptExpr>(E))
2515 return true;
2516
2517 // - class member access (5.2.5),
2518 if (isa<MemberExpr>(E))
2519 return true;
2520
2521 // - indirection (5.3.1),
2522 if (auto *UO = dyn_cast<UnaryOperator>(E))
2523 if (UO->getOpcode() == UO_Deref)
2524 return true;
2525
2526 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
2527 // - pointer-to-member operation (5.5),
2528 if (BO->isPtrMemOp())
2529 return true;
2530
2531 // - comma expression (5.18) where the right operand is one of the above.
2532 if (BO->getOpcode() == BO_Comma)
2533 return BO->getRHS()->isReadIfDiscardedInCPlusPlus11();
2534 }
2535
2536 // - conditional expression (5.16) where both the second and the third
2537 // operands are one of the above, or
2538 if (auto *CO = dyn_cast<ConditionalOperator>(E))
2539 return CO->getTrueExpr()->isReadIfDiscardedInCPlusPlus11() &&
2540 CO->getFalseExpr()->isReadIfDiscardedInCPlusPlus11();
2541 // The related edge case of "*x ?: *x".
2542 if (auto *BCO =
2543 dyn_cast<BinaryConditionalOperator>(E)) {
2544 if (auto *OVE = dyn_cast<OpaqueValueExpr>(BCO->getTrueExpr()))
2545 return OVE->getSourceExpr()->isReadIfDiscardedInCPlusPlus11() &&
2546 BCO->getFalseExpr()->isReadIfDiscardedInCPlusPlus11();
2547 }
2548
2549 // Objective-C++ extensions to the rule.
2550 if (isa<ObjCIvarRefExpr>(E))
2551 return true;
2552 if (const auto *POE = dyn_cast<PseudoObjectExpr>(E)) {
2553 if (isa<ObjCPropertyRefExpr, ObjCSubscriptRefExpr>(POE->getSyntacticForm()))
2554 return true;
2555 }
2556
2557 return false;
2558}
2559
2560/// isUnusedResultAWarning - Return true if this immediate expression should
2561/// be warned about if the result is unused. If so, fill in Loc and Ranges
2562/// with location to warn on and the source range[s] to report with the
2563/// warning.
2565 SourceRange &R1, SourceRange &R2,
2566 ASTContext &Ctx) const {
2567 // Don't warn if the expr is type dependent. The type could end up
2568 // instantiating to void.
2569 if (isTypeDependent())
2570 return false;
2571
2572 switch (getStmtClass()) {
2573 default:
2574 if (getType()->isVoidType())
2575 return false;
2576 WarnE = this;
2577 Loc = getExprLoc();
2578 R1 = getSourceRange();
2579 return true;
2580 case ParenExprClass:
2581 return cast<ParenExpr>(this)->getSubExpr()->
2582 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2583 case GenericSelectionExprClass:
2584 return cast<GenericSelectionExpr>(this)->getResultExpr()->
2585 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2586 case CoawaitExprClass:
2587 case CoyieldExprClass:
2588 return cast<CoroutineSuspendExpr>(this)->getResumeExpr()->
2589 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2590 case ChooseExprClass:
2591 return cast<ChooseExpr>(this)->getChosenSubExpr()->
2592 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2593 case UnaryOperatorClass: {
2594 const UnaryOperator *UO = cast<UnaryOperator>(this);
2595
2596 switch (UO->getOpcode()) {
2597 case UO_Plus:
2598 case UO_Minus:
2599 case UO_AddrOf:
2600 case UO_Not:
2601 case UO_LNot:
2602 case UO_Deref:
2603 break;
2604 case UO_Coawait:
2605 // This is just the 'operator co_await' call inside the guts of a
2606 // dependent co_await call.
2607 case UO_PostInc:
2608 case UO_PostDec:
2609 case UO_PreInc:
2610 case UO_PreDec: // ++/--
2611 return false; // Not a warning.
2612 case UO_Real:
2613 case UO_Imag:
2614 // accessing a piece of a volatile complex is a side-effect.
2615 if (Ctx.getCanonicalType(UO->getSubExpr()->getType())
2617 return false;
2618 break;
2619 case UO_Extension:
2620 return UO->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2621 }
2622 WarnE = this;
2623 Loc = UO->getOperatorLoc();
2624 R1 = UO->getSubExpr()->getSourceRange();
2625 return true;
2626 }
2627 case BinaryOperatorClass: {
2628 const BinaryOperator *BO = cast<BinaryOperator>(this);
2629 switch (BO->getOpcode()) {
2630 default:
2631 break;
2632 // Consider the RHS of comma for side effects. LHS was checked by
2633 // Sema::CheckCommaOperands.
2634 case BO_Comma:
2635 // ((foo = <blah>), 0) is an idiom for hiding the result (and
2636 // lvalue-ness) of an assignment written in a macro.
2637 if (IntegerLiteral *IE =
2638 dyn_cast<IntegerLiteral>(BO->getRHS()->IgnoreParens()))
2639 if (IE->getValue() == 0)
2640 return false;
2641 return BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2642 // Consider '||', '&&' to have side effects if the LHS or RHS does.
2643 case BO_LAnd:
2644 case BO_LOr:
2645 if (!BO->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx) ||
2646 !BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx))
2647 return false;
2648 break;
2649 }
2650 if (BO->isAssignmentOp())
2651 return false;
2652 WarnE = this;
2653 Loc = BO->getOperatorLoc();
2654 R1 = BO->getLHS()->getSourceRange();
2655 R2 = BO->getRHS()->getSourceRange();
2656 return true;
2657 }
2658 case CompoundAssignOperatorClass:
2659 case VAArgExprClass:
2660 case AtomicExprClass:
2661 return false;
2662
2663 case ConditionalOperatorClass: {
2664 // If only one of the LHS or RHS is a warning, the operator might
2665 // be being used for control flow. Only warn if both the LHS and
2666 // RHS are warnings.
2667 const auto *Exp = cast<ConditionalOperator>(this);
2668 return Exp->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx) &&
2669 Exp->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2670 }
2671 case BinaryConditionalOperatorClass: {
2672 const auto *Exp = cast<BinaryConditionalOperator>(this);
2673 return Exp->getFalseExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2674 }
2675
2676 case MemberExprClass:
2677 WarnE = this;
2678 Loc = cast<MemberExpr>(this)->getMemberLoc();
2679 R1 = SourceRange(Loc, Loc);
2680 R2 = cast<MemberExpr>(this)->getBase()->getSourceRange();
2681 return true;
2682
2683 case ArraySubscriptExprClass:
2684 WarnE = this;
2685 Loc = cast<ArraySubscriptExpr>(this)->getRBracketLoc();
2686 R1 = cast<ArraySubscriptExpr>(this)->getLHS()->getSourceRange();
2687 R2 = cast<ArraySubscriptExpr>(this)->getRHS()->getSourceRange();
2688 return true;
2689
2690 case CXXOperatorCallExprClass: {
2691 // Warn about operator ==,!=,<,>,<=, and >= even when user-defined operator
2692 // overloads as there is no reasonable way to define these such that they
2693 // have non-trivial, desirable side-effects. See the -Wunused-comparison
2694 // warning: operators == and != are commonly typo'ed, and so warning on them
2695 // provides additional value as well. If this list is updated,
2696 // DiagnoseUnusedComparison should be as well.
2697 const CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(this);
2698 switch (Op->getOperator()) {
2699 default:
2700 break;
2701 case OO_EqualEqual:
2702 case OO_ExclaimEqual:
2703 case OO_Less:
2704 case OO_Greater:
2705 case OO_GreaterEqual:
2706 case OO_LessEqual:
2707 if (Op->getCallReturnType(Ctx)->isReferenceType() ||
2708 Op->getCallReturnType(Ctx)->isVoidType())
2709 break;
2710 WarnE = this;
2711 Loc = Op->getOperatorLoc();
2712 R1 = Op->getSourceRange();
2713 return true;
2714 }
2715
2716 // Fallthrough for generic call handling.
2717 [[fallthrough]];
2718 }
2719 case CallExprClass:
2720 case CXXMemberCallExprClass:
2721 case UserDefinedLiteralClass: {
2722 // If this is a direct call, get the callee.
2723 const CallExpr *CE = cast<CallExpr>(this);
2724 if (const Decl *FD = CE->getCalleeDecl()) {
2725 // If the callee has attribute pure, const, or warn_unused_result, warn
2726 // about it. void foo() { strlen("bar"); } should warn.
2727 //
2728 // Note: If new cases are added here, DiagnoseUnusedExprResult should be
2729 // updated to match for QoI.
2730 if (CE->hasUnusedResultAttr(Ctx) ||
2731 FD->hasAttr<PureAttr>() || FD->hasAttr<ConstAttr>()) {
2732 WarnE = this;
2733 Loc = CE->getCallee()->getBeginLoc();
2734 R1 = CE->getCallee()->getSourceRange();
2735
2736 if (unsigned NumArgs = CE->getNumArgs())
2737 R2 = SourceRange(CE->getArg(0)->getBeginLoc(),
2738 CE->getArg(NumArgs - 1)->getEndLoc());
2739 return true;
2740 }
2741 }
2742 return false;
2743 }
2744
2745 // If we don't know precisely what we're looking at, let's not warn.
2746 case UnresolvedLookupExprClass:
2747 case CXXUnresolvedConstructExprClass:
2748 case RecoveryExprClass:
2749 return false;
2750
2751 case CXXTemporaryObjectExprClass:
2752 case CXXConstructExprClass: {
2753 if (const CXXRecordDecl *Type = getType()->getAsCXXRecordDecl()) {
2754 const auto *WarnURAttr = Type->getAttr<WarnUnusedResultAttr>();
2755 if (Type->hasAttr<WarnUnusedAttr>() ||
2756 (WarnURAttr && WarnURAttr->IsCXX11NoDiscard())) {
2757 WarnE = this;
2758 Loc = getBeginLoc();
2759 R1 = getSourceRange();
2760 return true;
2761 }
2762 }
2763
2764 const auto *CE = cast<CXXConstructExpr>(this);
2765 if (const CXXConstructorDecl *Ctor = CE->getConstructor()) {
2766 const auto *WarnURAttr = Ctor->getAttr<WarnUnusedResultAttr>();
2767 if (WarnURAttr && WarnURAttr->IsCXX11NoDiscard()) {
2768 WarnE = this;
2769 Loc = getBeginLoc();
2770 R1 = getSourceRange();
2771
2772 if (unsigned NumArgs = CE->getNumArgs())
2773 R2 = SourceRange(CE->getArg(0)->getBeginLoc(),
2774 CE->getArg(NumArgs - 1)->getEndLoc());
2775 return true;
2776 }
2777 }
2778
2779 return false;
2780 }
2781
2782 case ObjCMessageExprClass: {
2783 const ObjCMessageExpr *ME = cast<ObjCMessageExpr>(this);
2784 if (Ctx.getLangOpts().ObjCAutoRefCount &&
2785 ME->isInstanceMessage() &&
2786 !ME->getType()->isVoidType() &&
2787 ME->getMethodFamily() == OMF_init) {
2788 WarnE = this;
2789 Loc = getExprLoc();
2790 R1 = ME->getSourceRange();
2791 return true;
2792 }
2793
2794 if (const ObjCMethodDecl *MD = ME->getMethodDecl())
2795 if (MD->hasAttr<WarnUnusedResultAttr>()) {
2796 WarnE = this;
2797 Loc = getExprLoc();
2798 return true;
2799 }
2800
2801 return false;
2802 }
2803
2804 case ObjCPropertyRefExprClass:
2805 case ObjCSubscriptRefExprClass:
2806 WarnE = this;
2807 Loc = getExprLoc();
2808 R1 = getSourceRange();
2809 return true;
2810
2811 case PseudoObjectExprClass: {
2812 const auto *POE = cast<PseudoObjectExpr>(this);
2813
2814 // For some syntactic forms, we should always warn.
2815 if (isa<ObjCPropertyRefExpr, ObjCSubscriptRefExpr>(
2816 POE->getSyntacticForm())) {
2817 WarnE = this;
2818 Loc = getExprLoc();
2819 R1 = getSourceRange();
2820 return true;
2821 }
2822
2823 // For others, we should never warn.
2824 if (auto *BO = dyn_cast<BinaryOperator>(POE->getSyntacticForm()))
2825 if (BO->isAssignmentOp())
2826 return false;
2827 if (auto *UO = dyn_cast<UnaryOperator>(POE->getSyntacticForm()))
2828 if (UO->isIncrementDecrementOp())
2829 return false;
2830
2831 // Otherwise, warn if the result expression would warn.
2832 const Expr *Result = POE->getResultExpr();
2833 return Result && Result->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2834 }
2835
2836 case StmtExprClass: {
2837 // Statement exprs don't logically have side effects themselves, but are
2838 // sometimes used in macros in ways that give them a type that is unused.
2839 // For example ({ blah; foo(); }) will end up with a type if foo has a type.
2840 // however, if the result of the stmt expr is dead, we don't want to emit a
2841 // warning.
2842 const CompoundStmt *CS = cast<StmtExpr>(this)->getSubStmt();
2843 if (!CS->body_empty()) {
2844 if (const Expr *E = dyn_cast<Expr>(CS->body_back()))
2845 return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2846 if (const LabelStmt *Label = dyn_cast<LabelStmt>(CS->body_back()))
2847 if (const Expr *E = dyn_cast<Expr>(Label->getSubStmt()))
2848 return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2849 }
2850
2851 if (getType()->isVoidType())
2852 return false;
2853 WarnE = this;
2854 Loc = cast<StmtExpr>(this)->getLParenLoc();
2855 R1 = getSourceRange();
2856 return true;
2857 }
2858 case CXXFunctionalCastExprClass:
2859 case CStyleCastExprClass: {
2860 // Ignore an explicit cast to void, except in C++98 if the operand is a
2861 // volatile glvalue for which we would trigger an implicit read in any
2862 // other language mode. (Such an implicit read always happens as part of
2863 // the lvalue conversion in C, and happens in C++ for expressions of all
2864 // forms where it seems likely the user intended to trigger a volatile
2865 // load.)
2866 const CastExpr *CE = cast<CastExpr>(this);
2867 const Expr *SubE = CE->getSubExpr()->IgnoreParens();
2868 if (CE->getCastKind() == CK_ToVoid) {
2869 if (Ctx.getLangOpts().CPlusPlus && !Ctx.getLangOpts().CPlusPlus11 &&
2871 // Suppress the "unused value" warning for idiomatic usage of
2872 // '(void)var;' used to suppress "unused variable" warnings.
2873 if (auto *DRE = dyn_cast<DeclRefExpr>(SubE))
2874 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
2875 if (!VD->isExternallyVisible())
2876 return false;
2877
2878 // The lvalue-to-rvalue conversion would have no effect for an array.
2879 // It's implausible that the programmer expected this to result in a
2880 // volatile array load, so don't warn.
2881 if (SubE->getType()->isArrayType())
2882 return false;
2883
2884 return SubE->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2885 }
2886 return false;
2887 }
2888
2889 // If this is a cast to a constructor conversion, check the operand.
2890 // Otherwise, the result of the cast is unused.
2891 if (CE->getCastKind() == CK_ConstructorConversion)
2892 return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2893 if (CE->getCastKind() == CK_Dependent)
2894 return false;
2895
2896 WarnE = this;
2897 if (const CXXFunctionalCastExpr *CXXCE =
2898 dyn_cast<CXXFunctionalCastExpr>(this)) {
2899 Loc = CXXCE->getBeginLoc();
2900 R1 = CXXCE->getSubExpr()->getSourceRange();
2901 } else {
2902 const CStyleCastExpr *CStyleCE = cast<CStyleCastExpr>(this);
2903 Loc = CStyleCE->getLParenLoc();
2904 R1 = CStyleCE->getSubExpr()->getSourceRange();
2905 }
2906 return true;
2907 }
2908 case ImplicitCastExprClass: {
2909 const CastExpr *ICE = cast<ImplicitCastExpr>(this);
2910
2911 // lvalue-to-rvalue conversion on a volatile lvalue is a side-effect.
2912 if (ICE->getCastKind() == CK_LValueToRValue &&
2914 return false;
2915
2916 return ICE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2917 }
2918 case CXXDefaultArgExprClass:
2919 return (cast<CXXDefaultArgExpr>(this)
2920 ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
2921 case CXXDefaultInitExprClass:
2922 return (cast<CXXDefaultInitExpr>(this)
2923 ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
2924
2925 case CXXNewExprClass:
2926 // FIXME: In theory, there might be new expressions that don't have side
2927 // effects (e.g. a placement new with an uninitialized POD).
2928 case CXXDeleteExprClass:
2929 return false;
2930 case MaterializeTemporaryExprClass:
2931 return cast<MaterializeTemporaryExpr>(this)
2932 ->getSubExpr()
2933 ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2934 case CXXBindTemporaryExprClass:
2935 return cast<CXXBindTemporaryExpr>(this)->getSubExpr()
2936 ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2937 case ExprWithCleanupsClass:
2938 return cast<ExprWithCleanups>(this)->getSubExpr()
2939 ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2940 }
2941}
2942
2943/// isOBJCGCCandidate - Check if an expression is objc gc'able.
2944/// returns true, if it is; false otherwise.
2946 const Expr *E = IgnoreParens();
2947 switch (E->getStmtClass()) {
2948 default:
2949 return false;
2950 case ObjCIvarRefExprClass:
2951 return true;
2952 case Expr::UnaryOperatorClass:
2953 return cast<UnaryOperator>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
2954 case ImplicitCastExprClass:
2955 return cast<ImplicitCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
2956 case MaterializeTemporaryExprClass:
2957 return cast<MaterializeTemporaryExpr>(E)->getSubExpr()->isOBJCGCCandidate(
2958 Ctx);
2959 case CStyleCastExprClass:
2960 return cast<CStyleCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
2961 case DeclRefExprClass: {
2962 const Decl *D = cast<DeclRefExpr>(E)->getDecl();
2963
2964 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2965 if (VD->hasGlobalStorage())
2966 return true;
2967 QualType T = VD->getType();
2968 // dereferencing to a pointer is always a gc'able candidate,
2969 // unless it is __weak.
2970 return T->isPointerType() &&
2972 }
2973 return false;
2974 }
2975 case MemberExprClass: {
2976 const MemberExpr *M = cast<MemberExpr>(E);
2977 return M->getBase()->isOBJCGCCandidate(Ctx);
2978 }
2979 case ArraySubscriptExprClass:
2980 return cast<ArraySubscriptExpr>(E)->getBase()->isOBJCGCCandidate(Ctx);
2981 }
2982}
2983
2985 if (isTypeDependent())
2986 return false;
2988}
2989
2991 assert(expr->hasPlaceholderType(BuiltinType::BoundMember));
2992
2993 // Bound member expressions are always one of these possibilities:
2994 // x->m x.m x->*y x.*y
2995 // (possibly parenthesized)
2996
2997 expr = expr->IgnoreParens();
2998 if (const MemberExpr *mem = dyn_cast<MemberExpr>(expr)) {
2999 assert(isa<CXXMethodDecl>(mem->getMemberDecl()));
3000 return mem->getMemberDecl()->getType();
3001 }
3002
3003 if (const BinaryOperator *op = dyn_cast<BinaryOperator>(expr)) {
3004 QualType type = op->getRHS()->getType()->castAs<MemberPointerType>()
3005 ->getPointeeType();
3006 assert(type->isFunctionType());
3007 return type;
3008 }
3009
3010 assert(isa<UnresolvedMemberExpr>(expr) || isa<CXXPseudoDestructorExpr>(expr));
3011 return QualType();
3012}
3013
3016}
3017
3020}
3021
3024}
3025
3028}
3029
3032}
3033
3037}
3038
3041}
3042
3044 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(this)) {
3045 if (MCE->getMethodDecl() && isa<CXXConversionDecl>(MCE->getMethodDecl()))
3046 return MCE->getImplicitObjectArgument();
3047 }
3048 return this;
3049}
3050
3054}
3055
3059}
3060
3062 auto IgnoreNoopCastsSingleStep = [&Ctx](Expr *E) {
3063 if (auto *CE = dyn_cast<CastExpr>(E)) {
3064 // We ignore integer <-> casts that are of the same width, ptr<->ptr and
3065 // ptr<->int casts of the same width. We also ignore all identity casts.
3066 Expr *SubExpr = CE->getSubExpr();
3067 bool IsIdentityCast =
3068 Ctx.hasSameUnqualifiedType(E->getType(), SubExpr->getType());
3069 bool IsSameWidthCast = (E->getType()->isPointerType() ||
3070 E->getType()->isIntegralType(Ctx)) &&
3071 (SubExpr->getType()->isPointerType() ||
3072 SubExpr->getType()->isIntegralType(Ctx)) &&
3073 (Ctx.getTypeSize(E->getType()) ==
3074 Ctx.getTypeSize(SubExpr->getType()));
3075
3076 if (IsIdentityCast || IsSameWidthCast)
3077 return SubExpr;
3078 } else if (auto *NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E))
3079 return NTTP->getReplacement();
3080
3081 return E;
3082 };
3084 IgnoreNoopCastsSingleStep);
3085}
3086
3089 if (auto *Cast = dyn_cast<CXXFunctionalCastExpr>(E)) {
3090 auto *SE = Cast->getSubExpr();
3091 if (SE->getSourceRange() == E->getSourceRange())
3092 return SE;
3093 }
3094
3095 if (auto *C = dyn_cast<CXXConstructExpr>(E)) {
3096 auto NumArgs = C->getNumArgs();
3097 if (NumArgs == 1 ||
3098 (NumArgs > 1 && isa<CXXDefaultArgExpr>(C->getArg(1)))) {
3099 Expr *A = C->getArg(0);
3100 if (A->getSourceRange() == E->getSourceRange() || C->isElidable())
3101 return A;
3102 }
3103 }
3104 return E;
3105 };
3106 auto IgnoreImplicitMemberCallSingleStep = [](Expr *E) {
3107 if (auto *C = dyn_cast<CXXMemberCallExpr>(E)) {
3108 Expr *ExprNode = C->getImplicitObjectArgument();
3109 if (ExprNode->getSourceRange() == E->getSourceRange()) {
3110 return ExprNode;
3111 }
3112 if (auto *PE = dyn_cast<ParenExpr>(ExprNode)) {
3113 if (PE->getSourceRange() == C->getSourceRange()) {
3114 return cast<Expr>(PE);
3115 }
3116 }
3117 ExprNode = ExprNode->IgnoreParenImpCasts();
3118 if (ExprNode->getSourceRange() == E->getSourceRange())
3119 return ExprNode;
3120 }
3121 return E;
3122 };
3123 return IgnoreExprNodes(
3126 IgnoreImplicitMemberCallSingleStep);
3127}
3128
3130 const Expr *E = this;
3131 if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
3132 E = M->getSubExpr();
3133
3134 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3135 E = ICE->getSubExprAsWritten();
3136
3137 return isa<CXXDefaultArgExpr>(E);
3138}
3139
3140/// Skip over any no-op casts and any temporary-binding
3141/// expressions.
3143 if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
3144 E = M->getSubExpr();
3145
3146 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3147 if (ICE->getCastKind() == CK_NoOp)
3148 E = ICE->getSubExpr();
3149 else
3150 break;
3151 }
3152
3153 while (const CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
3154 E = BE->getSubExpr();
3155
3156 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3157 if (ICE->getCastKind() == CK_NoOp)
3158 E = ICE->getSubExpr();
3159 else
3160 break;
3161 }
3162
3163 return E->IgnoreParens();
3164}
3165
3166/// isTemporaryObject - Determines if this expression produces a
3167/// temporary of the given class type.
3169 if (!C.hasSameUnqualifiedType(getType(), C.getTypeDeclType(TempTy)))
3170 return false;
3171
3173
3174 // Temporaries are by definition pr-values of class type.
3175 if (!E->Classify(C).isPRValue()) {
3176 // In this context, property reference is a message call and is pr-value.
3177 if (!isa<ObjCPropertyRefExpr>(E))
3178 return false;
3179 }
3180
3181 // Black-list a few cases which yield pr-values of class type that don't
3182 // refer to temporaries of that type:
3183
3184 // - implicit derived-to-base conversions
3185 if (isa<ImplicitCastExpr>(E)) {
3186 switch (cast<ImplicitCastExpr>(E)->getCastKind()) {
3187 case CK_DerivedToBase:
3188 case CK_UncheckedDerivedToBase:
3189 return false;
3190 default:
3191 break;
3192 }
3193 }
3194
3195 // - member expressions (all)
3196 if (isa<MemberExpr>(E))
3197 return false;
3198
3199 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E))
3200 if (BO->isPtrMemOp())
3201 return false;
3202
3203 // - opaque values (all)
3204 if (isa<OpaqueValueExpr>(E))
3205 return false;
3206
3207 return true;
3208}
3209
3211 const Expr *E = this;
3212
3213 // Strip away parentheses and casts we don't care about.
3214 while (true) {
3215 if (const ParenExpr *Paren = dyn_cast<ParenExpr>(E)) {
3216 E = Paren->getSubExpr();
3217 continue;
3218 }
3219
3220 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3221 if (ICE->getCastKind() == CK_NoOp ||
3222 ICE->getCastKind() == CK_LValueToRValue ||
3223 ICE->getCastKind() == CK_DerivedToBase ||
3224 ICE->getCastKind() == CK_UncheckedDerivedToBase) {
3225 E = ICE->getSubExpr();
3226 continue;
3227 }
3228 }
3229
3230 if (const UnaryOperator* UnOp = dyn_cast<UnaryOperator>(E)) {
3231 if (UnOp->getOpcode() == UO_Extension) {
3232 E = UnOp->getSubExpr();
3233 continue;
3234 }
3235 }
3236
3237 if (const MaterializeTemporaryExpr *M
3238 = dyn_cast<MaterializeTemporaryExpr>(E)) {
3239 E = M->getSubExpr();
3240 continue;
3241 }
3242
3243 break;
3244 }
3245
3246 if (const CXXThisExpr *This = dyn_cast<CXXThisExpr>(E))
3247 return This->isImplicit();
3248
3249 return false;
3250}
3251
3252/// hasAnyTypeDependentArguments - Determines if any of the expressions
3253/// in Exprs is type-dependent.
3255 for (unsigned I = 0; I < Exprs.size(); ++I)
3256 if (Exprs[I]->isTypeDependent())
3257 return true;
3258
3259 return false;
3260}
3261
3263 const Expr **Culprit) const {
3264 assert(!isValueDependent() &&
3265 "Expression evaluator can't be called on a dependent expression.");
3266
3267 // This function is attempting whether an expression is an initializer
3268 // which can be evaluated at compile-time. It very closely parallels
3269 // ConstExprEmitter in CGExprConstant.cpp; if they don't match, it
3270 // will lead to unexpected results. Like ConstExprEmitter, it falls back
3271 // to isEvaluatable most of the time.
3272 //
3273 // If we ever capture reference-binding directly in the AST, we can
3274 // kill the second parameter.
3275
3276 if (IsForRef) {
3277 if (auto *EWC = dyn_cast<ExprWithCleanups>(this))
3278 return EWC->getSubExpr()->isConstantInitializer(Ctx, true, Culprit);
3279 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(this))
3280 return MTE->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
3282 if (EvaluateAsLValue(Result, Ctx) && !Result.HasSideEffects)
3283 return true;
3284 if (Culprit)
3285 *Culprit = this;
3286 return false;
3287 }
3288
3289 switch (getStmtClass()) {
3290 default: break;
3291 case Stmt::ExprWithCleanupsClass:
3292 return cast<ExprWithCleanups>(this)->getSubExpr()->isConstantInitializer(
3293 Ctx, IsForRef, Culprit);
3294 case StringLiteralClass:
3295 case ObjCEncodeExprClass:
3296 return true;
3297 case CXXTemporaryObjectExprClass:
3298 case CXXConstructExprClass: {
3299 const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
3300
3301 if (CE->getConstructor()->isTrivial() &&
3303 // Trivial default constructor
3304 if (!CE->getNumArgs()) return true;
3305
3306 // Trivial copy constructor
3307 assert(CE->getNumArgs() == 1 && "trivial ctor with > 1 argument");
3308 return CE->getArg(0)->isConstantInitializer(Ctx, false, Culprit);
3309 }
3310
3311 break;
3312 }
3313 case ConstantExprClass: {
3314 // FIXME: We should be able to return "true" here, but it can lead to extra
3315 // error messages. E.g. in Sema/array-init.c.
3316 const Expr *Exp = cast<ConstantExpr>(this)->getSubExpr();
3317 return Exp->isConstantInitializer(Ctx, false, Culprit);
3318 }
3319 case CompoundLiteralExprClass: {
3320 // This handles gcc's extension that allows global initializers like
3321 // "struct x {int x;} x = (struct x) {};".
3322 // FIXME: This accepts other cases it shouldn't!
3323 const Expr *Exp = cast<CompoundLiteralExpr>(this)->getInitializer();
3324 return Exp->isConstantInitializer(Ctx, false, Culprit);
3325 }
3326 case DesignatedInitUpdateExprClass: {
3327 const DesignatedInitUpdateExpr *DIUE = cast<DesignatedInitUpdateExpr>(this);
3328 return DIUE->getBase()->isConstantInitializer(Ctx, false, Culprit) &&
3329 DIUE->getUpdater()->isConstantInitializer(Ctx, false, Culprit);
3330 }
3331 case InitListExprClass: {
3332 // C++ [dcl.init.aggr]p2:
3333 // The elements of an aggregate are:
3334 // - for an array, the array elements in increasing subscript order, or
3335 // - for a class, the direct base classes in declaration order, followed
3336 // by the direct non-static data members (11.4) that are not members of
3337 // an anonymous union, in declaration order.
3338 const InitListExpr *ILE = cast<InitListExpr>(this);
3339 assert(ILE->isSemanticForm() && "InitListExpr must be in semantic form");
3340 if (ILE->getType()->isArrayType()) {
3341 unsigned numInits = ILE->getNumInits();
3342 for (unsigned i = 0; i < numInits; i++) {
3343 if (!ILE->getInit(i)->isConstantInitializer(Ctx, false, Culprit))
3344 return false;
3345 }
3346 return true;
3347 }
3348
3349 if (ILE->getType()->isRecordType()) {
3350 unsigned ElementNo = 0;
3351 RecordDecl *RD = ILE->getType()->castAs<RecordType>()->getDecl();
3352
3353 // In C++17, bases were added to the list of members used by aggregate
3354 // initialization.
3355 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3356 for (unsigned i = 0, e = CXXRD->getNumBases(); i < e; i++) {
3357 if (ElementNo < ILE->getNumInits()) {
3358 const Expr *Elt = ILE->getInit(ElementNo++);
3359 if (!Elt->isConstantInitializer(Ctx, false, Culprit))
3360 return false;
3361 }
3362 }
3363 }
3364
3365 for (const auto *Field : RD->fields()) {
3366 // If this is a union, skip all the fields that aren't being initialized.
3367 if (RD->isUnion() && ILE->getInitializedFieldInUnion() != Field)
3368 continue;
3369
3370 // Don't emit anonymous bitfields, they just affect layout.
3371 if (Field->isUnnamedBitfield())
3372 continue;
3373
3374 if (ElementNo < ILE->getNumInits()) {
3375 const Expr *Elt = ILE->getInit(ElementNo++);
3376 if (Field->isBitField()) {
3377 // Bitfields have to evaluate to an integer.
3379 if (!Elt->EvaluateAsInt(Result, Ctx)) {
3380 if (Culprit)
3381 *Culprit = Elt;
3382 return false;
3383 }
3384 } else {
3385 bool RefType = Field->getType()->isReferenceType();
3386 if (!Elt->isConstantInitializer(Ctx, RefType, Culprit))
3387 return false;
3388 }
3389 }
3390 }
3391 return true;
3392 }
3393
3394 break;
3395 }
3396 case ImplicitValueInitExprClass:
3397 case NoInitExprClass:
3398 return true;
3399 case ParenExprClass:
3400 return cast<ParenExpr>(this)->getSubExpr()
3401 ->isConstantInitializer(Ctx, IsForRef, Culprit);
3402 case GenericSelectionExprClass:
3403 return cast<GenericSelectionExpr>(this)->getResultExpr()
3404 ->isConstantInitializer(Ctx, IsForRef, Culprit);
3405 case ChooseExprClass:
3406 if (cast<ChooseExpr>(this)->isConditionDependent()) {
3407 if (Culprit)
3408 *Culprit = this;
3409 return false;
3410 }
3411 return cast<ChooseExpr>(this)->getChosenSubExpr()
3412 ->isConstantInitializer(Ctx, IsForRef, Culprit);
3413 case UnaryOperatorClass: {
3414 const UnaryOperator* Exp = cast<UnaryOperator>(this);
3415 if (Exp->getOpcode() == UO_Extension)
3416 return Exp->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
3417 break;
3418 }
3419 case PackIndexingExprClass: {
3420 return cast<PackIndexingExpr>(this)
3421 ->getSelectedExpr()
3422 ->isConstantInitializer(Ctx, false, Culprit);
3423 }
3424 case CXXFunctionalCastExprClass:
3425 case CXXStaticCastExprClass:
3426 case ImplicitCastExprClass:
3427 case CStyleCastExprClass:
3428 case ObjCBridgedCastExprClass:
3429 case CXXDynamicCastExprClass:
3430 case CXXReinterpretCastExprClass:
3431 case CXXAddrspaceCastExprClass:
3432 case CXXConstCastExprClass: {
3433 const CastExpr *CE = cast<CastExpr>(this);
3434
3435 // Handle misc casts we want to ignore.
3436 if (CE->getCastKind() == CK_NoOp ||
3437 CE->getCastKind() == CK_LValueToRValue ||
3438 CE->getCastKind() == CK_ToUnion ||
3439 CE->getCastKind() == CK_ConstructorConversion ||
3440 CE->getCastKind() == CK_NonAtomicToAtomic ||
3441 CE->getCastKind() == CK_AtomicToNonAtomic ||
3442 CE->getCastKind() == CK_NullToPointer ||
3443 CE->getCastKind() == CK_IntToOCLSampler)
3444 return CE->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
3445
3446 break;
3447 }
3448 case MaterializeTemporaryExprClass:
3449 return cast<MaterializeTemporaryExpr>(this)
3450 ->getSubExpr()
3451 ->isConstantInitializer(Ctx, false, Culprit);
3452
3453 case SubstNonTypeTemplateParmExprClass:
3454 return cast<SubstNonTypeTemplateParmExpr>(this)->getReplacement()
3455 ->isConstantInitializer(Ctx, false, Culprit);
3456 case CXXDefaultArgExprClass:
3457 return cast<CXXDefaultArgExpr>(this)->getExpr()
3458 ->isConstantInitializer(Ctx, false, Culprit);
3459 case CXXDefaultInitExprClass:
3460 return cast<CXXDefaultInitExpr>(this)->getExpr()
3461 ->isConstantInitializer(Ctx, false, Culprit);
3462 }
3463 // Allow certain forms of UB in constant initializers: signed integer
3464 // overflow and floating-point division by zero. We'll give a warning on
3465 // these, but they're common enough that we have to accept them.
3467 return true;
3468 if (Culprit)
3469 *Culprit = this;
3470 return false;
3471}
3472
3474 unsigned BuiltinID = getBuiltinCallee();
3475 if (BuiltinID != Builtin::BI__assume &&
3476 BuiltinID != Builtin::BI__builtin_assume)
3477 return false;
3478
3479 const Expr* Arg = getArg(0);
3480 bool ArgVal;
3481 return !Arg->isValueDependent() &&
3482 Arg->EvaluateAsBooleanCondition(ArgVal, Ctx) && !ArgVal;
3483}
3484
3486 return getBuiltinCallee() == Builtin::BImove;
3487}
3488
3489namespace {
3490 /// Look for any side effects within a Stmt.
3491 class SideEffectFinder : public ConstEvaluatedExprVisitor<SideEffectFinder> {
3493 const bool IncludePossibleEffects;
3494 bool HasSideEffects;
3495
3496 public:
3497 explicit SideEffectFinder(const ASTContext &Context, bool IncludePossible)
3498 : Inherited(Context),
3499 IncludePossibleEffects(IncludePossible), HasSideEffects(false) { }
3500
3501 bool hasSideEffects() const { return HasSideEffects; }
3502
3503 void VisitDecl(const Decl *D) {
3504 if (!D)
3505 return;
3506
3507 // We assume the caller checks subexpressions (eg, the initializer, VLA
3508 // bounds) for side-effects on our behalf.
3509 if (auto *VD = dyn_cast<VarDecl>(D)) {
3510 // Registering a destructor is a side-effect.
3511 if (IncludePossibleEffects && VD->isThisDeclarationADefinition() &&
3512 VD->needsDestruction(Context))
3513 HasSideEffects = true;
3514 }
3515 }
3516
3517 void VisitDeclStmt(const DeclStmt *DS) {
3518 for (auto *D : DS->decls())
3519 VisitDecl(D);
3520 Inherited::VisitDeclStmt(DS);
3521 }
3522
3523 void VisitExpr(const Expr *E) {
3524 if (!HasSideEffects &&
3525 E->HasSideEffects(Context, IncludePossibleEffects))
3526 HasSideEffects = true;
3527 }
3528 };
3529}
3530
3532 bool IncludePossibleEffects) const {
3533 // In circumstances where we care about definite side effects instead of
3534 // potential side effects, we want to ignore expressions that are part of a
3535 // macro expansion as a potential side effect.
3536 if (!IncludePossibleEffects && getExprLoc().isMacroID())
3537 return false;
3538
3539 switch (getStmtClass()) {
3540 case NoStmtClass:
3541 #define ABSTRACT_STMT(Type)
3542 #define STMT(Type, Base) case Type##Class:
3543 #define EXPR(Type, Base)
3544 #include "clang/AST/StmtNodes.inc"
3545 llvm_unreachable("unexpected Expr kind");
3546
3547 case DependentScopeDeclRefExprClass:
3548 case CXXUnresolvedConstructExprClass:
3549 case CXXDependentScopeMemberExprClass:
3550 case UnresolvedLookupExprClass:
3551 case UnresolvedMemberExprClass:
3552 case PackExpansionExprClass:
3553 case SubstNonTypeTemplateParmPackExprClass:
3554 case FunctionParmPackExprClass:
3555 case TypoExprClass:
3556 case RecoveryExprClass:
3557 case CXXFoldExprClass:
3558 // Make a conservative assumption for dependent nodes.
3559 return IncludePossibleEffects;
3560
3561 case DeclRefExprClass:
3562 case ObjCIvarRefExprClass:
3563 case PredefinedExprClass:
3564 case IntegerLiteralClass:
3565 case FixedPointLiteralClass:
3566 case FloatingLiteralClass:
3567 case ImaginaryLiteralClass:
3568 case StringLiteralClass:
3569 case CharacterLiteralClass:
3570 case OffsetOfExprClass:
3571 case ImplicitValueInitExprClass:
3572 case UnaryExprOrTypeTraitExprClass:
3573 case AddrLabelExprClass:
3574 case GNUNullExprClass:
3575 case ArrayInitIndexExprClass:
3576 case NoInitExprClass:
3577 case CXXBoolLiteralExprClass:
3578 case CXXNullPtrLiteralExprClass:
3579 case CXXThisExprClass:
3580 case CXXScalarValueInitExprClass:
3581 case TypeTraitExprClass:
3582 case ArrayTypeTraitExprClass:
3583 case ExpressionTraitExprClass:
3584 case CXXNoexceptExprClass:
3585 case SizeOfPackExprClass:
3586 case ObjCStringLiteralClass:
3587 case ObjCEncodeExprClass:
3588 case ObjCBoolLiteralExprClass:
3589 case ObjCAvailabilityCheckExprClass:
3590 case CXXUuidofExprClass:
3591 case OpaqueValueExprClass:
3592 case SourceLocExprClass:
3593 case ConceptSpecializationExprClass:
3594 case RequiresExprClass:
3595 case SYCLUniqueStableNameExprClass:
3596 // These never have a side-effect.
3597 return false;
3598
3599 case PackIndexingExprClass:
3600 return cast<PackIndexingExpr>(this)->getSelectedExpr()->HasSideEffects(
3601 Ctx, IncludePossibleEffects);
3602 case ConstantExprClass:
3603 // FIXME: Move this into the "return false;" block above.
3604 return cast<ConstantExpr>(this)->getSubExpr()->HasSideEffects(
3605 Ctx, IncludePossibleEffects);
3606
3607 case CallExprClass:
3608 case CXXOperatorCallExprClass:
3609 case CXXMemberCallExprClass:
3610 case CUDAKernelCallExprClass:
3611 case UserDefinedLiteralClass: {
3612 // We don't know a call definitely has side effects, except for calls
3613 // to pure/const functions that definitely don't.
3614 // If the call itself is considered side-effect free, check the operands.
3615 const Decl *FD = cast<CallExpr>(this)->getCalleeDecl();
3616 bool IsPure = FD && (FD->hasAttr<ConstAttr>() || FD->hasAttr<PureAttr>());
3617 if (IsPure || !IncludePossibleEffects)
3618 break;
3619 return true;
3620 }
3621
3622 case BlockExprClass:
3623 case CXXBindTemporaryExprClass:
3624 if (!IncludePossibleEffects)
3625 break;
3626 return true;
3627
3628 case MSPropertyRefExprClass:
3629 case MSPropertySubscriptExprClass:
3630 case CompoundAssignOperatorClass:
3631 case VAArgExprClass:
3632 case AtomicExprClass:
3633 case CXXThrowExprClass:
3634 case CXXNewExprClass:
3635 case CXXDeleteExprClass:
3636 case CoawaitExprClass:
3637 case DependentCoawaitExprClass:
3638 case CoyieldExprClass:
3639 // These always have a side-effect.
3640 return true;
3641
3642 case StmtExprClass: {
3643 // StmtExprs have a side-effect if any substatement does.
3644 SideEffectFinder Finder(Ctx, IncludePossibleEffects);
3645 Finder.Visit(cast<StmtExpr>(this)->getSubStmt());
3646 return Finder.hasSideEffects();
3647 }
3648
3649 case ExprWithCleanupsClass:
3650 if (IncludePossibleEffects)
3651 if (cast<ExprWithCleanups>(this)->cleanupsHaveSideEffects())
3652 return true;
3653 break;
3654
3655 case ParenExprClass:
3656 case ArraySubscriptExprClass:
3657 case MatrixSubscriptExprClass:
3658 case OMPArraySectionExprClass:
3659 case OMPArrayShapingExprClass:
3660 case OMPIteratorExprClass:
3661 case MemberExprClass:
3662 case ConditionalOperatorClass:
3663 case BinaryConditionalOperatorClass:
3664 case CompoundLiteralExprClass:
3665 case ExtVectorElementExprClass:
3666 case DesignatedInitExprClass:
3667 case DesignatedInitUpdateExprClass:
3668 case ArrayInitLoopExprClass:
3669 case ParenListExprClass:
3670 case CXXPseudoDestructorExprClass:
3671 case CXXRewrittenBinaryOperatorClass:
3672 case CXXStdInitializerListExprClass:
3673 case SubstNonTypeTemplateParmExprClass:
3674 case MaterializeTemporaryExprClass:
3675 case ShuffleVectorExprClass:
3676 case ConvertVectorExprClass:
3677 case AsTypeExprClass:
3678 case CXXParenListInitExprClass:
3679 // These have a side-effect if any subexpression does.
3680 break;
3681
3682 case UnaryOperatorClass:
3683 if (cast<UnaryOperator>(this)->isIncrementDecrementOp())
3684 return true;
3685 break;
3686
3687 case BinaryOperatorClass:
3688 if (cast<BinaryOperator>(this)->isAssignmentOp())
3689 return true;
3690 break;
3691
3692 case InitListExprClass:
3693 // FIXME: The children for an InitListExpr doesn't include the array filler.
3694 if (const Expr *E = cast<InitListExpr>(this)->getArrayFiller())
3695 if (E->HasSideEffects(Ctx, IncludePossibleEffects))
3696 return true;
3697 break;
3698
3699 case GenericSelectionExprClass:
3700 return cast<GenericSelectionExpr>(this)->getResultExpr()->
3701 HasSideEffects(Ctx, IncludePossibleEffects);
3702
3703 case ChooseExprClass:
3704 return cast<ChooseExpr>(this)->getChosenSubExpr()->HasSideEffects(
3705 Ctx, IncludePossibleEffects);
3706
3707 case CXXDefaultArgExprClass:
3708 return cast<CXXDefaultArgExpr>(this)->getExpr()->HasSideEffects(
3709 Ctx, IncludePossibleEffects);
3710
3711 case CXXDefaultInitExprClass: {
3712 const FieldDecl *FD = cast<CXXDefaultInitExpr>(this)->getField();
3713 if (const Expr *E = FD->getInClassInitializer())
3714 return E->HasSideEffects(Ctx, IncludePossibleEffects);
3715 // If we've not yet parsed the initializer, assume it has side-effects.
3716 return true;
3717 }
3718
3719 case CXXDynamicCastExprClass: {
3720 // A dynamic_cast expression has side-effects if it can throw.
3721 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(this);
3722 if (DCE->getTypeAsWritten()->isReferenceType() &&
3723 DCE->getCastKind() == CK_Dynamic)
3724 return true;
3725 }
3726 [[fallthrough]];
3727 case ImplicitCastExprClass:
3728 case CStyleCastExprClass:
3729 case CXXStaticCastExprClass:
3730 case CXXReinterpretCastExprClass:
3731 case CXXConstCastExprClass:
3732 case CXXAddrspaceCastExprClass:
3733 case CXXFunctionalCastExprClass:
3734 case BuiltinBitCastExprClass: {
3735 // While volatile reads are side-effecting in both C and C++, we treat them
3736 // as having possible (not definite) side-effects. This allows idiomatic
3737 // code to behave without warning, such as sizeof(*v) for a volatile-
3738 // qualified pointer.
3739 if (!IncludePossibleEffects)
3740 break;
3741
3742 const CastExpr *CE = cast<CastExpr>(this);
3743 if (CE->getCastKind() == CK_LValueToRValue &&
3745 return true;
3746 break;
3747 }
3748
3749 case CXXTypeidExprClass:
3750 // typeid might throw if its subexpression is potentially-evaluated, so has
3751 // side-effects in that case whether or not its subexpression does.
3752 return cast<CXXTypeidExpr>(this)->isPotentiallyEvaluated();
3753
3754 case CXXConstructExprClass:
3755 case CXXTemporaryObjectExprClass: {
3756 const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
3757 if (!CE->getConstructor()->isTrivial() && IncludePossibleEffects)
3758 return true;
3759 // A trivial constructor does not add any side-effects of its own. Just look
3760 // at its arguments.
3761 break;
3762 }
3763
3764 case CXXInheritedCtorInitExprClass: {
3765 const auto *ICIE = cast<CXXInheritedCtorInitExpr>(this);
3766 if (!ICIE->getConstructor()->isTrivial() && IncludePossibleEffects)
3767 return true;
3768 break;
3769 }
3770
3771 case LambdaExprClass: {
3772 const LambdaExpr *LE = cast<LambdaExpr>(this);
3773 for (Expr *E : LE->capture_inits())
3774 if (E && E->HasSideEffects(Ctx, IncludePossibleEffects))
3775 return true;
3776 return false;
3777 }
3778
3779 case PseudoObjectExprClass: {
3780 // Only look for side-effects in the semantic form, and look past
3781 // OpaqueValueExpr bindings in that form.
3782 const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this);
3784 E = PO->semantics_end();
3785 I != E; ++I) {
3786 const Expr *Subexpr = *I;
3787 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Subexpr))
3788 Subexpr = OVE->getSourceExpr();
3789 if (Subexpr->HasSideEffects(Ctx, IncludePossibleEffects))
3790 return true;
3791 }
3792 return false;
3793 }
3794
3795 case ObjCBoxedExprClass:
3796 case ObjCArrayLiteralClass:
3797 case ObjCDictionaryLiteralClass:
3798 case ObjCSelectorExprClass:
3799 case ObjCProtocolExprClass:
3800 case ObjCIsaExprClass:
3801 case ObjCIndirectCopyRestoreExprClass:
3802 case ObjCSubscriptRefExprClass:
3803 case ObjCBridgedCastExprClass:
3804 case ObjCMessageExprClass:
3805 case ObjCPropertyRefExprClass:
3806 // FIXME: Classify these cases better.
3807 if (IncludePossibleEffects)
3808 return true;
3809 break;
3810 }
3811
3812 // Recurse to children.
3813 for (const Stmt *SubStmt : children())
3814 if (SubStmt &&
3815 cast<Expr>(SubStmt)->HasSideEffects(Ctx, IncludePossibleEffects))
3816 return true;
3817
3818 return false;
3819}
3820
3822 if (auto Call = dyn_cast<CallExpr>(this))
3823 return Call->getFPFeaturesInEffect(LO);
3824 if (auto UO = dyn_cast<UnaryOperator>(this))
3825 return UO->getFPFeaturesInEffect(LO);
3826 if (auto BO = dyn_cast<BinaryOperator>(this))
3827 return BO->getFPFeaturesInEffect(LO);
3828 if (auto Cast = dyn_cast<CastExpr>(this))
3829 return Cast->getFPFeaturesInEffect(LO);
3831}
3832
3833namespace {
3834 /// Look for a call to a non-trivial function within an expression.
3835 class NonTrivialCallFinder : public ConstEvaluatedExprVisitor<NonTrivialCallFinder>
3836 {
3838
3839 bool NonTrivial;
3840
3841 public:
3842 explicit NonTrivialCallFinder(const ASTContext &Context)
3843 : Inherited(Context), NonTrivial(false) { }
3844
3845 bool hasNonTrivialCall() const { return NonTrivial; }
3846
3847 void VisitCallExpr(const CallExpr *E) {
3848 if (const CXXMethodDecl *Method
3849 = dyn_cast_or_null<const CXXMethodDecl>(E->getCalleeDecl())) {
3850 if (Method->isTrivial()) {
3851 // Recurse to children of the call.
3852 Inherited::VisitStmt(E);
3853 return;
3854 }
3855 }
3856
3857 NonTrivial = true;
3858 }
3859
3860 void VisitCXXConstructExpr(const CXXConstructExpr *E) {
3861 if (E->getConstructor()->isTrivial()) {
3862 // Recurse to children of the call.
3863 Inherited::VisitStmt(E);
3864 return;
3865 }
3866
3867 NonTrivial = true;
3868 }
3869
3870 void VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
3871 if (E->getTemporary()->getDestructor()->isTrivial()) {
3872 Inherited::VisitStmt(E);
3873 return;
3874 }
3875
3876 NonTrivial = true;
3877 }
3878 };
3879}
3880
3881bool Expr::hasNonTrivialCall(const ASTContext &Ctx) const {
3882 NonTrivialCallFinder Finder(Ctx);
3883 Finder.Visit(this);
3884 return Finder.hasNonTrivialCall();
3885}
3886
3887/// isNullPointerConstant - C99 6.3.2.3p3 - Return whether this is a null
3888/// pointer constant or not, as well as the specific kind of constant detected.
3889/// Null pointer constants can be integer constant expressions with the
3890/// value zero, casts of zero to void*, nullptr (C++0X), or __null
3891/// (a GNU extension).
3895 if (isValueDependent() &&
3896 (!Ctx.getLangOpts().CPlusPlus11 || Ctx.getLangOpts().MSVCCompat)) {
3897 // Error-dependent expr should never be a null pointer.
3898 if (containsErrors())
3899 return NPCK_NotNull;
3900 switch (NPC) {
3902 llvm_unreachable("Unexpected value dependent expression!");
3904 if (isTypeDependent() || getType()->isIntegralType(Ctx))
3905 return NPCK_ZeroExpression;
3906 else
3907 return NPCK_NotNull;
3908
3910 return NPCK_NotNull;
3911 }
3912 }
3913
3914 // Strip off a cast to void*, if it exists. Except in C++.
3915 if (const ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(this)) {
3916 if (!Ctx.getLangOpts().CPlusPlus) {
3917 // Check that it is a cast to void*.
3918 if (const PointerType *PT = CE->getType()->getAs<PointerType>()) {
3919 QualType Pointee = PT->getPointeeType();
3920 Qualifiers Qs = Pointee.getQualifiers();
3921 // Only (void*)0 or equivalent are treated as nullptr. If pointee type
3922 // has non-default address space it is not treated as nullptr.
3923 // (__generic void*)0 in OpenCL 2.0 should not be treated as nullptr
3924 // since it cannot be assigned to a pointer to constant address space.
3925 if (Ctx.getLangOpts().OpenCL &&
3927 Qs.removeAddressSpace();
3928
3929 if (Pointee->isVoidType() && Qs.empty() && // to void*
3930 CE->getSubExpr()->getType()->isIntegerType()) // from int
3931 return CE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
3932 }
3933 }
3934 } else if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(this)) {
3935 // Ignore the ImplicitCastExpr type entirely.
3936 return ICE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
3937 } else if (const ParenExpr *PE = dyn_cast<ParenExpr>(this)) {
3938 // Accept ((void*)0) as a null pointer constant, as many other
3939 // implementations do.
3940 return PE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
3941 } else if (const GenericSelectionExpr *GE =
3942 dyn_cast<GenericSelectionExpr>(this)) {
3943 if (GE->isResultDependent())
3944 return NPCK_NotNull;
3945 return GE->getResultExpr()->isNullPointerConstant(Ctx, NPC);
3946 } else if (const ChooseExpr *CE = dyn_cast<ChooseExpr>(this)) {
3947 if (CE->isConditionDependent())
3948 return NPCK_NotNull;
3949 return CE->getChosenSubExpr()->isNullPointerConstant(Ctx, NPC);
3950 } else if (const CXXDefaultArgExpr *DefaultArg
3951 = dyn_cast<CXXDefaultArgExpr>(this)) {
3952 // See through default argument expressions.
3953 return DefaultArg->getExpr()->isNullPointerConstant(Ctx, NPC);
3954 } else if (const CXXDefaultInitExpr *DefaultInit
3955 = dyn_cast<CXXDefaultInitExpr>(this)) {
3956 // See through default initializer expressions.
3957 return DefaultInit->getExpr()->isNullPointerConstant(Ctx, NPC);
3958 } else if (isa<GNUNullExpr>(this)) {
3959 // The GNU __null extension is always a null pointer constant.
3960 return NPCK_GNUNull;
3961 } else if (const MaterializeTemporaryExpr *M
3962 = dyn_cast<MaterializeTemporaryExpr>(this)) {
3963 return M->getSubExpr()->isNullPointerConstant(Ctx, NPC);
3964 } else if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(this)) {
3965 if (const Expr *Source = OVE->getSourceExpr())
3966 return Source->isNullPointerConstant(Ctx, NPC);
3967 }
3968
3969 // If the expression has no type information, it cannot be a null pointer
3970 // constant.
3971 if (getType().isNull())
3972 return NPCK_NotNull;
3973
3974 // C++11/C23 nullptr_t is always a null pointer constant.
3975 if (getType()->isNullPtrType())
3976 return NPCK_CXX11_nullptr;
3977
3978 if (const RecordType *UT = getType()->getAsUnionType())
3979 if (!Ctx.getLangOpts().CPlusPlus11 &&
3980 UT && UT->getDecl()->hasAttr<TransparentUnionAttr>())
3981 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(this)){
3982 const Expr *InitExpr = CLE->getInitializer();
3983 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(InitExpr))
3984 return ILE->getInit(0)->isNullPointerConstant(Ctx, NPC);
3985 }
3986 // This expression must be an integer type.
3987 if (!getType()->isIntegerType() ||
3988 (Ctx.getLangOpts().CPlusPlus && getType()->isEnumeralType()))
3989 return NPCK_NotNull;
3990
3991 if (Ctx.getLangOpts().CPlusPlus11) {
3992 // C++11 [conv.ptr]p1: A null pointer constant is an integer literal with
3993 // value zero or a prvalue of type std::nullptr_t.
3994 // Microsoft mode permits C++98 rules reflecting MSVC behavior.
3995 const IntegerLiteral *Lit = dyn_cast<IntegerLiteral>(this);
3996 if (Lit && !Lit->getValue())
3997 return NPCK_ZeroLiteral;
3998 if (!Ctx.getLangOpts().MSVCCompat || !isCXX98IntegralConstantExpr(Ctx))
3999 return NPCK_NotNull;
4000 } else {
4001 // If we have an integer constant expression, we need to *evaluate* it and
4002 // test for the value 0.
4003 if (!isIntegerConstantExpr(Ctx))
4004 return NPCK_NotNull;
4005 }
4006
4007 if (EvaluateKnownConstInt(Ctx) != 0)
4008 return NPCK_NotNull;
4009
4010 if (isa<IntegerLiteral>(this))
4011 return NPCK_ZeroLiteral;
4012 return NPCK_ZeroExpression;
4013}
4014
4015/// If this expression is an l-value for an Objective C
4016/// property, find the underlying property reference expression.
4018 const Expr *E = this;
4019 while (true) {
4020 assert((E->isLValue() && E->getObjectKind() == OK_ObjCProperty) &&
4021 "expression is not a property reference");
4022 E = E->IgnoreParenCasts();
4023 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
4024 if (BO->getOpcode() == BO_Comma) {
4025 E = BO->getRHS();
4026 continue;
4027 }
4028 }
4029
4030 break;
4031 }
4032
4033 return cast<ObjCPropertyRefExpr>(E);
4034}
4035
4037 const Expr *E = IgnoreParenImpCasts();
4038
4039 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
4040 if (!DRE)
4041 return false;
4042
4043 const ImplicitParamDecl *Param = dyn_cast<ImplicitParamDecl>(DRE->getDecl());
4044 if (!Param)
4045 return false;
4046
4047 const ObjCMethodDecl *M = dyn_cast<ObjCMethodDecl>(Param->getDeclContext());
4048 if (!M)
4049 return false;
4050
4051 return M->getSelfDecl() == Param;
4052}
4053
4055 Expr *E = this->IgnoreParens();
4056
4057 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
4058 if (ICE->getCastKind() == CK_LValueToRValue ||
4059 (ICE->isGLValue() && ICE->getCastKind() == CK_NoOp))
4060 E = ICE->getSubExpr()->IgnoreParens();
4061 else
4062 break;
4063 }
4064
4065 if (MemberExpr *MemRef = dyn_cast<MemberExpr>(E))
4066 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemRef->getMemberDecl()))
4067 if (Field->isBitField())
4068 return Field;
4069
4070 if (ObjCIvarRefExpr *IvarRef = dyn_cast<ObjCIvarRefExpr>(E)) {
4071 FieldDecl *Ivar = IvarRef->getDecl();
4072 if (Ivar->isBitField())
4073 return Ivar;
4074 }
4075
4076 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E)) {
4077 if (FieldDecl *Field = dyn_cast<FieldDecl>(DeclRef->getDecl()))
4078 if (Field->isBitField())
4079 return Field;
4080
4081 if (BindingDecl *BD = dyn_cast<BindingDecl>(DeclRef->getDecl()))
4082 if (Expr *E = BD->getBinding())
4083 return E->getSourceBitField();
4084 }
4085
4086 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(E)) {
4087 if (BinOp->isAssignmentOp() && BinOp->getLHS())
4088 return BinOp->getLHS()->getSourceBitField();
4089
4090 if (BinOp->getOpcode() == BO_Comma && BinOp->getRHS())
4091 return BinOp->getRHS()->getSourceBitField();
4092 }
4093
4094 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E))
4095 if (UnOp->isPrefix() && UnOp->isIncrementDecrementOp())
4096 return UnOp->getSubExpr()->getSourceBitField();
4097
4098 return nullptr;
4099}
4100
4102 // FIXME: Why do we not just look at the ObjectKind here?
4103 const Expr *E = this->IgnoreParens();
4104
4105 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
4106 if (ICE->isGLValue() && ICE->getCastKind() == CK_NoOp)
4107 E = ICE->getSubExpr()->IgnoreParens();
4108 else
4109 break;
4110 }
4111
4112 if (const ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(E))
4113 return ASE->getBase()->getType()->isVectorType();
4114
4115 if (isa<ExtVectorElementExpr>(E))
4116 return true;
4117
4118 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
4119 if (auto *BD = dyn_cast<BindingDecl>(DRE->getDecl()))
4120 if (auto *E = BD->getBinding())
4121 return E->refersToVectorElement();
4122
4123 return false;
4124}
4125
4127 const Expr *E = this->IgnoreParenImpCasts();
4128
4129 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
4130 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
4131 if (VD->getStorageClass() == SC_Register &&
4132 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
4133 return true;
4134
4135 return false;
4136}
4137
4138bool Expr::isSameComparisonOperand(const Expr* E1, const Expr* E2) {
4139 E1 = E1->IgnoreParens();
4140 E2 = E2->IgnoreParens();
4141
4142 if (E1->getStmtClass() != E2->getStmtClass())
4143 return false;
4144
4145 switch (E1->getStmtClass()) {
4146 default:
4147 return false;
4148 case CXXThisExprClass:
4149 return true;
4150 case DeclRefExprClass: {
4151 // DeclRefExpr without an ImplicitCastExpr can happen for integral
4152 // template parameters.
4153 const auto *DRE1 = cast<DeclRefExpr>(E1);
4154 const auto *DRE2 = cast<DeclRefExpr>(E2);
4155 return DRE1->isPRValue() && DRE2->isPRValue() &&
4156 DRE1->getDecl() == DRE2->getDecl();
4157 }
4158 case ImplicitCastExprClass: {
4159 // Peel off implicit casts.
4160 while (true) {
4161 const auto *ICE1 = dyn_cast<ImplicitCastExpr>(E1);
4162 const auto *ICE2 = dyn_cast<ImplicitCastExpr>(E2);
4163 if (!ICE1 || !ICE2)
4164 return false;
4165 if (ICE1->getCastKind() != ICE2->getCastKind())
4166 return false;
4167 E1 = ICE1->getSubExpr()->IgnoreParens();
4168 E2 = ICE2->getSubExpr()->IgnoreParens();
4169 // The final cast must be one of these types.
4170 if (ICE1->getCastKind() == CK_LValueToRValue ||
4171 ICE1->getCastKind() == CK_ArrayToPointerDecay ||
4172 ICE1->getCastKind() == CK_FunctionToPointerDecay) {
4173 break;
4174 }
4175 }
4176
4177 const auto *DRE1 = dyn_cast<DeclRefExpr>(E1);
4178 const auto *DRE2 = dyn_cast<DeclRefExpr>(E2);
4179 if (DRE1 && DRE2)
4180 return declaresSameEntity(DRE1->getDecl(), DRE2->getDecl());
4181
4182 const auto *Ivar1 = dyn_cast<ObjCIvarRefExpr>(E1);
4183 const auto *Ivar2 = dyn_cast<ObjCIvarRefExpr>(E2);
4184 if (Ivar1 && Ivar2) {
4185 return Ivar1->isFreeIvar() && Ivar2->isFreeIvar() &&
4186 declaresSameEntity(Ivar1->getDecl(), Ivar2->getDecl());
4187 }
4188
4189 const auto *Array1 = dyn_cast<ArraySubscriptExpr>(E1);
4190 const auto *Array2 = dyn_cast<ArraySubscriptExpr>(E2);
4191 if (Array1 && Array2) {
4192 if (!isSameComparisonOperand(Array1->getBase(), Array2->getBase()))
4193 return false;
4194
4195 auto Idx1 = Array1->getIdx();
4196 auto Idx2 = Array2->getIdx();
4197 const auto Integer1 = dyn_cast<IntegerLiteral>(Idx1);
4198 const auto Integer2 = dyn_cast<IntegerLiteral>(Idx2);
4199 if (Integer1 && Integer2) {
4200 if (!llvm::APInt::isSameValue(Integer1->getValue(),
4201 Integer2->getValue()))
4202 return false;
4203 } else {
4204 if (!isSameComparisonOperand(Idx1, Idx2))
4205 return false;
4206 }
4207
4208 return true;
4209 }
4210
4211 // Walk the MemberExpr chain.
4212 while (isa<MemberExpr>(E1) && isa<MemberExpr>(E2)) {
4213 const auto *ME1 = cast<MemberExpr>(E1);
4214 const auto *ME2 = cast<MemberExpr>(E2);
4215 if (!declaresSameEntity(ME1->getMemberDecl(), ME2->getMemberDecl()))
4216 return false;
4217 if (const auto *D = dyn_cast<VarDecl>(ME1->getMemberDecl()))
4218 if (D->isStaticDataMember())
4219 return true;
4220 E1 = ME1->getBase()->IgnoreParenImpCasts();
4221 E2 = ME2->getBase()->IgnoreParenImpCasts();
4222 }
4223
4224 if (isa<CXXThisExpr>(E1) && isa<CXXThisExpr>(E2))
4225 return true;
4226
4227 // A static member variable can end the MemberExpr chain with either
4228 // a MemberExpr or a DeclRefExpr.
4229 auto getAnyDecl = [](const Expr *E) -> const ValueDecl * {
4230 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
4231 return DRE->getDecl();
4232 if (const auto *ME = dyn_cast<MemberExpr>(E))
4233 return ME->getMemberDecl();
4234 return nullptr;
4235 };
4236
4237 const ValueDecl *VD1 = getAnyDecl(E1);
4238 const ValueDecl *VD2 = getAnyDecl(E2);
4239 return declaresSameEntity(VD1, VD2);
4240 }
4241 }
4242}
4243
4244/// isArrow - Return true if the base expression is a pointer to vector,
4245/// return false if the base expression is a vector.
4247 return getBase()->getType()->isPointerType();
4248}
4249
4251 if (const VectorType *VT = getType()->getAs<VectorType>())
4252 return VT->getNumElements();
4253 return 1;
4254}
4255
4256/// containsDuplicateElements - Return true if any element access is repeated.
4258 // FIXME: Refactor this code to an accessor on the AST node which returns the
4259 // "type" of component access, and share with code below and in Sema.
4260 StringRef Comp = Accessor->getName();
4261
4262 // Halving swizzles do not contain duplicate elements.
4263 if (Comp == "hi" || Comp == "lo" || Comp == "even" || Comp == "odd")
4264 return false;
4265
4266 // Advance past s-char prefix on hex swizzles.
4267 if (Comp[0] == 's' || Comp[0] == 'S')
4268 Comp = Comp.substr(1);
4269
4270 for (unsigned i = 0, e = Comp.size(); i != e; ++i)
4271 if (Comp.substr(i + 1).contains(Comp[i]))
4272 return true;
4273
4274 return false;
4275}
4276
4277/// getEncodedElementAccess - We encode the fields as a llvm ConstantArray.
4279 SmallVectorImpl<uint32_t> &Elts) const {
4280 StringRef Comp = Accessor->getName();
4281 bool isNumericAccessor = false;
4282 if (Comp[0] == 's' || Comp[0] == 'S') {
4283 Comp = Comp.substr(1);
4284 isNumericAccessor = true;
4285 }
4286
4287 bool isHi = Comp == "hi";
4288 bool isLo = Comp == "lo";
4289 bool isEven = Comp == "even";
4290 bool isOdd = Comp == "odd";
4291
4292 for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
4293 uint64_t Index;
4294
4295 if (isHi)
4296 Index = e + i;
4297 else if (isLo)
4298 Index = i;
4299 else if (isEven)
4300 Index = 2 * i;
4301 else if (isOdd)
4302 Index = 2 * i + 1;
4303 else
4304 Index = ExtVectorType::getAccessorIdx(Comp[i], isNumericAccessor);
4305
4306 Elts.push_back(Index);
4307 }
4308}
4309
4312 SourceLocation RP)
4313 : Expr(ShuffleVectorExprClass, Type, VK_PRValue, OK_Ordinary),
4314 BuiltinLoc(BLoc), RParenLoc(RP), NumExprs(args.size()) {
4315 SubExprs = new (C) Stmt*[args.size()];
4316 for (unsigned i = 0; i != args.size(); i++)
4317 SubExprs[i] = args[i];
4318
4320}
4321
4323 if (SubExprs) C.Deallocate(SubExprs);
4324
4325 this->NumExprs = Exprs.size();
4326 SubExprs = new (C) Stmt*[NumExprs];
4327 memcpy(SubExprs, Exprs.data(), sizeof(Expr *) * Exprs.size());
4328}
4329
4330GenericSelectionExpr::GenericSelectionExpr(
4331 const ASTContext &, SourceLocation GenericLoc, Expr *ControllingExpr,
4332 ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
4333 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4334 bool ContainsUnexpandedParameterPack, unsigned ResultIndex)
4335 : Expr(GenericSelectionExprClass, AssocExprs[ResultIndex]->getType(),
4336 AssocExprs[ResultIndex]->getValueKind(),
4337 AssocExprs[ResultIndex]->getObjectKind()),
4338 NumAssocs(AssocExprs.size()), ResultIndex(ResultIndex),
4339 IsExprPredicate(true), DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
4340 assert(AssocTypes.size() == AssocExprs.size() &&
4341 "Must have the same number of association expressions"
4342 " and TypeSourceInfo!");
4343 assert(ResultIndex < NumAssocs && "ResultIndex is out-of-bounds!");
4344
4345 GenericSelectionExprBits.GenericLoc = GenericLoc;
4346 getTrailingObjects<Stmt *>()[getIndexOfControllingExpression()] =
4347 ControllingExpr;
4348 std::copy(AssocExprs.begin(), AssocExprs.end(),
4349 getTrailingObjects<Stmt *>() + getIndexOfStartOfAssociatedExprs());
4350 std::copy(AssocTypes.begin(), AssocTypes.end(),
4351 getTrailingObjects<TypeSourceInfo *>() +
4352 getIndexOfStartOfAssociatedTypes());
4353
4354 setDependence(computeDependence(this, ContainsUnexpandedParameterPack));
4355}
4356
4357GenericSelectionExpr::GenericSelectionExpr(
4358 const ASTContext &, SourceLocation GenericLoc,
4359 TypeSourceInfo *ControllingType, ArrayRef<TypeSourceInfo *> AssocTypes,
4360 ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,
4361 SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack,
4362 unsigned ResultIndex)
4363 : Expr(GenericSelectionExprClass, AssocExprs[ResultIndex]->getType(),
4364 AssocExprs[ResultIndex]->getValueKind(),
4365 AssocExprs[ResultIndex]->getObjectKind()),
4366 NumAssocs(AssocExprs.size()), ResultIndex(ResultIndex),
4367 IsExprPredicate(false), DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
4368 assert(AssocTypes.size() == AssocExprs.size() &&
4369 "Must have the same number of association expressions"
4370 " and TypeSourceInfo!");
4371 assert(ResultIndex < NumAssocs && "ResultIndex is out-of-bounds!");
4372
4373 GenericSelectionExprBits.GenericLoc = GenericLoc;
4374 getTrailingObjects<TypeSourceInfo *>()[getIndexOfControllingType()] =
4375 ControllingType;
4376 std::copy(AssocExprs.begin(), AssocExprs.end(),
4377 getTrailingObjects<Stmt *>() + getIndexOfStartOfAssociatedExprs());
4378 std::copy(AssocTypes.begin(), AssocTypes.end(),
4379 getTrailingObjects<TypeSourceInfo *>() +
4380 getIndexOfStartOfAssociatedTypes());
4381
4382 setDependence(computeDependence(this, ContainsUnexpandedParameterPack));
4383}
4384
4385GenericSelectionExpr::GenericSelectionExpr(
4386 const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,
4387 ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
4388 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4389 bool ContainsUnexpandedParameterPack)
4390 : Expr(GenericSelectionExprClass, Context.DependentTy, VK_PRValue,
4391 OK_Ordinary),
4392 NumAssocs(AssocExprs.size()), ResultIndex(ResultDependentIndex),
4393 IsExprPredicate(true), DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
4394 assert(AssocTypes.size() == AssocExprs.size() &&
4395 "Must have the same number of association expressions"
4396 " and TypeSourceInfo!");
4397
4398 GenericSelectionExprBits.GenericLoc = GenericLoc;
4399 getTrailingObjects<Stmt *>()[getIndexOfControllingExpression()] =
4400 ControllingExpr;
4401 std::copy(AssocExprs.begin(), AssocExprs.end(),
4402 getTrailingObjects<Stmt *>() + getIndexOfStartOfAssociatedExprs());
4403 std::copy(AssocTypes.begin(), AssocTypes.end(),
4404 getTrailingObjects<TypeSourceInfo *>() +
4405 getIndexOfStartOfAssociatedTypes());
4406
4407 setDependence(computeDependence(this, ContainsUnexpandedParameterPack));
4408}
4409
4410GenericSelectionExpr::GenericSelectionExpr(
4411 const ASTContext &Context, SourceLocation GenericLoc,
4412 TypeSourceInfo *ControllingType, ArrayRef<TypeSourceInfo *> AssocTypes,
4413 ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,
4414 SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack)
4415 : Expr(GenericSelectionExprClass, Context.DependentTy, VK_PRValue,
4416 OK_Ordinary),
4417 NumAssocs(AssocExprs.size()), ResultIndex(ResultDependentIndex),
4418 IsExprPredicate(false), DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
4419 assert(AssocTypes.size() == AssocExprs.size() &&
4420 "Must have the same number of association expressions"
4421 " and TypeSourceInfo!");
4422
4423 GenericSelectionExprBits.GenericLoc = GenericLoc;
4424 getTrailingObjects<TypeSourceInfo *>()[getIndexOfControllingType()] =
4425 ControllingType;
4426 std::copy(AssocExprs.begin(), AssocExprs.end(),
4427 getTrailingObjects<Stmt *>() + getIndexOfStartOfAssociatedExprs());
4428 std::copy(AssocTypes.begin(), AssocTypes.end(),
4429 getTrailingObjects<TypeSourceInfo *>() +
4430 getIndexOfStartOfAssociatedTypes());
4431
4432 setDependence(computeDependence(this, ContainsUnexpandedParameterPack));
4433}
4434
4435GenericSelectionExpr::GenericSelectionExpr(EmptyShell Empty, unsigned NumAssocs)
4436 : Expr(GenericSelectionExprClass, Empty), NumAssocs(NumAssocs) {}
4437
4439 const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,
4440 ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
4441 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4442 bool ContainsUnexpandedParameterPack, unsigned ResultIndex) {
4443 unsigned NumAssocs = AssocExprs.size();
4444 void *Mem = Context.Allocate(
4445 totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
4446 alignof(GenericSelectionExpr));
4447 return new (Mem) GenericSelectionExpr(
4448 Context, GenericLoc, ControllingExpr, AssocTypes, AssocExprs, DefaultLoc,
4449 RParenLoc, ContainsUnexpandedParameterPack, ResultIndex);
4450}
4451
4453 const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,
4454 ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
4455 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4456 bool ContainsUnexpandedParameterPack) {
4457 unsigned NumAssocs = AssocExprs.size();
4458 void *Mem = Context.Allocate(
4459 totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
4460 alignof(GenericSelectionExpr));
4461 return new (Mem) GenericSelectionExpr(
4462 Context, GenericLoc, ControllingExpr, AssocTypes, AssocExprs, DefaultLoc,
4463 RParenLoc, ContainsUnexpandedParameterPack);
4464}
4465
4467 const ASTContext &Context, SourceLocation GenericLoc,
4468 TypeSourceInfo *ControllingType, ArrayRef<TypeSourceInfo *> AssocTypes,
4469 ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,
4470 SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack,
4471 unsigned ResultIndex) {
4472 unsigned NumAssocs = AssocExprs.size();
4473 void *Mem = Context.Allocate(
4474 totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
4475 alignof(GenericSelectionExpr));
4476 return new (Mem) GenericSelectionExpr(
4477 Context, GenericLoc, ControllingType, AssocTypes, AssocExprs, DefaultLoc,
4478 RParenLoc, ContainsUnexpandedParameterPack, ResultIndex);
4479}
4480
4482 const ASTContext &Context, SourceLocation GenericLoc,
4483 TypeSourceInfo *ControllingType, ArrayRef<TypeSourceInfo *> AssocTypes,
4484 ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,
4485 SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack) {
4486 unsigned NumAssocs = AssocExprs.size();
4487 void *Mem = Context.Allocate(
4488 totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
4489 alignof(GenericSelectionExpr));
4490 return new (Mem) GenericSelectionExpr(
4491 Context, GenericLoc, ControllingType, AssocTypes, AssocExprs, DefaultLoc,
4492 RParenLoc, ContainsUnexpandedParameterPack);
4493}
4494
4497 unsigned NumAssocs) {
4498 void *Mem = Context.Allocate(
4499 totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
4500 alignof(GenericSelectionExpr));
4501 return new (Mem) GenericSelectionExpr(EmptyShell(), NumAssocs);
4502}
4503
4504//===----------------------------------------------------------------------===//
4505// DesignatedInitExpr
4506//===----------------------------------------------------------------------===//
4507
4509 assert(isFieldDesignator() && "Only valid on a field designator");
4510 if (FieldInfo.NameOrField & 0x01)
4511 return reinterpret_cast<IdentifierInfo *>(FieldInfo.NameOrField & ~0x01);
4512 return getFieldDecl()->getIdentifier();
4513}
4514
4515DesignatedInitExpr::DesignatedInitExpr(const ASTContext &C, QualType Ty,
4516 llvm::ArrayRef<Designator> Designators,
4517 SourceLocation EqualOrColonLoc,
4518 bool GNUSyntax,
4519 ArrayRef<Expr *> IndexExprs, Expr *Init)
4520 : Expr(DesignatedInitExprClass, Ty, Init->getValueKind(),
4521 Init->getObjectKind()),
4522 EqualOrColonLoc(EqualOrColonLoc), GNUSyntax(GNUSyntax),
4523 NumDesignators(Designators.size()), NumSubExprs(IndexExprs.size() + 1) {
4524 this->Designators = new (C) Designator[NumDesignators];
4525
4526 // Record the initializer itself.
4527 child_iterator Child = child_begin();
4528 *Child++ = Init;
4529
4530 // Copy the designators and their subexpressions, computing
4531 // value-dependence along the way.
4532 unsigned IndexIdx = 0;
4533 for (unsigned I = 0; I != NumDesignators; ++I) {
4534 this->Designators[I] = Designators[I];
4535 if (this->Designators[I].isArrayDesignator()) {
4536 // Copy the index expressions into permanent storage.
4537 *Child++ = IndexExprs[IndexIdx++];
4538 } else if (this->Designators[I].isArrayRangeDesignator()) {
4539 // Copy the start/end expressions into permanent storage.
4540 *Child++ = IndexExprs[IndexIdx++];
4541 *Child++ = IndexExprs[IndexIdx++];
4542 }
4543 }
4544
4545 assert(IndexIdx == IndexExprs.size() && "Wrong number of index expressions");
4547}
4548
4551 llvm::ArrayRef<Designator> Designators,
4552 ArrayRef<Expr*> IndexExprs,
4553 SourceLocation ColonOrEqualLoc,
4554 bool UsesColonSyntax, Expr *Init) {
4555 void *Mem = C.Allocate(totalSizeToAlloc<Stmt *>(IndexExprs.size() + 1),
4556 alignof(DesignatedInitExpr));
4557 return new (Mem) DesignatedInitExpr(C, C.VoidTy, Designators,
4558 ColonOrEqualLoc, UsesColonSyntax,
4559 IndexExprs, Init);
4560}
4561
4563 unsigned NumIndexExprs) {
4564 void *Mem = C.Allocate(totalSizeToAlloc<Stmt *>(NumIndexExprs + 1),
4565 alignof(DesignatedInitExpr));
4566 return new (Mem) DesignatedInitExpr(NumIndexExprs + 1);
4567}
4568
4570 const Designator *Desigs,
4571 unsigned NumDesigs) {
4572 Designators = new (C) Designator[NumDesigs];
4573 NumDesignators = NumDesigs;
4574 for (unsigned I = 0; I != NumDesigs; ++I)
4575 Designators[I] = Desigs[I];
4576}
4577
4579 DesignatedInitExpr *DIE = const_cast<DesignatedInitExpr*>(this);
4580 if (size() == 1)
4581 return DIE->getDesignator(0)->getSourceRange();
4582 return SourceRange(DIE->getDesignator(0)->getBeginLoc(),
4583 DIE->getDesignator(size() - 1)->getEndLoc());
4584}
4585
4587 auto *DIE = const_cast<DesignatedInitExpr *>(this);
4588 Designator &First = *DIE->getDesignator(0);
4589 if (First.isFieldDesignator())
4590 return GNUSyntax ? First.getFieldLoc() : First.getDotLoc();
4591 return First.getLBracketLoc();
4592}
4593
4595 return getInit()->getEndLoc();
4596}
4597
4599 assert(D.isArrayDesignator() && "Requires array designator");
4600 return getSubExpr(D.getArrayIndex() + 1);
4601}
4602
4604 assert(D.isArrayRangeDesignator() && "Requires array range designator");
4605 return getSubExpr(D.getArrayIndex() + 1);
4606}
4607
4609 assert(D.isArrayRangeDesignator() && "Requires array range designator");
4610 return getSubExpr(D.getArrayIndex() + 2);
4611}
4612
4613/// Replaces the designator at index @p Idx with the series
4614/// of designators in [First, Last).
4616 const Designator *First,
4617 const Designator *Last) {
4618 unsigned NumNewDesignators = Last - First;
4619 if (NumNewDesignators == 0) {
4620 std::copy_backward(Designators + Idx + 1,
4621 Designators + NumDesignators,
4622 Designators + Idx);
4623 --NumNewDesignators;
4624 return;
4625 }
4626 if (NumNewDesignators == 1) {
4627 Designators[Idx] = *First;
4628 return;
4629 }
4630
4631 Designator *NewDesignators
4632 = new (C) Designator[NumDesignators - 1 + NumNewDesignators];
4633 std::copy(Designators, Designators + Idx, NewDesignators);
4634 std::copy(First, Last, NewDesignators + Idx);
4635 std::copy(Designators + Idx + 1, Designators + NumDesignators,
4636 NewDesignators + Idx + NumNewDesignators);
4637 Designators = NewDesignators;
4638 NumDesignators = NumDesignators - 1 + NumNewDesignators;
4639}
4640
4642 SourceLocation lBraceLoc,
4643 Expr *baseExpr,
4644 SourceLocation rBraceLoc)
4645 : Expr(DesignatedInitUpdateExprClass, baseExpr->getType(), VK_PRValue,
4646 OK_Ordinary) {
4647 BaseAndUpdaterExprs[0] = baseExpr;
4648
4649 InitListExpr *ILE =
4650 new (C) InitListExpr(C, lBraceLoc, std::nullopt, rBraceLoc);
4651 ILE->setType(baseExpr->getType());
4652 BaseAndUpdaterExprs[1] = ILE;
4653
4654 // FIXME: this is wrong, set it correctly.
4655 setDependence(ExprDependence::None);
4656}
4657
4659 return getBase()->getBeginLoc();
4660}
4661
4663 return getBase()->getEndLoc();
4664}
4665
4666ParenListExpr::ParenListExpr(SourceLocation LParenLoc, ArrayRef<Expr *> Exprs,
4667 SourceLocation RParenLoc)
4668 : Expr(ParenListExprClass, QualType(), VK_PRValue, OK_Ordinary),
4669 LParenLoc(LParenLoc), RParenLoc(RParenLoc) {
4670 ParenListExprBits.NumExprs = Exprs.size();
4671
4672 for (unsigned I = 0, N = Exprs.size(); I != N; ++I)
4673 getTrailingObjects<Stmt *>()[I] = Exprs[I];
4675}
4676
4677ParenListExpr::ParenListExpr(EmptyShell Empty, unsigned NumExprs)
4678 : Expr(ParenListExprClass, Empty) {
4679 ParenListExprBits.NumExprs = NumExprs;
4680}
4681
4683 SourceLocation LParenLoc,
4684 ArrayRef<Expr *> Exprs,
4685 SourceLocation RParenLoc) {
4686 void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *>(Exprs.size()),
4687 alignof(ParenListExpr));
4688 return new (Mem) ParenListExpr(LParenLoc, Exprs, RParenLoc);
4689}
4690
4692 unsigned NumExprs) {
4693 void *Mem =
4694 Ctx.Allocate(totalSizeToAlloc<Stmt *>(NumExprs), alignof(ParenListExpr));
4695 return new (Mem) ParenListExpr(EmptyShell(), NumExprs);
4696}
4697
4699 Opcode opc, QualType ResTy, ExprValueKind VK,
4701 FPOptionsOverride FPFeatures)
4702 : Expr(BinaryOperatorClass, ResTy, VK, OK) {
4703 BinaryOperatorBits.Opc = opc;
4704 assert(!isCompoundAssignmentOp() &&
4705 "Use CompoundAssignOperator for compound assignments");
4706 BinaryOperatorBits.OpLoc = opLoc;
4707 SubExprs[LHS] = lhs;
4708 SubExprs[RHS] = rhs;
4709 BinaryOperatorBits.HasFPFeatures = FPFeatures.requiresTrailingStorage();
4710 if (hasStoredFPFeatures())
4711 setStoredFPFeatures(FPFeatures);
4713}
4714
4716 Opcode opc, QualType ResTy, ExprValueKind VK,
4718 FPOptionsOverride FPFeatures, bool dead2)
4719 : Expr(CompoundAssignOperatorClass, ResTy, VK, OK) {
4720 BinaryOperatorBits.Opc = opc;
4721 assert(isCompoundAssignmentOp() &&
4722 "Use CompoundAssignOperator for compound assignments");
4723 BinaryOperatorBits.OpLoc = opLoc;
4724 SubExprs[LHS] = lhs;
4725 SubExprs[RHS] = rhs;
4726 BinaryOperatorBits.HasFPFeatures = FPFeatures.requiresTrailingStorage();
4727 if (hasStoredFPFeatures())
4728 setStoredFPFeatures(FPFeatures);
4730}
4731
4733 bool HasFPFeatures) {
4734 unsigned Extra = sizeOfTrailingObjects(HasFPFeatures);
4735 void *Mem =
4736 C.Allocate(sizeof(BinaryOperator) + Extra, alignof(BinaryOperator));
4737 return new (Mem) BinaryOperator(EmptyShell());
4738}
4739
4741 Expr *rhs, Opcode opc, QualType ResTy,
4743 SourceLocation opLoc,
4744 FPOptionsOverride FPFeatures) {
4745 bool HasFPFeatures = FPFeatures.requiresTrailingStorage();
4746 unsigned Extra = sizeOfTrailingObjects(HasFPFeatures);
4747 void *Mem =
4748 C.Allocate(sizeof(BinaryOperator) + Extra, alignof(BinaryOperator));
4749 return new (Mem)
4750 BinaryOperator(C, lhs, rhs, opc, ResTy, VK, OK, opLoc, FPFeatures);
4751}
4752
4755 unsigned Extra = sizeOfTrailingObjects(HasFPFeatures);
4756 void *Mem = C.Allocate(sizeof(CompoundAssignOperator) + Extra,
4757 alignof(CompoundAssignOperator));
4758 return new (Mem) CompoundAssignOperator(C, EmptyShell(), HasFPFeatures);
4759}
4760
4763 Opcode opc, QualType ResTy, ExprValueKind VK,
4765 FPOptionsOverride FPFeatures,
4766 QualType CompLHSType, QualType CompResultType) {
4767 bool HasFPFeatures = FPFeatures.requiresTrailingStorage();
4768 unsigned Extra = sizeOfTrailingObjects(HasFPFeatures);
4769 void *Mem = C.Allocate(sizeof(CompoundAssignOperator) + Extra,
4770 alignof(CompoundAssignOperator));
4771 return new (Mem)
4772 CompoundAssignOperator(C, lhs, rhs, opc, ResTy, VK, OK, opLoc, FPFeatures,
4773 CompLHSType, CompResultType);
4774}
4775
4777 bool hasFPFeatures) {
4778 void *Mem = C.Allocate(totalSizeToAlloc<FPOptionsOverride>(hasFPFeatures),
4779 alignof(UnaryOperator));
4780 return new (Mem) UnaryOperator(hasFPFeatures, EmptyShell());
4781}
4782
4785 SourceLocation l, bool CanOverflow,
4786 FPOptionsOverride FPFeatures)
4787 : Expr(UnaryOperatorClass, type, VK, OK), Val(input) {
4788 UnaryOperatorBits.Opc = opc;
4789 UnaryOperatorBits.CanOverflow = CanOverflow;
4790 UnaryOperatorBits.Loc = l;
4791 UnaryOperatorBits.HasFPFeatures = FPFeatures.requiresTrailingStorage();
4792 if (hasStoredFPFeatures())
4793 setStoredFPFeatures(FPFeatures);
4794 setDependence(computeDependence(this, Ctx));
4795}
4796
4798 Opcode opc, QualType type,
4800 SourceLocation l, bool CanOverflow,
4801 FPOptionsOverride FPFeatures) {
4802 bool HasFPFeatures = FPFeatures.requiresTrailingStorage();
4803 unsigned Size = totalSizeToAlloc<FPOptionsOverride>(HasFPFeatures);
4804 void *Mem = C.Allocate(Size, alignof(UnaryOperator));
4805 return new (Mem)
4806 UnaryOperator(C, input, opc, type, VK, OK, l, CanOverflow, FPFeatures);
4807}
4808
4810 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(e))
4811 e = ewc->getSubExpr();
4812 if (const MaterializeTemporaryExpr *m = dyn_cast<MaterializeTemporaryExpr>(e))
4813 e = m->getSubExpr();
4814 e = cast<CXXConstructExpr>(e)->getArg(0);
4815 while (const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
4816 e = ice->getSubExpr();
4817 return cast<OpaqueValueExpr>(e);
4818}
4819
4821 EmptyShell sh,
4822 unsigned numSemanticExprs) {
4823 void *buffer =
4824 Context.Allocate(totalSizeToAlloc<Expr *>(1 + numSemanticExprs),
4825 alignof(PseudoObjectExpr));
4826 return new(buffer) PseudoObjectExpr(sh, numSemanticExprs);
4827}
4828
4829PseudoObjectExpr::PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs)
4830 : Expr(PseudoObjectExprClass, shell) {
4831 PseudoObjectExprBits.NumSubExprs = numSemanticExprs + 1;
4832}
4833
4835 ArrayRef<Expr*> semantics,
4836 unsigned resultIndex) {
4837 assert(syntax && "no syntactic expression!");
4838 assert(semantics.size() && "no semantic expressions!");
4839
4840 QualType type;
4841 ExprValueKind VK;
4842 if (resultIndex == NoResult) {
4843 type = C.VoidTy;
4844 VK = VK_PRValue;
4845 } else {
4846 assert(resultIndex < semantics.size());
4847 type = semantics[resultIndex]->getType();
4848 VK = semantics[resultIndex]->getValueKind();
4849 assert(semantics[resultIndex]->getObjectKind() == OK_Ordinary);
4850 }
4851
4852 void *buffer = C.Allocate(totalSizeToAlloc<Expr *>(semantics.size() + 1),
4853 alignof(PseudoObjectExpr));
4854 return new(buffer) PseudoObjectExpr(type, VK, syntax, semantics,
4855 resultIndex);
4856}
4857
4858PseudoObjectExpr::PseudoObjectExpr(QualType type, ExprValueKind VK,
4859 Expr *syntax, ArrayRef<Expr *> semantics,
4860 unsigned resultIndex)
4861 : Expr(PseudoObjectExprClass, type, VK, OK_Ordinary) {
4862 PseudoObjectExprBits.NumSubExprs = semantics.size() + 1;
4863 PseudoObjectExprBits.ResultIndex = resultIndex + 1;
4864
4865 for (unsigned i = 0, e = semantics.size() + 1; i != e; ++i) {
4866 Expr *E = (i == 0 ? syntax : semantics[i-1]);
4867 getSubExprsBuffer()[i] = E;
4868
4869 if (isa<OpaqueValueExpr>(E))
4870 assert(cast<OpaqueValueExpr>(E)->getSourceExpr() != nullptr &&
4871 "opaque-value semantic expressions for pseudo-object "
4872 "operations must have sources");
4873 }
4874
4876}
4877
4878//===----------------------------------------------------------------------===//
4879// Child Iterators for iterating over subexpressions/substatements
4880//===----------------------------------------------------------------------===//
4881
4882// UnaryExprOrTypeTraitExpr
4884 const_child_range CCR =
4885 const_cast<const UnaryExprOrTypeTraitExpr *>(this)->children();
4886 return child_range(cast_away_const(CCR.begin()), cast_away_const(CCR.end()));
4887}
4888
4890 // If this is of a type and the type is a VLA type (and not a typedef), the
4891 // size expression of the VLA needs to be treated as an executable expression.
4892 // Why isn't this weirdness documented better in StmtIterator?
4893 if (isArgumentType()) {
4894 if (const VariableArrayType *T =
4895 dyn_cast<VariableArrayType>(getArgumentType().getTypePtr()))
4898 }
4899 return const_child_range(&Argument.Ex, &Argument.Ex + 1);
4900}
4901
4903 AtomicOp op, SourceLocation RP)
4904 : Expr(AtomicExprClass, t, VK_PRValue, OK_Ordinary),
4905 NumSubExprs(args.size()), BuiltinLoc(BLoc), RParenLoc(RP), Op(op) {
4906 assert(args.size() == getNumSubExprs(op) && "wrong number of subexpressions");
4907 for (unsigned i = 0; i != args.size(); i++)
4908 SubExprs[i] = args[i];
4910}
4911
4913 switch (Op) {
4914 case AO__c11_atomic_init:
4915 case AO__opencl_atomic_init:
4916 case AO__c11_atomic_load:
4917 case AO__atomic_load_n:
4918 return 2;
4919
4920 case AO__scoped_atomic_load_n:
4921 case AO__opencl_atomic_load:
4922 case AO__hip_atomic_load:
4923 case AO__c11_atomic_store:
4924 case AO__c11_atomic_exchange:
4925 case AO__atomic_load:
4926 case AO__atomic_store:
4927 case AO__atomic_store_n:
4928 case AO__atomic_exchange_n:
4929 case AO__c11_atomic_fetch_add:
4930 case AO__c11_atomic_fetch_sub:
4931 case AO__c11_atomic_fetch_and:
4932 case AO__c11_atomic_fetch_or:
4933 case AO__c11_atomic_fetch_xor:
4934 case AO__c11_atomic_fetch_nand:
4935 case AO__c11_atomic_fetch_max:
4936 case AO__c11_atomic_fetch_min:
4937 case AO__atomic_fetch_add:
4938 case AO__atomic_fetch_sub:
4939 case AO__atomic_fetch_and:
4940 case AO__atomic_fetch_or:
4941 case AO__atomic_fetch_xor:
4942 case AO__atomic_fetch_nand:
4943 case AO__atomic_add_fetch:
4944 case AO__atomic_sub_fetch:
4945 case AO__atomic_and_fetch:
4946 case AO__atomic_or_fetch:
4947 case AO__atomic_xor_fetch:
4948 case AO__atomic_nand_fetch:
4949 case AO__atomic_min_fetch:
4950 case AO__atomic_max_fetch:
4951 case AO__atomic_fetch_min:
4952 case AO__atomic_fetch_max:
4953 return 3;
4954
4955 case AO__scoped_atomic_load:
4956 case AO__scoped_atomic_store:
4957 case AO__scoped_atomic_store_n:
4958 case AO__scoped_atomic_fetch_add:
4959 case AO__scoped_atomic_fetch_sub:
4960 case AO__scoped_atomic_fetch_and:
4961 case AO__scoped_atomic_fetch_or:
4962 case AO__scoped_atomic_fetch_xor:
4963 case AO__scoped_atomic_fetch_nand:
4964 case AO__scoped_atomic_add_fetch:
4965 case AO__scoped_atomic_sub_fetch:
4966 case AO__scoped_atomic_and_fetch:
4967 case AO__scoped_atomic_or_fetch:
4968 case AO__scoped_atomic_xor_fetch:
4969 case AO__scoped_atomic_nand_fetch:
4970 case AO__scoped_atomic_min_fetch:
4971 case AO__scoped_atomic_max_fetch:
4972 case AO__scoped_atomic_fetch_min:
4973 case AO__scoped_atomic_fetch_max:
4974 case AO__scoped_atomic_exchange_n:
4975 case AO__hip_atomic_exchange:
4976 case AO__hip_atomic_fetch_add:
4977 case AO__hip_atomic_fetch_sub:
4978 case AO__hip_atomic_fetch_and:
4979 case AO__hip_atomic_fetch_or:
4980 case AO__hip_atomic_fetch_xor:
4981 case AO__hip_atomic_fetch_min:
4982 case AO__hip_atomic_fetch_max:
4983 case AO__opencl_atomic_store:
4984 case AO__hip_atomic_store:
4985 case AO__opencl_atomic_exchange:
4986 case AO__opencl_atomic_fetch_add:
4987 case AO__opencl_atomic_fetch_sub:
4988 case AO__opencl_atomic_fetch_and:
4989 case AO__opencl_atomic_fetch_or:
4990 case AO__opencl_atomic_fetch_xor:
4991 case AO__opencl_atomic_fetch_min:
4992 case AO__opencl_atomic_fetch_max:
4993 case AO__atomic_exchange:
4994 return 4;
4995
4996 case AO__scoped_atomic_exchange:
4997 case AO__c11_atomic_compare_exchange_strong:
4998 case AO__c11_atomic_compare_exchange_weak:
4999 return 5;
5000 case AO__hip_atomic_compare_exchange_strong:
5001 case AO__opencl_atomic_compare_exchange_strong:
5002 case AO__opencl_atomic_compare_exchange_weak:
5003 case AO__hip_atomic_compare_exchange_weak:
5004 case AO__atomic_compare_exchange:
5005 case AO__atomic_compare_exchange_n:
5006 return 6;
5007
5008 case AO__scoped_atomic_compare_exchange:
5009 case AO__scoped_atomic_compare_exchange_n:
5010 return 7;
5011 }
5012 llvm_unreachable("unknown atomic op");
5013}
5014
5016 auto T = getPtr()->getType()->castAs<PointerType>()->getPointeeType();
5017 if (auto AT = T->getAs<AtomicType>())
5018 return AT->getValueType();
5019 return T;
5020}
5021
5023 unsigned ArraySectionCount = 0;
5024 while (auto *OASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParens())) {
5025 Base = OASE->getBase();
5026 ++ArraySectionCount;
5027 }
5028 while (auto *ASE =
5029 dyn_cast<ArraySubscriptExpr>(Base->IgnoreParenImpCasts())) {
5030 Base = ASE->getBase();
5031 ++ArraySectionCount;
5032 }
5033 Base = Base->IgnoreParenImpCasts();
5034 auto OriginalTy = Base->getType();
5035 if (auto *DRE = dyn_cast<DeclRefExpr>(Base))
5036 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
5037 OriginalTy = PVD->getOriginalType().getNonReferenceType();
5038
5039 for (unsigned Cnt = 0; Cnt < ArraySectionCount; ++Cnt) {
5040 if (OriginalTy->isAnyPointerType())
5041 OriginalTy = OriginalTy->getPointeeType();
5042 else if (OriginalTy->isArrayType())
5043 OriginalTy = OriginalTy->castAsArrayTypeUnsafe()->getElementType();
5044 else
5045 return {};
5046 }
5047 return OriginalTy;
5048}
5049
5050RecoveryExpr::RecoveryExpr(ASTContext &Ctx, QualType T, SourceLocation BeginLoc,
5051 SourceLocation EndLoc, ArrayRef<Expr *> SubExprs)
5052 : Expr(RecoveryExprClass, T.getNonReferenceType(),
5053 T->isDependentType() ? VK_LValue : getValueKindForType(T),
5054 OK_Ordinary),
5055 BeginLoc(BeginLoc), EndLoc(EndLoc), NumExprs(SubExprs.size()) {
5056 assert(!T.isNull());
5057 assert(!llvm::is_contained(SubExprs, nullptr));
5058
5059 llvm::copy(SubExprs, getTrailingObjects<Expr *>());
5061}
5062
5064 SourceLocation BeginLoc,
5065 SourceLocation EndLoc,
5066 ArrayRef<Expr *> SubExprs) {
5067 void *Mem = Ctx.Allocate(totalSizeToAlloc<Expr *>(SubExprs.size()),
5068 alignof(RecoveryExpr));
5069 return new (Mem) RecoveryExpr(Ctx, T, BeginLoc, EndLoc, SubE