clang 24.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/ASTLambda.h"
17#include "clang/AST/Attr.h"
19#include "clang/AST/DeclCXX.h"
20#include "clang/AST/DeclObjC.h"
24#include "clang/AST/ExprCXX.h"
26#include "clang/AST/Mangle.h"
29#include "clang/AST/TypeBase.h"
34#include "clang/Lex/Lexer.h"
37#include "llvm/Support/ErrorHandling.h"
38#include "llvm/Support/Format.h"
39#include "llvm/Support/raw_ostream.h"
40#include <algorithm>
41#include <cstring>
42#include <optional>
43using namespace clang;
44
46 const Expr *E = this;
47 while (true) {
48 E = E->IgnoreParenBaseCasts();
49
50 // Follow the RHS of a comma operator.
51 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
52 if (BO->getOpcode() == BO_Comma) {
53 E = BO->getRHS();
54 continue;
55 }
56 }
57
58 // Step into initializer for materialized temporaries.
59 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
60 E = MTE->getSubExpr();
61 continue;
62 }
63
64 break;
65 }
66
67 return E;
68}
69
72 QualType DerivedType = E->getType();
73 if (const PointerType *PTy = DerivedType->getAs<PointerType>())
74 DerivedType = PTy->getPointeeType();
75
76 while (const ArrayType *ATy = DerivedType->getAsArrayTypeUnsafe())
77 DerivedType = ATy->getElementType();
78
79 if (DerivedType->isDependentType())
80 return nullptr;
81
82 return DerivedType->castAsCXXRecordDecl();
83}
84
87 SmallVectorImpl<SubobjectAdjustment> &Adjustments) const {
88 const Expr *E = this;
89 while (true) {
90 E = E->IgnoreParens();
91
92 if (const auto *CE = dyn_cast<CastExpr>(E)) {
93 if ((CE->getCastKind() == CK_DerivedToBase ||
94 CE->getCastKind() == CK_UncheckedDerivedToBase) &&
95 E->getType()->isRecordType()) {
96 E = CE->getSubExpr();
97 const auto *Derived = E->getType()->castAsCXXRecordDecl();
98 Adjustments.push_back(SubobjectAdjustment(CE, Derived));
99 continue;
100 }
101
102 if (CE->getCastKind() == CK_NoOp) {
103 E = CE->getSubExpr();
104 continue;
105 }
106 } else if (const auto *ME = dyn_cast<MemberExpr>(E)) {
107 if (!ME->isArrow()) {
108 assert(ME->getBase()->getType()->getAsRecordDecl());
109 if (const auto *Field = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
110 if (!Field->isBitField() && !Field->getType()->isReferenceType()) {
111 E = ME->getBase();
112 Adjustments.push_back(SubobjectAdjustment(Field));
113 continue;
114 }
115 }
116 }
117 } else if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
118 if (BO->getOpcode() == BO_PtrMemD) {
119 assert(BO->getRHS()->isPRValue());
120 E = BO->getLHS();
121 const auto *MPT = BO->getRHS()->getType()->getAs<MemberPointerType>();
122 Adjustments.push_back(SubobjectAdjustment(MPT, BO->getRHS()));
123 continue;
124 }
125 if (BO->getOpcode() == BO_Comma) {
126 CommaLHSs.push_back(BO->getLHS());
127 E = BO->getRHS();
128 continue;
129 }
130 }
131
132 // Nothing changed.
133 break;
134 }
135 return E;
136}
137
138bool Expr::isKnownToHaveBooleanValue(bool Semantic) const {
139 const Expr *E = IgnoreParens();
140
141 // If this value has _Bool type, it is obvious 0/1.
142 if (E->getType()->isBooleanType()) return true;
143 // If this is a non-scalar-integer type, we don't care enough to try.
144 if (!E->getType()->isIntegralOrEnumerationType()) return false;
145
146 if (!Semantic)
147 if (const auto *BIT = E->getType()->getAs<BitIntType>();
148 BIT && BIT->isUnsigned() && BIT->getNumBits() == 1)
149 return true;
150
151 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
152 switch (UO->getOpcode()) {
153 case UO_Plus:
154 return UO->getSubExpr()->isKnownToHaveBooleanValue(Semantic);
155 case UO_LNot:
156 return true;
157 default:
158 return false;
159 }
160 }
161
162 // Only look through implicit casts. If the user writes
163 // '(int) (a && b)' treat it as an arbitrary int.
164 // FIXME: Should we look through any cast expression in !Semantic mode?
165 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
166 return CE->getSubExpr()->isKnownToHaveBooleanValue(Semantic);
167
168 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
169 switch (BO->getOpcode()) {
170 default: return false;
171 case BO_LT: // Relational operators.
172 case BO_GT:
173 case BO_LE:
174 case BO_GE:
175 case BO_EQ: // Equality operators.
176 case BO_NE:
177 case BO_LAnd: // AND operator.
178 case BO_LOr: // Logical OR operator.
179 return true;
180
181 case BO_And: // Bitwise AND operator.
182 case BO_Xor: // Bitwise XOR operator.
183 case BO_Or: // Bitwise OR operator.
184 // Handle things like (x==2)|(y==12).
185 return BO->getLHS()->isKnownToHaveBooleanValue(Semantic) &&
186 BO->getRHS()->isKnownToHaveBooleanValue(Semantic);
187
188 case BO_Comma:
189 case BO_Assign:
190 return BO->getRHS()->isKnownToHaveBooleanValue(Semantic);
191 }
192 }
193
194 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
195 return CO->getTrueExpr()->isKnownToHaveBooleanValue(Semantic) &&
196 CO->getFalseExpr()->isKnownToHaveBooleanValue(Semantic);
197
199 return true;
200
201 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
202 return OVE->getSourceExpr()->isKnownToHaveBooleanValue(Semantic);
203
204 if (const FieldDecl *FD = E->getSourceBitField())
205 if (!Semantic && FD->getType()->isUnsignedIntegerType() &&
206 !FD->getBitWidth()->isValueDependent() && FD->getBitWidthValue() == 1)
207 return true;
208
209 return false;
210}
211
213 const ASTContext &Ctx,
214 LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel,
215 bool IgnoreTemplateOrMacroSubstitution) const {
216 const Expr *E = IgnoreParens();
217 const Decl *D = nullptr;
218
219 if (const auto *ME = dyn_cast<MemberExpr>(E))
220 D = ME->getMemberDecl();
221 else if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
222 D = DRE->getDecl();
223 else if (const auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
224 D = IRE->getDecl();
225
226 return Decl::isFlexibleArrayMemberLike(Ctx, D, E->getType(),
227 StrictFlexArraysLevel,
228 IgnoreTemplateOrMacroSubstitution);
229}
230
231const ValueDecl *
233 Expr::EvalResult Eval;
234
235 if (EvaluateAsConstantExpr(Eval, Context)) {
236 APValue &Value = Eval.Val;
237
238 if (Value.isMemberPointer())
239 return Value.getMemberPointerDecl();
240
241 if (Value.isLValue() && Value.getLValueOffset().isZero())
242 return Value.getLValueBase().dyn_cast<const ValueDecl *>();
243 }
244
245 return nullptr;
246}
247
248// Amusing macro metaprogramming hack: check whether a class provides
249// a more specific implementation of getExprLoc().
250//
251// See also Stmt.cpp:{getBeginLoc(),getEndLoc()}.
252namespace {
253 /// This implementation is used when a class provides a custom
254 /// implementation of getExprLoc.
255 template <class E, class T>
256 SourceLocation getExprLocImpl(const Expr *expr,
257 SourceLocation (T::*v)() const) {
258 return static_cast<const E*>(expr)->getExprLoc();
259 }
260
261 /// This implementation is used when a class doesn't provide
262 /// a custom implementation of getExprLoc. Overload resolution
263 /// should pick it over the implementation above because it's
264 /// more specialized according to function template partial ordering.
265 template <class E>
266 SourceLocation getExprLocImpl(const Expr *expr,
267 SourceLocation (Expr::*v)() const) {
268 return static_cast<const E *>(expr)->getBeginLoc();
269 }
270}
271
273 if (isa<EnumType>(getType()))
274 return getType();
275 if (const auto *ECD = getEnumConstantDecl()) {
276 const auto *ED = cast<EnumDecl>(ECD->getDeclContext());
277 if (ED->isCompleteDefinition())
278 return Ctx.getCanonicalTagType(ED);
279 }
280 return getType();
281}
282
284 switch (getStmtClass()) {
285 case Stmt::NoStmtClass: llvm_unreachable("statement without class");
286#define ABSTRACT_STMT(type)
287#define STMT(type, base) \
288 case Stmt::type##Class: break;
289#define EXPR(type, base) \
290 case Stmt::type##Class: return getExprLocImpl<type>(this, &type::getExprLoc);
291#include "clang/AST/StmtNodes.inc"
292 }
293 llvm_unreachable("unknown expression kind");
294}
295
296//===----------------------------------------------------------------------===//
297// Primary Expressions.
298//===----------------------------------------------------------------------===//
299
301 assert((Kind == ConstantResultStorageKind::APValue ||
304 "Invalid StorageKind Value");
305 (void)Kind;
306}
307
309 switch (Value.getKind()) {
310 case APValue::None:
313 case APValue::Int:
314 if (!Value.getInt().needsCleanup())
316 [[fallthrough]];
317 default:
319 }
320}
321
324 if (T->isIntegralOrEnumerationType() && Context.getTypeInfo(T).Width <= 64)
327}
328
329ConstantExpr::ConstantExpr(Expr *SubExpr, ConstantResultStorageKind StorageKind,
330 bool IsImmediateInvocation)
331 : FullExpr(ConstantExprClass, SubExpr) {
332 ConstantExprBits.ResultKind = llvm::to_underlying(StorageKind);
333 ConstantExprBits.APValueKind = APValue::None;
334 ConstantExprBits.IsUnsigned = false;
335 ConstantExprBits.BitWidth = 0;
336 ConstantExprBits.HasCleanup = false;
337 ConstantExprBits.IsImmediateInvocation = IsImmediateInvocation;
338
339 if (StorageKind == ConstantResultStorageKind::APValue)
340 ::new (getTrailingObjects<APValue>()) APValue();
341}
342
343ConstantExpr *ConstantExpr::Create(const ASTContext &Context, Expr *E,
344 ConstantResultStorageKind StorageKind,
345 bool IsImmediateInvocation) {
346 assert(!isa<ConstantExpr>(E));
347 AssertResultStorageKind(StorageKind);
348
349 unsigned Size = totalSizeToAlloc<APValue, uint64_t>(
351 StorageKind == ConstantResultStorageKind::Int64);
352 void *Mem = Context.Allocate(Size, alignof(ConstantExpr));
353 return new (Mem) ConstantExpr(E, StorageKind, IsImmediateInvocation);
354}
355
356ConstantExpr *ConstantExpr::Create(const ASTContext &Context, Expr *E,
357 const APValue &Result) {
359 ConstantExpr *Self = Create(Context, E, StorageKind);
360 Self->SetResult(Result, Context);
361 return Self;
362}
363
364ConstantExpr::ConstantExpr(EmptyShell Empty,
365 ConstantResultStorageKind StorageKind)
366 : FullExpr(ConstantExprClass, Empty) {
367 ConstantExprBits.ResultKind = llvm::to_underlying(StorageKind);
368
369 if (StorageKind == ConstantResultStorageKind::APValue)
370 ::new (getTrailingObjects<APValue>()) APValue();
371}
372
373ConstantExpr *ConstantExpr::CreateEmpty(const ASTContext &Context,
374 ConstantResultStorageKind StorageKind) {
375 AssertResultStorageKind(StorageKind);
376
377 unsigned Size = totalSizeToAlloc<APValue, uint64_t>(
379 StorageKind == ConstantResultStorageKind::Int64);
380 void *Mem = Context.Allocate(Size, alignof(ConstantExpr));
381 return new (Mem) ConstantExpr(EmptyShell(), StorageKind);
382}
383
385 assert((unsigned)getStorageKind(Value) <= ConstantExprBits.ResultKind &&
386 "Invalid storage for this value kind");
387 ConstantExprBits.APValueKind = Value.getKind();
388 switch (getResultStorageKind()) {
390 return;
392 Int64Result() = *Value.getInt().getRawData();
393 ConstantExprBits.BitWidth = Value.getInt().getBitWidth();
394 ConstantExprBits.IsUnsigned = Value.getInt().isUnsigned();
395 return;
397 if (!ConstantExprBits.HasCleanup && Value.needsCleanup()) {
398 ConstantExprBits.HasCleanup = true;
399 Context.addDestruction(&APValueResult());
400 }
401 APValueResult() = std::move(Value);
402 return;
403 }
404 llvm_unreachable("Invalid ResultKind Bits");
405}
406
408 switch (getResultStorageKind()) {
410 return APValueResult().getInt();
412 return llvm::APSInt(llvm::APInt(ConstantExprBits.BitWidth, Int64Result()),
413 ConstantExprBits.IsUnsigned);
414 default:
415 llvm_unreachable("invalid Accessor");
416 }
417}
418
420
421 switch (getResultStorageKind()) {
423 return APValueResult();
425 return APValue(
426 llvm::APSInt(llvm::APInt(ConstantExprBits.BitWidth, Int64Result()),
427 ConstantExprBits.IsUnsigned));
429 if (ConstantExprBits.APValueKind == APValue::Indeterminate)
431 return APValue();
432 }
433 llvm_unreachable("invalid ResultKind");
434}
435
436DeclRefExpr::DeclRefExpr(const ASTContext &Ctx, ValueDecl *D,
437 bool RefersToEnclosingVariableOrCapture, QualType T,
439 const DeclarationNameLoc &LocInfo,
440 NonOdrUseReason NOUR)
441 : Expr(DeclRefExprClass, T, VK, OK_Ordinary), D(D), DNLoc(LocInfo) {
442 DeclRefExprBits.HasQualifier = false;
443 DeclRefExprBits.HasTemplateKWAndArgsInfo = false;
444 DeclRefExprBits.HasFoundDecl = false;
445 DeclRefExprBits.HadMultipleCandidates = false;
446 DeclRefExprBits.RefersToEnclosingVariableOrCapture =
447 RefersToEnclosingVariableOrCapture;
448 DeclRefExprBits.CapturedByCopyInLambdaWithExplicitObjectParameter = false;
449 DeclRefExprBits.NonOdrUseReason = NOUR;
450 DeclRefExprBits.IsImmediateEscalating = false;
451 DeclRefExprBits.Loc = L;
453}
454
455DeclRefExpr::DeclRefExpr(const ASTContext &Ctx,
456 NestedNameSpecifierLoc QualifierLoc,
457 SourceLocation TemplateKWLoc, ValueDecl *D,
458 bool RefersToEnclosingVariableOrCapture,
459 const DeclarationNameInfo &NameInfo, NamedDecl *FoundD,
460 const TemplateArgumentListInfo *TemplateArgs,
462 : Expr(DeclRefExprClass, T, VK, OK_Ordinary), D(D),
463 DNLoc(NameInfo.getInfo()) {
464 DeclRefExprBits.Loc = NameInfo.getLoc();
465 DeclRefExprBits.HasQualifier = QualifierLoc ? 1 : 0;
466 if (QualifierLoc)
467 new (getTrailingObjects<NestedNameSpecifierLoc>())
468 NestedNameSpecifierLoc(QualifierLoc);
469 DeclRefExprBits.HasFoundDecl = FoundD ? 1 : 0;
470 if (FoundD)
471 *getTrailingObjects<NamedDecl *>() = FoundD;
472 DeclRefExprBits.HasTemplateKWAndArgsInfo
473 = (TemplateArgs || TemplateKWLoc.isValid()) ? 1 : 0;
474 DeclRefExprBits.RefersToEnclosingVariableOrCapture =
475 RefersToEnclosingVariableOrCapture;
476 DeclRefExprBits.CapturedByCopyInLambdaWithExplicitObjectParameter = false;
477 DeclRefExprBits.NonOdrUseReason = NOUR;
478 if (TemplateArgs) {
479 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
480 TemplateKWLoc, *TemplateArgs,
481 getTrailingObjects<TemplateArgumentLoc>());
482#ifndef NDEBUG
483 auto Deps = TemplateArgumentDependence::None;
484 for (const TemplateArgumentLoc &Loc : TemplateArgs->arguments())
485 Deps |= Loc.getArgument().getDependence();
486 assert(!(Deps & TemplateArgumentDependence::Dependent) &&
487 "built a DeclRefExpr with dependent template args");
488#endif
489 } else if (TemplateKWLoc.isValid()) {
490 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
491 TemplateKWLoc);
492 }
493 DeclRefExprBits.IsImmediateEscalating = false;
494 DeclRefExprBits.HadMultipleCandidates = 0;
496}
497
498DeclRefExpr *DeclRefExpr::Create(const ASTContext &Context,
499 NestedNameSpecifierLoc QualifierLoc,
500 SourceLocation TemplateKWLoc, ValueDecl *D,
501 bool RefersToEnclosingVariableOrCapture,
502 SourceLocation NameLoc, QualType T,
503 ExprValueKind VK, NamedDecl *FoundD,
504 const TemplateArgumentListInfo *TemplateArgs,
505 NonOdrUseReason NOUR) {
506 return Create(Context, QualifierLoc, TemplateKWLoc, D,
507 RefersToEnclosingVariableOrCapture,
508 DeclarationNameInfo(D->getDeclName(), NameLoc),
509 T, VK, FoundD, TemplateArgs, NOUR);
510}
511
512DeclRefExpr *DeclRefExpr::Create(const ASTContext &Context,
513 NestedNameSpecifierLoc QualifierLoc,
514 SourceLocation TemplateKWLoc, ValueDecl *D,
515 bool RefersToEnclosingVariableOrCapture,
516 const DeclarationNameInfo &NameInfo,
518 NamedDecl *FoundD,
519 const TemplateArgumentListInfo *TemplateArgs,
520 NonOdrUseReason NOUR) {
521 // Filter out cases where the found Decl is the same as the value refenenced.
522 if (D == FoundD)
523 FoundD = nullptr;
524
525 bool HasTemplateKWAndArgsInfo = TemplateArgs || TemplateKWLoc.isValid();
526 std::size_t Size =
527 totalSizeToAlloc<NestedNameSpecifierLoc, NamedDecl *,
529 QualifierLoc ? 1 : 0, FoundD ? 1 : 0,
530 HasTemplateKWAndArgsInfo ? 1 : 0,
531 TemplateArgs ? TemplateArgs->size() : 0);
532
533 void *Mem = Context.Allocate(Size, alignof(DeclRefExpr));
534 return new (Mem) DeclRefExpr(Context, QualifierLoc, TemplateKWLoc, D,
535 RefersToEnclosingVariableOrCapture, NameInfo,
536 FoundD, TemplateArgs, T, VK, NOUR);
537}
538
539DeclRefExpr *DeclRefExpr::CreateEmpty(const ASTContext &Context,
540 bool HasQualifier,
541 bool HasFoundDecl,
542 bool HasTemplateKWAndArgsInfo,
543 unsigned NumTemplateArgs) {
544 assert(NumTemplateArgs == 0 || HasTemplateKWAndArgsInfo);
545 std::size_t Size =
546 totalSizeToAlloc<NestedNameSpecifierLoc, NamedDecl *,
548 HasQualifier ? 1 : 0, HasFoundDecl ? 1 : 0, HasTemplateKWAndArgsInfo,
549 NumTemplateArgs);
550 void *Mem = Context.Allocate(Size, alignof(DeclRefExpr));
551 return new (Mem) DeclRefExpr(EmptyShell());
552}
553
555 D = NewD;
556 if (getType()->isUndeducedType())
557 setType(NewD->getType());
559}
560
566
567SYCLUniqueStableNameExpr::SYCLUniqueStableNameExpr(SourceLocation OpLoc,
568 SourceLocation LParen,
569 SourceLocation RParen,
570 QualType ResultTy,
571 TypeSourceInfo *TSI)
572 : Expr(SYCLUniqueStableNameExprClass, ResultTy, VK_PRValue, OK_Ordinary),
573 OpLoc(OpLoc), LParen(LParen), RParen(RParen) {
574 setTypeSourceInfo(TSI);
576}
577
578SYCLUniqueStableNameExpr::SYCLUniqueStableNameExpr(EmptyShell Empty,
579 QualType ResultTy)
580 : Expr(SYCLUniqueStableNameExprClass, ResultTy, VK_PRValue, OK_Ordinary) {}
581
584 SourceLocation LParen, SourceLocation RParen,
585 TypeSourceInfo *TSI) {
586 QualType ResultTy = Ctx.getPointerType(Ctx.CharTy.withConst());
587 return new (Ctx)
588 SYCLUniqueStableNameExpr(OpLoc, LParen, RParen, ResultTy, TSI);
589}
590
593 QualType ResultTy = Ctx.getPointerType(Ctx.CharTy.withConst());
594 return new (Ctx) SYCLUniqueStableNameExpr(EmptyShell(), ResultTy);
595}
596
601
603 QualType Ty) {
604 auto MangleCallback = [](ASTContext &Ctx,
605 const NamedDecl *ND) -> UnsignedOrNone {
606 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND))
607 return RD->getDeviceLambdaManglingNumber();
608 return std::nullopt;
609 };
610
611 std::unique_ptr<MangleContext> Ctx{ItaniumMangleContext::create(
612 Context, Context.getDiagnostics(), MangleCallback)};
613
614 std::string Buffer;
615 Buffer.reserve(128);
616 llvm::raw_string_ostream Out(Buffer);
617 Ctx->mangleCanonicalTypeName(Ty, Out);
618
619 return Buffer;
620}
621
622PredefinedExpr::PredefinedExpr(SourceLocation L, QualType FNTy,
623 PredefinedIdentKind IK, bool IsTransparent,
624 StringLiteral *SL)
625 : Expr(PredefinedExprClass, FNTy, VK_LValue, OK_Ordinary) {
626 PredefinedExprBits.Kind = llvm::to_underlying(IK);
627 assert((getIdentKind() == IK) &&
628 "IdentKind do not fit in PredefinedExprBitfields!");
629 bool HasFunctionName = SL != nullptr;
630 PredefinedExprBits.HasFunctionName = HasFunctionName;
631 PredefinedExprBits.IsTransparent = IsTransparent;
632 PredefinedExprBits.Loc = L;
633 if (HasFunctionName)
634 setFunctionName(SL);
636}
637
638PredefinedExpr::PredefinedExpr(EmptyShell Empty, bool HasFunctionName)
639 : Expr(PredefinedExprClass, Empty) {
640 PredefinedExprBits.HasFunctionName = HasFunctionName;
641}
642
645 bool IsTransparent, StringLiteral *SL) {
646 bool HasFunctionName = SL != nullptr;
647 void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *>(HasFunctionName),
648 alignof(PredefinedExpr));
649 return new (Mem) PredefinedExpr(L, FNTy, IK, IsTransparent, SL);
650}
651
652PredefinedExpr *PredefinedExpr::CreateEmpty(const ASTContext &Ctx,
653 bool HasFunctionName) {
654 void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *>(HasFunctionName),
655 alignof(PredefinedExpr));
656 return new (Mem) PredefinedExpr(EmptyShell(), HasFunctionName);
657}
658
660 switch (IK) {
662 return "__func__";
664 return "__FUNCTION__";
666 return "__FUNCDNAME__";
668 return "L__FUNCTION__";
670 return "__PRETTY_FUNCTION__";
672 return "__FUNCSIG__";
674 return "L__FUNCSIG__";
676 break;
677 }
678 llvm_unreachable("Unknown ident kind for PredefinedExpr");
679}
680
681// FIXME: Maybe this should use DeclPrinter with a special "print predefined
682// expr" policy instead.
684 const Decl *CurrentDecl,
685 bool ForceElaboratedPrinting) {
686 ASTContext &Context = CurrentDecl->getASTContext();
687
689 if (const NamedDecl *ND = dyn_cast<NamedDecl>(CurrentDecl)) {
690 std::unique_ptr<MangleContext> MC;
691 MC.reset(Context.createMangleContext());
692
693 if (MC->shouldMangleDeclName(ND)) {
694 SmallString<256> Buffer;
695 llvm::raw_svector_ostream Out(Buffer);
696 GlobalDecl GD;
697 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(ND))
698 GD = GlobalDecl(CD, Ctor_Base);
699 else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(ND))
700 GD = GlobalDecl(DD, Dtor_Base);
701 else if (auto FD = dyn_cast<FunctionDecl>(ND)) {
702 GD = FD->isReferenceableKernel() ? GlobalDecl(FD) : GlobalDecl(ND);
703 } else
704 GD = GlobalDecl(ND);
705 MC->mangleName(GD, Out);
706
707 if (!Buffer.empty() && Buffer.front() == '\01')
708 return std::string(Buffer.substr(1));
709 return std::string(Buffer);
710 }
711 return std::string(ND->getIdentifier()->getName());
712 }
713 return "";
714 }
715 if (isa<BlockDecl>(CurrentDecl)) {
716 // For blocks we only emit something if it is enclosed in a function
717 // For top-level block we'd like to include the name of variable, but we
718 // don't have it at this point.
719 auto DC = CurrentDecl->getDeclContext();
720 if (DC->isFileContext())
721 return "";
722
723 SmallString<256> Buffer;
724 llvm::raw_svector_ostream Out(Buffer);
725 if (auto *DCBlock = dyn_cast<BlockDecl>(DC))
726 // For nested blocks, propagate up to the parent.
727 Out << ComputeName(IK, DCBlock);
728 else if (auto *DCDecl = dyn_cast<Decl>(DC))
729 Out << ComputeName(IK, DCDecl) << "_block_invoke";
730 return std::string(Out.str());
731 }
732 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CurrentDecl)) {
733 const auto &LO = Context.getLangOpts();
734 bool IsFuncOrFunctionInNonMSVCCompatEnv =
736 IK == PredefinedIdentKind ::Function) &&
737 !LO.MSVCCompat);
738 bool IsLFunctionInMSVCCommpatEnv =
739 IK == PredefinedIdentKind::LFunction && LO.MSVCCompat;
740 bool IsFuncOrFunctionOrLFunctionOrFuncDName =
745 if ((ForceElaboratedPrinting &&
746 (IsFuncOrFunctionInNonMSVCCompatEnv || IsLFunctionInMSVCCommpatEnv)) ||
747 (!ForceElaboratedPrinting && IsFuncOrFunctionOrLFunctionOrFuncDName))
748 return FD->getNameAsString();
749
750 SmallString<256> Name;
751 llvm::raw_svector_ostream Out(Name);
752
753 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
754 if (MD->isVirtual() && IK != PredefinedIdentKind::PrettyFunctionNoVirtual)
755 Out << "virtual ";
756 if (MD->isStatic() && !ForceElaboratedPrinting)
757 Out << "static ";
758 }
759
760 class PrettyCallbacks final : public PrintingCallbacks {
761 public:
762 PrettyCallbacks(const LangOptions &LO) : LO(LO) {}
763 std::string remapPath(StringRef Path) const override {
764 SmallString<128> p(Path);
765 LO.remapPathPrefix(p);
766 return std::string(p);
767 }
768
769 private:
770 const LangOptions &LO;
771 };
772 PrintingPolicy Policy(Context.getLangOpts());
773 PrettyCallbacks PrettyCB(Context.getLangOpts());
774 Policy.Callbacks = &PrettyCB;
775 if (IK == PredefinedIdentKind::Function && ForceElaboratedPrinting)
776 Policy.SuppressTagKeyword = !LO.MSVCCompat;
777 std::string Proto;
778 llvm::raw_string_ostream POut(Proto);
779
780 const FunctionDecl *Decl = FD;
781 if (const FunctionDecl* Pattern = FD->getTemplateInstantiationPattern())
782 Decl = Pattern;
783
784 // Bail out if the type of the function has not been set yet.
785 // This can notably happen in the trailing return type of a lambda
786 // expression.
787 const Type *Ty = Decl->getType().getTypePtrOrNull();
788 if (!Ty)
789 return "";
790
791 const FunctionType *AFT = Ty->getAs<FunctionType>();
792 const FunctionProtoType *FT = nullptr;
793 if (FD->hasWrittenPrototype())
794 FT = dyn_cast<FunctionProtoType>(AFT);
795
798 switch (AFT->getCallConv()) {
799 case CC_C: POut << "__cdecl "; break;
800 case CC_X86StdCall: POut << "__stdcall "; break;
801 case CC_X86FastCall: POut << "__fastcall "; break;
802 case CC_X86ThisCall: POut << "__thiscall "; break;
803 case CC_X86VectorCall: POut << "__vectorcall "; break;
804 case CC_X86RegCall: POut << "__regcall "; break;
805 // Only bother printing the conventions that MSVC knows about.
806 default: break;
807 }
808 }
809
810 FD->printQualifiedName(POut, Policy);
811
813 Out << Proto;
814 return std::string(Name);
815 }
816
817 POut << "(";
818 if (FT) {
819 for (unsigned i = 0, e = Decl->getNumParams(); i != e; ++i) {
820 if (i) POut << ", ";
821 POut << Decl->getParamDecl(i)->getType().stream(Policy);
822 }
823
824 if (FT->isVariadic()) {
825 if (FD->getNumParams()) POut << ", ";
826 POut << "...";
827 } else if ((IK == PredefinedIdentKind::FuncSig ||
829 !Context.getLangOpts().CPlusPlus) &&
830 !Decl->getNumParams()) {
831 POut << "void";
832 }
833 }
834 POut << ")";
835
836 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
837 assert(FT && "We must have a written prototype in this case.");
838 if (FT->isConst())
839 POut << " const";
840 if (FT->isVolatile())
841 POut << " volatile";
842 RefQualifierKind Ref = MD->getRefQualifier();
843 if (Ref == RQ_LValue)
844 POut << " &";
845 else if (Ref == RQ_RValue)
846 POut << " &&";
847 }
848
850 SpecsTy Specs;
851 const DeclContext *Ctx = FD->getDeclContext();
852 while (isa_and_nonnull<NamedDecl>(Ctx)) {
854 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx);
855 if (Spec && !Spec->isExplicitSpecialization())
856 Specs.push_back(Spec);
857 Ctx = Ctx->getParent();
858 }
859
860 std::string TemplateParams;
861 llvm::raw_string_ostream TOut(TemplateParams);
862 for (const ClassTemplateSpecializationDecl *D : llvm::reverse(Specs)) {
863 const TemplateParameterList *Params =
864 D->getSpecializedTemplate()->getTemplateParameters();
865 const TemplateArgumentList &Args = D->getTemplateArgs();
866 assert(Params->size() == Args.size());
867 for (unsigned i = 0, numParams = Params->size(); i != numParams; ++i) {
868 StringRef Param = Params->getParam(i)->getName();
869 if (Param.empty()) continue;
870 TOut << Param << " = ";
871 Args.get(i).print(Policy, TOut,
873 Policy, Params, i));
874 TOut << ", ";
875 }
876 }
877
879 = FD->getTemplateSpecializationInfo();
880 if (FSI && !FSI->isExplicitSpecialization()) {
881 const TemplateParameterList* Params
883 const TemplateArgumentList* Args = FSI->TemplateArguments;
884 assert(Params->size() == Args->size());
885 for (unsigned i = 0, e = Params->size(); i != e; ++i) {
886 StringRef Param = Params->getParam(i)->getName();
887 if (Param.empty()) continue;
888 TOut << Param << " = ";
889 Args->get(i).print(Policy, TOut, /*IncludeType*/ true);
890 TOut << ", ";
891 }
892 }
893
894 if (!TemplateParams.empty()) {
895 // remove the trailing comma and space
896 TemplateParams.resize(TemplateParams.size() - 2);
897 POut << " [" << TemplateParams << "]";
898 }
899
900 // Print "auto" for all deduced return types. This includes C++1y return
901 // type deduction and lambdas. For trailing return types resolve the
902 // decltype expression. Otherwise print the real type when this is
903 // not a constructor or destructor.
904 if (isLambdaMethod(FD))
905 Proto = "auto " + Proto;
906 else if (FT && FT->getReturnType()->getAs<DecltypeType>())
907 FT->getReturnType()
908 ->getAs<DecltypeType>()
910 .getAsStringInternal(Proto, Policy);
912 AFT->getReturnType().getAsStringInternal(Proto, Policy);
913
914 Out << Proto;
915
916 return std::string(Name);
917 }
918 if (const CapturedDecl *CD = dyn_cast<CapturedDecl>(CurrentDecl)) {
919 for (const DeclContext *DC = CD->getParent(); DC; DC = DC->getParent())
920 // Skip to its enclosing function or method, but not its enclosing
921 // CapturedDecl.
922 if (DC->isFunctionOrMethod() && (DC->getDeclKind() != Decl::Captured)) {
923 const Decl *D = Decl::castFromDeclContext(DC);
924 return ComputeName(IK, D);
925 }
926 llvm_unreachable("CapturedDecl not inside a function or method");
927 }
928 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurrentDecl)) {
929 SmallString<256> Name;
930 llvm::raw_svector_ostream Out(Name);
931 Out << (MD->isInstanceMethod() ? '-' : '+');
932 Out << '[';
933
934 // For incorrect code, there might not be an ObjCInterfaceDecl. Do
935 // a null check to avoid a crash.
936 if (const ObjCInterfaceDecl *ID = MD->getClassInterface())
937 Out << *ID;
938
939 if (const ObjCCategoryImplDecl *CID =
940 dyn_cast<ObjCCategoryImplDecl>(MD->getDeclContext()))
941 Out << '(' << *CID << ')';
942
943 Out << ' ';
944 MD->getSelector().print(Out);
945 Out << ']';
946
947 return std::string(Name);
948 }
949 if (isa<TranslationUnitDecl>(CurrentDecl) &&
951 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
952 return "top level";
953 }
954 return "";
955}
956
958 const llvm::APInt &Val) {
959 if (hasAllocation())
960 C.Deallocate(pVal);
961
962 BitWidth = Val.getBitWidth();
963 unsigned NumWords = Val.getNumWords();
964 const uint64_t* Words = Val.getRawData();
965 if (NumWords > 1) {
966 pVal = new (C) uint64_t[NumWords];
967 std::copy(Words, Words + NumWords, pVal);
968 } else if (NumWords == 1)
969 VAL = Words[0];
970 else
971 VAL = 0;
972}
973
974IntegerLiteral::IntegerLiteral(const ASTContext &C, const llvm::APInt &V,
976 : Expr(IntegerLiteralClass, type, VK_PRValue, OK_Ordinary), Loc(l) {
977 assert(type->isIntegerType() && "Illegal type in IntegerLiteral");
978 assert(V.getBitWidth() == C.getIntWidth(type) &&
979 "Integer type is not the correct size for constant.");
980 setValue(C, V);
981 setDependence(ExprDependence::None);
982}
983
985IntegerLiteral::Create(const ASTContext &C, const llvm::APInt &V,
987 return new (C) IntegerLiteral(C, V, type, l);
988}
989
992 return new (C) IntegerLiteral(Empty);
993}
994
995FixedPointLiteral::FixedPointLiteral(const ASTContext &C, const llvm::APInt &V,
997 unsigned Scale)
998 : Expr(FixedPointLiteralClass, type, VK_PRValue, OK_Ordinary), Loc(l),
999 Scale(Scale) {
1000 assert(type->isFixedPointType() && "Illegal type in FixedPointLiteral");
1001 assert(V.getBitWidth() == C.getTypeInfo(type).Width &&
1002 "Fixed point type is not the correct size for constant.");
1003 setValue(C, V);
1004 setDependence(ExprDependence::None);
1005}
1006
1008 const llvm::APInt &V,
1009 QualType type,
1011 unsigned Scale) {
1012 return new (C) FixedPointLiteral(C, V, type, l, Scale);
1013}
1014
1015FixedPointLiteral *FixedPointLiteral::Create(const ASTContext &C,
1016 EmptyShell Empty) {
1017 return new (C) FixedPointLiteral(Empty);
1018}
1019
1020std::string FixedPointLiteral::getValueAsString(unsigned Radix) const {
1021 // Currently the longest decimal number that can be printed is the max for an
1022 // unsigned long _Accum: 4294967295.99999999976716935634613037109375
1023 // which is 43 characters.
1026 S, llvm::APSInt::getUnsigned(getValue().getZExtValue()), Scale);
1027 return std::string(S);
1028}
1029
1031 raw_ostream &OS) {
1032 switch (Kind) {
1034 break; // no prefix.
1036 OS << 'L';
1037 break;
1039 OS << "u8";
1040 break;
1042 OS << 'u';
1043 break;
1045 OS << 'U';
1046 break;
1047 }
1048
1049 StringRef Escaped = escapeCStyle<EscapeChar::Single>(Val);
1050 if (!Escaped.empty()) {
1051 OS << "'" << Escaped << "'";
1052 } else {
1053 // A character literal might be sign-extended, which
1054 // would result in an invalid \U escape sequence.
1055 // FIXME: multicharacter literals such as '\xFF\xFF\xFF\xFF'
1056 // are not correctly handled.
1057 if ((Val & ~0xFFu) == ~0xFFu && Kind == CharacterLiteralKind::Ascii)
1058 Val &= 0xFFu;
1059 if (Val < 256 && isPrintable((unsigned char)Val))
1060 OS << "'" << (char)Val << "'";
1061 else if (Val < 256)
1062 OS << "'\\x" << llvm::format("%02x", Val) << "'";
1063 else if (Val <= 0xFFFF)
1064 OS << "'\\u" << llvm::format("%04x", Val) << "'";
1065 else
1066 OS << "'\\U" << llvm::format("%08x", Val) << "'";
1067 }
1068}
1069
1070FloatingLiteral::FloatingLiteral(const ASTContext &C, const llvm::APFloat &V,
1071 bool isexact, QualType Type, SourceLocation L)
1072 : Expr(FloatingLiteralClass, Type, VK_PRValue, OK_Ordinary), Loc(L) {
1073 setSemantics(V.getSemantics());
1074 FloatingLiteralBits.IsExact = isexact;
1075 setValue(C, V);
1076 setDependence(ExprDependence::None);
1077}
1078
1079FloatingLiteral::FloatingLiteral(const ASTContext &C, EmptyShell Empty)
1080 : Expr(FloatingLiteralClass, Empty) {
1081 setRawSemantics(llvm::APFloatBase::S_IEEEhalf);
1082 FloatingLiteralBits.IsExact = false;
1083}
1084
1086FloatingLiteral::Create(const ASTContext &C, const llvm::APFloat &V,
1087 bool isexact, QualType Type, SourceLocation L) {
1088 return new (C) FloatingLiteral(C, V, isexact, Type, L);
1089}
1090
1093 return new (C) FloatingLiteral(C, Empty);
1094}
1095
1096/// getValueAsApproximateDouble - This returns the value as an inaccurate
1097/// double. Note that this may cause loss of precision, but is useful for
1098/// debugging dumps, etc.
1100 llvm::APFloat V = getValue();
1101 bool ignored;
1102 V.convert(llvm::APFloat::IEEEdouble(), llvm::APFloat::rmNearestTiesToEven,
1103 &ignored);
1104 return V.convertToDouble();
1105}
1106
1107unsigned StringLiteral::mapCharByteWidth(TargetInfo const &Target,
1108 StringLiteralKind SK) {
1109 unsigned CharByteWidth = 0;
1110 switch (SK) {
1114 CharByteWidth = Target.getCharWidth();
1115 break;
1117 CharByteWidth = Target.getWCharWidth();
1118 break;
1120 CharByteWidth = Target.getChar16Width();
1121 break;
1123 CharByteWidth = Target.getChar32Width();
1124 break;
1126 return sizeof(char); // Host;
1127 }
1128 assert((CharByteWidth & 7) == 0 && "Assumes character size is byte multiple");
1129 CharByteWidth /= 8;
1130 assert((CharByteWidth == 1 || CharByteWidth == 2 || CharByteWidth == 4) &&
1131 "The only supported character byte widths are 1,2 and 4!");
1132 return CharByteWidth;
1133}
1134
1135StringLiteral::StringLiteral(const ASTContext &Ctx, StringRef Str,
1136 StringLiteralKind Kind, bool Pascal, QualType Ty,
1138 : Expr(StringLiteralClass, Ty, VK_LValue, OK_Ordinary) {
1139
1140 unsigned Length = Str.size();
1141
1142 StringLiteralBits.Kind = llvm::to_underlying(Kind);
1143 StringLiteralBits.NumConcatenated = Locs.size();
1144
1145 if (Kind != StringLiteralKind::Unevaluated) {
1146 assert(Ctx.getAsConstantArrayType(Ty) &&
1147 "StringLiteral must be of constant array type!");
1148 unsigned CharByteWidth = mapCharByteWidth(Ctx.getTargetInfo(), Kind);
1149 unsigned ByteLength = Str.size();
1150 assert((ByteLength % CharByteWidth == 0) &&
1151 "The size of the data must be a multiple of CharByteWidth!");
1152
1153 // Avoid the expensive division. The compiler should be able to figure it
1154 // out by itself. However as of clang 7, even with the appropriate
1155 // llvm_unreachable added just here, it is not able to do so.
1156 switch (CharByteWidth) {
1157 case 1:
1158 Length = ByteLength;
1159 break;
1160 case 2:
1161 Length = ByteLength / 2;
1162 break;
1163 case 4:
1164 Length = ByteLength / 4;
1165 break;
1166 default:
1167 llvm_unreachable("Unsupported character width!");
1168 }
1169
1170 StringLiteralBits.CharByteWidth = CharByteWidth;
1171 StringLiteralBits.IsPascal = Pascal;
1172 } else {
1173 assert(!Pascal && "Can't make an unevaluated Pascal string");
1174 StringLiteralBits.CharByteWidth = 1;
1175 StringLiteralBits.IsPascal = false;
1176 }
1177
1178 *getTrailingObjects<unsigned>() = Length;
1179
1180 // Initialize the trailing array of SourceLocation.
1181 // This is safe since SourceLocation is POD-like.
1182 llvm::copy(Locs, getTrailingObjects<SourceLocation>());
1183
1184 // Initialize the trailing array of char holding the string data.
1185 llvm::copy(Str, getTrailingObjects<char>());
1186
1187 setDependence(ExprDependence::None);
1188}
1189
1190StringLiteral::StringLiteral(EmptyShell Empty, unsigned NumConcatenated,
1191 unsigned Length, unsigned CharByteWidth)
1192 : Expr(StringLiteralClass, Empty) {
1193 StringLiteralBits.CharByteWidth = CharByteWidth;
1194 StringLiteralBits.NumConcatenated = NumConcatenated;
1195 *getTrailingObjects<unsigned>() = Length;
1196}
1197
1198StringLiteral *StringLiteral::Create(const ASTContext &Ctx, StringRef Str,
1199 StringLiteralKind Kind, bool Pascal,
1200 QualType Ty,
1202 void *Mem = Ctx.Allocate(totalSizeToAlloc<unsigned, SourceLocation, char>(
1203 1, Locs.size(), Str.size()),
1204 alignof(StringLiteral));
1205 return new (Mem) StringLiteral(Ctx, Str, Kind, Pascal, Ty, Locs);
1206}
1207
1208StringLiteral *StringLiteral::CreateEmpty(const ASTContext &Ctx,
1209 unsigned NumConcatenated,
1210 unsigned Length,
1211 unsigned CharByteWidth) {
1212 void *Mem = Ctx.Allocate(totalSizeToAlloc<unsigned, SourceLocation, char>(
1213 1, NumConcatenated, Length * CharByteWidth),
1214 alignof(StringLiteral));
1215 return new (Mem)
1216 StringLiteral(EmptyShell(), NumConcatenated, Length, CharByteWidth);
1217}
1218
1219void StringLiteral::outputString(raw_ostream &OS) const {
1220 switch (getKind()) {
1224 break; // no prefix.
1226 OS << 'L';
1227 break;
1229 OS << "u8";
1230 break;
1232 OS << 'u';
1233 break;
1235 OS << 'U';
1236 break;
1237 }
1238 OS << '"';
1239 static const char Hex[] = "0123456789ABCDEF";
1240
1241 unsigned LastSlashX = getLength();
1242 for (unsigned I = 0, N = getLength(); I != N; ++I) {
1243 uint32_t Char = getCodeUnit(I);
1244 StringRef Escaped = escapeCStyle<EscapeChar::Double>(Char);
1245 if (Escaped.empty()) {
1246 // FIXME: Convert UTF-8 back to codepoints before rendering.
1247
1248 // Convert UTF-16 surrogate pairs back to codepoints before rendering.
1249 // Leave invalid surrogates alone; we'll use \x for those.
1250 if (getKind() == StringLiteralKind::UTF16 && I != N - 1 &&
1251 Char >= 0xd800 && Char <= 0xdbff) {
1252 uint32_t Trail = getCodeUnit(I + 1);
1253 if (Trail >= 0xdc00 && Trail <= 0xdfff) {
1254 Char = 0x10000 + ((Char - 0xd800) << 10) + (Trail - 0xdc00);
1255 ++I;
1256 }
1257 }
1258
1259 if (Char > 0xff) {
1260 // If this is a wide string, output characters over 0xff using \x
1261 // escapes. Otherwise, this is a UTF-16 or UTF-32 string, and Char is a
1262 // codepoint: use \x escapes for invalid codepoints.
1264 (Char >= 0xd800 && Char <= 0xdfff) || Char >= 0x110000) {
1265 // FIXME: Is this the best way to print wchar_t?
1266 OS << "\\x";
1267 int Shift = 28;
1268 while ((Char >> Shift) == 0)
1269 Shift -= 4;
1270 for (/**/; Shift >= 0; Shift -= 4)
1271 OS << Hex[(Char >> Shift) & 15];
1272 LastSlashX = I;
1273 continue;
1274 }
1275
1276 if (Char > 0xffff)
1277 OS << "\\U00"
1278 << Hex[(Char >> 20) & 15]
1279 << Hex[(Char >> 16) & 15];
1280 else
1281 OS << "\\u";
1282 OS << Hex[(Char >> 12) & 15]
1283 << Hex[(Char >> 8) & 15]
1284 << Hex[(Char >> 4) & 15]
1285 << Hex[(Char >> 0) & 15];
1286 continue;
1287 }
1288
1289 // If we used \x... for the previous character, and this character is a
1290 // hexadecimal digit, prevent it being slurped as part of the \x.
1291 if (LastSlashX + 1 == I) {
1292 switch (Char) {
1293 case '0': case '1': case '2': case '3': case '4':
1294 case '5': case '6': case '7': case '8': case '9':
1295 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
1296 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
1297 OS << "\"\"";
1298 }
1299 }
1300
1301 assert(Char <= 0xff &&
1302 "Characters above 0xff should already have been handled.");
1303
1304 if (isPrintable(Char))
1305 OS << (char)Char;
1306 else // Output anything hard as an octal escape.
1307 OS << '\\'
1308 << (char)('0' + ((Char >> 6) & 7))
1309 << (char)('0' + ((Char >> 3) & 7))
1310 << (char)('0' + ((Char >> 0) & 7));
1311 } else {
1312 // Handle some common non-printable cases to make dumps prettier.
1313 OS << Escaped;
1314 }
1315 }
1316 OS << '"';
1317}
1318
1319/// getLocationOfByte - Return a source location that points to the specified
1320/// byte of this string literal.
1321///
1322/// Strings are amazingly complex. They can be formed from multiple tokens and
1323/// can have escape sequences in them in addition to the usual trigraph and
1324/// escaped newline business. This routine handles this complexity.
1325///
1326/// The *StartToken sets the first token to be searched in this function and
1327/// the *StartTokenByteOffset is the byte offset of the first token. Before
1328/// returning, it updates the *StartToken to the TokNo of the token being found
1329/// and sets *StartTokenByteOffset to the byte offset of the token in the
1330/// string.
1331/// Using these two parameters can reduce the time complexity from O(n^2) to
1332/// O(n) if one wants to get the location of byte for all the tokens in a
1333/// string.
1334///
1337 const LangOptions &Features,
1338 const TargetInfo &Target, unsigned *StartToken,
1339 unsigned *StartTokenByteOffset) const {
1340 // No source location of bytes for binary literals since they don't come from
1341 // source.
1343 return getStrTokenLoc(0);
1344
1345 assert((getKind() == StringLiteralKind::Ordinary ||
1348 "Only narrow string literals are currently supported");
1349
1350 // Loop over all of the tokens in this string until we find the one that
1351 // contains the byte we're looking for.
1352 unsigned TokNo = 0;
1353 unsigned StringOffset = 0;
1354 if (StartToken)
1355 TokNo = *StartToken;
1356 if (StartTokenByteOffset) {
1357 StringOffset = *StartTokenByteOffset;
1358 ByteNo -= StringOffset;
1359 }
1360 while (true) {
1361 assert(TokNo < getNumConcatenated() && "Invalid byte number!");
1362 SourceLocation StrTokLoc = getStrTokenLoc(TokNo);
1363
1364 // Get the spelling of the string so that we can get the data that makes up
1365 // the string literal, not the identifier for the macro it is potentially
1366 // expanded through.
1367 SourceLocation StrTokSpellingLoc = SM.getSpellingLoc(StrTokLoc);
1368
1369 // Re-lex the token to get its length and original spelling.
1370 FileIDAndOffset LocInfo = SM.getDecomposedLoc(StrTokSpellingLoc);
1371 bool Invalid = false;
1372 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
1373 if (Invalid) {
1374 if (StartTokenByteOffset != nullptr)
1375 *StartTokenByteOffset = StringOffset;
1376 if (StartToken != nullptr)
1377 *StartToken = TokNo;
1378 return StrTokSpellingLoc;
1379 }
1380
1381 const char *StrData = Buffer.data()+LocInfo.second;
1382
1383 // Create a lexer starting at the beginning of this token.
1384 Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), Features,
1385 Buffer.begin(), StrData, Buffer.end());
1386 Token TheTok;
1387 TheLexer.LexFromRawLexer(TheTok);
1388
1389 // Use the StringLiteralParser to compute the length of the string in bytes.
1390 StringLiteralParser SLP(TheTok, SM, Features, Target);
1391 unsigned TokNumBytes = SLP.GetStringLength();
1392
1393 // If the byte is in this token, return the location of the byte.
1394 if (ByteNo < TokNumBytes ||
1395 (ByteNo == TokNumBytes && TokNo == getNumConcatenated() - 1)) {
1396 unsigned Offset = SLP.getOffsetOfStringByte(TheTok, ByteNo);
1397
1398 // Now that we know the offset of the token in the spelling, use the
1399 // preprocessor to get the offset in the original source.
1400 if (StartTokenByteOffset != nullptr)
1401 *StartTokenByteOffset = StringOffset;
1402 if (StartToken != nullptr)
1403 *StartToken = TokNo;
1404 return Lexer::AdvanceToTokenCharacter(StrTokLoc, Offset, SM, Features);
1405 }
1406
1407 // Move to the next string token.
1408 StringOffset += TokNumBytes;
1409 ++TokNo;
1410 ByteNo -= TokNumBytes;
1411 }
1412}
1413
1415 unsigned Length = getLength();
1416 if (StartIndex > Length)
1417 return std::nullopt;
1418
1419 if (getCharByteWidth() == 1) {
1420 StringRef::size_type Pos = getString().substr(StartIndex).find('\0');
1421 if (Pos == StringRef::npos)
1422 return Length - StartIndex;
1423 return Pos;
1424 }
1425
1426 unsigned Result = 0;
1427 for (unsigned I = StartIndex; I != Length; ++I) {
1428 if (getCodeUnit(I) == 0)
1429 break;
1430 ++Result;
1431 }
1432
1433 return Result;
1434}
1435
1436/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1437/// corresponds to, e.g. "sizeof" or "[pre]++".
1439 switch (Op) {
1440#define UNARY_OPERATION(Name, Spelling) case UO_##Name: return Spelling;
1441#include "clang/AST/OperationKinds.def"
1442 }
1443 llvm_unreachable("Unknown unary operator");
1444}
1445
1448 switch (OO) {
1449 default: llvm_unreachable("No unary operator for overloaded function");
1450 case OO_PlusPlus: return Postfix ? UO_PostInc : UO_PreInc;
1451 case OO_MinusMinus: return Postfix ? UO_PostDec : UO_PreDec;
1452 case OO_Amp: return UO_AddrOf;
1453 case OO_Star: return UO_Deref;
1454 case OO_Plus: return UO_Plus;
1455 case OO_Minus: return UO_Minus;
1456 case OO_Tilde: return UO_Not;
1457 case OO_Exclaim: return UO_LNot;
1458 case OO_Coawait: return UO_Coawait;
1459 }
1460}
1461
1463 switch (Opc) {
1464 case UO_PostInc: case UO_PreInc: return OO_PlusPlus;
1465 case UO_PostDec: case UO_PreDec: return OO_MinusMinus;
1466 case UO_AddrOf: return OO_Amp;
1467 case UO_Deref: return OO_Star;
1468 case UO_Plus: return OO_Plus;
1469 case UO_Minus: return OO_Minus;
1470 case UO_Not: return OO_Tilde;
1471 case UO_LNot: return OO_Exclaim;
1472 case UO_Coawait: return OO_Coawait;
1473 default: return OO_None;
1474 }
1475}
1476
1477
1478//===----------------------------------------------------------------------===//
1479// Postfix Operators.
1480//===----------------------------------------------------------------------===//
1481#ifndef NDEBUG
1483 switch (SC) {
1484 case Expr::CallExprClass:
1485 return sizeof(CallExpr);
1486 case Expr::CXXOperatorCallExprClass:
1487 return sizeof(CXXOperatorCallExpr);
1488 case Expr::CXXMemberCallExprClass:
1489 return sizeof(CXXMemberCallExpr);
1490 case Expr::UserDefinedLiteralClass:
1491 return sizeof(UserDefinedLiteral);
1492 case Expr::CUDAKernelCallExprClass:
1493 return sizeof(CUDAKernelCallExpr);
1494 default:
1495 llvm_unreachable("unexpected class deriving from CallExpr!");
1496 }
1497}
1498#endif
1499
1500// changing the size of SourceLocation, CallExpr, and
1501// subclasses requires careful considerations
1502static_assert(sizeof(SourceLocation) == 4 && sizeof(CXXOperatorCallExpr) <= 32,
1503 "we assume CXXOperatorCallExpr is at most 32 bytes");
1504
1507 SourceLocation RParenLoc, FPOptionsOverride FPFeatures,
1508 unsigned MinNumArgs, ADLCallKind UsesADL)
1509 : Expr(SC, Ty, VK, OK_Ordinary), RParenLoc(RParenLoc) {
1510 NumArgs = std::max<unsigned>(Args.size(), MinNumArgs);
1511 unsigned NumPreArgs = PreArgs.size();
1512 CallExprBits.NumPreArgs = NumPreArgs;
1513 assert((NumPreArgs == getNumPreArgs()) && "NumPreArgs overflow!");
1515 "This CallExpr subclass is too big or unsupported");
1516
1517 CallExprBits.UsesADL = static_cast<bool>(UsesADL);
1518
1519 setCallee(Fn);
1520 for (unsigned I = 0; I != NumPreArgs; ++I)
1521 setPreArg(I, PreArgs[I]);
1522 for (unsigned I = 0; I != Args.size(); ++I)
1523 setArg(I, Args[I]);
1524 for (unsigned I = Args.size(); I != NumArgs; ++I)
1525 setArg(I, nullptr);
1526
1527 this->computeDependence();
1528
1529 CallExprBits.HasFPFeatures = FPFeatures.requiresTrailingStorage();
1530 CallExprBits.IsCoroElideSafe = false;
1531 CallExprBits.ExplicitObjectMemFunUsingMemberSyntax = false;
1532 CallExprBits.HasTrailingSourceLoc = false;
1533
1534 if (hasStoredFPFeatures())
1535 setStoredFPFeatures(FPFeatures);
1536}
1537
1538CallExpr::CallExpr(StmtClass SC, unsigned NumPreArgs, unsigned NumArgs,
1539 bool HasFPFeatures, EmptyShell Empty)
1540 : Expr(SC, Empty), NumArgs(NumArgs) {
1541 CallExprBits.NumPreArgs = NumPreArgs;
1542 assert((NumPreArgs == getNumPreArgs()) && "NumPreArgs overflow!");
1543 CallExprBits.HasFPFeatures = HasFPFeatures;
1544 CallExprBits.IsCoroElideSafe = false;
1545 CallExprBits.ExplicitObjectMemFunUsingMemberSyntax = false;
1546 CallExprBits.HasTrailingSourceLoc = false;
1547}
1548
1551 SourceLocation RParenLoc,
1552 FPOptionsOverride FPFeatures, unsigned MinNumArgs,
1554 unsigned NumArgs = std::max<unsigned>(Args.size(), MinNumArgs);
1555 unsigned SizeOfTrailingObjects = CallExpr::sizeOfTrailingObjects(
1556 /*NumPreArgs=*/0, NumArgs, FPFeatures.requiresTrailingStorage());
1557 void *Mem = Ctx.Allocate(
1558 sizeToAllocateForCallExprSubclass<CallExpr>(SizeOfTrailingObjects),
1559 alignof(CallExpr));
1560 CallExpr *E =
1561 new (Mem) CallExpr(CallExprClass, Fn, /*PreArgs=*/{}, Args, Ty, VK,
1562 RParenLoc, FPFeatures, MinNumArgs, UsesADL);
1563 E->updateTrailingSourceLoc();
1564 return E;
1565}
1566
1567CallExpr *CallExpr::CreateEmpty(const ASTContext &Ctx, unsigned NumArgs,
1568 bool HasFPFeatures, EmptyShell Empty) {
1569 unsigned SizeOfTrailingObjects =
1570 CallExpr::sizeOfTrailingObjects(/*NumPreArgs=*/0, NumArgs, HasFPFeatures);
1571 void *Mem = Ctx.Allocate(
1572 sizeToAllocateForCallExprSubclass<CallExpr>(SizeOfTrailingObjects),
1573 alignof(CallExpr));
1574 return new (Mem)
1575 CallExpr(CallExprClass, /*NumPreArgs=*/0, NumArgs, HasFPFeatures, Empty);
1576}
1577
1579
1580 // Optimize for the common case first
1581 // (simple function or member function call)
1582 // then try more exotic possibilities.
1583 Expr *CEE = IgnoreImpCasts();
1584
1585 if (auto *DRE = dyn_cast<DeclRefExpr>(CEE))
1586 return DRE->getDecl();
1587
1588 if (auto *ME = dyn_cast<MemberExpr>(CEE))
1589 return ME->getMemberDecl();
1590
1591 CEE = CEE->IgnoreParens();
1592
1593 while (auto *NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(CEE))
1594 CEE = NTTP->getReplacement()->IgnoreParenImpCasts();
1595
1596 // If we're calling a dereference, look at the pointer instead.
1597 while (true) {
1598 if (auto *BO = dyn_cast<BinaryOperator>(CEE)) {
1599 if (BO->isPtrMemOp()) {
1600 CEE = BO->getRHS()->IgnoreParenImpCasts();
1601 continue;
1602 }
1603 } else if (auto *UO = dyn_cast<UnaryOperator>(CEE)) {
1604 if (UO->getOpcode() == UO_Deref || UO->getOpcode() == UO_AddrOf ||
1605 UO->getOpcode() == UO_Plus) {
1606 CEE = UO->getSubExpr()->IgnoreParenImpCasts();
1607 continue;
1608 }
1609 }
1610 break;
1611 }
1612
1613 if (auto *DRE = dyn_cast<DeclRefExpr>(CEE))
1614 return DRE->getDecl();
1615 if (auto *ME = dyn_cast<MemberExpr>(CEE))
1616 return ME->getMemberDecl();
1617 if (auto *BE = dyn_cast<BlockExpr>(CEE))
1618 return BE->getBlockDecl();
1619
1620 return nullptr;
1621}
1622
1623/// If this is a call to a builtin, return the builtin ID. If not, return 0.
1625 const auto *FDecl = getDirectCallee();
1626 return FDecl ? FDecl->getBuiltinID() : 0;
1627}
1628
1630 if (unsigned BI = getBuiltinCallee())
1631 return Ctx.BuiltinInfo.isUnevaluated(BI);
1632 return false;
1633}
1634
1636 const Expr *Callee = getCallee();
1637 QualType CalleeType = Callee->getType();
1638 if (const auto *FnTypePtr = CalleeType->getAs<PointerType>()) {
1639 CalleeType = FnTypePtr->getPointeeType();
1640 } else if (const auto *BPT = CalleeType->getAs<BlockPointerType>()) {
1641 CalleeType = BPT->getPointeeType();
1642 } else if (CalleeType->isSpecificPlaceholderType(BuiltinType::BoundMember)) {
1643 if (isa<CXXPseudoDestructorExpr>(Callee->IgnoreParens()))
1644 return Ctx.VoidTy;
1645
1646 if (isa<UnresolvedMemberExpr>(Callee->IgnoreParens()))
1647 return Ctx.DependentTy;
1648
1649 // This should never be overloaded and so should never return null.
1650 CalleeType = Expr::findBoundMemberType(Callee);
1651 assert(!CalleeType.isNull());
1652 } else if (CalleeType->isRecordType()) {
1653 // If the Callee is a record type, then it is a not-yet-resolved
1654 // dependent call to the call operator of that type.
1655 return Ctx.DependentTy;
1656 } else if (CalleeType->isDependentType() ||
1657 CalleeType->isSpecificPlaceholderType(BuiltinType::Overload) ||
1658 CalleeType->isSpecificPlaceholderType(BuiltinType::BuiltinFn)) {
1659 // Dependent builtin calls keep their placeholder until instantiation.
1660 return Ctx.DependentTy;
1661 }
1662
1663 if (isTypeDependent() && !CalleeType->isFunctionType())
1664 return Ctx.DependentTy;
1665
1666 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
1667 return FnType->getReturnType();
1668}
1669
1670std::pair<const NamedDecl *, const WarnUnusedResultAttr *>
1671Expr::getUnusedResultAttrImpl(const Decl *Callee, QualType ReturnType) {
1672 // If the callee is marked nodiscard, return that attribute
1673 if (Callee != nullptr)
1674 if (const auto *A = Callee->getAttr<WarnUnusedResultAttr>())
1675 return {nullptr, A};
1676
1677 // If the return type is a struct, union, or enum that is marked nodiscard,
1678 // then return the return type attribute.
1679 if (const TagDecl *TD = ReturnType->getAsTagDecl())
1680 if (const auto *A = TD->getAttr<WarnUnusedResultAttr>())
1681 return {TD, A};
1682
1683 for (const auto *TD = ReturnType->getAs<TypedefType>(); TD;
1684 TD = TD->desugar()->getAs<TypedefType>())
1685 if (const auto *A = TD->getDecl()->getAttr<WarnUnusedResultAttr>())
1686 return {TD->getDecl(), A};
1687 return {nullptr, nullptr};
1688}
1689
1691 SourceLocation OperatorLoc,
1692 TypeSourceInfo *tsi,
1694 ArrayRef<Expr*> exprs,
1695 SourceLocation RParenLoc) {
1696 void *Mem = C.Allocate(
1697 totalSizeToAlloc<OffsetOfNode, Expr *>(comps.size(), exprs.size()));
1698
1699 return new (Mem) OffsetOfExpr(C, type, OperatorLoc, tsi, comps, exprs,
1700 RParenLoc);
1701}
1702
1704 unsigned numComps, unsigned numExprs) {
1705 void *Mem =
1706 C.Allocate(totalSizeToAlloc<OffsetOfNode, Expr *>(numComps, numExprs));
1707 return new (Mem) OffsetOfExpr(numComps, numExprs);
1708}
1709
1710OffsetOfExpr::OffsetOfExpr(const ASTContext &C, QualType type,
1711 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
1713 SourceLocation RParenLoc)
1714 : Expr(OffsetOfExprClass, type, VK_PRValue, OK_Ordinary),
1715 OperatorLoc(OperatorLoc), RParenLoc(RParenLoc), TSInfo(tsi),
1716 NumComps(comps.size()), NumExprs(exprs.size()) {
1717 for (unsigned i = 0; i != comps.size(); ++i)
1718 setComponent(i, comps[i]);
1719 for (unsigned i = 0; i != exprs.size(); ++i)
1720 setIndexExpr(i, exprs[i]);
1721
1723}
1724
1726 assert(getKind() == Field || getKind() == Identifier);
1727 if (getKind() == Field)
1728 return getField()->getIdentifier();
1729
1730 return reinterpret_cast<IdentifierInfo *> (Data & ~(uintptr_t)Mask);
1731}
1732
1734 UnaryExprOrTypeTrait ExprKind, Expr *E, QualType resultType,
1736 : Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_PRValue, OK_Ordinary),
1737 OpLoc(op), RParenLoc(rp) {
1738 assert(ExprKind <= UETT_Last && "invalid enum value!");
1739 UnaryExprOrTypeTraitExprBits.Kind = ExprKind;
1740 assert(static_cast<unsigned>(ExprKind) == UnaryExprOrTypeTraitExprBits.Kind &&
1741 "UnaryExprOrTypeTraitExprBits.Kind overflow!");
1742 UnaryExprOrTypeTraitExprBits.IsType = false;
1743 Argument.Ex = E;
1745}
1746
1747MemberExpr::MemberExpr(Expr *Base, bool IsArrow, SourceLocation OperatorLoc,
1748 NestedNameSpecifierLoc QualifierLoc,
1749 SourceLocation TemplateKWLoc, ValueDecl *MemberDecl,
1750 DeclAccessPair FoundDecl,
1751 const DeclarationNameInfo &NameInfo,
1752 const TemplateArgumentListInfo *TemplateArgs, QualType T,
1754 NonOdrUseReason NOUR)
1755 : Expr(MemberExprClass, T, VK, OK), Base(Base), MemberDecl(MemberDecl),
1756 MemberDNLoc(NameInfo.getInfo()), MemberLoc(NameInfo.getLoc()) {
1757 assert(!NameInfo.getName() ||
1758 MemberDecl->getDeclName() == NameInfo.getName());
1759 MemberExprBits.IsArrow = IsArrow;
1760 MemberExprBits.HasQualifier = QualifierLoc.hasQualifier();
1761 MemberExprBits.HasFoundDecl =
1762 FoundDecl.getDecl() != MemberDecl ||
1763 FoundDecl.getAccess() != MemberDecl->getAccess();
1764 MemberExprBits.HasTemplateKWAndArgsInfo =
1765 TemplateArgs || TemplateKWLoc.isValid();
1766 MemberExprBits.HadMultipleCandidates = false;
1767 MemberExprBits.NonOdrUseReason = NOUR;
1768 MemberExprBits.OperatorLoc = OperatorLoc;
1769
1770 if (hasQualifier())
1771 new (getTrailingObjects<NestedNameSpecifierLoc>())
1772 NestedNameSpecifierLoc(QualifierLoc);
1773 if (hasFoundDecl())
1774 *getTrailingObjects<DeclAccessPair>() = FoundDecl;
1775 if (TemplateArgs) {
1776 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
1777 TemplateKWLoc, *TemplateArgs,
1778 getTrailingObjects<TemplateArgumentLoc>());
1779 } else if (TemplateKWLoc.isValid()) {
1780 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
1781 TemplateKWLoc);
1782 }
1784}
1785
1787 const ASTContext &C, Expr *Base, bool IsArrow, SourceLocation OperatorLoc,
1788 NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,
1789 ValueDecl *MemberDecl, DeclAccessPair FoundDecl,
1790 DeclarationNameInfo NameInfo, const TemplateArgumentListInfo *TemplateArgs,
1792 bool HasQualifier = QualifierLoc.hasQualifier();
1793 bool HasFoundDecl = FoundDecl.getDecl() != MemberDecl ||
1794 FoundDecl.getAccess() != MemberDecl->getAccess();
1795 bool HasTemplateKWAndArgsInfo = TemplateArgs || TemplateKWLoc.isValid();
1796 std::size_t Size =
1797 totalSizeToAlloc<NestedNameSpecifierLoc, DeclAccessPair,
1799 HasQualifier, HasFoundDecl, HasTemplateKWAndArgsInfo,
1800 TemplateArgs ? TemplateArgs->size() : 0);
1801
1802 void *Mem = C.Allocate(Size, alignof(MemberExpr));
1803 return new (Mem) MemberExpr(Base, IsArrow, OperatorLoc, QualifierLoc,
1804 TemplateKWLoc, MemberDecl, FoundDecl, NameInfo,
1805 TemplateArgs, T, VK, OK, NOUR);
1806}
1807
1808MemberExpr *MemberExpr::CreateEmpty(const ASTContext &Context,
1809 bool HasQualifier, bool HasFoundDecl,
1810 bool HasTemplateKWAndArgsInfo,
1811 unsigned NumTemplateArgs) {
1812 assert((!NumTemplateArgs || HasTemplateKWAndArgsInfo) &&
1813 "template args but no template arg info?");
1814 std::size_t Size =
1815 totalSizeToAlloc<NestedNameSpecifierLoc, DeclAccessPair,
1817 HasQualifier, HasFoundDecl, HasTemplateKWAndArgsInfo,
1818 NumTemplateArgs);
1819 void *Mem = Context.Allocate(Size, alignof(MemberExpr));
1820 return new (Mem) MemberExpr(EmptyShell());
1821}
1822
1824 MemberDecl = NewD;
1825 if (getType()->isUndeducedType())
1826 setType(NewD->getType());
1828}
1829
1831 if (isImplicitAccess()) {
1832 if (hasQualifier())
1833 return getQualifierLoc().getBeginLoc();
1834 return MemberLoc;
1835 }
1836
1837 // FIXME: We don't want this to happen. Rather, we should be able to
1838 // detect all kinds of implicit accesses more cleanly.
1839 SourceLocation BaseStartLoc = getBase()->getBeginLoc();
1840 if (BaseStartLoc.isValid())
1841 return BaseStartLoc;
1842 return MemberLoc;
1843}
1847 EndLoc = getRAngleLoc();
1848 else if (EndLoc.isInvalid())
1849 EndLoc = getBase()->getEndLoc();
1850 return EndLoc;
1851}
1852
1853bool CastExpr::CastConsistency() const {
1854 switch (getCastKind()) {
1855 case CK_DerivedToBase:
1856 case CK_UncheckedDerivedToBase:
1857 case CK_DerivedToBaseMemberPointer:
1858 case CK_BaseToDerived:
1859 case CK_BaseToDerivedMemberPointer:
1860 assert(!path_empty() && "Cast kind should have a base path!");
1861 break;
1862
1863 case CK_CPointerToObjCPointerCast:
1864 assert(getType()->isObjCObjectPointerType());
1865 assert(getSubExpr()->getType()->isPointerType());
1866 goto CheckNoBasePath;
1867
1868 case CK_BlockPointerToObjCPointerCast:
1869 assert(getType()->isObjCObjectPointerType());
1870 assert(getSubExpr()->getType()->isBlockPointerType());
1871 goto CheckNoBasePath;
1872
1873 case CK_ReinterpretMemberPointer:
1874 assert(getType()->isMemberPointerType());
1875 assert(getSubExpr()->getType()->isMemberPointerType());
1876 goto CheckNoBasePath;
1877
1878 case CK_BitCast:
1879 // Arbitrary casts to C pointer types count as bitcasts.
1880 // Otherwise, we should only have block and ObjC pointer casts
1881 // here if they stay within the type kind.
1882 if (!getType()->isPointerType()) {
1883 assert(getType()->isObjCObjectPointerType() ==
1884 getSubExpr()->getType()->isObjCObjectPointerType());
1885 assert(getType()->isBlockPointerType() ==
1886 getSubExpr()->getType()->isBlockPointerType());
1887 }
1888 goto CheckNoBasePath;
1889
1890 case CK_AnyPointerToBlockPointerCast:
1891 assert(getType()->isBlockPointerType());
1892 assert(getSubExpr()->getType()->isAnyPointerType() &&
1893 !getSubExpr()->getType()->isBlockPointerType());
1894 goto CheckNoBasePath;
1895
1896 case CK_CopyAndAutoreleaseBlockObject:
1897 assert(getType()->isBlockPointerType());
1898 assert(getSubExpr()->getType()->isBlockPointerType());
1899 goto CheckNoBasePath;
1900
1901 case CK_FunctionToPointerDecay:
1902 assert(getType()->isPointerType());
1903 assert(getSubExpr()->getType()->isFunctionType());
1904 goto CheckNoBasePath;
1905
1906 case CK_AddressSpaceConversion: {
1907 auto Ty = getType();
1908 auto SETy = getSubExpr()->getType();
1910 if (isPRValue() && !Ty->isDependentType() && !SETy->isDependentType()) {
1911 Ty = Ty->getPointeeType();
1912 SETy = SETy->getPointeeType();
1913 }
1914 assert((Ty->isDependentType() || SETy->isDependentType()) ||
1915 (!Ty.isNull() && !SETy.isNull() &&
1916 Ty.getAddressSpace() != SETy.getAddressSpace()));
1917 goto CheckNoBasePath;
1918 }
1919 // These should not have an inheritance path.
1920 case CK_Dynamic:
1921 case CK_ToUnion:
1922 case CK_ArrayToPointerDecay:
1923 case CK_NullToMemberPointer:
1924 case CK_NullToPointer:
1925 case CK_ConstructorConversion:
1926 case CK_IntegralToPointer:
1927 case CK_PointerToIntegral:
1928 case CK_ToVoid:
1929 case CK_VectorSplat:
1930 case CK_IntegralCast:
1931 case CK_BooleanToSignedIntegral:
1932 case CK_IntegralToFloating:
1933 case CK_FloatingToIntegral:
1934 case CK_FloatingCast:
1935 case CK_ObjCObjectLValueCast:
1936 case CK_FloatingRealToComplex:
1937 case CK_FloatingComplexToReal:
1938 case CK_FloatingComplexCast:
1939 case CK_FloatingComplexToIntegralComplex:
1940 case CK_IntegralRealToComplex:
1941 case CK_IntegralComplexToReal:
1942 case CK_IntegralComplexCast:
1943 case CK_IntegralComplexToFloatingComplex:
1944 case CK_ARCProduceObject:
1945 case CK_ARCConsumeObject:
1946 case CK_ARCReclaimReturnedObject:
1947 case CK_ARCExtendBlockObject:
1948 case CK_ZeroToOCLOpaqueType:
1949 case CK_IntToOCLSampler:
1950 case CK_FloatingToFixedPoint:
1951 case CK_FixedPointToFloating:
1952 case CK_FixedPointCast:
1953 case CK_FixedPointToIntegral:
1954 case CK_IntegralToFixedPoint:
1955 case CK_MatrixCast:
1956 assert(!getType()->isBooleanType() && "unheralded conversion to bool");
1957 goto CheckNoBasePath;
1958
1959 case CK_Dependent:
1960 case CK_LValueToRValue:
1961 case CK_NoOp:
1962 case CK_AtomicToNonAtomic:
1963 case CK_NonAtomicToAtomic:
1964 case CK_PointerToBoolean:
1965 case CK_IntegralToBoolean:
1966 case CK_FloatingToBoolean:
1967 case CK_MemberPointerToBoolean:
1968 case CK_FloatingComplexToBoolean:
1969 case CK_IntegralComplexToBoolean:
1970 case CK_LValueBitCast: // -> bool&
1971 case CK_LValueToRValueBitCast:
1972 case CK_UserDefinedConversion: // operator bool()
1973 case CK_BuiltinFnToFnPtr:
1974 case CK_FixedPointToBoolean:
1975 case CK_HLSLArrayRValue:
1976 case CK_HLSLVectorTruncation:
1977 case CK_HLSLMatrixTruncation:
1978 case CK_HLSLElementwiseCast:
1979 case CK_HLSLAggregateSplatCast:
1980 CheckNoBasePath:
1981 assert(path_empty() && "Cast kind should not have a base path!");
1982 break;
1983 }
1984 return true;
1985}
1986
1988 switch (CK) {
1989#define CAST_OPERATION(Name) case CK_##Name: return #Name;
1990#include "clang/AST/OperationKinds.def"
1991 }
1992 llvm_unreachable("Unhandled cast kind!");
1993}
1994
1995namespace {
1996// Skip over implicit nodes produced as part of semantic analysis.
1997// Designed for use with IgnoreExprNodes.
1998static Expr *ignoreImplicitSemaNodes(Expr *E) {
1999 if (auto *Materialize = dyn_cast<MaterializeTemporaryExpr>(E))
2000 return Materialize->getSubExpr();
2001
2002 if (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
2003 return Binder->getSubExpr();
2004
2005 if (auto *Full = dyn_cast<FullExpr>(E))
2006 return Full->getSubExpr();
2007
2008 if (auto *CPLIE = dyn_cast<CXXParenListInitExpr>(E);
2009 CPLIE && CPLIE->getInitExprs().size() == 1)
2010 return CPLIE->getInitExprs()[0];
2011
2012 return E;
2013}
2014} // namespace
2015
2017 const Expr *SubExpr = nullptr;
2018
2019 for (const CastExpr *E = this; E; E = dyn_cast<ImplicitCastExpr>(SubExpr)) {
2020 SubExpr = IgnoreExprNodes(E->getSubExpr(), ignoreImplicitSemaNodes);
2021
2022 // Conversions by constructor and conversion functions have a
2023 // subexpression describing the call; strip it off.
2024 if (E->getCastKind() == CK_ConstructorConversion) {
2025 SubExpr = IgnoreExprNodes(cast<CXXConstructExpr>(SubExpr)->getArg(0),
2026 ignoreImplicitSemaNodes);
2027 } else if (E->getCastKind() == CK_UserDefinedConversion) {
2028 assert((isa<CallExpr, BlockExpr>(SubExpr)) &&
2029 "Unexpected SubExpr for CK_UserDefinedConversion.");
2030 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SubExpr))
2031 SubExpr = MCE->getImplicitObjectArgument();
2032 }
2033 }
2034
2035 return const_cast<Expr *>(SubExpr);
2036}
2037
2039 const Expr *SubExpr = nullptr;
2040
2041 for (const CastExpr *E = this; E; E = dyn_cast<ImplicitCastExpr>(SubExpr)) {
2042 SubExpr = IgnoreExprNodes(E->getSubExpr(), ignoreImplicitSemaNodes);
2043
2044 if (E->getCastKind() == CK_ConstructorConversion)
2045 return cast<CXXConstructExpr>(SubExpr)->getConstructor();
2046
2047 if (E->getCastKind() == CK_UserDefinedConversion) {
2048 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SubExpr))
2049 return MCE->getMethodDecl();
2050 }
2051 }
2052
2053 return nullptr;
2054}
2055
2056CXXBaseSpecifier **CastExpr::path_buffer() {
2057 switch (getStmtClass()) {
2058#define ABSTRACT_STMT(x)
2059#define CASTEXPR(Type, Base) \
2060 case Stmt::Type##Class: \
2061 return static_cast<Type *>(this) \
2062 ->getTrailingObjectsNonStrict<CXXBaseSpecifier *>();
2063#define STMT(Type, Base)
2064#include "clang/AST/StmtNodes.inc"
2065 default:
2066 llvm_unreachable("non-cast expressions not possible here");
2067 }
2068}
2069
2071 QualType opType) {
2072 return getTargetFieldForToUnionCast(unionType->castAsRecordDecl(), opType);
2073}
2074
2076 QualType OpType) {
2077 auto &Ctx = RD->getASTContext();
2078 RecordDecl::field_iterator Field, FieldEnd;
2079 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
2080 Field != FieldEnd; ++Field) {
2081 if (Ctx.hasSameUnqualifiedType(Field->getType(), OpType) &&
2082 !Field->isUnnamedBitField()) {
2083 return *Field;
2084 }
2085 }
2086 return nullptr;
2087}
2088
2090 assert(hasStoredFPFeatures());
2091 switch (getStmtClass()) {
2092 case ImplicitCastExprClass:
2093 return static_cast<ImplicitCastExpr *>(this)
2094 ->getTrailingObjects<FPOptionsOverride>();
2095 case CStyleCastExprClass:
2096 return static_cast<CStyleCastExpr *>(this)
2097 ->getTrailingObjects<FPOptionsOverride>();
2098 case CXXFunctionalCastExprClass:
2099 return static_cast<CXXFunctionalCastExpr *>(this)
2100 ->getTrailingObjects<FPOptionsOverride>();
2101 case CXXStaticCastExprClass:
2102 return static_cast<CXXStaticCastExpr *>(this)
2103 ->getTrailingObjects<FPOptionsOverride>();
2104 default:
2105 llvm_unreachable("Cast does not have FPFeatures");
2106 }
2107}
2108
2110 CastKind Kind, Expr *Operand,
2111 const CXXCastPath *BasePath,
2113 FPOptionsOverride FPO) {
2114 unsigned PathSize = (BasePath ? BasePath->size() : 0);
2115 void *Buffer =
2116 C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *, FPOptionsOverride>(
2117 PathSize, FPO.requiresTrailingStorage()));
2118 // Per C++ [conv.lval]p3, lvalue-to-rvalue conversions on class and
2119 // std::nullptr_t have special semantics not captured by CK_LValueToRValue.
2120 assert((Kind != CK_LValueToRValue ||
2121 !(T->isNullPtrType() ||
2122 (T->getAsCXXRecordDecl() && !C.getLangOpts().HLSL))) &&
2123 "invalid type for lvalue-to-rvalue conversion");
2124 ImplicitCastExpr *E =
2125 new (Buffer) ImplicitCastExpr(T, Kind, Operand, PathSize, FPO, VK);
2126 if (PathSize)
2127 llvm::uninitialized_copy(*BasePath,
2128 E->getTrailingObjects<CXXBaseSpecifier *>());
2129 return E;
2130}
2131
2133 unsigned PathSize,
2134 bool HasFPFeatures) {
2135 void *Buffer =
2136 C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *, FPOptionsOverride>(
2137 PathSize, HasFPFeatures));
2138 return new (Buffer) ImplicitCastExpr(EmptyShell(), PathSize, HasFPFeatures);
2139}
2140
2142 ExprValueKind VK, CastKind K, Expr *Op,
2143 const CXXCastPath *BasePath,
2145 TypeSourceInfo *WrittenTy,
2147 unsigned PathSize = (BasePath ? BasePath->size() : 0);
2148 void *Buffer =
2149 C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *, FPOptionsOverride>(
2150 PathSize, FPO.requiresTrailingStorage()));
2151 CStyleCastExpr *E =
2152 new (Buffer) CStyleCastExpr(T, VK, K, Op, PathSize, FPO, WrittenTy, L, R);
2153 if (PathSize)
2154 llvm::uninitialized_copy(*BasePath,
2155 E->getTrailingObjects<CXXBaseSpecifier *>());
2156 return E;
2157}
2158
2160 unsigned PathSize,
2161 bool HasFPFeatures) {
2162 void *Buffer =
2163 C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *, FPOptionsOverride>(
2164 PathSize, HasFPFeatures));
2165 return new (Buffer) CStyleCastExpr(EmptyShell(), PathSize, HasFPFeatures);
2166}
2167
2168/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
2169/// corresponds to, e.g. "<<=".
2171 switch (Op) {
2172#define BINARY_OPERATION(Name, Spelling) case BO_##Name: return Spelling;
2173#include "clang/AST/OperationKinds.def"
2174 }
2175 llvm_unreachable("Invalid OpCode!");
2176}
2177
2180 switch (OO) {
2181 default: llvm_unreachable("Not an overloadable binary operator");
2182 case OO_Plus: return BO_Add;
2183 case OO_Minus: return BO_Sub;
2184 case OO_Star: return BO_Mul;
2185 case OO_Slash: return BO_Div;
2186 case OO_Percent: return BO_Rem;
2187 case OO_Caret: return BO_Xor;
2188 case OO_Amp: return BO_And;
2189 case OO_Pipe: return BO_Or;
2190 case OO_Equal: return BO_Assign;
2191 case OO_Spaceship: return BO_Cmp;
2192 case OO_Less: return BO_LT;
2193 case OO_Greater: return BO_GT;
2194 case OO_PlusEqual: return BO_AddAssign;
2195 case OO_MinusEqual: return BO_SubAssign;
2196 case OO_StarEqual: return BO_MulAssign;
2197 case OO_SlashEqual: return BO_DivAssign;
2198 case OO_PercentEqual: return BO_RemAssign;
2199 case OO_CaretEqual: return BO_XorAssign;
2200 case OO_AmpEqual: return BO_AndAssign;
2201 case OO_PipeEqual: return BO_OrAssign;
2202 case OO_LessLess: return BO_Shl;
2203 case OO_GreaterGreater: return BO_Shr;
2204 case OO_LessLessEqual: return BO_ShlAssign;
2205 case OO_GreaterGreaterEqual: return BO_ShrAssign;
2206 case OO_EqualEqual: return BO_EQ;
2207 case OO_ExclaimEqual: return BO_NE;
2208 case OO_LessEqual: return BO_LE;
2209 case OO_GreaterEqual: return BO_GE;
2210 case OO_AmpAmp: return BO_LAnd;
2211 case OO_PipePipe: return BO_LOr;
2212 case OO_Comma: return BO_Comma;
2213 case OO_ArrowStar: return BO_PtrMemI;
2214 }
2215}
2216
2218 static const OverloadedOperatorKind OverOps[] = {
2219 /* .* Cannot be overloaded */OO_None, OO_ArrowStar,
2220 OO_Star, OO_Slash, OO_Percent,
2221 OO_Plus, OO_Minus,
2222 OO_LessLess, OO_GreaterGreater,
2223 OO_Spaceship,
2224 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
2225 OO_EqualEqual, OO_ExclaimEqual,
2226 OO_Amp,
2227 OO_Caret,
2228 OO_Pipe,
2229 OO_AmpAmp,
2230 OO_PipePipe,
2231 OO_Equal, OO_StarEqual,
2232 OO_SlashEqual, OO_PercentEqual,
2233 OO_PlusEqual, OO_MinusEqual,
2234 OO_LessLessEqual, OO_GreaterGreaterEqual,
2235 OO_AmpEqual, OO_CaretEqual,
2236 OO_PipeEqual,
2237 OO_Comma
2238 };
2239 return OverOps[Opc];
2240}
2241
2243 Opcode Opc,
2244 const Expr *LHS,
2245 const Expr *RHS) {
2246 if (Opc != BO_Add)
2247 return false;
2248
2249 // Check that we have one pointer and one integer operand.
2250 const Expr *PExp;
2251 if (LHS->getType()->isPointerType()) {
2252 if (!RHS->getType()->isIntegerType())
2253 return false;
2254 PExp = LHS;
2255 } else if (RHS->getType()->isPointerType()) {
2256 if (!LHS->getType()->isIntegerType())
2257 return false;
2258 PExp = RHS;
2259 } else {
2260 return false;
2261 }
2262
2263 // Workaround for old glibc's __PTR_ALIGN macro
2264 if (auto *Select =
2265 dyn_cast<ConditionalOperator>(PExp->IgnoreParenNoopCasts(Ctx))) {
2266 // If the condition can be constant evaluated, we check the selected arm.
2267 bool EvalResult;
2268 if (!Select->getCond()->EvaluateAsBooleanCondition(EvalResult, Ctx))
2269 return false;
2270 PExp = EvalResult ? Select->getTrueExpr() : Select->getFalseExpr();
2271 }
2272
2273 // Check that the pointer is a nullptr.
2274 if (!PExp->IgnoreParenCasts()
2276 return false;
2277
2278 // Check that the pointee type is char-sized.
2279 const PointerType *PTy = PExp->getType()->getAs<PointerType>();
2280 if (!PTy || !PTy->getPointeeType()->isCharType())
2281 return false;
2282
2283 return true;
2284}
2285
2287 QualType ResultTy, SourceLocation BLoc,
2288 SourceLocation RParenLoc,
2289 DeclContext *ParentContext)
2290 : Expr(SourceLocExprClass, ResultTy, VK_PRValue, OK_Ordinary),
2291 BuiltinLoc(BLoc), RParenLoc(RParenLoc), ParentContext(ParentContext) {
2292 SourceLocExprBits.Kind = llvm::to_underlying(Kind);
2293 // In dependent contexts, function names may change.
2294 setDependence(MayBeDependent(Kind) && ParentContext->isDependentContext()
2295 ? ExprDependence::ValueInstantiation
2296 : ExprDependence::None);
2297}
2298
2300 switch (getIdentKind()) {
2302 return "__builtin_FILE";
2304 return "__builtin_FILE_NAME";
2306 return "__builtin_FUNCTION";
2308 return "__builtin_FUNCSIG";
2310 return "__builtin_LINE";
2312 return "__builtin_COLUMN";
2314 return "__builtin_source_location";
2315 }
2316 llvm_unreachable("unexpected IdentKind!");
2317}
2318
2320 const Expr *DefaultExpr) const {
2321 SourceLocation Loc;
2322 const DeclContext *Context;
2323
2324 if (const auto *DIE = dyn_cast_if_present<CXXDefaultInitExpr>(DefaultExpr)) {
2325 Loc = DIE->getUsedLocation();
2326 Context = DIE->getUsedContext();
2327 } else if (const auto *DAE =
2328 dyn_cast_if_present<CXXDefaultArgExpr>(DefaultExpr)) {
2329 Loc = DAE->getUsedLocation();
2330 Context = DAE->getUsedContext();
2331 } else {
2332 Loc = getLocation();
2333 Context = getParentContext();
2334 }
2335
2336 // If we are currently parsing a lambda declarator, we might not have a fully
2337 // formed call operator declaration yet, and we could not form a function name
2338 // for it. Because we do not have access to Sema/function scopes here, we
2339 // detect this case by relying on the fact such method doesn't yet have a
2340 // type.
2341 if (const auto *D = dyn_cast<CXXMethodDecl>(Context);
2342 D && D->getFunctionTypeLoc().isNull() && isLambdaCallOperator(D))
2343 Context = D->getParent()->getParent();
2344
2347
2348 auto MakeStringLiteral = [&](StringRef Tmp) {
2349 using LValuePathEntry = APValue::LValuePathEntry;
2351 // Decay the string to a pointer to the first character.
2352 LValuePathEntry Path[1] = {LValuePathEntry::ArrayIndex(0)};
2353 return APValue(Res, CharUnits::Zero(), Path, /*OnePastTheEnd=*/false);
2354 };
2355
2356 switch (getIdentKind()) {
2358 // __builtin_FILE_NAME() is a Clang-specific extension that expands to the
2359 // the last part of __builtin_FILE().
2362 FileName, PLoc, Ctx.getLangOpts(), Ctx.getTargetInfo());
2363 return MakeStringLiteral(FileName);
2364 }
2366 SmallString<256> Path(PLoc.getFilename());
2368 Ctx.getTargetInfo());
2369 return MakeStringLiteral(Path);
2370 }
2373 const auto *CurDecl = dyn_cast<Decl>(Context);
2374 const auto Kind = getIdentKind() == SourceLocIdentKind::Function
2377 return MakeStringLiteral(
2378 CurDecl ? PredefinedExpr::ComputeName(Kind, CurDecl) : std::string(""));
2379 }
2381 return APValue(Ctx.MakeIntValue(PLoc.getLine(), Ctx.UnsignedIntTy));
2383 return APValue(Ctx.MakeIntValue(PLoc.getColumn(), Ctx.UnsignedIntTy));
2385 // Fill in a std::source_location::__impl structure, by creating an
2386 // artificial file-scoped CompoundLiteralExpr, and returning a pointer to
2387 // that.
2388 const CXXRecordDecl *ImplDecl = getType()->getPointeeCXXRecordDecl();
2389 assert(ImplDecl);
2390
2391 // Construct an APValue for the __impl struct, and get or create a Decl
2392 // corresponding to that. Note that we've already verified that the shape of
2393 // the ImplDecl type is as expected.
2394
2396 for (const FieldDecl *F : ImplDecl->fields()) {
2397 StringRef Name = F->getName();
2398 if (Name == "_M_file_name") {
2399 SmallString<256> Path(PLoc.getFilename());
2401 Ctx.getTargetInfo());
2402 Value.getStructField(F->getFieldIndex()) = MakeStringLiteral(Path);
2403 } else if (Name == "_M_function_name") {
2404 // Note: this emits the PrettyFunction name -- different than what
2405 // __builtin_FUNCTION() above returns!
2406 const auto *CurDecl = dyn_cast<Decl>(Context);
2407 Value.getStructField(F->getFieldIndex()) = MakeStringLiteral(
2408 CurDecl && !isa<TranslationUnitDecl>(CurDecl)
2409 ? StringRef(PredefinedExpr::ComputeName(
2411 : "");
2412 } else if (Name == "_M_line") {
2413 llvm::APSInt IntVal = Ctx.MakeIntValue(PLoc.getLine(), F->getType());
2414 Value.getStructField(F->getFieldIndex()) = APValue(IntVal);
2415 } else if (Name == "_M_column") {
2416 llvm::APSInt IntVal = Ctx.MakeIntValue(PLoc.getColumn(), F->getType());
2417 Value.getStructField(F->getFieldIndex()) = APValue(IntVal);
2418 }
2419 }
2420
2423
2425 false);
2426 }
2427 }
2428 llvm_unreachable("unhandled case");
2429}
2430
2432 EmbedDataStorage *Data, unsigned Begin,
2433 unsigned NumOfElements)
2434 : Expr(EmbedExprClass, Ctx.IntTy, VK_PRValue, OK_Ordinary),
2435 EmbedKeywordLoc(Loc), Ctx(&Ctx), Data(Data), Begin(Begin),
2436 NumOfElements(NumOfElements) {
2437 setDependence(ExprDependence::None);
2438 FakeChildNode = IntegerLiteral::Create(
2439 Ctx, llvm::APInt::getZero(Ctx.getTypeSize(getType())), getType(), Loc);
2440 assert(getType()->isSignedIntegerType() && "IntTy should be signed");
2441}
2442
2444 ArrayRef<Expr *> initExprs, SourceLocation rbraceloc,
2445 bool isExplicit)
2446 : Expr(InitListExprClass, QualType(), VK_PRValue, OK_Ordinary),
2447 InitExprs(C, initExprs.size()), LBraceLoc(lbraceloc),
2448 RBraceLoc(rbraceloc), AltForm(nullptr, true) {
2450 InitExprs.insert(C, InitExprs.end(), initExprs.begin(), initExprs.end());
2451 InitListExprBits.IsExplicit = isExplicit;
2452
2454}
2455
2456void InitListExpr::reserveInits(const ASTContext &C, unsigned NumInits) {
2457 if (NumInits > InitExprs.size())
2458 InitExprs.reserve(C, NumInits);
2459}
2460
2461void InitListExpr::resizeInits(const ASTContext &C, unsigned NumInits) {
2462 InitExprs.resize(C, NumInits, nullptr);
2463}
2464
2466 if (Init >= InitExprs.size()) {
2467 InitExprs.insert(C, InitExprs.end(), Init - InitExprs.size() + 1, nullptr);
2468 setInit(Init, expr);
2469 return nullptr;
2470 }
2471
2472 Expr *Result = cast_or_null<Expr>(InitExprs[Init]);
2473 setInit(Init, expr);
2474 return Result;
2475}
2476
2478 assert(!hasArrayFiller() && "Filler already set!");
2479 ArrayFillerOrUnionFieldInit = filler;
2480 // Fill out any "holes" in the array due to designated initializers.
2481 Expr **inits = getInits();
2482 for (unsigned i = 0, e = getNumInits(); i != e; ++i)
2483 if (inits[i] == nullptr)
2484 inits[i] = filler;
2485}
2486
2488 if (getNumInits() != 1)
2489 return false;
2490 const ArrayType *AT = getType()->getAsArrayTypeUnsafe();
2491 if (!AT || !AT->getElementType()->isIntegerType())
2492 return false;
2493 // It is possible for getInit() to return null.
2494 const Expr *Init = getInit(0);
2495 if (!Init)
2496 return false;
2497 Init = Init->IgnoreParenImpCasts();
2499}
2500
2502 assert(isSemanticForm() && "syntactic form never semantically transparent");
2503
2504 // A glvalue InitListExpr is always just sugar.
2505 if (isGLValue()) {
2506 assert(getNumInits() == 1 && "multiple inits in glvalue init list");
2507 return true;
2508 }
2509
2510 // Otherwise, we're sugar if and only if we have exactly one initializer that
2511 // is of the same type.
2512 if (getNumInits() != 1 || !getInit(0))
2513 return false;
2514
2515 // Don't confuse aggregate initialization of a struct X { X &x; }; with a
2516 // transparent struct copy.
2517 if (!getInit(0)->isPRValue() && getType()->isRecordType())
2518 return false;
2519
2520 return getType().getCanonicalType() ==
2522}
2523
2525 assert(isSyntacticForm() && "only test syntactic form as zero initializer");
2526
2527 if (LangOpts.CPlusPlus || getNumInits() != 1 || !getInit(0)) {
2528 return false;
2529 }
2530
2531 const IntegerLiteral *Lit = dyn_cast<IntegerLiteral>(getInit(0)->IgnoreImplicit());
2532 return Lit && Lit->getValue() == 0;
2533}
2534
2536 if (InitListExpr *SyntacticForm = getSyntacticForm())
2537 return SyntacticForm->getBeginLoc();
2538 SourceLocation Beg = LBraceLoc;
2539 if (Beg.isInvalid()) {
2540 // Find the first non-null initializer.
2541 for (InitExprsTy::const_iterator I = InitExprs.begin(),
2542 E = InitExprs.end();
2543 I != E; ++I) {
2544 if (Stmt *S = *I) {
2545 Beg = S->getBeginLoc();
2546 break;
2547 }
2548 }
2549 }
2550 return Beg;
2551}
2552
2554 if (InitListExpr *SyntacticForm = getSyntacticForm())
2555 return SyntacticForm->getEndLoc();
2556 SourceLocation End = RBraceLoc;
2557 if (End.isInvalid()) {
2558 // Find the first non-null initializer from the end.
2559 for (Stmt *S : llvm::reverse(InitExprs)) {
2560 if (S) {
2561 End = S->getEndLoc();
2562 break;
2563 }
2564 }
2565 }
2566 return End;
2567}
2568
2569/// getFunctionType - Return the underlying function type for this block.
2570///
2572 // The block pointer is never sugared, but the function type might be.
2574 ->getPointeeType()->castAs<FunctionProtoType>();
2575}
2576
2578 return TheBlock->getCaretLocation();
2579}
2580const Stmt *BlockExpr::getBody() const {
2581 return TheBlock->getBody();
2582}
2584 return TheBlock->getBody();
2585}
2586
2587
2588//===----------------------------------------------------------------------===//
2589// Generic Expression Routines
2590//===----------------------------------------------------------------------===//
2591
2592/// Helper to determine wether \c E is a CXXConstructExpr constructing
2593/// a DecompositionDecl. Used to skip Clang-generated calls to std::get
2594/// for structured bindings.
2595static bool IsDecompositionDeclRefExpr(const Expr *E) {
2596 const auto *Unwrapped = E->IgnoreUnlessSpelledInSource();
2597 const auto *Ref = dyn_cast<DeclRefExpr>(Unwrapped);
2598 if (!Ref)
2599 return false;
2600
2601 return isa_and_nonnull<DecompositionDecl>(Ref->getDecl());
2602}
2603
2605 // In C++11, discarded-value expressions of a certain form are special,
2606 // according to [expr]p10:
2607 // The lvalue-to-rvalue conversion (4.1) is applied only if the
2608 // expression is a glvalue of volatile-qualified type and it has
2609 // one of the following forms:
2610 if (!isGLValue() || !getType().isVolatileQualified())
2611 return false;
2612
2613 const Expr *E = IgnoreParens();
2614
2615 // - id-expression (5.1.1),
2616 if (isa<DeclRefExpr>(E))
2617 return true;
2618
2619 // - subscripting (5.2.1),
2621 return true;
2622
2623 // - class member access (5.2.5),
2624 if (isa<MemberExpr>(E))
2625 return true;
2626
2627 // - indirection (5.3.1),
2628 if (auto *UO = dyn_cast<UnaryOperator>(E))
2629 if (UO->getOpcode() == UO_Deref)
2630 return true;
2631
2632 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
2633 // - pointer-to-member operation (5.5),
2634 if (BO->isPtrMemOp())
2635 return true;
2636
2637 // - comma expression (5.18) where the right operand is one of the above.
2638 if (BO->getOpcode() == BO_Comma)
2639 return BO->getRHS()->isReadIfDiscardedInCPlusPlus11();
2640 }
2641
2642 // - conditional expression (5.16) where both the second and the third
2643 // operands are one of the above, or
2644 if (auto *CO = dyn_cast<ConditionalOperator>(E))
2645 return CO->getTrueExpr()->isReadIfDiscardedInCPlusPlus11() &&
2646 CO->getFalseExpr()->isReadIfDiscardedInCPlusPlus11();
2647 // The related edge case of "*x ?: *x".
2648 if (auto *BCO =
2649 dyn_cast<BinaryConditionalOperator>(E)) {
2650 if (auto *OVE = dyn_cast<OpaqueValueExpr>(BCO->getTrueExpr()))
2651 return OVE->getSourceExpr()->isReadIfDiscardedInCPlusPlus11() &&
2652 BCO->getFalseExpr()->isReadIfDiscardedInCPlusPlus11();
2653 }
2654
2655 // Objective-C++ extensions to the rule.
2656 if (isa<ObjCIvarRefExpr>(E))
2657 return true;
2658 if (const auto *POE = dyn_cast<PseudoObjectExpr>(E)) {
2659 if (isa<ObjCPropertyRefExpr, ObjCSubscriptRefExpr>(POE->getSyntacticForm()))
2660 return true;
2661 }
2662
2663 return false;
2664}
2665
2666/// isUnusedResultAWarning - Return true if this immediate expression should
2667/// be warned about if the result is unused. If so, fill in Loc and Ranges
2668/// with location to warn on and the source range[s] to report with the
2669/// warning.
2671 SourceRange &R1, SourceRange &R2,
2672 ASTContext &Ctx) const {
2673 // Don't warn if the expr is type dependent. The type could end up
2674 // instantiating to void.
2675 if (isTypeDependent())
2676 return false;
2677
2678 switch (getStmtClass()) {
2679 default:
2680 if (getType()->isVoidType())
2681 return false;
2682 WarnE = this;
2683 Loc = getExprLoc();
2684 R1 = getSourceRange();
2685 return true;
2686 case ParenExprClass:
2687 return cast<ParenExpr>(this)->getSubExpr()->
2688 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2689 case GenericSelectionExprClass:
2690 return cast<GenericSelectionExpr>(this)->getResultExpr()->
2691 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2692 case CoawaitExprClass:
2693 case CoyieldExprClass:
2694 return cast<CoroutineSuspendExpr>(this)->getResumeExpr()->
2695 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2696 case ChooseExprClass:
2697 return cast<ChooseExpr>(this)->getChosenSubExpr()->
2698 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2699 case UnaryOperatorClass: {
2700 const UnaryOperator *UO = cast<UnaryOperator>(this);
2701
2702 switch (UO->getOpcode()) {
2703 case UO_Plus:
2704 case UO_Minus:
2705 case UO_AddrOf:
2706 case UO_Not:
2707 case UO_LNot:
2708 case UO_Deref:
2709 break;
2710 case UO_Coawait:
2711 // This is just the 'operator co_await' call inside the guts of a
2712 // dependent co_await call.
2713 case UO_PostInc:
2714 case UO_PostDec:
2715 case UO_PreInc:
2716 case UO_PreDec: // ++/--
2717 return false; // Not a warning.
2718 case UO_Real:
2719 case UO_Imag:
2720 // accessing a piece of a volatile complex is a side-effect.
2721 if (Ctx.getCanonicalType(UO->getSubExpr()->getType())
2723 return false;
2724 break;
2725 case UO_Extension:
2726 return UO->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2727 }
2728 WarnE = this;
2729 Loc = UO->getOperatorLoc();
2730 R1 = UO->getSubExpr()->getSourceRange();
2731 return true;
2732 }
2733 case BinaryOperatorClass: {
2734 const BinaryOperator *BO = cast<BinaryOperator>(this);
2735 switch (BO->getOpcode()) {
2736 default:
2737 break;
2738 // Consider the RHS of comma for side effects. LHS was checked by
2739 // Sema::CheckCommaOperands.
2740 case BO_Comma:
2741 // ((foo = <blah>), 0) is an idiom for hiding the result (and
2742 // lvalue-ness) of an assignment written in a macro.
2743 if (IntegerLiteral *IE =
2744 dyn_cast<IntegerLiteral>(BO->getRHS()->IgnoreParens()))
2745 if (IE->getValue() == 0)
2746 return false;
2747 return BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2748 // Consider '||', '&&' to have side effects if the LHS or RHS does.
2749 case BO_LAnd:
2750 case BO_LOr:
2751 if (!BO->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx) ||
2752 !BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx))
2753 return false;
2754 break;
2755 }
2756 if (BO->isAssignmentOp())
2757 return false;
2758 WarnE = this;
2759 Loc = BO->getOperatorLoc();
2760 R1 = BO->getLHS()->getSourceRange();
2761 R2 = BO->getRHS()->getSourceRange();
2762 return true;
2763 }
2764 case CompoundAssignOperatorClass:
2765 case VAArgExprClass:
2766 case AtomicExprClass:
2767 return false;
2768
2769 case ConditionalOperatorClass: {
2770 // If only one of the LHS or RHS is a warning, the operator might
2771 // be being used for control flow. Only warn if both the LHS and
2772 // RHS are warnings.
2773 const auto *Exp = cast<ConditionalOperator>(this);
2774 return Exp->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx) &&
2775 Exp->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2776 }
2777 case BinaryConditionalOperatorClass: {
2778 const auto *Exp = cast<BinaryConditionalOperator>(this);
2779 return Exp->getFalseExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2780 }
2781
2782 case MemberExprClass:
2783 WarnE = this;
2784 Loc = cast<MemberExpr>(this)->getMemberLoc();
2785 R1 = SourceRange(Loc, Loc);
2786 R2 = cast<MemberExpr>(this)->getBase()->getSourceRange();
2787 return true;
2788
2789 case ArraySubscriptExprClass:
2790 WarnE = this;
2791 Loc = cast<ArraySubscriptExpr>(this)->getRBracketLoc();
2792 R1 = cast<ArraySubscriptExpr>(this)->getLHS()->getSourceRange();
2793 R2 = cast<ArraySubscriptExpr>(this)->getRHS()->getSourceRange();
2794 return true;
2795
2796 case CXXOperatorCallExprClass: {
2797 // Warn about operator ==,!=,<,>,<=, and >= even when user-defined operator
2798 // overloads as there is no reasonable way to define these such that they
2799 // have non-trivial, desirable side-effects. See the -Wunused-comparison
2800 // warning: operators == and != are commonly typo'ed, and so warning on them
2801 // provides additional value as well. If this list is updated,
2802 // DiagnoseUnusedComparison should be as well.
2804 switch (Op->getOperator()) {
2805 default:
2806 break;
2807 case OO_EqualEqual:
2808 case OO_ExclaimEqual:
2809 case OO_Less:
2810 case OO_Greater:
2811 case OO_GreaterEqual:
2812 case OO_LessEqual:
2813 if (Op->getCallReturnType(Ctx)->isReferenceType() ||
2814 Op->getCallReturnType(Ctx)->isVoidType())
2815 break;
2816 WarnE = this;
2817 Loc = Op->getOperatorLoc();
2818 R1 = Op->getSourceRange();
2819 return true;
2820 }
2821
2822 // Fallthrough for generic call handling.
2823 [[fallthrough]];
2824 }
2825 case CallExprClass:
2826 case CXXMemberCallExprClass:
2827 case UserDefinedLiteralClass: {
2828 // If this is a direct call, get the callee.
2829 const CallExpr *CE = cast<CallExpr>(this);
2830 // If the callee has attribute pure, const, or warn_unused_result, warn
2831 // about it. void foo() { strlen("bar"); } should warn.
2832 // Note: If new cases are added here, DiagnoseUnusedExprResult should be
2833 // updated to match for QoI.
2834 const Decl *FD = CE->getCalleeDecl();
2835 bool PureOrConst =
2836 FD && (FD->hasAttr<PureAttr>() || FD->hasAttr<ConstAttr>());
2837 if (CE->hasUnusedResultAttr(Ctx) || PureOrConst) {
2838 WarnE = this;
2839 Loc = getBeginLoc();
2840 R1 = getSourceRange();
2841
2842 if (unsigned NumArgs = CE->getNumArgs())
2843 R2 = SourceRange(CE->getArg(0)->getBeginLoc(),
2844 CE->getArg(NumArgs - 1)->getEndLoc());
2845 return true;
2846 }
2847 return false;
2848 }
2849
2850 // If we don't know precisely what we're looking at, let's not warn.
2851 case UnresolvedLookupExprClass:
2852 case CXXUnresolvedConstructExprClass:
2853 case RecoveryExprClass:
2854 return false;
2855
2856 case CXXTemporaryObjectExprClass:
2857 case CXXConstructExprClass: {
2858 const auto *CE = cast<CXXConstructExpr>(this);
2860
2861 if ((Type && Type->hasAttr<WarnUnusedAttr>()) ||
2862 CE->hasUnusedResultAttr(Ctx)) {
2863 WarnE = this;
2864 Loc = getBeginLoc();
2865 R1 = getSourceRange();
2866
2867 if (unsigned NumArgs = CE->getNumArgs())
2868 R2 = SourceRange(CE->getArg(0)->getBeginLoc(),
2869 CE->getArg(NumArgs - 1)->getEndLoc());
2870 return true;
2871 }
2872 return false;
2873 }
2874
2875 case ObjCMessageExprClass: {
2876 const ObjCMessageExpr *ME = cast<ObjCMessageExpr>(this);
2877 if (Ctx.getLangOpts().ObjCAutoRefCount &&
2878 ME->isInstanceMessage() &&
2879 !ME->getType()->isVoidType() &&
2880 ME->getMethodFamily() == OMF_init) {
2881 WarnE = this;
2882 Loc = getExprLoc();
2883 R1 = ME->getSourceRange();
2884 return true;
2885 }
2886
2887 if (ME->hasUnusedResultAttr(Ctx)) {
2888 WarnE = this;
2889 Loc = getExprLoc();
2890 return true;
2891 }
2892
2893 return false;
2894 }
2895
2896 case ObjCPropertyRefExprClass:
2897 case ObjCSubscriptRefExprClass:
2898 WarnE = this;
2899 Loc = getExprLoc();
2900 R1 = getSourceRange();
2901 return true;
2902
2903 case PseudoObjectExprClass: {
2904 const auto *POE = cast<PseudoObjectExpr>(this);
2905
2906 // For some syntactic forms, we should always warn.
2908 POE->getSyntacticForm())) {
2909 WarnE = this;
2910 Loc = getExprLoc();
2911 R1 = getSourceRange();
2912 return true;
2913 }
2914
2915 // For others, we should never warn.
2916 if (auto *BO = dyn_cast<BinaryOperator>(POE->getSyntacticForm()))
2917 if (BO->isAssignmentOp())
2918 return false;
2919 if (auto *UO = dyn_cast<UnaryOperator>(POE->getSyntacticForm()))
2920 if (UO->isIncrementDecrementOp())
2921 return false;
2922
2923 // Otherwise, warn if the result expression would warn.
2924 const Expr *Result = POE->getResultExpr();
2925 return Result && Result->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2926 }
2927
2928 case StmtExprClass: {
2929 // Statement exprs don't logically have side effects themselves, but are
2930 // sometimes used in macros in ways that give them a type that is unused.
2931 // For example ({ blah; foo(); }) will end up with a type if foo has a type.
2932 // however, if the result of the stmt expr is dead, we don't want to emit a
2933 // warning.
2934 const CompoundStmt *CS = cast<StmtExpr>(this)->getSubStmt();
2935 if (!CS->body_empty()) {
2936 if (const Expr *E = dyn_cast<Expr>(CS->body_back()))
2937 return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2938 if (const LabelStmt *Label = dyn_cast<LabelStmt>(CS->body_back()))
2939 if (const Expr *E = dyn_cast<Expr>(Label->getSubStmt()))
2940 return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2941 }
2942
2943 if (getType()->isVoidType())
2944 return false;
2945 WarnE = this;
2946 Loc = cast<StmtExpr>(this)->getLParenLoc();
2947 R1 = getSourceRange();
2948 return true;
2949 }
2950 case CXXFunctionalCastExprClass:
2951 case CStyleCastExprClass: {
2952 // Ignore an explicit cast to void, except in C++98 if the operand is a
2953 // volatile glvalue for which we would trigger an implicit read in any
2954 // other language mode. (Such an implicit read always happens as part of
2955 // the lvalue conversion in C, and happens in C++ for expressions of all
2956 // forms where it seems likely the user intended to trigger a volatile
2957 // load.)
2958 const CastExpr *CE = cast<CastExpr>(this);
2959 const Expr *SubE = CE->getSubExpr()->IgnoreParens();
2960 if (CE->getCastKind() == CK_ToVoid) {
2961 if (Ctx.getLangOpts().CPlusPlus && !Ctx.getLangOpts().CPlusPlus11 &&
2963 // Suppress the "unused value" warning for idiomatic usage of
2964 // '(void)var;' used to suppress "unused variable" warnings.
2965 if (auto *DRE = dyn_cast<DeclRefExpr>(SubE))
2966 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
2967 if (!VD->isExternallyVisible())
2968 return false;
2969
2970 // The lvalue-to-rvalue conversion would have no effect for an array.
2971 // It's implausible that the programmer expected this to result in a
2972 // volatile array load, so don't warn.
2973 if (SubE->getType()->isArrayType())
2974 return false;
2975
2976 return SubE->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2977 }
2978 return false;
2979 }
2980
2981 // If this is a cast to a constructor conversion, check the operand.
2982 // Otherwise, the result of the cast is unused.
2983 if (CE->getCastKind() == CK_ConstructorConversion)
2984 return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2985 if (CE->getCastKind() == CK_Dependent)
2986 return false;
2987
2988 WarnE = this;
2989 if (const CXXFunctionalCastExpr *CXXCE =
2990 dyn_cast<CXXFunctionalCastExpr>(this)) {
2991 Loc = CXXCE->getBeginLoc();
2992 R1 = CXXCE->getSubExpr()->getSourceRange();
2993 } else {
2994 const CStyleCastExpr *CStyleCE = cast<CStyleCastExpr>(this);
2995 Loc = CStyleCE->getLParenLoc();
2996 R1 = CStyleCE->getSubExpr()->getSourceRange();
2997 }
2998 return true;
2999 }
3000 case ImplicitCastExprClass: {
3001 const CastExpr *ICE = cast<ImplicitCastExpr>(this);
3002
3003 // lvalue-to-rvalue conversion on a volatile lvalue is a side-effect.
3004 if (ICE->getCastKind() == CK_LValueToRValue &&
3006 return false;
3007
3008 return ICE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
3009 }
3010 case CXXDefaultArgExprClass:
3011 return (cast<CXXDefaultArgExpr>(this)
3012 ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
3013 case CXXDefaultInitExprClass:
3014 return (cast<CXXDefaultInitExpr>(this)
3015 ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
3016
3017 case CXXNewExprClass:
3018 // FIXME: In theory, there might be new expressions that don't have side
3019 // effects (e.g. a placement new with an uninitialized POD).
3020 case CXXDeleteExprClass:
3021 return false;
3022 case MaterializeTemporaryExprClass:
3024 ->getSubExpr()
3025 ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
3026 case CXXBindTemporaryExprClass:
3027 return cast<CXXBindTemporaryExpr>(this)->getSubExpr()
3028 ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
3029 case ExprWithCleanupsClass:
3030 return cast<ExprWithCleanups>(this)->getSubExpr()
3031 ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
3032 case OpaqueValueExprClass:
3033 return cast<OpaqueValueExpr>(this)->getSourceExpr()->isUnusedResultAWarning(
3034 WarnE, Loc, R1, R2, Ctx);
3035 }
3036}
3037
3038/// isOBJCGCCandidate - Check if an expression is objc gc'able.
3039/// returns true, if it is; false otherwise.
3041 const Expr *E = IgnoreParens();
3042 switch (E->getStmtClass()) {
3043 default:
3044 return false;
3045 case ObjCIvarRefExprClass:
3046 return true;
3047 case Expr::UnaryOperatorClass:
3048 return cast<UnaryOperator>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
3049 case ImplicitCastExprClass:
3050 return cast<ImplicitCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
3051 case MaterializeTemporaryExprClass:
3052 return cast<MaterializeTemporaryExpr>(E)->getSubExpr()->isOBJCGCCandidate(
3053 Ctx);
3054 case CStyleCastExprClass:
3055 return cast<CStyleCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
3056 case DeclRefExprClass: {
3057 const Decl *D = cast<DeclRefExpr>(E)->getDecl();
3058
3059 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
3060 if (VD->hasGlobalStorage())
3061 return true;
3062 QualType T = VD->getType();
3063 // dereferencing to a pointer is always a gc'able candidate,
3064 // unless it is __weak.
3065 return T->isPointerType() &&
3067 }
3068 return false;
3069 }
3070 case MemberExprClass: {
3071 const MemberExpr *M = cast<MemberExpr>(E);
3072 return M->getBase()->isOBJCGCCandidate(Ctx);
3073 }
3074 case ArraySubscriptExprClass:
3075 return cast<ArraySubscriptExpr>(E)->getBase()->isOBJCGCCandidate(Ctx);
3076 }
3077}
3078
3080 if (isTypeDependent())
3081 return false;
3083}
3084
3086 assert(expr->hasPlaceholderType(BuiltinType::BoundMember));
3087
3088 // Bound member expressions are always one of these possibilities:
3089 // x->m x.m x->*y x.*y
3090 // (possibly parenthesized)
3091
3092 expr = expr->IgnoreParens();
3093 if (const MemberExpr *mem = dyn_cast<MemberExpr>(expr)) {
3094 assert(isa<CXXMethodDecl>(mem->getMemberDecl()));
3095 return mem->getMemberDecl()->getType();
3096 }
3097
3098 if (const BinaryOperator *op = dyn_cast<BinaryOperator>(expr)) {
3099 QualType type = op->getRHS()->getType()->castAs<MemberPointerType>()
3100 ->getPointeeType();
3101 assert(type->isFunctionType());
3102 return type;
3103 }
3104
3106 return QualType();
3107}
3108
3112
3116
3120
3124
3128
3133
3137
3139 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(this)) {
3140 if (isa_and_nonnull<CXXConversionDecl>(MCE->getMethodDecl()))
3141 return MCE->getImplicitObjectArgument();
3142 }
3143 return this;
3144}
3145
3150
3155
3157 auto IgnoreNoopCastsSingleStep = [&Ctx](Expr *E) {
3158 if (auto *CE = dyn_cast<CastExpr>(E)) {
3159 // We ignore integer <-> casts that are of the same width, ptr<->ptr and
3160 // ptr<->int casts of the same width. We also ignore all identity casts.
3161 Expr *SubExpr = CE->getSubExpr();
3162 bool IsIdentityCast =
3163 Ctx.hasSameUnqualifiedType(E->getType(), SubExpr->getType());
3164 bool IsSameWidthCast = (E->getType()->isPointerType() ||
3165 E->getType()->isIntegralType(Ctx)) &&
3166 (SubExpr->getType()->isPointerType() ||
3167 SubExpr->getType()->isIntegralType(Ctx)) &&
3168 (Ctx.getTypeSize(E->getType()) ==
3169 Ctx.getTypeSize(SubExpr->getType()));
3170
3171 if (IsIdentityCast || IsSameWidthCast)
3172 return SubExpr;
3173 } else if (auto *NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E))
3174 return NTTP->getReplacement();
3175
3176 return E;
3177 };
3179 IgnoreNoopCastsSingleStep);
3180}
3181
3184 if (auto *Cast = dyn_cast<CXXFunctionalCastExpr>(E)) {
3185 auto *SE = Cast->getSubExpr();
3186 if (SE->getSourceRange() == E->getSourceRange())
3187 return SE;
3188 }
3189
3190 if (auto *C = dyn_cast<CXXConstructExpr>(E)) {
3191 auto NumArgs = C->getNumArgs();
3192 if (NumArgs == 1 ||
3193 (NumArgs > 1 && isa<CXXDefaultArgExpr>(C->getArg(1)))) {
3194 Expr *A = C->getArg(0);
3195 if (A->getSourceRange() == E->getSourceRange() || C->isElidable())
3196 return A;
3197 }
3198 }
3199 return E;
3200 };
3201 auto IgnoreImplicitMemberCallSingleStep = [](Expr *E) {
3202 if (auto *C = dyn_cast<CXXMemberCallExpr>(E)) {
3203 Expr *ExprNode = C->getImplicitObjectArgument();
3204 if (ExprNode->getSourceRange() == E->getSourceRange()) {
3205 return ExprNode;
3206 }
3207 if (auto *PE = dyn_cast<ParenExpr>(ExprNode)) {
3208 if (PE->getSourceRange() == C->getSourceRange()) {
3209 return cast<Expr>(PE);
3210 }
3211 }
3212 ExprNode = ExprNode->IgnoreParenImpCasts();
3213 if (ExprNode->getSourceRange() == E->getSourceRange())
3214 return ExprNode;
3215 }
3216 return E;
3217 };
3218
3219 // Used when Clang generates calls to std::get for decomposing
3220 // structured bindings.
3221 auto IgnoreImplicitCallSingleStep = [](Expr *E) {
3222 auto *C = dyn_cast<CallExpr>(E);
3223 if (!C)
3224 return E;
3225
3226 // Looking for calls to a std::get, which usually just takes
3227 // 1 argument (i.e., the structure being decomposed). If it has
3228 // more than 1 argument, the others need to be defaulted.
3229 unsigned NumArgs = C->getNumArgs();
3230 if (NumArgs == 0 || (NumArgs > 1 && !isa<CXXDefaultArgExpr>(C->getArg(1))))
3231 return E;
3232
3233 Expr *A = C->getArg(0);
3234
3235 // This was spelled out in source. Don't ignore.
3236 if (A->getSourceRange() != E->getSourceRange())
3237 return E;
3238
3239 // If the argument refers to a DecompositionDecl construction,
3240 // ignore it.
3242 return A;
3243
3244 return E;
3245 };
3246
3247 return IgnoreExprNodes(
3250 IgnoreImplicitMemberCallSingleStep, IgnoreImplicitCallSingleStep);
3251}
3252
3254 const Expr *E = this;
3255 if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
3256 E = M->getSubExpr();
3257
3258 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3259 E = ICE->getSubExprAsWritten();
3260
3261 return isa<CXXDefaultArgExpr>(E);
3262}
3263
3264/// Skip over any no-op casts and any temporary-binding
3265/// expressions.
3267 if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
3268 E = M->getSubExpr();
3269
3270 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3271 if (ICE->getCastKind() == CK_NoOp)
3272 E = ICE->getSubExpr();
3273 else
3274 break;
3275 }
3276
3277 while (const CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
3278 E = BE->getSubExpr();
3279
3280 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3281 if (ICE->getCastKind() == CK_NoOp)
3282 E = ICE->getSubExpr();
3283 else
3284 break;
3285 }
3286
3287 return E->IgnoreParens();
3288}
3289
3290/// isTemporaryObject - Determines if this expression produces a
3291/// temporary of the given class type.
3293 if (!C.hasSameUnqualifiedType(getType(), C.getCanonicalTagType(TempTy)))
3294 return false;
3295
3297
3298 // Temporaries are by definition pr-values of class type.
3299 if (!E->Classify(C).isPRValue()) {
3300 // In this context, property reference is a message call and is pr-value.
3302 return false;
3303 }
3304
3305 // Black-list a few cases which yield pr-values of class type that don't
3306 // refer to temporaries of that type:
3307
3308 // - implicit derived-to-base conversions
3309 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3310 switch (ICE->getCastKind()) {
3311 case CK_DerivedToBase:
3312 case CK_UncheckedDerivedToBase:
3313 return false;
3314 default:
3315 break;
3316 }
3317 }
3318
3319 // - member expressions (all)
3320 if (isa<MemberExpr>(E))
3321 return false;
3322
3323 if (const auto *BO = dyn_cast<BinaryOperator>(E))
3324 if (BO->isPtrMemOp())
3325 return false;
3326
3327 // - opaque values (all)
3328 if (isa<OpaqueValueExpr>(E))
3329 return false;
3330
3331 return true;
3332}
3333
3335 const Expr *E = this;
3336
3337 // Strip away parentheses and casts we don't care about.
3338 while (true) {
3339 if (const ParenExpr *Paren = dyn_cast<ParenExpr>(E)) {
3340 E = Paren->getSubExpr();
3341 continue;
3342 }
3343
3344 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3345 if (ICE->getCastKind() == CK_NoOp ||
3346 ICE->getCastKind() == CK_LValueToRValue ||
3347 ICE->getCastKind() == CK_DerivedToBase ||
3348 ICE->getCastKind() == CK_UncheckedDerivedToBase) {
3349 E = ICE->getSubExpr();
3350 continue;
3351 }
3352 }
3353
3354 if (const UnaryOperator* UnOp = dyn_cast<UnaryOperator>(E)) {
3355 if (UnOp->getOpcode() == UO_Extension) {
3356 E = UnOp->getSubExpr();
3357 continue;
3358 }
3359 }
3360
3361 if (const MaterializeTemporaryExpr *M
3362 = dyn_cast<MaterializeTemporaryExpr>(E)) {
3363 E = M->getSubExpr();
3364 continue;
3365 }
3366
3367 break;
3368 }
3369
3370 if (const CXXThisExpr *This = dyn_cast<CXXThisExpr>(E))
3371 return This->isImplicit();
3372
3373 return false;
3374}
3375
3376/// hasAnyTypeDependentArguments - Determines if any of the expressions
3377/// in Exprs is type-dependent.
3379 for (unsigned I = 0; I < Exprs.size(); ++I)
3380 if (Exprs[I]->isTypeDependent())
3381 return true;
3382
3383 return false;
3384}
3385
3387 const Expr **Culprit) const {
3388 assert(!isValueDependent() &&
3389 "Expression evaluator can't be called on a dependent expression.");
3390
3391 // This function is attempting whether an expression is an initializer
3392 // which can be evaluated at compile-time. It very closely parallels
3393 // ConstExprEmitter in CGExprConstant.cpp; if they don't match, it
3394 // will lead to unexpected results. Like ConstExprEmitter, it falls back
3395 // to isEvaluatable most of the time.
3396 //
3397 // If we ever capture reference-binding directly in the AST, we can
3398 // kill the second parameter.
3399
3400 if (IsForRef) {
3401 if (auto *EWC = dyn_cast<ExprWithCleanups>(this))
3402 return EWC->getSubExpr()->isConstantInitializer(Ctx, true, Culprit);
3403 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(this))
3404 return MTE->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
3406 if (EvaluateAsLValue(Result, Ctx) && !Result.HasSideEffects)
3407 return true;
3408 if (Culprit)
3409 *Culprit = this;
3410 return false;
3411 }
3412
3413 switch (getStmtClass()) {
3414 default: break;
3415 case Stmt::ExprWithCleanupsClass:
3416 return cast<ExprWithCleanups>(this)->getSubExpr()->isConstantInitializer(
3417 Ctx, IsForRef, Culprit);
3418 case StringLiteralClass:
3419 case ObjCEncodeExprClass:
3420 return true;
3421 case CXXTemporaryObjectExprClass:
3422 case CXXConstructExprClass: {
3423 const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
3424
3425 if (CE->getConstructor()->isTrivial() &&
3427 // Trivial default constructor
3428 if (!CE->getNumArgs()) return true;
3429
3430 // Trivial copy constructor
3431 assert(CE->getNumArgs() == 1 && "trivial ctor with > 1 argument");
3432 return CE->getArg(0)->isConstantInitializer(Ctx, false, Culprit);
3433 }
3434
3435 break;
3436 }
3437 case ConstantExprClass: {
3438 // FIXME: We should be able to return "true" here, but it can lead to extra
3439 // error messages. E.g. in Sema/array-init.c.
3440 const Expr *Exp = cast<ConstantExpr>(this)->getSubExpr();
3441 return Exp->isConstantInitializer(Ctx, false, Culprit);
3442 }
3443 case CompoundLiteralExprClass: {
3444 // This handles gcc's extension that allows global initializers like
3445 // "struct x {int x;} x = (struct x) {};".
3446 // FIXME: This accepts other cases it shouldn't!
3447 const Expr *Exp = cast<CompoundLiteralExpr>(this)->getInitializer();
3448 return Exp->isConstantInitializer(Ctx, false, Culprit);
3449 }
3450 case DesignatedInitUpdateExprClass: {
3452 return DIUE->getBase()->isConstantInitializer(Ctx, false, Culprit) &&
3453 DIUE->getUpdater()->isConstantInitializer(Ctx, false, Culprit);
3454 }
3455 case InitListExprClass: {
3456 // C++ [dcl.init.aggr]p2:
3457 // The elements of an aggregate are:
3458 // - for an array, the array elements in increasing subscript order, or
3459 // - for a class, the direct base classes in declaration order, followed
3460 // by the direct non-static data members (11.4) that are not members of
3461 // an anonymous union, in declaration order.
3462 const InitListExpr *ILE = cast<InitListExpr>(this);
3463 assert(ILE->isSemanticForm() && "InitListExpr must be in semantic form");
3464
3465 if (ILE->isTransparent())
3466 return ILE->getInit(0)->isConstantInitializer(Ctx, false, Culprit);
3467
3468 if (ILE->getType()->isArrayType()) {
3469 unsigned numInits = ILE->getNumInits();
3470 for (unsigned i = 0; i < numInits; i++) {
3471 if (!ILE->getInit(i)->isConstantInitializer(Ctx, false, Culprit))
3472 return false;
3473 }
3474 return true;
3475 }
3476
3477 if (ILE->getType()->isRecordType()) {
3478 unsigned ElementNo = 0;
3479 auto *RD = ILE->getType()->castAsRecordDecl();
3480
3481 // In C++17, bases were added to the list of members used by aggregate
3482 // initialization.
3483 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3484 for (unsigned i = 0, e = CXXRD->getNumBases(); i < e; i++) {
3485 if (ElementNo < ILE->getNumInits()) {
3486 const Expr *Elt = ILE->getInit(ElementNo++);
3487 if (!Elt->isConstantInitializer(Ctx, false, Culprit))
3488 return false;
3489 }
3490 }
3491 }
3492
3493 for (const auto *Field : RD->fields()) {
3494 // If this is a union, skip all the fields that aren't being initialized.
3495 if (RD->isUnion() && ILE->getInitializedFieldInUnion() != Field)
3496 continue;
3497
3498 // Don't emit anonymous bitfields, they just affect layout.
3499 if (Field->isUnnamedBitField())
3500 continue;
3501
3502 if (ElementNo < ILE->getNumInits()) {
3503 const Expr *Elt = ILE->getInit(ElementNo++);
3504 if (Field->isBitField()) {
3505 // Bitfields have to evaluate to an integer.
3507 if (!Elt->EvaluateAsInt(Result, Ctx)) {
3508 if (Culprit)
3509 *Culprit = Elt;
3510 return false;
3511 }
3512 } else {
3513 bool RefType = Field->getType()->isReferenceType();
3514 if (!Elt->isConstantInitializer(Ctx, RefType, Culprit))
3515 return false;
3516 }
3517 }
3518 }
3519 return true;
3520 }
3521
3522 break;
3523 }
3524 case ImplicitValueInitExprClass:
3525 case NoInitExprClass:
3526 return true;
3527 case ParenExprClass:
3528 return cast<ParenExpr>(this)->getSubExpr()
3529 ->isConstantInitializer(Ctx, IsForRef, Culprit);
3530 case GenericSelectionExprClass:
3531 return cast<GenericSelectionExpr>(this)->getResultExpr()
3532 ->isConstantInitializer(Ctx, IsForRef, Culprit);
3533 case ChooseExprClass:
3534 if (cast<ChooseExpr>(this)->isConditionDependent()) {
3535 if (Culprit)
3536 *Culprit = this;
3537 return false;
3538 }
3539 return cast<ChooseExpr>(this)->getChosenSubExpr()
3540 ->isConstantInitializer(Ctx, IsForRef, Culprit);
3541 case UnaryOperatorClass: {
3542 const UnaryOperator* Exp = cast<UnaryOperator>(this);
3543 if (Exp->getOpcode() == UO_Extension)
3544 return Exp->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
3545 break;
3546 }
3547 case ObjCBoxedExprClass: {
3548 const ObjCBoxedExpr *BE = cast<ObjCBoxedExpr>(this);
3549 if (Culprit)
3550 *Culprit = this;
3552 }
3553 case ObjCArrayLiteralClass: {
3554 const ObjCArrayLiteral *ALE = cast<ObjCArrayLiteral>(this);
3555 if (Culprit)
3556 *Culprit = this;
3558 }
3559 case ObjCDictionaryLiteralClass: {
3561 if (Culprit)
3562 *Culprit = this;
3564 }
3565 case PackIndexingExprClass: {
3566 return cast<PackIndexingExpr>(this)
3567 ->getSelectedExpr()
3568 ->isConstantInitializer(Ctx, false, Culprit);
3569 }
3570 case CXXFunctionalCastExprClass:
3571 case CXXStaticCastExprClass:
3572 case ImplicitCastExprClass:
3573 case CStyleCastExprClass:
3574 case ObjCBridgedCastExprClass:
3575 case CXXDynamicCastExprClass:
3576 case CXXReinterpretCastExprClass:
3577 case CXXAddrspaceCastExprClass:
3578 case CXXConstCastExprClass: {
3579 const CastExpr *CE = cast<CastExpr>(this);
3580
3581 // Handle misc casts we want to ignore.
3582 if (CE->getCastKind() == CK_NoOp ||
3583 CE->getCastKind() == CK_LValueToRValue ||
3584 CE->getCastKind() == CK_ToUnion ||
3585 CE->getCastKind() == CK_ConstructorConversion ||
3586 CE->getCastKind() == CK_NonAtomicToAtomic ||
3587 CE->getCastKind() == CK_AtomicToNonAtomic ||
3588 CE->getCastKind() == CK_NullToPointer ||
3589 CE->getCastKind() == CK_ARCReclaimReturnedObject ||
3590 CE->getCastKind() == CK_IntToOCLSampler)
3591 return CE->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
3592
3593 break;
3594 }
3595 case MaterializeTemporaryExprClass:
3597 ->getSubExpr()
3598 ->isConstantInitializer(Ctx, false, Culprit);
3599
3600 case SubstNonTypeTemplateParmExprClass:
3601 return cast<SubstNonTypeTemplateParmExpr>(this)->getReplacement()
3602 ->isConstantInitializer(Ctx, false, Culprit);
3603 case CXXDefaultArgExprClass:
3604 return cast<CXXDefaultArgExpr>(this)->getExpr()
3605 ->isConstantInitializer(Ctx, false, Culprit);
3606 case CXXDefaultInitExprClass:
3607 return cast<CXXDefaultInitExpr>(this)->getExpr()
3608 ->isConstantInitializer(Ctx, false, Culprit);
3609 }
3610 // Allow certain forms of UB in constant initializers: signed integer
3611 // overflow and floating-point division by zero. We'll give a warning on
3612 // these, but they're common enough that we have to accept them.
3614 return true;
3615 if (Culprit)
3616 *Culprit = this;
3617 return false;
3618}
3619
3621 unsigned BuiltinID = getBuiltinCallee();
3622 if (BuiltinID != Builtin::BI__assume &&
3623 BuiltinID != Builtin::BI__builtin_assume)
3624 return false;
3625
3626 const Expr* Arg = getArg(0);
3627 bool ArgVal;
3628 return !Arg->isValueDependent() &&
3629 Arg->EvaluateAsBooleanCondition(ArgVal, Ctx) && !ArgVal;
3630}
3631
3632const AllocSizeAttr *CallExpr::getCalleeAllocSizeAttr() const {
3633 if (const FunctionDecl *DirectCallee = getDirectCallee())
3634 return DirectCallee->getAttr<AllocSizeAttr>();
3635 if (const Decl *IndirectCallee = getCalleeDecl())
3636 return IndirectCallee->getAttr<AllocSizeAttr>();
3637 return nullptr;
3638}
3639
3640std::optional<llvm::APInt>
3642 const AllocSizeAttr *AllocSize = getCalleeAllocSizeAttr();
3643
3644 assert(AllocSize && AllocSize->getElemSizeParam().isValid());
3645 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
3646 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
3647 if (getNumArgs() <= SizeArgNo)
3648 return std::nullopt;
3649
3650 auto EvaluateAsSizeT = [&](const Expr *E, llvm::APSInt &Into) {
3652 if (E->isValueDependent() ||
3654 return false;
3655 Into = ExprResult.Val.getInt();
3656 if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
3657 return false;
3658 Into = Into.extOrTrunc(BitsInSizeT);
3659 return true;
3660 };
3661
3662 llvm::APSInt SizeOfElem;
3663 if (!EvaluateAsSizeT(getArg(SizeArgNo), SizeOfElem))
3664 return std::nullopt;
3665
3666 if (!AllocSize->getNumElemsParam().isValid())
3667 return SizeOfElem;
3668
3669 llvm::APSInt NumberOfElems;
3670 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
3671 if (!EvaluateAsSizeT(getArg(NumArgNo), NumberOfElems))
3672 return std::nullopt;
3673
3674 bool Overflow;
3675 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
3676 if (Overflow)
3677 return std::nullopt;
3678
3679 return BytesAvailable;
3680}
3681
3683 return getBuiltinCallee() == Builtin::BImove;
3684}
3685
3686namespace {
3687 /// Look for any side effects within a Stmt.
3688 class SideEffectFinder : public ConstEvaluatedExprVisitor<SideEffectFinder> {
3690 const bool IncludePossibleEffects;
3691 bool HasSideEffects;
3692
3693 public:
3694 explicit SideEffectFinder(const ASTContext &Context, bool IncludePossible)
3695 : Inherited(Context),
3696 IncludePossibleEffects(IncludePossible), HasSideEffects(false) { }
3697
3698 bool hasSideEffects() const { return HasSideEffects; }
3699
3700 void VisitDecl(const Decl *D) {
3701 if (!D)
3702 return;
3703
3704 // We assume the caller checks subexpressions (eg, the initializer, VLA
3705 // bounds) for side-effects on our behalf.
3706 if (auto *VD = dyn_cast<VarDecl>(D)) {
3707 // Registering a destructor is a side-effect.
3708 if (IncludePossibleEffects && VD->isThisDeclarationADefinition() &&
3709 VD->needsDestruction(Context))
3710 HasSideEffects = true;
3711 }
3712 }
3713
3714 void VisitDeclStmt(const DeclStmt *DS) {
3715 for (auto *D : DS->decls())
3716 VisitDecl(D);
3717 Inherited::VisitDeclStmt(DS);
3718 }
3719
3720 void VisitExpr(const Expr *E) {
3721 if (!HasSideEffects &&
3722 E->HasSideEffects(Context, IncludePossibleEffects))
3723 HasSideEffects = true;
3724 }
3725 };
3726}
3727
3729 bool IncludePossibleEffects) const {
3730 // In circumstances where we care about definite side effects instead of
3731 // potential side effects, we want to ignore expressions that are part of a
3732 // macro expansion as a potential side effect.
3733 if (!IncludePossibleEffects && getExprLoc().isMacroID())
3734 return false;
3735
3736 switch (getStmtClass()) {
3737 case NoStmtClass:
3738#define ABSTRACT_STMT(Type)
3739#define STMT(Type, Base) case Type##Class:
3740#define EXPR(Type, Base)
3741#include "clang/AST/StmtNodes.inc"
3742 llvm_unreachable("unexpected Expr kind");
3743
3744 case DependentScopeDeclRefExprClass:
3745 case DependentTemplateIdExprClass:
3746 case CXXUnresolvedConstructExprClass:
3747 case CXXDependentScopeMemberExprClass:
3748 case UnresolvedLookupExprClass:
3749 case UnresolvedMemberExprClass:
3750 case PackExpansionExprClass:
3751 case SubstNonTypeTemplateParmPackExprClass:
3752 case FunctionParmPackExprClass:
3753 case RecoveryExprClass:
3754 case CXXFoldExprClass:
3755 case CXXExpansionSelectExprClass:
3756 // Make a conservative assumption for dependent nodes.
3757 return IncludePossibleEffects;
3758
3759 case DeclRefExprClass:
3760 case ObjCIvarRefExprClass:
3761 case PredefinedExprClass:
3762 case IntegerLiteralClass:
3763 case FixedPointLiteralClass:
3764 case FloatingLiteralClass:
3765 case ImaginaryLiteralClass:
3766 case StringLiteralClass:
3767 case CharacterLiteralClass:
3768 case OffsetOfExprClass:
3769 case ImplicitValueInitExprClass:
3770 case UnaryExprOrTypeTraitExprClass:
3771 case AddrLabelExprClass:
3772 case GNUNullExprClass:
3773 case ArrayInitIndexExprClass:
3774 case NoInitExprClass:
3775 case CXXBoolLiteralExprClass:
3776 case CXXNullPtrLiteralExprClass:
3777 case CXXThisExprClass:
3778 case CXXScalarValueInitExprClass:
3779 case TypeTraitExprClass:
3780 case ArrayTypeTraitExprClass:
3781 case ExpressionTraitExprClass:
3782 case CXXNoexceptExprClass:
3783 case SizeOfPackExprClass:
3784 case ObjCStringLiteralClass:
3785 case ObjCEncodeExprClass:
3786 case ObjCBoolLiteralExprClass:
3787 case ObjCAvailabilityCheckExprClass:
3788 case CXXUuidofExprClass:
3789 case OpaqueValueExprClass:
3790 case SourceLocExprClass:
3791 case EmbedExprClass:
3792 case ConceptSpecializationExprClass:
3793 case RequiresExprClass:
3794 case SYCLUniqueStableNameExprClass:
3795 case PackIndexingExprClass:
3796 case HLSLOutArgExprClass:
3797 case OpenACCAsteriskSizeExprClass:
3798 case CXXReflectExprClass:
3799 // These never have a side-effect.
3800 return false;
3801
3802 case ConstantExprClass:
3803 // FIXME: Move this into the "return false;" block above.
3804 return cast<ConstantExpr>(this)->getSubExpr()->HasSideEffects(
3805 Ctx, IncludePossibleEffects);
3806
3807 case CallExprClass:
3808 case CXXOperatorCallExprClass:
3809 case CXXMemberCallExprClass:
3810 case CUDAKernelCallExprClass:
3811 case UserDefinedLiteralClass: {
3812 // We don't know a call definitely has side effects, except for calls
3813 // to pure/const functions that definitely don't.
3814 // If the call itself is considered side-effect free, check the operands.
3815 const Decl *FD = cast<CallExpr>(this)->getCalleeDecl();
3816 bool IsPure = FD && (FD->hasAttr<ConstAttr>() || FD->hasAttr<PureAttr>());
3817 if (IsPure || !IncludePossibleEffects)
3818 break;
3819 return true;
3820 }
3821
3822 case BlockExprClass:
3823 case CXXBindTemporaryExprClass:
3824 if (!IncludePossibleEffects)
3825 break;
3826 return true;
3827
3828 case MSPropertyRefExprClass:
3829 case MSPropertySubscriptExprClass:
3830 case CompoundAssignOperatorClass:
3831 case VAArgExprClass:
3832 case AtomicExprClass:
3833 case CXXThrowExprClass:
3834 case CXXNewExprClass:
3835 case CXXDeleteExprClass:
3836 case CoawaitExprClass:
3837 case DependentCoawaitExprClass:
3838 case CoyieldExprClass:
3839 // These always have a side-effect.
3840 return true;
3841
3842 case StmtExprClass: {
3843 // StmtExprs have a side-effect if any substatement does.
3844 SideEffectFinder Finder(Ctx, IncludePossibleEffects);
3845 Finder.Visit(cast<StmtExpr>(this)->getSubStmt());
3846 return Finder.hasSideEffects();
3847 }
3848
3849 case ExprWithCleanupsClass:
3850 if (IncludePossibleEffects)
3851 if (cast<ExprWithCleanups>(this)->cleanupsHaveSideEffects())
3852 return true;
3853 break;
3854
3855 case ParenExprClass:
3856 case ArraySubscriptExprClass:
3857 case MatrixSingleSubscriptExprClass:
3858 case MatrixSubscriptExprClass:
3859 case ArraySectionExprClass:
3860 case OMPArrayShapingExprClass:
3861 case OMPIteratorExprClass:
3862 case MemberExprClass:
3863 case ConditionalOperatorClass:
3864 case BinaryConditionalOperatorClass:
3865 case CompoundLiteralExprClass:
3866 case ExtVectorElementExprClass:
3867 case MatrixElementExprClass:
3868 case DesignatedInitExprClass:
3869 case DesignatedInitUpdateExprClass:
3870 case ArrayInitLoopExprClass:
3871 case ParenListExprClass:
3872 case CXXPseudoDestructorExprClass:
3873 case CXXRewrittenBinaryOperatorClass:
3874 case CXXStdInitializerListExprClass:
3875 case SubstNonTypeTemplateParmExprClass:
3876 case MaterializeTemporaryExprClass:
3877 case ShuffleVectorExprClass:
3878 case ConvertVectorExprClass:
3879 case AsTypeExprClass:
3880 case CXXParenListInitExprClass:
3881 // These have a side-effect if any subexpression does.
3882 break;
3883
3884 case UnaryOperatorClass:
3885 if (cast<UnaryOperator>(this)->isIncrementDecrementOp())
3886 return true;
3887 break;
3888
3889 case BinaryOperatorClass:
3890 if (cast<BinaryOperator>(this)->isAssignmentOp())
3891 return true;
3892 break;
3893
3894 case InitListExprClass:
3895 // FIXME: The children for an InitListExpr doesn't include the array filler.
3896 if (const Expr *E = cast<InitListExpr>(this)->getArrayFiller())
3897 if (E->HasSideEffects(Ctx, IncludePossibleEffects))
3898 return true;
3899 break;
3900
3901 case GenericSelectionExprClass:
3902 return cast<GenericSelectionExpr>(this)->getResultExpr()->HasSideEffects(
3903 Ctx, IncludePossibleEffects);
3904
3905 case ChooseExprClass:
3906 return cast<ChooseExpr>(this)->getChosenSubExpr()->HasSideEffects(
3907 Ctx, IncludePossibleEffects);
3908
3909 case CXXDefaultArgExprClass:
3910 return cast<CXXDefaultArgExpr>(this)->getExpr()->HasSideEffects(
3911 Ctx, IncludePossibleEffects);
3912
3913 case CXXDefaultInitExprClass: {
3914 const FieldDecl *FD = cast<CXXDefaultInitExpr>(this)->getField();
3915 if (const Expr *E = FD->getInClassInitializer())
3916 return E->HasSideEffects(Ctx, IncludePossibleEffects);
3917 // If we've not yet parsed the initializer, assume it has side-effects.
3918 return true;
3919 }
3920
3921 case CXXDynamicCastExprClass: {
3922 // A dynamic_cast expression has side-effects if it can throw.
3924 if (DCE->getTypeAsWritten()->isReferenceType() &&
3925 DCE->getCastKind() == CK_Dynamic)
3926 return true;
3927 }
3928 [[fallthrough]];
3929 case ImplicitCastExprClass:
3930 case CStyleCastExprClass:
3931 case CXXStaticCastExprClass:
3932 case CXXReinterpretCastExprClass:
3933 case CXXConstCastExprClass:
3934 case CXXAddrspaceCastExprClass:
3935 case CXXFunctionalCastExprClass:
3936 case BuiltinBitCastExprClass: {
3937 // While volatile reads are side-effecting in both C and C++, we treat them
3938 // as having possible (not definite) side-effects. This allows idiomatic
3939 // code to behave without warning, such as sizeof(*v) for a volatile-
3940 // qualified pointer.
3941 if (!IncludePossibleEffects)
3942 break;
3943
3944 const CastExpr *CE = cast<CastExpr>(this);
3945 if (CE->getCastKind() == CK_LValueToRValue &&
3947 return true;
3948 break;
3949 }
3950
3951 case CXXTypeidExprClass: {
3952 const auto *TE = cast<CXXTypeidExpr>(this);
3953 if (!TE->isPotentiallyEvaluated())
3954 return false;
3955
3956 // If this type id expression can throw because of a null pointer, that is a
3957 // side-effect independent of if the operand has a side-effect
3958 if (IncludePossibleEffects && TE->hasNullCheck())
3959 return true;
3960
3961 break;
3962 }
3963
3964 case CXXConstructExprClass:
3965 case CXXTemporaryObjectExprClass: {
3966 const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
3967 if (!CE->getConstructor()->isTrivial() && IncludePossibleEffects)
3968 return true;
3969 // A trivial constructor does not add any side-effects of its own. Just look
3970 // at its arguments.
3971 break;
3972 }
3973
3974 case CXXInheritedCtorInitExprClass: {
3975 const auto *ICIE = cast<CXXInheritedCtorInitExpr>(this);
3976 if (!ICIE->getConstructor()->isTrivial() && IncludePossibleEffects)
3977 return true;
3978 break;
3979 }
3980
3981 case LambdaExprClass: {
3982 const LambdaExpr *LE = cast<LambdaExpr>(this);
3983 for (Expr *E : LE->capture_inits())
3984 if (E && E->HasSideEffects(Ctx, IncludePossibleEffects))
3985 return true;
3986 return false;
3987 }
3988
3989 case PseudoObjectExprClass: {
3990 // Only look for side-effects in the semantic form, and look past
3991 // OpaqueValueExpr bindings in that form.
3992 const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this);
3994 E = PO->semantics_end();
3995 I != E; ++I) {
3996 const Expr *Subexpr = *I;
3997 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Subexpr))
3998 Subexpr = OVE->getSourceExpr();
3999 if (Subexpr->HasSideEffects(Ctx, IncludePossibleEffects))
4000 return true;
4001 }
4002 return false;
4003 }
4004
4005 case ObjCBoxedExprClass:
4006 case ObjCArrayLiteralClass:
4007 case ObjCDictionaryLiteralClass:
4008 case ObjCSelectorExprClass:
4009 case ObjCProtocolExprClass:
4010 case ObjCIsaExprClass:
4011 case ObjCIndirectCopyRestoreExprClass:
4012 case ObjCSubscriptRefExprClass:
4013 case ObjCBridgedCastExprClass:
4014 case ObjCMessageExprClass:
4015 case ObjCPropertyRefExprClass:
4016 // FIXME: Classify these cases better.
4017 if (IncludePossibleEffects)
4018 return true;
4019 break;
4020 }
4021
4022 // Recurse to children.
4023 for (const Stmt *SubStmt : children())
4024 if (SubStmt &&
4025 cast<Expr>(SubStmt)->HasSideEffects(Ctx, IncludePossibleEffects))
4026 return true;
4027
4028 return false;
4029}
4030
4032 if (auto Call = dyn_cast<CallExpr>(this))
4033 return Call->getFPFeaturesInEffect(LO);
4034 if (auto UO = dyn_cast<UnaryOperator>(this))
4035 return UO->getFPFeaturesInEffect(LO);
4036 if (auto BO = dyn_cast<BinaryOperator>(this))
4037 return BO->getFPFeaturesInEffect(LO);
4038 if (auto Cast = dyn_cast<CastExpr>(this))
4039 return Cast->getFPFeaturesInEffect(LO);
4040 if (auto ConvertVector = dyn_cast<ConvertVectorExpr>(this))
4041 return ConvertVector->getFPFeaturesInEffect(LO);
4043}
4044
4045namespace {
4046 /// Look for a call to a non-trivial function within an expression.
4047 class NonTrivialCallFinder : public ConstEvaluatedExprVisitor<NonTrivialCallFinder>
4048 {
4050
4051 bool NonTrivial;
4052
4053 public:
4054 explicit NonTrivialCallFinder(const ASTContext &Context)
4055 : Inherited(Context), NonTrivial(false) { }
4056
4057 bool hasNonTrivialCall() const { return NonTrivial; }
4058
4059 void VisitCallExpr(const CallExpr *E) {
4060 if (const CXXMethodDecl *Method
4061 = dyn_cast_or_null<const CXXMethodDecl>(E->getCalleeDecl())) {
4062 if (Method->isTrivial()) {
4063 // Recurse to children of the call.
4064 Inherited::VisitStmt(E);
4065 return;
4066 }
4067 }
4068
4069 NonTrivial = true;
4070 }
4071
4072 void VisitCXXConstructExpr(const CXXConstructExpr *E) {
4073 if (E->getConstructor()->isTrivial()) {
4074 // Recurse to children of the call.
4075 Inherited::VisitStmt(E);
4076 return;
4077 }
4078
4079 NonTrivial = true;
4080 }
4081
4082 void VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
4083 // Destructor of the temporary might be null if destructor declaration
4084 // is not valid.
4085 if (const CXXDestructorDecl *DtorDecl =
4086 E->getTemporary()->getDestructor()) {
4087 if (DtorDecl->isTrivial()) {
4088 Inherited::VisitStmt(E);
4089 return;
4090 }
4091 }
4092
4093 NonTrivial = true;
4094 }
4095 };
4096}
4097
4098bool Expr::hasNonTrivialCall(const ASTContext &Ctx) const {
4099 NonTrivialCallFinder Finder(Ctx);
4100 Finder.Visit(this);
4101 return Finder.hasNonTrivialCall();
4102}
4103
4104/// isNullPointerConstant - C99 6.3.2.3p3 - Return whether this is a null
4105/// pointer constant or not, as well as the specific kind of constant detected.
4106/// Null pointer constants can be integer constant expressions with the
4107/// value zero, casts of zero to void*, nullptr (C++0X), or __null
4108/// (a GNU extension).
4112 if (isValueDependent() &&
4113 (!Ctx.getLangOpts().CPlusPlus11 || Ctx.getLangOpts().MSVCCompat)) {
4114 // Error-dependent expr should never be a null pointer.
4115 if (containsErrors())
4116 return NPCK_NotNull;
4117 switch (NPC) {
4119 llvm_unreachable("Unexpected value dependent expression!");
4121 if (isTypeDependent() || getType()->isIntegralType(Ctx))
4122 return NPCK_ZeroExpression;
4123 else
4124 return NPCK_NotNull;
4125
4127 return NPCK_NotNull;
4128 }
4129 }
4130
4131 // Strip off a cast to void*, if it exists. Except in C++.
4132 if (const ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(this)) {
4133 if (!Ctx.getLangOpts().CPlusPlus) {
4134 // Check that it is a cast to void*.
4135 if (const PointerType *PT = CE->getType()->getAs<PointerType>()) {
4136 QualType Pointee = PT->getPointeeType();
4137 Qualifiers Qs = Pointee.getQualifiers();
4138 // Only (void*)0 or equivalent are treated as nullptr. If pointee type
4139 // has non-default address space it is not treated as nullptr.
4140 // (__generic void*)0 in OpenCL 2.0 should not be treated as nullptr
4141 // since it cannot be assigned to a pointer to constant address space.
4142 if (Ctx.getLangOpts().OpenCL &&
4144 Qs.removeAddressSpace();
4145
4146 if (Pointee->isVoidType() && Qs.empty() && // to void*
4147 CE->getSubExpr()->getType()->isIntegerType()) // from int
4148 return CE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
4149 }
4150 }
4151 } else if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(this)) {
4152 // Ignore the ImplicitCastExpr type entirely.
4153 return ICE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
4154 } else if (const ParenExpr *PE = dyn_cast<ParenExpr>(this)) {
4155 // Accept ((void*)0) as a null pointer constant, as many other
4156 // implementations do.
4157 return PE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
4158 } else if (const GenericSelectionExpr *GE =
4159 dyn_cast<GenericSelectionExpr>(this)) {
4160 if (GE->isResultDependent())
4161 return NPCK_NotNull;
4162 return GE->getResultExpr()->isNullPointerConstant(Ctx, NPC);
4163 } else if (const ChooseExpr *CE = dyn_cast<ChooseExpr>(this)) {
4164 if (CE->isConditionDependent())
4165 return NPCK_NotNull;
4166 return CE->getChosenSubExpr()->isNullPointerConstant(Ctx, NPC);
4167 } else if (const CXXDefaultArgExpr *DefaultArg
4168 = dyn_cast<CXXDefaultArgExpr>(this)) {
4169 // See through default argument expressions.
4170 return DefaultArg->getExpr()->isNullPointerConstant(Ctx, NPC);
4171 } else if (const CXXDefaultInitExpr *DefaultInit
4172 = dyn_cast<CXXDefaultInitExpr>(this)) {
4173 // See through default initializer expressions.
4174 return DefaultInit->getExpr()->isNullPointerConstant(Ctx, NPC);
4175 } else if (isa<GNUNullExpr>(this)) {
4176 // The GNU __null extension is always a null pointer constant.
4177 return NPCK_GNUNull;
4178 } else if (const MaterializeTemporaryExpr *M
4179 = dyn_cast<MaterializeTemporaryExpr>(this)) {
4180 return M->getSubExpr()->isNullPointerConstant(Ctx, NPC);
4181 } else if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(this)) {
4182 if (const Expr *Source = OVE->getSourceExpr())
4183 return Source->isNullPointerConstant(Ctx, NPC);
4184 }
4185
4186 // If the expression has no type information, it cannot be a null pointer
4187 // constant.
4188 if (getType().isNull())
4189 return NPCK_NotNull;
4190
4191 // C++11/C23 nullptr_t is always a null pointer constant.
4192 if (getType()->isNullPtrType())
4193 return NPCK_CXX11_nullptr;
4194
4195 if (const RecordType *UT = getType()->getAsUnionType())
4196 if (!Ctx.getLangOpts().CPlusPlus11 && UT &&
4197 UT->getDecl()->getMostRecentDecl()->hasAttr<TransparentUnionAttr>())
4198 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(this)){
4199 const Expr *InitExpr = CLE->getInitializer();
4200 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(InitExpr))
4201 return ILE->getInit(0)->isNullPointerConstant(Ctx, NPC);
4202 }
4203 // This expression must be an integer type.
4204 if (!getType()->isIntegerType() ||
4205 (Ctx.getLangOpts().CPlusPlus && getType()->isEnumeralType()))
4206 return NPCK_NotNull;
4207
4208 if (Ctx.getLangOpts().CPlusPlus11) {
4209 // C++11 [conv.ptr]p1: A null pointer constant is an integer literal with
4210 // value zero or a prvalue of type std::nullptr_t.
4211 // Microsoft mode permits C++98 rules reflecting MSVC behavior.
4212 const IntegerLiteral *Lit = dyn_cast<IntegerLiteral>(this);
4213 if (Lit && !Lit->getValue())
4214 return NPCK_ZeroLiteral;
4215 if (!Ctx.getLangOpts().MSVCCompat || !isCXX98IntegralConstantExpr(Ctx))
4216 return NPCK_NotNull;
4217 } else {
4218 // If we have an integer constant expression, we need to *evaluate* it and
4219 // test for the value 0.
4220 if (!isIntegerConstantExpr(Ctx))
4221 return NPCK_NotNull;
4222 }
4223
4224 if (EvaluateKnownConstInt(Ctx) != 0)
4225 return NPCK_NotNull;
4226
4227 if (isa<IntegerLiteral>(this))
4228 return NPCK_ZeroLiteral;
4229 return NPCK_ZeroExpression;
4230}
4231
4232/// If this expression is an l-value for an Objective C
4233/// property, find the underlying property reference expression.
4235 const Expr *E = this;
4236 while (true) {
4237 assert((E->isLValue() && E->getObjectKind() == OK_ObjCProperty) &&
4238 "expression is not a property reference");
4239 E = E->IgnoreParenCasts();
4240 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
4241 if (BO->getOpcode() == BO_Comma) {
4242 E = BO->getRHS();
4243 continue;
4244 }
4245 }
4246
4247 break;
4248 }
4249
4250 return cast<ObjCPropertyRefExpr>(E);
4251}
4252
4254 const Expr *E = IgnoreParenImpCasts();
4255
4256 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
4257 if (!DRE)
4258 return false;
4259
4260 const ImplicitParamDecl *Param = dyn_cast<ImplicitParamDecl>(DRE->getDecl());
4261 if (!Param)
4262 return false;
4263
4264 const ObjCMethodDecl *M = dyn_cast<ObjCMethodDecl>(Param->getDeclContext());
4265 if (!M)
4266 return false;
4267
4268 return M->getSelfDecl() == Param;
4269}
4270
4272 Expr *E = this->IgnoreParens();
4273
4274 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
4275 if (ICE->getCastKind() == CK_LValueToRValue ||
4276 (ICE->isGLValue() && ICE->getCastKind() == CK_NoOp))
4277 E = ICE->getSubExpr()->IgnoreParens();
4278 else
4279 break;
4280 }
4281
4282 if (StmtExpr *SE = dyn_cast<StmtExpr>(E)) {
4283 CompoundStmt *CS = SE->getSubStmt();
4284 if (ValueStmt *VS = dyn_cast_or_null<ValueStmt>(CS->body_back()))
4285 if (Expr *EX = VS->getExprStmt())
4286 return EX->getSourceBitField();
4287 }
4288
4289 if (MemberExpr *MemRef = dyn_cast<MemberExpr>(E))
4290 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemRef->getMemberDecl()))
4291 if (Field->isBitField())
4292 return Field;
4293
4294 if (ObjCIvarRefExpr *IvarRef = dyn_cast<ObjCIvarRefExpr>(E)) {
4295 FieldDecl *Ivar = IvarRef->getDecl();
4296 if (Ivar->isBitField())
4297 return Ivar;
4298 }
4299
4300 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E)) {
4301 if (FieldDecl *Field = dyn_cast<FieldDecl>(DeclRef->getDecl()))
4302 if (Field->isBitField())
4303 return Field;
4304
4305 if (BindingDecl *BD = dyn_cast<BindingDecl>(DeclRef->getDecl()))
4306 if (Expr *E = BD->getBinding())
4307 return E->getSourceBitField();
4308 }
4309
4310 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(E)) {
4311 if (BinOp->isAssignmentOp() && BinOp->getLHS())
4312 return BinOp->getLHS()->getSourceBitField();
4313
4314 if (BinOp->getOpcode() == BO_Comma && BinOp->getRHS())
4315 return BinOp->getRHS()->getSourceBitField();
4316 }
4317
4318 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E))
4319 if (UnOp->isPrefix() && UnOp->isIncrementDecrementOp())
4320 return UnOp->getSubExpr()->getSourceBitField();
4321
4322 return nullptr;
4323}
4324
4326 Expr *E = this->IgnoreParenImpCasts();
4327 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
4328 return dyn_cast<EnumConstantDecl>(DRE->getDecl());
4329 return nullptr;
4330}
4331
4333 // FIXME: Why do we not just look at the ObjectKind here?
4334 const Expr *E = this->IgnoreParens();
4335
4336 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
4337 if (ICE->isGLValue() && ICE->getCastKind() == CK_NoOp)
4338 E = ICE->getSubExpr()->IgnoreParens();
4339 else
4340 break;
4341 }
4342
4343 if (const ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(E))
4344 return ASE->getBase()->getType()->isVectorType();
4345
4347 return true;
4348
4349 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
4350 if (auto *BD = dyn_cast<BindingDecl>(DRE->getDecl()))
4351 if (auto *E = BD->getBinding())
4352 return E->refersToVectorElement();
4353
4354 return false;
4355}
4356
4358 const Expr *E = this->IgnoreParenImpCasts();
4359
4360 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
4361 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
4362 if (VD->getStorageClass() == SC_Register &&
4363 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
4364 return true;
4365
4366 return false;
4367}
4368
4369bool Expr::isSameComparisonOperand(const Expr* E1, const Expr* E2) {
4370 E1 = E1->IgnoreParens();
4371 E2 = E2->IgnoreParens();
4372
4373 if (E1->getStmtClass() != E2->getStmtClass())
4374 return false;
4375
4376 switch (E1->getStmtClass()) {
4377 default:
4378 return false;
4379 case CXXThisExprClass:
4380 return true;
4381 case DeclRefExprClass: {
4382 // DeclRefExpr without an ImplicitCastExpr can happen for integral
4383 // template parameters.
4384 const auto *DRE1 = cast<DeclRefExpr>(E1);
4385 const auto *DRE2 = cast<DeclRefExpr>(E2);
4386
4387 if (DRE1->getDecl() != DRE2->getDecl())
4388 return false;
4389
4390 if ((DRE1->isPRValue() && DRE2->isPRValue()) ||
4391 (DRE1->isLValue() && DRE2->isLValue()))
4392 return true;
4393
4394 return false;
4395 }
4396 case ImplicitCastExprClass: {
4397 // Peel off implicit casts.
4398 while (true) {
4399 const auto *ICE1 = dyn_cast<ImplicitCastExpr>(E1);
4400 const auto *ICE2 = dyn_cast<ImplicitCastExpr>(E2);
4401 if (!ICE1 || !ICE2)
4402 return false;
4403 if (ICE1->getCastKind() != ICE2->getCastKind())
4404 return isSameComparisonOperand(ICE1->IgnoreParenImpCasts(),
4405 ICE2->IgnoreParenImpCasts());
4406 E1 = ICE1->getSubExpr()->IgnoreParens();
4407 E2 = ICE2->getSubExpr()->IgnoreParens();
4408 // The final cast must be one of these types.
4409 if (ICE1->getCastKind() == CK_LValueToRValue ||
4410 ICE1->getCastKind() == CK_ArrayToPointerDecay ||
4411 ICE1->getCastKind() == CK_FunctionToPointerDecay) {
4412 break;
4413 }
4414 }
4415
4416 const auto *DRE1 = dyn_cast<DeclRefExpr>(E1);
4417 const auto *DRE2 = dyn_cast<DeclRefExpr>(E2);
4418 if (DRE1 && DRE2)
4419 return declaresSameEntity(DRE1->getDecl(), DRE2->getDecl());
4420
4421 const auto *Ivar1 = dyn_cast<ObjCIvarRefExpr>(E1);
4422 const auto *Ivar2 = dyn_cast<ObjCIvarRefExpr>(E2);
4423 if (Ivar1 && Ivar2) {
4424 return Ivar1->isFreeIvar() && Ivar2->isFreeIvar() &&
4425 declaresSameEntity(Ivar1->getDecl(), Ivar2->getDecl());
4426 }
4427
4428 const auto *Array1 = dyn_cast<ArraySubscriptExpr>(E1);
4429 const auto *Array2 = dyn_cast<ArraySubscriptExpr>(E2);
4430 if (Array1 && Array2) {
4431 if (!isSameComparisonOperand(Array1->getBase(), Array2->getBase()))
4432 return false;
4433
4434 auto Idx1 = Array1->getIdx();
4435 auto Idx2 = Array2->getIdx();
4436 const auto Integer1 = dyn_cast<IntegerLiteral>(Idx1);
4437 const auto Integer2 = dyn_cast<IntegerLiteral>(Idx2);
4438 if (Integer1 && Integer2) {
4439 if (!llvm::APInt::isSameValue(Integer1->getValue(),
4440 Integer2->getValue()))
4441 return false;
4442 } else {
4443 if (!isSameComparisonOperand(Idx1, Idx2))
4444 return false;
4445 }
4446
4447 return true;
4448 }
4449
4450 // Walk the MemberExpr chain.
4451 while (isa<MemberExpr>(E1) && isa<MemberExpr>(E2)) {
4452 const auto *ME1 = cast<MemberExpr>(E1);
4453 const auto *ME2 = cast<MemberExpr>(E2);
4454 if (!declaresSameEntity(ME1->getMemberDecl(), ME2->getMemberDecl()))
4455 return false;
4456 if (const auto *D = dyn_cast<VarDecl>(ME1->getMemberDecl()))
4457 if (D->isStaticDataMember())
4458 return true;
4459 E1 = ME1->getBase()->IgnoreParenImpCasts();
4460 E2 = ME2->getBase()->IgnoreParenImpCasts();
4461 }
4462
4463 if (isa<CXXThisExpr>(E1) && isa<CXXThisExpr>(E2))
4464 return true;
4465
4466 // A static member variable can end the MemberExpr chain with either
4467 // a MemberExpr or a DeclRefExpr.
4468 auto getAnyDecl = [](const Expr *E) -> const ValueDecl * {
4469 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
4470 return DRE->getDecl();
4471 if (const auto *ME = dyn_cast<MemberExpr>(E))
4472 return ME->getMemberDecl();
4473 return nullptr;
4474 };
4475
4476 const ValueDecl *VD1 = getAnyDecl(E1);
4477 const ValueDecl *VD2 = getAnyDecl(E2);
4478 return declaresSameEntity(VD1, VD2);
4479 }
4480 }
4481}
4482
4483/// isArrow - Return true if the base expression is a pointer to vector,
4484/// return false if the base expression is a vector.
4486 return getBase()->getType()->isPointerType();
4487}
4488
4490 if (const VectorType *VT = getType()->getAs<VectorType>())
4491 return VT->getNumElements();
4492 return 1;
4493}
4494
4496 if (const auto *MT = getType()->getAs<ConstantMatrixType>())
4497 return MT->getNumElementsFlattened();
4498 return 1;
4499}
4500
4501/// containsDuplicateElements - Return true if any Vector element access is
4502/// repeated.
4504 // FIXME: Refactor this code to an accessor on the AST node which returns the
4505 // "type" of component access, and share with code below and in Sema.
4506 StringRef Comp = Accessor->getName();
4507
4508 // Halving swizzles do not contain duplicate elements.
4509 if (Comp == "hi" || Comp == "lo" || Comp == "even" || Comp == "odd")
4510 return false;
4511
4512 // Advance past s-char prefix on hex swizzles.
4513 if (Comp[0] == 's' || Comp[0] == 'S')
4514 Comp = Comp.substr(1);
4515
4516 for (unsigned i = 0, e = Comp.size(); i != e; ++i)
4517 if (Comp.substr(i + 1).contains(Comp[i]))
4518 return true;
4519
4520 return false;
4521}
4522
4523namespace {
4524struct MatrixAccessorFormat {
4525 bool IsZeroIndexed = false;
4526 unsigned ChunkLen = 0;
4527};
4528
4529static MatrixAccessorFormat GetHLSLMatrixAccessorFormat(StringRef Comp) {
4530 assert(!Comp.empty() && Comp[0] == '_' && "invalid matrix accessor");
4531
4532 MatrixAccessorFormat F;
4533 if (Comp.size() >= 2 && Comp[0] == '_' && Comp[1] == 'm') {
4534 F.IsZeroIndexed = true;
4535 F.ChunkLen = 4; // _mRC
4536 } else {
4537 F.IsZeroIndexed = false;
4538 F.ChunkLen = 3; // _RC
4539 }
4540
4541 assert(F.ChunkLen != 0 && "unrecognized matrix swizzle format");
4542 assert(Comp.size() % F.ChunkLen == 0 &&
4543 "matrix swizzle accessor has invalid length");
4544 return F;
4545}
4546
4547template <typename Fn>
4548static bool ForEachMatrixAccessorIndex(StringRef Comp,
4549 const ConstantMatrixType *MT, Fn &&F) {
4550 auto Format = GetHLSLMatrixAccessorFormat(Comp);
4551
4552 for (unsigned I = 0, E = Comp.size(); I < E; I += Format.ChunkLen) {
4553 unsigned Row = 0, Col = 0;
4554 unsigned ZeroIndexOffset = static_cast<unsigned>(Format.IsZeroIndexed);
4555 unsigned OneIndexOffset = static_cast<unsigned>(!Format.IsZeroIndexed);
4556 Row = static_cast<unsigned>(Comp[I + ZeroIndexOffset + 1] - '0') -
4557 OneIndexOffset;
4558 Col = static_cast<unsigned>(Comp[I + ZeroIndexOffset + 2] - '0') -
4559 OneIndexOffset;
4560
4561 assert(Row < MT->getNumRows() && Col < MT->getNumColumns() &&
4562 "matrix swizzle index out of bounds");
4563 // NOTE: AST layer has no access to LangOptions so we will default to row
4564 // major b\c all other AST matrix representations are row major.
4565 // However in codegen we need to convert to column major if the flag
4566 // requires it.
4567 const unsigned Index = MT->getFlattenedIndex(Row, Col, /*IsRowMajor*/ true);
4568 // Callback returns true to continue, false to stop early.
4569 if (!F(Index))
4570 return false;
4571 }
4572 return true;
4573}
4574
4575} // namespace
4576
4577/// containsDuplicateElements - Return true if any Matrix element access is
4578/// repeated.
4580 StringRef Comp = Accessor->getName();
4581 const auto *MT = getBase()->getType()->castAs<ConstantMatrixType>();
4582
4583 llvm::BitVector Seen(MT->getNumElementsFlattened(), /*t=*/false);
4584 bool HasDup = false;
4585 ForEachMatrixAccessorIndex(Comp, MT, [&](unsigned Index) -> bool {
4586 if (Seen[Index]) {
4587 HasDup = true;
4588 return false; // exit early
4589 }
4590 Seen.set(Index);
4591 return true;
4592 });
4593
4594 return HasDup;
4595}
4596
4597/// getEncodedElementAccess - We encode the fields as a llvm ConstantArray.
4599 SmallVectorImpl<uint32_t> &Elts) const {
4600 StringRef Comp = Accessor->getName();
4601 bool isNumericAccessor = false;
4602 if (Comp[0] == 's' || Comp[0] == 'S') {
4603 Comp = Comp.substr(1);
4604 isNumericAccessor = true;
4605 }
4606
4607 bool isHi = Comp == "hi";
4608 bool isLo = Comp == "lo";
4609 bool isEven = Comp == "even";
4610 bool isOdd = Comp == "odd";
4611
4612 for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
4613 uint64_t Index;
4614
4615 if (isHi)
4616 Index = e + i;
4617 else if (isLo)
4618 Index = i;
4619 else if (isEven)
4620 Index = 2 * i;
4621 else if (isOdd)
4622 Index = 2 * i + 1;
4623 else
4624 Index = ExtVectorType::getAccessorIdx(Comp[i], isNumericAccessor);
4625
4626 Elts.push_back(Index);
4627 }
4628}
4629
4631 SmallVectorImpl<uint32_t> &Elts) const {
4632 StringRef Comp = Accessor->getName();
4633 const auto *MT = getBase()->getType()->castAs<ConstantMatrixType>();
4634 ForEachMatrixAccessorIndex(Comp, MT, [&](unsigned Index) -> bool {
4635 Elts.push_back(Index);
4636 return true;
4637 });
4638}
4639
4642 SourceLocation RP)
4643 : Expr(ShuffleVectorExprClass, Type, VK_PRValue, OK_Ordinary),
4644 BuiltinLoc(BLoc), RParenLoc(RP) {
4645 ShuffleVectorExprBits.NumExprs = args.size();
4646 SubExprs = new (C) Stmt*[args.size()];
4647 for (unsigned i = 0; i != args.size(); i++)
4648 SubExprs[i] = args[i];
4649
4651}
4652
4654 if (SubExprs) C.Deallocate(SubExprs);
4655
4656 this->ShuffleVectorExprBits.NumExprs = Exprs.size();
4657 SubExprs = new (C) Stmt *[ShuffleVectorExprBits.NumExprs];
4658 llvm::copy(Exprs, SubExprs);
4659}
4660
4661GenericSelectionExpr::GenericSelectionExpr(
4662 const ASTContext &, SourceLocation GenericLoc, Expr *ControllingExpr,
4663 ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
4664 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4665 bool ContainsUnexpandedParameterPack, unsigned ResultIndex)
4666 : Expr(GenericSelectionExprClass, AssocExprs[ResultIndex]->getType(),
4667 AssocExprs[ResultIndex]->getValueKind(),
4668 AssocExprs[ResultIndex]->getObjectKind()),
4669 NumAssocs(AssocExprs.size()), ResultIndex(ResultIndex),
4670 IsExprPredicate(true), DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
4671 assert(AssocTypes.size() == AssocExprs.size() &&
4672 "Must have the same number of association expressions"
4673 " and TypeSourceInfo!");
4674 assert(ResultIndex < NumAssocs && "ResultIndex is out-of-bounds!");
4675
4676 GenericSelectionExprBits.GenericLoc = GenericLoc;
4677 getTrailingObjects<Stmt *>()[getIndexOfControllingExpression()] =
4678 ControllingExpr;
4679 llvm::copy(AssocExprs,
4680 getTrailingObjects<Stmt *>() + getIndexOfStartOfAssociatedExprs());
4681 llvm::copy(AssocTypes, getTrailingObjects<TypeSourceInfo *>() +
4682 getIndexOfStartOfAssociatedTypes());
4683
4684 setDependence(computeDependence(this, ContainsUnexpandedParameterPack));
4685}
4686
4687GenericSelectionExpr::GenericSelectionExpr(
4688 const ASTContext &, SourceLocation GenericLoc,
4689 TypeSourceInfo *ControllingType, ArrayRef<TypeSourceInfo *> AssocTypes,
4690 ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,
4691 SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack,
4692 unsigned ResultIndex)
4693 : Expr(GenericSelectionExprClass, AssocExprs[ResultIndex]->getType(),
4694 AssocExprs[ResultIndex]->getValueKind(),
4695 AssocExprs[ResultIndex]->getObjectKind()),
4696 NumAssocs(AssocExprs.size()), ResultIndex(ResultIndex),
4697 IsExprPredicate(false), DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
4698 assert(AssocTypes.size() == AssocExprs.size() &&
4699 "Must have the same number of association expressions"
4700 " and TypeSourceInfo!");
4701 assert(ResultIndex < NumAssocs && "ResultIndex is out-of-bounds!");
4702
4703 GenericSelectionExprBits.GenericLoc = GenericLoc;
4704 getTrailingObjects<TypeSourceInfo *>()[getIndexOfControllingType()] =
4705 ControllingType;
4706 llvm::copy(AssocExprs,
4707 getTrailingObjects<Stmt *>() + getIndexOfStartOfAssociatedExprs());
4708 llvm::copy(AssocTypes, getTrailingObjects<TypeSourceInfo *>() +
4709 getIndexOfStartOfAssociatedTypes());
4710
4711 setDependence(computeDependence(this, ContainsUnexpandedParameterPack));
4712}
4713
4714GenericSelectionExpr::GenericSelectionExpr(
4715 const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,
4716 ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
4717 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4718 bool ContainsUnexpandedParameterPack)
4719 : Expr(GenericSelectionExprClass, Context.DependentTy, VK_PRValue,
4720 OK_Ordinary),
4721 NumAssocs(AssocExprs.size()), ResultIndex(ResultDependentIndex),
4722 IsExprPredicate(true), DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
4723 assert(AssocTypes.size() == AssocExprs.size() &&
4724 "Must have the same number of association expressions"
4725 " and TypeSourceInfo!");
4726
4727 GenericSelectionExprBits.GenericLoc = GenericLoc;
4728 getTrailingObjects<Stmt *>()[getIndexOfControllingExpression()] =
4729 ControllingExpr;
4730 llvm::copy(AssocExprs,
4731 getTrailingObjects<Stmt *>() + getIndexOfStartOfAssociatedExprs());
4732 llvm::copy(AssocTypes, getTrailingObjects<TypeSourceInfo *>() +
4733 getIndexOfStartOfAssociatedTypes());
4734
4735 setDependence(computeDependence(this, ContainsUnexpandedParameterPack));
4736}
4737
4738GenericSelectionExpr::GenericSelectionExpr(
4739 const ASTContext &Context, SourceLocation GenericLoc,
4740 TypeSourceInfo *ControllingType, ArrayRef<TypeSourceInfo *> AssocTypes,
4741 ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,
4742 SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack)
4743 : Expr(GenericSelectionExprClass, Context.DependentTy, VK_PRValue,
4744 OK_Ordinary),
4745 NumAssocs(AssocExprs.size()), ResultIndex(ResultDependentIndex),
4746 IsExprPredicate(false), DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
4747 assert(AssocTypes.size() == AssocExprs.size() &&
4748 "Must have the same number of association expressions"
4749 " and TypeSourceInfo!");
4750
4751 GenericSelectionExprBits.GenericLoc = GenericLoc;
4752 getTrailingObjects<TypeSourceInfo *>()[getIndexOfControllingType()] =
4753 ControllingType;
4754 llvm::copy(AssocExprs,
4755 getTrailingObjects<Stmt *>() + getIndexOfStartOfAssociatedExprs());
4756 llvm::copy(AssocTypes, getTrailingObjects<TypeSourceInfo *>() +
4757 getIndexOfStartOfAssociatedTypes());
4758
4759 setDependence(computeDependence(this, ContainsUnexpandedParameterPack));
4760}
4761
4762GenericSelectionExpr::GenericSelectionExpr(EmptyShell Empty, unsigned NumAssocs)
4763 : Expr(GenericSelectionExprClass, Empty), NumAssocs(NumAssocs) {}
4764
4765GenericSelectionExpr *GenericSelectionExpr::Create(
4766 const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,
4767 ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
4768 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4769 bool ContainsUnexpandedParameterPack, unsigned ResultIndex) {
4770 unsigned NumAssocs = AssocExprs.size();
4771 void *Mem = Context.Allocate(
4772 totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
4773 alignof(GenericSelectionExpr));
4774 return new (Mem) GenericSelectionExpr(
4775 Context, GenericLoc, ControllingExpr, AssocTypes, AssocExprs, DefaultLoc,
4776 RParenLoc, ContainsUnexpandedParameterPack, ResultIndex);
4777}
4778
4779GenericSelectionExpr *GenericSelectionExpr::Create(
4780 const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,
4781 ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
4782 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4783 bool ContainsUnexpandedParameterPack) {
4784 unsigned NumAssocs = AssocExprs.size();
4785 void *Mem = Context.Allocate(
4786 totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
4787 alignof(GenericSelectionExpr));
4788 return new (Mem) GenericSelectionExpr(
4789 Context, GenericLoc, ControllingExpr, AssocTypes, AssocExprs, DefaultLoc,
4790 RParenLoc, ContainsUnexpandedParameterPack);
4791}
4792
4793GenericSelectionExpr *GenericSelectionExpr::Create(
4794 const ASTContext &Context, SourceLocation GenericLoc,
4795 TypeSourceInfo *ControllingType, ArrayRef<TypeSourceInfo *> AssocTypes,
4796 ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,
4797 SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack,
4798 unsigned ResultIndex) {
4799 unsigned NumAssocs = AssocExprs.size();
4800 void *Mem = Context.Allocate(
4801 totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
4802 alignof(GenericSelectionExpr));
4803 return new (Mem) GenericSelectionExpr(
4804 Context, GenericLoc, ControllingType, AssocTypes, AssocExprs, DefaultLoc,
4805 RParenLoc, ContainsUnexpandedParameterPack, ResultIndex);
4806}
4807
4808GenericSelectionExpr *GenericSelectionExpr::Create(
4809 const ASTContext &Context, SourceLocation GenericLoc,
4810 TypeSourceInfo *ControllingType, ArrayRef<TypeSourceInfo *> AssocTypes,
4811 ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,
4812 SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack) {
4813 unsigned NumAssocs = AssocExprs.size();
4814 void *Mem = Context.Allocate(
4815 totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
4816 alignof(GenericSelectionExpr));
4817 return new (Mem) GenericSelectionExpr(
4818 Context, GenericLoc, ControllingType, AssocTypes, AssocExprs, DefaultLoc,
4819 RParenLoc, ContainsUnexpandedParameterPack);
4820}
4821
4824 unsigned NumAssocs) {
4825 void *Mem = Context.Allocate(
4826 totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
4827 alignof(GenericSelectionExpr));
4828 return new (Mem) GenericSelectionExpr(EmptyShell(), NumAssocs);
4829}
4830
4831//===----------------------------------------------------------------------===//
4832// DesignatedInitExpr
4833//===----------------------------------------------------------------------===//
4834
4836 assert(isFieldDesignator() && "Only valid on a field designator");
4837 if (FieldInfo.NameOrField & 0x01)
4838 return reinterpret_cast<IdentifierInfo *>(FieldInfo.NameOrField & ~0x01);
4839 return getFieldDecl()->getIdentifier();
4840}
4841
4842DesignatedInitExpr::DesignatedInitExpr(const ASTContext &C, QualType Ty,
4843 ArrayRef<Designator> Designators,
4844 SourceLocation EqualOrColonLoc,
4845 bool GNUSyntax,
4846 ArrayRef<Expr *> IndexExprs, Expr *Init)
4847 : Expr(DesignatedInitExprClass, Ty, Init->getValueKind(),
4848 Init->getObjectKind()),
4849 EqualOrColonLoc(EqualOrColonLoc), GNUSyntax(GNUSyntax),
4850 NumDesignators(Designators.size()), NumSubExprs(IndexExprs.size() + 1) {
4851 this->Designators = new (C) Designator[NumDesignators];
4852
4853 // Record the initializer itself.
4854 child_iterator Child = child_begin();
4855 *Child++ = Init;
4856
4857 // Copy the designators and their subexpressions, computing
4858 // value-dependence along the way.
4859 unsigned IndexIdx = 0;
4860 for (unsigned I = 0; I != NumDesignators; ++I) {
4861 this->Designators[I] = Designators[I];
4862 if (this->Designators[I].isArrayDesignator()) {
4863 // Copy the index expressions into permanent storage.
4864 *Child++ = IndexExprs[IndexIdx++];
4865 } else if (this->Designators[I].isArrayRangeDesignator()) {
4866 // Copy the start/end expressions into permanent storage.
4867 *Child++ = IndexExprs[IndexIdx++];
4868 *Child++ = IndexExprs[IndexIdx++];
4869 }
4870 }
4871
4872 assert(IndexIdx == IndexExprs.size() && "Wrong number of index expressions");
4874}
4875
4876DesignatedInitExpr *DesignatedInitExpr::Create(const ASTContext &C,
4877 ArrayRef<Designator> Designators,
4878 ArrayRef<Expr *> IndexExprs,
4879 SourceLocation ColonOrEqualLoc,
4880 bool UsesColonSyntax,
4881 Expr *Init) {
4882 void *Mem = C.Allocate(totalSizeToAlloc<Stmt *>(IndexExprs.size() + 1),
4883 alignof(DesignatedInitExpr));
4884 return new (Mem) DesignatedInitExpr(C, C.VoidTy, Designators,
4885 ColonOrEqualLoc, UsesColonSyntax,
4886 IndexExprs, Init);
4887}
4888
4890 unsigned NumIndexExprs) {
4891 void *Mem = C.Allocate(totalSizeToAlloc<Stmt *>(NumIndexExprs + 1),
4892 alignof(DesignatedInitExpr));
4893 return new (Mem) DesignatedInitExpr(NumIndexExprs + 1);
4894}
4895
4897 const Designator *Desigs,
4898 unsigned NumDesigs) {
4899 Designators = new (C) Designator[NumDesigs];
4900 NumDesignators = NumDesigs;
4901 for (unsigned I = 0; I != NumDesigs; ++I)
4902 Designators[I] = Desigs[I];
4903}
4904
4906 DesignatedInitExpr *DIE = const_cast<DesignatedInitExpr*>(this);
4907 if (size() == 1)
4908 return DIE->getDesignator(0)->getSourceRange();
4909 return SourceRange(DIE->getDesignator(0)->getBeginLoc(),
4910 DIE->getDesignator(size() - 1)->getEndLoc());
4911}
4912
4914 auto *DIE = const_cast<DesignatedInitExpr *>(this);
4915 Designator &First = *DIE->getDesignator(0);
4916 if (First.isFieldDesignator()) {
4917 // Skip past implicit designators for anonymous structs/unions, since
4918 // these do not have valid source locations.
4919 for (unsigned int i = 0; i < DIE->size(); i++) {
4920 Designator &Des = *DIE->getDesignator(i);
4921 SourceLocation retval = GNUSyntax ? Des.getFieldLoc() : Des.getDotLoc();
4922 if (!retval.isValid())
4923 continue;
4924 return retval;
4925 }
4926 }
4927 return First.getLBracketLoc();
4928}
4929
4933
4935 assert(D.isArrayDesignator() && "Requires array designator");
4936 return getSubExpr(D.getArrayIndex() + 1);
4937}
4938
4940 assert(D.isArrayRangeDesignator() && "Requires array range designator");
4941 return getSubExpr(D.getArrayIndex() + 1);
4942}
4943
4945 assert(D.isArrayRangeDesignator() && "Requires array range designator");
4946 return getSubExpr(D.getArrayIndex() + 2);
4947}
4948
4949/// Replaces the designator at index @p Idx with the series
4950/// of designators in [First, Last).
4952 const Designator *First,
4953 const Designator *Last) {
4954 unsigned NumNewDesignators = Last - First;
4955 if (NumNewDesignators == 0) {
4956 std::copy_backward(Designators + Idx + 1,
4957 Designators + NumDesignators,
4958 Designators + Idx);
4959 --NumNewDesignators;
4960 return;
4961 }
4962 if (NumNewDesignators == 1) {
4963 Designators[Idx] = *First;
4964 return;
4965 }
4966
4967 Designator *NewDesignators
4968 = new (C) Designator[NumDesignators - 1 + NumNewDesignators];
4969 std::copy(Designators, Designators + Idx, NewDesignators);
4970 std::copy(First, Last, NewDesignators + Idx);
4971 std::copy(Designators + Idx + 1, Designators + NumDesignators,
4972 NewDesignators + Idx + NumNewDesignators);
4973 Designators = NewDesignators;
4974 NumDesignators = NumDesignators - 1 + NumNewDesignators;
4975}
4976
4978 SourceLocation lBraceLoc,
4979 Expr *baseExpr,
4980 SourceLocation rBraceLoc)
4981 : Expr(DesignatedInitUpdateExprClass, baseExpr->getType(), VK_PRValue,
4982 OK_Ordinary) {
4983 BaseAndUpdaterExprs[0] = baseExpr;
4984
4985 InitListExpr *ILE =
4986 new (C) InitListExpr(C, lBraceLoc, {}, rBraceLoc, /*isExplicit=*/false);
4987 ILE->setType(baseExpr->getType());
4988 BaseAndUpdaterExprs[1] = ILE;
4989
4990 // FIXME: this is wrong, set it correctly.
4991 setDependence(ExprDependence::None);
4992}
4993
4997
5001
5002ParenListExpr::ParenListExpr(SourceLocation LParenLoc, ArrayRef<Expr *> Exprs,
5003 SourceLocation RParenLoc)
5004 : Expr(ParenListExprClass, QualType(), VK_PRValue, OK_Ordinary),
5005 LParenLoc(LParenLoc), RParenLoc(RParenLoc) {
5006 ParenListExprBits.NumExprs = Exprs.size();
5007 llvm::copy(Exprs, getTrailingObjects());
5009}
5010
5011ParenListExpr::ParenListExpr(EmptyShell Empty, unsigned NumExprs)
5012 : Expr(ParenListExprClass, Empty) {
5013 ParenListExprBits.NumExprs = NumExprs;
5014}
5015
5016ParenListExpr *ParenListExpr::Create(const ASTContext &Ctx,
5017 SourceLocation LParenLoc,
5018 ArrayRef<Expr *> Exprs,
5019 SourceLocation RParenLoc) {
5020 void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *>(Exprs.size()),
5021 alignof(ParenListExpr));
5022 return new (Mem) ParenListExpr(LParenLoc, Exprs, RParenLoc);
5023}
5024
5025ParenListExpr *ParenListExpr::CreateEmpty(const ASTContext &Ctx,
5026 unsigned NumExprs) {
5027 void *Mem =
5028 Ctx.Allocate(totalSizeToAlloc<Stmt *>(NumExprs), alignof(ParenListExpr));
5029 return new (Mem) ParenListExpr(EmptyShell(), NumExprs);
5030}
5031
5032/// Certain overflow-dependent code patterns can have their integer overflow
5033/// sanitization disabled. Check for the common pattern `if (a + b < a)` and
5034/// return the resulting BinaryOperator responsible for the addition so we can
5035/// elide overflow checks during codegen.
5036static std::optional<BinaryOperator *>
5038 Expr *Addition, *ComparedTo;
5039 if (E->getOpcode() == BO_LT) {
5040 Addition = E->getLHS();
5041 ComparedTo = E->getRHS();
5042 } else if (E->getOpcode() == BO_GT) {
5043 Addition = E->getRHS();
5044 ComparedTo = E->getLHS();
5045 } else {
5046 return {};
5047 }
5048
5049 const Expr *AddLHS = nullptr, *AddRHS = nullptr;
5050 BinaryOperator *BO = dyn_cast<BinaryOperator>(Addition);
5051
5052 if (BO && BO->getOpcode() == clang::BO_Add) {
5053 // now store addends for lookup on other side of '>'
5054 AddLHS = BO->getLHS();
5055 AddRHS = BO->getRHS();
5056 }
5057
5058 if (!AddLHS || !AddRHS)
5059 return {};
5060
5061 const Decl *LHSDecl, *RHSDecl, *OtherDecl;
5062
5063 LHSDecl = AddLHS->IgnoreParenImpCasts()->getReferencedDeclOfCallee();
5064 RHSDecl = AddRHS->IgnoreParenImpCasts()->getReferencedDeclOfCallee();
5065 OtherDecl = ComparedTo->IgnoreParenImpCasts()->getReferencedDeclOfCallee();
5066
5067 if (!OtherDecl)
5068 return {};
5069
5070 if (!LHSDecl && !RHSDecl)
5071 return {};
5072
5073 if ((LHSDecl && LHSDecl == OtherDecl && LHSDecl != RHSDecl) ||
5074 (RHSDecl && RHSDecl == OtherDecl && RHSDecl != LHSDecl))
5075 return BO;
5076 return {};
5077}
5078
5079/// Compute and set the OverflowPatternExclusion bit based on whether the
5080/// BinaryOperator expression matches an overflow pattern being ignored by
5081/// -fsanitize-undefined-ignore-overflow-pattern=add-signed-overflow-test or
5082/// -fsanitize-undefined-ignore-overflow-pattern=add-unsigned-overflow-test
5084 const BinaryOperator *E) {
5085 std::optional<BinaryOperator *> Result = getOverflowPatternBinOp(E);
5086 if (!Result.has_value())
5087 return;
5088 QualType AdditionResultType = Result.value()->getType();
5089
5090 if ((AdditionResultType->isSignedIntegerType() &&
5093 (AdditionResultType->isUnsignedIntegerType() &&
5096 Result.value()->setExcludedOverflowPattern(true);
5097}
5098
5100 Opcode opc, QualType ResTy, ExprValueKind VK,
5102 FPOptionsOverride FPFeatures)
5103 : Expr(BinaryOperatorClass, ResTy, VK, OK) {
5104 BinaryOperatorBits.Opc = opc;
5105 assert(!isCompoundAssignmentOp() &&
5106 "Use CompoundAssignOperator for compound assignments");
5107 BinaryOperatorBits.OpLoc = opLoc;
5108 BinaryOperatorBits.ExcludedOverflowPattern = false;
5109 SubExprs[LHS] = lhs;
5110 SubExprs[RHS] = rhs;
5112 BinaryOperatorBits.HasFPFeatures = FPFeatures.requiresTrailingStorage();
5113 if (hasStoredFPFeatures())
5114 setStoredFPFeatures(FPFeatures);
5116}
5117
5119 Opcode opc, QualType ResTy, ExprValueKind VK,
5121 FPOptionsOverride FPFeatures, bool dead2)
5122 : Expr(CompoundAssignOperatorClass, ResTy, VK, OK) {
5123 BinaryOperatorBits.Opc = opc;
5124 BinaryOperatorBits.ExcludedOverflowPattern = false;
5125 assert(isCompoundAssignmentOp() &&
5126 "Use CompoundAssignOperator for compound assignments");
5127 BinaryOperatorBits.OpLoc = opLoc;
5128 SubExprs[LHS] = lhs;
5129 SubExprs[RHS] = rhs;
5130 BinaryOperatorBits.HasFPFeatures = FPFeatures.requiresTrailingStorage();
5131 if (hasStoredFPFeatures())
5132 setStoredFPFeatures(FPFeatures);
5134}
5135
5137 bool HasFPFeatures) {
5138 unsigned Extra = sizeOfTrailingObjects(HasFPFeatures);
5139 void *Mem =
5140 C.Allocate(sizeof(BinaryOperator) + Extra, alignof(BinaryOperator));
5141 return new (Mem) BinaryOperator(EmptyShell());
5142}
5143
5145 Expr *rhs, Opcode opc, QualType ResTy,
5147 SourceLocation opLoc,
5148 FPOptionsOverride FPFeatures) {
5149 bool HasFPFeatures = FPFeatures.requiresTrailingStorage();
5150 unsigned Extra = sizeOfTrailingObjects(HasFPFeatures);
5151 void *Mem =
5152 C.Allocate(sizeof(BinaryOperator) + Extra, alignof(BinaryOperator));
5153 return new (Mem)
5154 BinaryOperator(C, lhs, rhs, opc, ResTy, VK, OK, opLoc, FPFeatures);
5155}
5156
5159 unsigned Extra = sizeOfTrailingObjects(HasFPFeatures);
5160 void *Mem = C.Allocate(sizeof(CompoundAssignOperator) + Extra,
5161 alignof(CompoundAssignOperator));
5162 return new (Mem) CompoundAssignOperator(C, EmptyShell(), HasFPFeatures);
5163}
5164
5167 Opcode opc, QualType ResTy, ExprValueKind VK,
5169 FPOptionsOverride FPFeatures,
5170 QualType CompLHSType, QualType CompResultType) {
5171 bool HasFPFeatures = FPFeatures.requiresTrailingStorage();
5172 unsigned Extra = sizeOfTrailingObjects(HasFPFeatures);
5173 void *Mem = C.Allocate(sizeof(CompoundAssignOperator) + Extra,
5174 alignof(CompoundAssignOperator));
5175 return new (Mem)
5176 CompoundAssignOperator(C, lhs, rhs, opc, ResTy, VK, OK, opLoc, FPFeatures,
5177 CompLHSType, CompResultType);
5178}
5179
5181 bool hasFPFeatures) {
5182 void *Mem = C.Allocate(totalSizeToAlloc<FPOptionsOverride>(hasFPFeatures),
5183 alignof(UnaryOperator));
5184 return new (Mem) UnaryOperator(hasFPFeatures, EmptyShell());
5185}
5186
5189 SourceLocation l, bool CanOverflow,
5190 FPOptionsOverride FPFeatures)
5191 : Expr(UnaryOperatorClass, type, VK, OK), Val(input) {
5192 UnaryOperatorBits.Opc = opc;
5193 UnaryOperatorBits.CanOverflow = CanOverflow;
5194 UnaryOperatorBits.Loc = l;
5195 UnaryOperatorBits.HasFPFeatures = FPFeatures.requiresTrailingStorage();
5196 if (hasStoredFPFeatures())
5197 setStoredFPFeatures(FPFeatures);
5198 setDependence(computeDependence(this, Ctx));
5199}
5200
5202 Opcode opc, QualType type,
5204 SourceLocation l, bool CanOverflow,
5205 FPOptionsOverride FPFeatures) {
5206 bool HasFPFeatures = FPFeatures.requiresTrailingStorage();
5207 unsigned Size = totalSizeToAlloc<FPOptionsOverride>(HasFPFeatures);
5208 void *Mem = C.Allocate(Size, alignof(UnaryOperator));
5209 return new (Mem)
5210 UnaryOperator(C, input, opc, type, VK, OK, l, CanOverflow, FPFeatures);
5211}
5212
5214 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(e))
5215 e = ewc->getSubExpr();
5216 if (const MaterializeTemporaryExpr *m = dyn_cast<MaterializeTemporaryExpr>(e))
5217 e = m->getSubExpr();
5218 e = cast<CXXConstructExpr>(e)->getArg(0);
5219 while (const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
5220 e = ice->getSubExpr();
5221 return cast<OpaqueValueExpr>(e);
5222}
5223
5224PseudoObjectExpr *PseudoObjectExpr::Create(const ASTContext &Context,
5225 EmptyShell sh,
5226 unsigned numSemanticExprs) {
5227 void *buffer =
5228 Context.Allocate(totalSizeToAlloc<Expr *>(1 + numSemanticExprs),
5229 alignof(PseudoObjectExpr));
5230 return new(buffer) PseudoObjectExpr(sh, numSemanticExprs);
5231}
5232
5233PseudoObjectExpr::PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs)
5234 : Expr(PseudoObjectExprClass, shell) {
5235 PseudoObjectExprBits.NumSubExprs = numSemanticExprs + 1;
5236}
5237
5240 unsigned resultIndex) {
5241 assert(syntax && "no syntactic expression!");
5242 assert(semantics.size() && "no semantic expressions!");
5243
5244 QualType type;
5246 if (resultIndex == NoResult) {
5247 type = C.VoidTy;
5248 VK = VK_PRValue;
5249 } else {
5250 assert(resultIndex < semantics.size());
5251 type = semantics[resultIndex]->getType();
5252 VK = semantics[resultIndex]->getValueKind();
5253 assert(semantics[resultIndex]->getObjectKind() == OK_Ordinary);
5254 }
5255
5256 void *buffer = C.Allocate(totalSizeToAlloc<Expr *>(semantics.size() + 1),
5257 alignof(PseudoObjectExpr));
5258 return new(buffer) PseudoObjectExpr(type, VK, syntax, semantics,
5259 resultIndex);
5260}
5261
5262PseudoObjectExpr::PseudoObjectExpr(QualType type, ExprValueKind VK,
5263 Expr *syntax, ArrayRef<Expr *> semantics,
5264 unsigned resultIndex)
5265 : Expr(PseudoObjectExprClass, type, VK, OK_Ordinary) {
5266 PseudoObjectExprBits.NumSubExprs = semantics.size() + 1;
5267 PseudoObjectExprBits.ResultIndex = resultIndex + 1;
5268 MutableArrayRef<Expr *> Trail = getTrailingObjects(semantics.size() + 1);
5269 Trail[0] = syntax;
5270
5271 assert(llvm::all_of(semantics,
5272 [](const Expr *E) {
5273 return !isa<OpaqueValueExpr>(E) ||
5274 cast<OpaqueValueExpr>(E)->getSourceExpr() !=
5275 nullptr;
5276 }) &&
5277 "opaque-value semantic expressions for pseudo-object "
5278 "operations must have sources");
5279
5280 llvm::copy(semantics, Trail.drop_front().begin());
5282}
5283
5284//===----------------------------------------------------------------------===//
5285// Child Iterators for iterating over subexpressions/substatements
5286//===----------------------------------------------------------------------===//
5287
5288// UnaryExprOrTypeTraitExpr
5290 const_child_range CCR =
5291 const_cast<const UnaryExprOrTypeTraitExpr *>(this)->children();
5292 return child_range(cast_away_const(CCR.begin()), cast_away_const(CCR.end()));
5293}
5294
5296 // If this is of a type and the type is a VLA type (and not a typedef), the
5297 // size expression of the VLA needs to be treated as an executable expression.
5298 // Why isn't this weirdness documented better in StmtIterator?
5299 if (isArgumentType()) {
5300 if (const VariableArrayType *T =
5301 dyn_cast<VariableArrayType>(getArgumentType().getTypePtr()))
5304 }
5305 return const_child_range(&Argument.Ex, &Argument.Ex + 1);
5306}
5307
5309 AtomicOp op, SourceLocation RP)
5310 : Expr(AtomicExprClass, t, VK_PRValue, OK_Ordinary),
5311 NumSubExprs(args.size()), BuiltinLoc(BLoc), RParenLoc(RP), Op(op) {
5312 assert(args.size() == getNumSubExprs(op) && "wrong number of subexpressions");
5313 for (unsigned i = 0; i != args.size(); i++)
5314 SubExprs[i] = args[i];
5316}
5317
5319 switch (Op) {
5320 case AO__c11_atomic_init:
5321 case AO__opencl_atomic_init:
5322 case AO__c11_atomic_load:
5323 case AO__atomic_load_n:
5324 case AO__atomic_test_and_set:
5325 case AO__atomic_clear:
5326 return 2;
5327
5328 case AO__scoped_atomic_load_n:
5329 case AO__opencl_atomic_load:
5330 case AO__hip_atomic_load:
5331 case AO__c11_atomic_store:
5332 case AO__c11_atomic_exchange:
5333 case AO__atomic_load:
5334 case AO__atomic_store:
5335 case AO__atomic_store_n:
5336 case AO__atomic_exchange_n:
5337 case AO__c11_atomic_fetch_add:
5338 case AO__c11_atomic_fetch_sub:
5339 case AO__c11_atomic_fetch_and:
5340 case AO__c11_atomic_fetch_or:
5341 case AO__c11_atomic_fetch_xor:
5342 case AO__c11_atomic_fetch_nand:
5343 case AO__c11_atomic_fetch_max:
5344 case AO__c11_atomic_fetch_min:
5345 case AO__atomic_fetch_add:
5346 case AO__atomic_fetch_sub:
5347 case AO__atomic_fetch_and:
5348 case AO__atomic_fetch_or:
5349 case AO__atomic_fetch_xor:
5350 case AO__atomic_fetch_nand:
5351 case AO__atomic_add_fetch:
5352 case AO__atomic_sub_fetch:
5353 case AO__atomic_and_fetch:
5354 case AO__atomic_or_fetch:
5355 case AO__atomic_xor_fetch:
5356 case AO__atomic_nand_fetch:
5357 case AO__atomic_min_fetch:
5358 case AO__atomic_max_fetch:
5359 case AO__atomic_fetch_min:
5360 case AO__atomic_fetch_max:
5361 case AO__atomic_fetch_fminimum:
5362 case AO__atomic_fetch_fmaximum:
5363 case AO__atomic_fetch_fminimum_num:
5364 case AO__atomic_fetch_fmaximum_num:
5365 case AO__atomic_fetch_uinc:
5366 case AO__atomic_fetch_udec:
5367 return 3;
5368
5369 case AO__scoped_atomic_load:
5370 case AO__scoped_atomic_store:
5371 case AO__scoped_atomic_store_n:
5372 case AO__scoped_atomic_fetch_add:
5373 case AO__scoped_atomic_fetch_sub:
5374 case AO__scoped_atomic_fetch_and:
5375 case AO__scoped_atomic_fetch_or:
5376 case AO__scoped_atomic_fetch_xor:
5377 case AO__scoped_atomic_fetch_nand:
5378 case AO__scoped_atomic_add_fetch:
5379 case AO__scoped_atomic_sub_fetch:
5380 case AO__scoped_atomic_and_fetch:
5381 case AO__scoped_atomic_or_fetch:
5382 case AO__scoped_atomic_xor_fetch:
5383 case AO__scoped_atomic_nand_fetch:
5384 case AO__scoped_atomic_min_fetch:
5385 case AO__scoped_atomic_max_fetch:
5386 case AO__scoped_atomic_fetch_min:
5387 case AO__scoped_atomic_fetch_max:
5388 case AO__scoped_atomic_fetch_fminimum:
5389 case AO__scoped_atomic_fetch_fmaximum:
5390 case AO__scoped_atomic_fetch_fminimum_num:
5391 case AO__scoped_atomic_fetch_fmaximum_num:
5392 case AO__scoped_atomic_exchange_n:
5393 case AO__scoped_atomic_fetch_uinc:
5394 case AO__scoped_atomic_fetch_udec:
5395 case AO__hip_atomic_exchange:
5396 case AO__hip_atomic_fetch_add:
5397 case AO__hip_atomic_fetch_sub:
5398 case AO__hip_atomic_fetch_and:
5399 case AO__hip_atomic_fetch_or:
5400 case AO__hip_atomic_fetch_xor:
5401 case AO__hip_atomic_fetch_min:
5402 case AO__hip_atomic_fetch_max:
5403 case AO__opencl_atomic_store:
5404 case AO__hip_atomic_store:
5405 case AO__opencl_atomic_exchange:
5406 case AO__opencl_atomic_fetch_add:
5407 case AO__opencl_atomic_fetch_sub:
5408 case AO__opencl_atomic_fetch_and:
5409 case AO__opencl_atomic_fetch_or:
5410 case AO__opencl_atomic_fetch_xor:
5411 case AO__opencl_atomic_fetch_min:
5412 case AO__opencl_atomic_fetch_max:
5413 case AO__atomic_exchange:
5414 return 4;
5415
5416 case AO__scoped_atomic_exchange:
5417 case AO__c11_atomic_compare_exchange_strong:
5418 case AO__c11_atomic_compare_exchange_weak:
5419 return 5;
5420 case AO__hip_atomic_compare_exchange_strong:
5421 case AO__opencl_atomic_compare_exchange_strong:
5422 case AO__opencl_atomic_compare_exchange_weak:
5423 case AO__hip_atomic_compare_exchange_weak:
5424 case AO__atomic_compare_exchange:
5425 case AO__atomic_compare_exchange_n:
5426 return 6;
5427
5428 case AO__scoped_atomic_compare_exchange:
5429 case AO__scoped_atomic_compare_exchange_n:
5430 return 7;
5431 }
5432 llvm_unreachable("unknown atomic op");
5433}
5434
5436 auto T = getPtr()->getType()->castAs<PointerType>()->getPointeeType();
5437 if (auto AT = T->getAs<AtomicType>())
5438 return AT->getValueType();
5439 return T;
5440}
5441
5443 unsigned ArraySectionCount = 0;
5444 while (auto *OASE = dyn_cast<ArraySectionExpr>(Base->IgnoreParens())) {
5445 Base = OASE->getBase();
5446 ++ArraySectionCount;
5447 }
5448 while (auto *ASE =
5449 dyn_cast<ArraySubscriptExpr>(Base->IgnoreParenImpCasts())) {
5450 Base = ASE->getBase();
5451 ++ArraySectionCount;
5452 }
5453 Base = Base->IgnoreParenImpCasts();
5454 auto OriginalTy = Base->getType();
5455 if (auto *DRE = dyn_cast<DeclRefExpr>(Base))
5456 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
5457 OriginalTy = PVD->getOriginalType().getNonReferenceType();
5458
5459 for (unsigned Cnt = 0; Cnt < ArraySectionCount; ++Cnt) {
5460 if (OriginalTy->isAnyPointerType())
5461 OriginalTy = OriginalTy->getPointeeType();
5462 else if (OriginalTy->isArrayType())
5463 OriginalTy = OriginalTy->castAsArrayTypeUnsafe()->getElementType();
5464 else
5465 return {};
5466 }
5467 return OriginalTy;
5468}
5469
5472 // We only have to look into the array section exprs, else we will get the
5473 // type of the base, which should already be valid.
5474 if (auto *ASE = dyn_cast<ArraySectionExpr>(getBase()->IgnoreParenImpCasts()))
5475 BaseTy = ASE->getElementType();
5476
5477 if (BaseTy->isAnyPointerType())
5478 return BaseTy->getPointeeType();
5479 if (BaseTy->isArrayType())
5480 return BaseTy->castAsArrayTypeUnsafe()->getElementType();
5481
5482 // If this isn't a pointer or array, the base is a dependent expression, so
5483 // just return the BaseTy anyway.
5484 assert(BaseTy->isInstantiationDependentType());
5485 return BaseTy;
5486}
5487
5489 // We only have to look into the array section exprs, else we will get the
5490 // type of the base, which should already be valid.
5491 if (auto *ASE = dyn_cast<ArraySectionExpr>(getBase()->IgnoreParenImpCasts()))
5492 return ASE->getElementType();
5493
5494 return getBase()->IgnoreParenImpCasts()->getType();
5495}
5496
5497RecoveryExpr::RecoveryExpr(ASTContext &Ctx, QualType T, SourceLocation BeginLoc,
5498 SourceLocation EndLoc, ArrayRef<Expr *> SubExprs)
5499 : Expr(RecoveryExprClass, T.getNonReferenceType(),
5500 T->isDependentType() ? VK_LValue : getValueKindForType(T),
5501 OK_Ordinary),
5502 BeginLoc(BeginLoc), EndLoc(EndLoc), NumExprs(SubExprs.size()) {
5503 assert(!T.isNull());
5504 assert(!llvm::is_contained(SubExprs, nullptr));
5505
5506 llvm::copy(SubExprs, getTrailingObjects());
5508}
5509
5511 SourceLocation BeginLoc,
5512 SourceLocation EndLoc,
5513 ArrayRef<Expr *> SubExprs) {
5514 void *Mem = Ctx.Allocate(totalSizeToAlloc<Expr *>(SubExprs.size()),
5515 alignof(RecoveryExpr));
5516 return new (Mem) RecoveryExpr(Ctx, T, BeginLoc, EndLoc, SubExprs);
5517}
5518
5519RecoveryExpr *RecoveryExpr::CreateEmpty(ASTContext &Ctx, unsigned NumSubExprs) {
5520 void *Mem = Ctx.Allocate(totalSizeToAlloc<Expr *>(NumSubExprs),
5521 alignof(RecoveryExpr));
5522 return new (Mem) RecoveryExpr(EmptyShell(), NumSubExprs);
5523}
5524
5525void OMPArrayShapingExpr::setDimensions(ArrayRef<Expr *> Dims) {
5526 assert(
5527 NumDims == Dims.size() &&
5528 "Preallocated number of dimensions is different from the provided one.");
5529 llvm::copy(Dims, getTrailingObjects<Expr *>());
5530}
5531
5532void OMPArrayShapingExpr::setBracketsRanges(ArrayRef<SourceRange> BR) {
5533 assert(
5534 NumDims == BR.size() &&
5535 "Preallocated number of dimensions is different from the provided one.");
5536 llvm::copy(BR, getTrailingObjects<SourceRange>());
5537}
5538
5539OMPArrayShapingExpr::OMPArrayShapingExpr(QualType ExprTy, Expr *Op,
5541 ArrayRef<Expr *> Dims)
5542 : Expr(OMPArrayShapingExprClass, ExprTy, VK_LValue, OK_Ordinary), LPLoc(L),
5543 RPLoc(R), NumDims(Dims.size()) {
5544 setBase(Op);
5545 setDimensions(Dims);
5547}
5548
5552 ArrayRef<Expr *> Dims,
5553 ArrayRef<SourceRange> BracketRanges) {
5554 assert(Dims.size() == BracketRanges.size() &&
5555 "Different number of dimensions and brackets ranges.");
5556 void *Mem = Context.Allocate(
5557 totalSizeToAlloc<Expr *, SourceRange>(Dims.size() + 1, Dims.size()),
5558 alignof(OMPArrayShapingExpr));
5559 auto *E = new (Mem) OMPArrayShapingExpr(T, Op, L, R, Dims);
5560 E->setBracketsRanges(BracketRanges);
5561 return E;
5562}
5563
5564OMPArrayShapingExpr *OMPArrayShapingExpr::CreateEmpty(const ASTContext &Context,
5565 unsigned NumDims) {
5566 void *Mem = Context.Allocate(
5567 totalSizeToAlloc<Expr *, SourceRange>(NumDims + 1, NumDims),
5568 alignof(OMPArrayShapingExpr));
5569 return new (Mem) OMPArrayShapingExpr(EmptyShell(), NumDims);
5570}
5571
5572void OMPIteratorExpr::setIteratorDeclaration(unsigned I, Decl *D) {
5573 getTrailingObjects<Decl *>(NumIterators)[I] = D;
5574}
5575
5576void OMPIteratorExpr::setAssignmentLoc(unsigned I, SourceLocation Loc) {
5577 assert(I < NumIterators &&
5578 "Idx is greater or equal the number of iterators definitions.");
5579 getTrailingObjects<
5580 SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +
5581 static_cast<int>(RangeLocOffset::AssignLoc)] = Loc;
5582}
5583
5584void OMPIteratorExpr::setIteratorRange(unsigned I, Expr *Begin,
5585 SourceLocation ColonLoc, Expr *End,
5586 SourceLocation SecondColonLoc,
5587 Expr *Step) {
5588 assert(I < NumIterators &&
5589 "Idx is greater or equal the number of iterators definitions.");
5590 getTrailingObjects<Expr *>()[I * static_cast<int>(RangeExprOffset::Total) +
5591 static_cast<int>(RangeExprOffset::Begin)] =
5592 Begin;
5593 getTrailingObjects<Expr *>()[I * static_cast<int>(RangeExprOffset::Total) +
5594 static_cast<int>(RangeExprOffset::End)] = End;
5595 getTrailingObjects<Expr *>()[I * static_cast<int>(RangeExprOffset::Total) +
5596 static_cast<int>(RangeExprOffset::Step)] = Step;
5597 getTrailingObjects<
5598 SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +
5599 static_cast<int>(RangeLocOffset::FirstColonLoc)] =
5600 ColonLoc;
5601 getTrailingObjects<
5602 SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +
5603 static_cast<int>(RangeLocOffset::SecondColonLoc)] =
5604 SecondColonLoc;
5605}
5606
5608 return getTrailingObjects<Decl *>()[I];
5609}
5610
5612 IteratorRange Res;
5613 Res.Begin =
5614 getTrailingObjects<Expr *>()[I * static_cast<int>(
5615 RangeExprOffset::Total) +
5616 static_cast<int>(RangeExprOffset::Begin)];
5617 Res.End =
5618 getTrailingObjects<Expr *>()[I * static_cast<int>(
5619 RangeExprOffset::Total) +
5620 static_cast<int>(RangeExprOffset::End)];
5621 Res.Step =
5622 getTrailingObjects<Expr *>()[I * static_cast<int>(
5623 RangeExprOffset::Total) +
5624 static_cast<int>(RangeExprOffset::Step)];
5625 return Res;
5626}
5627
5629 return getTrailingObjects<
5630 SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +
5631 static_cast<int>(RangeLocOffset::AssignLoc)];
5632}
5633
5635 return getTrailingObjects<
5636 SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +
5637 static_cast<int>(RangeLocOffset::FirstColonLoc)];
5638}
5639
5641 return getTrailingObjects<
5642 SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +
5643 static_cast<int>(RangeLocOffset::SecondColonLoc)];
5644}
5645
5646void OMPIteratorExpr::setHelper(unsigned I, const OMPIteratorHelperData &D) {
5647 getTrailingObjects<OMPIteratorHelperData>()[I] = D;
5648}
5649
5651 return getTrailingObjects<OMPIteratorHelperData>()[I];
5652}
5653
5655 return getTrailingObjects<OMPIteratorHelperData>()[I];
5656}
5657
5658OMPIteratorExpr::OMPIteratorExpr(
5659 QualType ExprTy, SourceLocation IteratorKwLoc, SourceLocation L,
5662 : Expr(OMPIteratorExprClass, ExprTy, VK_LValue, OK_Ordinary),
5663 IteratorKwLoc(IteratorKwLoc), LPLoc(L), RPLoc(R),
5664 NumIterators(Data.size()) {
5665 for (unsigned I = 0, E = Data.size(); I < E; ++I) {
5666 const IteratorDefinition &D = Data[I];
5667 setIteratorDeclaration(I, D.IteratorDecl);
5668 setAssignmentLoc(I, D.AssignmentLoc);
5669 setIteratorRange(I, D.Range.Begin, D.ColonLoc, D.Range.End,
5670 D.SecondColonLoc, D.Range.Step);
5671 setHelper(I, Helpers[I]);
5672 }
5674}
5675
5678 SourceLocation IteratorKwLoc, SourceLocation L,
5682 assert(Data.size() == Helpers.size() &&
5683 "Data and helpers must have the same size.");
5684 void *Mem = Context.Allocate(
5685 totalSizeToAlloc<Decl *, Expr *, SourceLocation, OMPIteratorHelperData>(
5686 Data.size(), Data.size() * static_cast<int>(RangeExprOffset::Total),
5687 Data.size() * static_cast<int>(RangeLocOffset::Total),
5688 Helpers.size()),
5689 alignof(OMPIteratorExpr));
5690 return new (Mem) OMPIteratorExpr(T, IteratorKwLoc, L, R, Data, Helpers);
5691}
5692
5693OMPIteratorExpr *OMPIteratorExpr::CreateEmpty(const ASTContext &Context,
5694 unsigned NumIterators) {
5695 void *Mem = Context.Allocate(
5696 totalSizeToAlloc<Decl *, Expr *, SourceLocation, OMPIteratorHelperData>(
5697 NumIterators, NumIterators * static_cast<int>(RangeExprOffset::Total),
5698 NumIterators * static_cast<int>(RangeLocOffset::Total), NumIterators),
5699 alignof(OMPIteratorExpr));
5700 return new (Mem) OMPIteratorExpr(EmptyShell(), NumIterators);
5701}
5702
5703HLSLOutArgExpr *HLSLOutArgExpr::Create(const ASTContext &C, QualType Ty,
5705 OpaqueValueExpr *OpV, Expr *WB,
5706 bool IsInOut) {
5707 return new (C) HLSLOutArgExpr(Ty, Base, OpV, WB, IsInOut);
5708}
5709
5711 return new (C) HLSLOutArgExpr(EmptyShell());
5712}
5713
5714OpenACCAsteriskSizeExpr *OpenACCAsteriskSizeExpr::Create(const ASTContext &C,
5715 SourceLocation Loc) {
5716 return new (C) OpenACCAsteriskSizeExpr(Loc, C.IntTy);
5717}
5718
5721 return new (C) OpenACCAsteriskSizeExpr({}, C.IntTy);
5722}
5723
5725 bool hasFPFeatures) {
5726 void *Mem = C.Allocate(totalSizeToAlloc<FPOptionsOverride>(hasFPFeatures),
5727 alignof(ConvertVectorExpr));
5728 return new (Mem) ConvertVectorExpr(hasFPFeatures, EmptyShell());
5729}
5730
5731ConvertVectorExpr *ConvertVectorExpr::Create(
5732 const ASTContext &C, Expr *SrcExpr, TypeSourceInfo *TI, QualType DstType,
5734 SourceLocation RParenLoc, FPOptionsOverride FPFeatures) {
5735 bool HasFPFeatures = FPFeatures.requiresTrailingStorage();
5736 unsigned Size = totalSizeToAlloc<FPOptionsOverride>(HasFPFeatures);
5737 void *Mem = C.Allocate(Size, alignof(ConvertVectorExpr));
5738 return new (Mem) ConvertVectorExpr(SrcExpr, TI, DstType, VK, OK, BuiltinLoc,
5739 RParenLoc, FPFeatures);
5740}
5741
5743 assert(hasStaticStorage());
5744 if (!StaticValue) {
5745 StaticValue = new (Ctx) APValue;
5746 Ctx.addDestruction(StaticValue);
5747 }
5748 return *StaticValue;
5749}
5750
5752 assert(StaticValue);
5753 return *StaticValue;
5754}
5755
5756namespace {
5757/// Visitor that walks an Expr to the head of a struct-field access chain;
5758/// see clang::findStructFieldAccess.
5759class StructFieldAccessVisitor
5760 : public ConstStmtVisitor<StructFieldAccessVisitor, const Expr *> {
5761 bool AddrOfSeen = false;
5762
5763public:
5764 const Expr *ArrayIndex = nullptr;
5765 QualType ArrayElementTy;
5766
5767 const Expr *VisitMemberExpr(const MemberExpr *E) {
5768 if (AddrOfSeen && E->getType()->isArrayType())
5769 // '&fam' designates the array object as a whole, not the
5770 // pointer-to-element value that 'fam' decays to.
5771 return nullptr;
5772 return E;
5773 }
5774
5775 const Expr *VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
5776 if (ArrayIndex)
5777 // We don't support multiple subscripts.
5778 return nullptr;
5779
5780 AddrOfSeen = false; // '&ptr->array[idx]' is okay.
5781 ArrayIndex = E->getIdx();
5782 ArrayElementTy = E->getBase()->getType();
5783 return Visit(E->getBase());
5784 }
5785 const Expr *VisitCastExpr(const CastExpr *E) {
5786 if (E->getCastKind() == CK_LValueToRValue)
5787 return E;
5788 return Visit(E->getSubExpr());
5789 }
5790 const Expr *VisitParenExpr(const ParenExpr *E) {
5791 return Visit(E->getSubExpr());
5792 }
5793 const Expr *VisitUnaryAddrOf(const UnaryOperator *E) {
5794 AddrOfSeen = true;
5795 return Visit(E->getSubExpr());
5796 }
5797 const Expr *VisitUnaryDeref(const UnaryOperator *E) {
5798 AddrOfSeen = false;
5799 return Visit(E->getSubExpr());
5800 }
5801 const Expr *VisitBinaryOperator(const BinaryOperator *Op) {
5802 return Op->isCommaOp() ? Visit(Op->getRHS()) : nullptr;
5803 }
5804};
5805} // namespace
5806
5808 const Expr **OutArrayIndex,
5809 QualType *OutArrayElementTy) {
5810 StructFieldAccessVisitor V;
5811 const Expr *Result = V.Visit(E);
5812 if (OutArrayIndex)
5813 *OutArrayIndex = V.ArrayIndex;
5814 if (OutArrayElementTy)
5815 *OutArrayElementTy = V.ArrayElementTy;
5816 return Result;
5817}
Defines the clang::ASTContext interface.
#define V(N, I)
This file provides some common utility functions for processing Lambda related AST Constructs.
static bool isBooleanType(QualType Ty)
static Expr * IgnoreImplicitConstructorSingleStep(Expr *E)
Definition BuildTree.cpp:47
Defines enum values for all the target-independent builtin functions.
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the C++ template declaration subclasses.
Defines the clang::Expr interface and subclasses for C++ expressions.
static const Expr * skipTemporaryBindingsNoOpCastsAndParens(const Expr *E)
Skip over any no-op casts and any temporary-binding expressions.
Definition Expr.cpp:3266
static bool IsDecompositionDeclRefExpr(const Expr *E)
Helper to determine wether E is a CXXConstructExpr constructing a DecompositionDecl.
Definition Expr.cpp:2595
static unsigned SizeOfCallExprInstance(Expr::StmtClass SC)
Definition Expr.cpp:1482
static void AssertResultStorageKind(ConstantResultStorageKind Kind)
Definition Expr.cpp:300
static void computeOverflowPatternExclusion(const ASTContext &Ctx, const BinaryOperator *E)
Compute and set the OverflowPatternExclusion bit based on whether the BinaryOperator expression match...
Definition Expr.cpp:5083
static std::optional< BinaryOperator * > getOverflowPatternBinOp(const BinaryOperator *E)
Certain overflow-dependent code patterns can have their integer overflow sanitization disabled.
Definition Expr.cpp:5037
TokenType getType() const
Returns the token's type, e.g.
Result
Implement __builtin_bit_cast and related operations.
Defines the clang::Preprocessor interface.
static QualType getUnderlyingType(const SubRegion *R)
static bool isRecordType(QualType T)
Defines the SourceManager interface.
static QualType getPointeeType(const MemRegion *R)
C Language Family Type Representation.
static const TypeInfo & getInfo(unsigned id)
Definition Types.cpp:44
a trap message and trap category.
void setValue(const ASTContext &C, const llvm::APInt &Val)
llvm::APInt getValue() const
uint64_t * pVal
Used to store the >64 bits integer value.
uint64_t VAL
Used to store the <= 64 bits integer value.
void setIntValue(const ASTContext &C, const llvm::APInt &Val)
Definition Expr.cpp:957
A non-discriminated union of a base, field, or array index.
Definition APValue.h:245
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:158
static APValue IndeterminateValue()
Definition APValue.h:508
@ Indeterminate
This object has an indeterminate value (C++ [basic.indet]).
Definition APValue.h:167
@ None
There is no such object (it's outside its lifetime).
Definition APValue.h:165
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:245
SourceManager & getSourceManager()
Definition ASTContext.h:917
const ConstantArrayType * getAsConstantArrayType(QualType T) const
static CanQualType getCanonicalType(QualType T)
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
CanQualType DependentTy
Builtin::Context & BuiltinInfo
Definition ASTContext.h:858
const LangOptions & getLangOpts() const
Qualifiers::GC getObjCGCAttrKind(QualType Ty) const
Return one of the GCNone, Weak or Strong Objective-C garbage collection attributes.
CanQualType CharTy
LangAS getDefaultOpenCLPointeeAddrSpace()
Returns default address space based on OpenCL version and enabled features.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
CanQualType VoidTy
void * Allocate(size_t Size, unsigned Align=8) const
Definition ASTContext.h:930
CanQualType UnsignedIntTy
llvm::APSInt MakeIntValue(uint64_t Value, QualType Type) const
Make an APSInt of the appropriate width and signedness for the given Value and integer Type.
StringLiteral * getPredefinedStringLiteralFromCache(StringRef Key) const
Return a string representing the human readable name for the specified function declaration or file n...
QualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
UnnamedGlobalConstantDecl * getUnnamedGlobalConstantDecl(QualType Ty, const APValue &Value) const
Return a declaration for a uniquified anonymous global constant corresponding to a given APValue.
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:975
void addDestruction(T *Ptr) const
If T isn't trivially destructible, calls AddDeallocation to register it for destruction.
CanQualType getCanonicalTagType(const TagDecl *TD) const
static bool hasSameUnqualifiedType(QualType T1, QualType T2)
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
const Stmt ** const_iterator
Definition ASTVector.h:86
QualType getElementType() const
Return the effective 'element' type of this array section.
Definition Expr.cpp:5470
Expr * getBase()
Get base of the array section.
Definition Expr.h:7351
static QualType getBaseOriginalType(const Expr *Base)
Return original type of the base expression for array section.
Definition Expr.cpp:5442
QualType getBaseType() const
Returns the effective 'type' of the base of this array section.
Definition Expr.cpp:5488
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition Expr.h:2769
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3820
QualType getElementType() const
Definition TypeBase.h:3832
static unsigned getNumSubExprs(AtomicOp Op)
Determine the number of arguments the specified atomic builtin should have.
Definition Expr.cpp:5318
QualType getValueType() const
Definition Expr.cpp:5435
Expr * getPtr() const
Definition Expr.h:7013
AtomicExpr(SourceLocation BLoc, ArrayRef< Expr * > args, QualType t, AtomicOp op, SourceLocation RP)
Definition Expr.cpp:5308
unsigned getNumSubExprs() const
Definition Expr.h:7055
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4086
Expr * getLHS() const
Definition Expr.h:4136
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given binary opcode.
Definition Expr.cpp:2217
StringRef getOpcodeStr() const
Definition Expr.h:4152
static bool isCommaOp(Opcode Opc)
Definition Expr.h:4189
SourceLocation getOperatorLoc() const
Definition Expr.h:4128
bool hasStoredFPFeatures() const
Definition Expr.h:4271
bool isCompoundAssignmentOp() const
Definition Expr.h:4230
Expr * getRHS() const
Definition Expr.h:4138
static unsigned sizeOfTrailingObjects(bool HasFPFeatures)
Return the size in bytes needed for the trailing objects.
Definition Expr.h:4337
static BinaryOperator * Create(const ASTContext &C, Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy, ExprValueKind VK, ExprObjectKind OK, SourceLocation opLoc, FPOptionsOverride FPFeatures)
Definition Expr.cpp:5144
static BinaryOperator * CreateEmpty(const ASTContext &C, bool hasFPFeatures)
Definition Expr.cpp:5136
static bool isAssignmentOp(Opcode Opc)
Definition Expr.h:4222
static bool isNullPointerArithmeticExtension(ASTContext &Ctx, Opcode Opc, const Expr *LHS, const Expr *RHS)
Return true if a binary operator using the specified opcode and operands would match the 'p = (i8*)nu...
Definition Expr.cpp:2242
Opcode getOpcode() const
Definition Expr.h:4131
void setStoredFPFeatures(FPOptionsOverride F)
Set FPFeatures in trailing storage, used only by Serialization.
Definition Expr.h:4288
static Opcode getOverloadedOpcode(OverloadedOperatorKind OO)
Retrieve the binary opcode that corresponds to the given overloaded operator.
Definition Expr.cpp:2179
BinaryOperator(const ASTContext &Ctx, Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy, ExprValueKind VK, ExprObjectKind OK, SourceLocation opLoc, FPOptionsOverride FPFeatures)
Build a binary operator, assuming that appropriate storage has been allocated for the trailing object...
Definition Expr.cpp:5099
BinaryOperatorKind Opcode
Definition Expr.h:4091
A binding in a decomposition declaration.
Definition DeclCXX.h:4215
A fixed int type of a specified bitwidth.
Definition TypeBase.h:8304
bool isUnsigned() const
Definition TypeBase.h:8314
SourceLocation getCaretLocation() const
Definition Expr.cpp:2577
BlockDecl * TheBlock
Definition Expr.h:6728
const Stmt * getBody() const
Definition Expr.cpp:2580
const FunctionProtoType * getFunctionType() const
getFunctionType - Return the underlying function type for this block.
Definition Expr.cpp:2571
Pointer to a block type.
Definition TypeBase.h:3653
bool isUnevaluated(unsigned ID) const
Returns true if this builtin does not perform the side-effects of its arguments.
Definition Builtins.h:305
CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style cast in C++ (C++ [expr....
Definition Expr.h:4017
static CStyleCastExpr * CreateEmpty(const ASTContext &Context, unsigned PathSize, bool HasFPFeatures)
Definition Expr.cpp:2159
static CStyleCastExpr * Create(const ASTContext &Context, QualType T, ExprValueKind VK, CastKind K, Expr *Op, const CXXCastPath *BasePath, FPOptionsOverride FPO, TypeSourceInfo *WrittenTy, SourceLocation L, SourceLocation R)
Definition Expr.cpp:2141
SourceLocation getLParenLoc() const
Definition Expr.h:4049
Represents a call to a CUDA kernel function.
Definition ExprCXX.h:239
Represents a base class of a C++ class.
Definition DeclCXX.h:146
Represents binding an expression to a temporary.
Definition ExprCXX.h:1498
CXXTemporary * getTemporary()
Definition ExprCXX.h:1516
Represents a call to a C++ constructor.
Definition ExprCXX.h:1553
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition ExprCXX.h:1696
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition ExprCXX.h:1616
unsigned getNumArgs() const
Return the number of arguments to the constructor call.
Definition ExprCXX.h:1693
Represents a C++ constructor within a class.
Definition DeclCXX.h:2642
A default argument (C++ [dcl.fct.default]).
Definition ExprCXX.h:1275
A use of a default initializer in a constructor or in aggregate initialization.
Definition ExprCXX.h:1382
Represents a C++ destructor within a class.
Definition DeclCXX.h:2907
A C++ dynamic_cast expression (C++ [expr.dynamic.cast]).
Definition ExprCXX.h:486
Represents an explicit C++ type conversion that uses "functional" notation (C++ [expr....
Definition ExprCXX.h:1836
Represents a call to a member function that may be written either with member call syntax (e....
Definition ExprCXX.h:184
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2150
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2293
A call to an overloaded operator written using operator syntax.
Definition ExprCXX.h:86
SourceLocation getOperatorLoc() const
Returns the location of the operator symbol in the expression.
Definition ExprCXX.h:157
OverloadedOperatorKind getOperator() const
Returns the kind of overloaded operator that this expression refers to.
Definition ExprCXX.h:116
SourceRange getSourceRange() const
Definition ExprCXX.h:169
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
Definition DeclCXX.h:1382
A C++ static_cast expression (C++ [expr.static.cast]).
Definition ExprCXX.h:441
const CXXDestructorDecl * getDestructor() const
Definition ExprCXX.h:1475
Represents the this expression in C++.
Definition ExprCXX.h:1159
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2991
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3195
bool hasStoredFPFeatures() const
Definition Expr.h:3150
std::optional< llvm::APInt > evaluateBytesReturnedByAllocSizeCall(const ASTContext &Ctx) const
Evaluates the total size in bytes allocated by calling a function decorated with alloc_size.
Definition Expr.cpp:3641
static unsigned sizeOfTrailingObjects(unsigned NumPreArgs, unsigned NumArgs, bool HasFPFeatures)
Return the size in bytes needed for the trailing objects.
Definition Expr.h:3074
void setArg(unsigned Arg, Expr *ArgExpr)
setArg - Set the specified argument.
Definition Expr.h:3208
static CallExpr * Create(const ASTContext &Ctx, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation RParenLoc, FPOptionsOverride FPFeatures, unsigned MinNumArgs=0, ADLCallKind UsesADL=NotADL)
Create a call expression.
Definition Expr.cpp:1549
const AllocSizeAttr * getCalleeAllocSizeAttr() const
Try to get the alloc_size attribute of the callee. May return null.
Definition Expr.cpp:3632
unsigned getBuiltinCallee() const
getBuiltinCallee - If this is a call to a builtin, return the builtin ID of the callee.
Definition Expr.cpp:1624
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3174
static CallExpr * CreateEmpty(const ASTContext &Ctx, unsigned NumArgs, bool HasFPFeatures, EmptyShell Empty)
Create an empty call expression, for deserialization.
Definition Expr.cpp:1567
bool isCallToStdMove() const
Definition Expr.cpp:3682
void setPreArg(unsigned I, Stmt *PreArg)
Definition Expr.h:3088
Expr * getCallee()
Definition Expr.h:3138
static constexpr unsigned OffsetToTrailingObjects
Definition Expr.h:3028
void computeDependence()
Compute and set dependence bits.
Definition Expr.h:3214
void setStoredFPFeatures(FPOptionsOverride F)
Set FPOptionsOverride in trailing storage. Used only by Serialization.
Definition Expr.h:3272
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition Expr.h:3182
CallExpr(StmtClass SC, Expr *Fn, ArrayRef< Expr * > PreArgs, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation RParenLoc, FPOptionsOverride FPFeatures, unsigned MinNumArgs, ADLCallKind UsesADL)
Build a call expression, assuming that appropriate storage has been allocated for the trailing object...
Definition Expr.cpp:1505
static constexpr unsigned sizeToAllocateForCallExprSubclass(unsigned SizeOfTrailingObjects)
Definition Expr.h:3031
static constexpr ADLCallKind UsesADL
Definition Expr.h:3058
bool isBuiltinAssumeFalse(const ASTContext &Ctx) const
Return true if this is a call to __assume() or __builtin_assume() with a non-value-dependent constant...
Definition Expr.cpp:3620
Decl * getCalleeDecl()
Definition Expr.h:3168
QualType getCallReturnType(const ASTContext &Ctx) const
getCallReturnType - Get the return type of the call expr.
Definition Expr.cpp:1635
bool isUnevaluatedBuiltinCall(const ASTContext &Ctx) const
Returns true if this is a call to a builtin which does not evaluate side-effects within its arguments...
Definition Expr.cpp:1629
void setCallee(Expr *F)
Definition Expr.h:3140
unsigned getNumPreArgs() const
Definition Expr.h:3093
bool hasUnusedResultAttr(const ASTContext &Ctx) const
Returns true if this call expression should warn on unused results.
Definition Expr.h:3318
QualType withConst() const
Retrieves a version of this type with const applied.
bool isVolatileQualified() const
Represents the body of a CapturedStmt, and serves as its DeclContext.
Definition Decl.h:5086
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition Expr.h:3724
FPOptionsOverride * getTrailingFPFeatures()
Return a pointer to the trailing FPOptions.
Definition Expr.cpp:2089
NamedDecl * getConversionFunction() const
If this cast applies a user-defined conversion, retrieve the conversion function that it invokes.
Definition Expr.cpp:2038
Expr * getSubExprAsWritten()
Retrieve the cast subexpression as it was written in the source code, looking through any implicit ca...
Definition Expr.cpp:2016
CastKind getCastKind() const
Definition Expr.h:3768
bool hasStoredFPFeatures() const
Definition Expr.h:3823
static const FieldDecl * getTargetFieldForToUnionCast(QualType unionType, QualType opType)
Definition Expr.cpp:2070
CastExpr(StmtClass SC, QualType ty, ExprValueKind VK, const CastKind kind, Expr *op, unsigned BasePathSize, bool HasFPFeatures)
Definition Expr.h:3737
const char * getCastKindName() const
Definition Expr.h:3772
bool path_empty() const
Definition Expr.h:3792
Expr * getSubExpr()
Definition Expr.h:3774
SourceLocation getEnd() const
static CharUnits Zero()
Construct a CharUnits quantity of zero.
Definition CharUnits.h:52
void setValue(unsigned Val)
Definition Expr.h:1659
static void print(unsigned val, CharacterLiteralKind Kind, raw_ostream &OS)
Definition Expr.cpp:1030
ChooseExpr - GNU builtin-in function __builtin_choose_expr.
Definition Expr.h:4896
Represents a class template specialization, which refers to a class template with a given set of temp...
CompoundAssignOperator - For compound assignments (e.g.
Definition Expr.h:4348
static CompoundAssignOperator * CreateEmpty(const ASTContext &C, bool hasFPFeatures)
Definition Expr.cpp:5158
static CompoundAssignOperator * Create(const ASTContext &C, Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy, ExprValueKind VK, ExprObjectKind OK, SourceLocation opLoc, FPOptionsOverride FPFeatures, QualType CompLHSType=QualType(), QualType CompResultType=QualType())
Definition Expr.cpp:5166
CompoundLiteralExpr - [C99 6.5.2.5].
Definition Expr.h:3653
bool hasStaticStorage() const
Definition Expr.h:3698
APValue & getStaticValue() const
Definition Expr.cpp:5751
APValue & getOrCreateStaticValue(ASTContext &Ctx) const
Definition Expr.cpp:5742
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition Stmt.h:1752
bool body_empty() const
Definition Stmt.h:1796
Stmt * body_back()
Definition Stmt.h:1820
ConditionalOperator - The ?
Definition Expr.h:4439
ConstEvaluatedExprVisitor - This class visits 'const Expr *'s.
ConstStmtVisitor - This class implements a simple visitor for Stmt subclasses.
APValue getAPValueResult() const
Definition Expr.cpp:419
static ConstantResultStorageKind getStorageKind(const APValue &Value)
Definition Expr.cpp:308
void MoveIntoResult(APValue &Value, const ASTContext &Context)
Definition Expr.cpp:384
llvm::APSInt getResultAsAPSInt() const
Definition Expr.cpp:407
ConstantResultStorageKind getResultStorageKind() const
Definition Expr.h:1175
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition Expr.cpp:356
static ConstantExpr * CreateEmpty(const ASTContext &Context, ConstantResultStorageKind StorageKind)
Definition Expr.cpp:373
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4490
unsigned getNumElementsFlattened() const
Returns the number of elements required to embed the matrix into a vector.
Definition TypeBase.h:4517
unsigned getFlattenedIndex(unsigned Row, unsigned Column, bool IsRowMajor=false) const
Returns the flattened index of a matrix element located at row Row, and column Column.
Definition TypeBase.h:4537
static ConvertVectorExpr * Create(const ASTContext &C, Expr *SrcExpr, TypeSourceInfo *TI, QualType DstType, ExprValueKind VK, ExprObjectKind OK, SourceLocation BuiltinLoc, SourceLocation RParenLoc, FPOptionsOverride FPFeatures)
Definition Expr.cpp:5731
static ConvertVectorExpr * CreateEmpty(const ASTContext &C, bool hasFPFeatures)
Definition Expr.cpp:5724
A POD class for pairing a NamedDecl* with an access specifier.
NamedDecl * getDecl() const
AccessSpecifier getAccess() const
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1466
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2120
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1294
bool hasExplicitTemplateArgs() const
Determines whether this declaration reference was followed by an explicit template argument list.
Definition Expr.h:1449
void setDecl(ValueDecl *NewD)
Definition Expr.cpp:554
static DeclRefExpr * CreateEmpty(const ASTContext &Context, bool HasQualifier, bool HasFoundDecl, bool HasTemplateKWAndArgsInfo, unsigned NumTemplateArgs)
Construct an empty declaration reference expression.
Definition Expr.cpp:539
DeclarationNameInfo getNameInfo() const
Definition Expr.h:1366
static DeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *D, bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc, QualType T, ExprValueKind VK, NamedDecl *FoundD=nullptr, const TemplateArgumentListInfo *TemplateArgs=nullptr, NonOdrUseReason NOUR=NOUR_None)
Definition Expr.cpp:498
ValueDecl * getDecl()
Definition Expr.h:1362
SourceLocation getEndLoc() const LLVM_READONLY
Definition Expr.cpp:561
SourceLocation getRAngleLoc() const
Retrieve the location of the right angle bracket ending the explicit template argument list following...
Definition Expr.h:1437
decl_range decls()
Definition Stmt.h:1691
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
static bool isFlexibleArrayMemberLike(const ASTContext &Context, const Decl *D, QualType Ty, LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel, bool IgnoreTemplateOrMacroSubstitution)
Whether it resembles a flexible array member.
Definition DeclBase.cpp:463
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:550
static Decl * castFromDeclContext(const DeclContext *)
DeclContext * getDeclContext()
Definition DeclBase.h:456
AccessSpecifier getAccess() const
Definition DeclBase.h:515
bool hasAttr() const
Definition DeclBase.h:585
DeclarationNameLoc - Additional source/type location info for a declaration name.
Represents a single C99 designator.
Definition Expr.h:5648
SourceRange getSourceRange() const LLVM_READONLY
Definition Expr.h:5820
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:5810
struct FieldDesignatorInfo FieldInfo
A field designator, e.g., ".x".
Definition Expr.h:5710
FieldDecl * getFieldDecl() const
Definition Expr.h:5739
SourceLocation getFieldLoc() const
Definition Expr.h:5756
const IdentifierInfo * getFieldName() const
Definition Expr.cpp:4835
SourceLocation getDotLoc() const
Definition Expr.h:5751
static DesignatedInitExpr * CreateEmpty(const ASTContext &C, unsigned NumIndexExprs)
Definition Expr.cpp:4889
Expr * getArrayRangeEnd(const Designator &D) const
Definition Expr.cpp:4944
Expr * getSubExpr(unsigned Idx) const
Definition Expr.h:5887
SourceRange getDesignatorsSourceRange() const
Definition Expr.cpp:4905
Expr * getArrayRangeStart(const Designator &D) const
Definition Expr.cpp:4939
void ExpandDesignator(const ASTContext &C, unsigned Idx, const Designator *First, const Designator *Last)
Replaces the designator at index Idx with the series of designators in [First, Last).
Definition Expr.cpp:4951
Expr * getArrayIndex(const Designator &D) const
Definition Expr.cpp:4934
Designator * getDesignator(unsigned Idx)
Definition Expr.h:5846
Expr * getInit() const
Retrieve the initializer value.
Definition Expr.h:5873
unsigned size() const
Returns the number of designators in this initializer.
Definition Expr.h:5835
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.cpp:4913
void setDesignators(const ASTContext &C, const Designator *Desigs, unsigned NumDesigs)
Definition Expr.cpp:4896
SourceLocation getEndLoc() const LLVM_READONLY
Definition Expr.cpp:4930
static DesignatedInitExpr * Create(const ASTContext &C, ArrayRef< Designator > Designators, ArrayRef< Expr * > IndexExprs, SourceLocation EqualOrColonLoc, bool GNUSyntax, Expr *Init)
Definition Expr.cpp:4876
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.cpp:4994
DesignatedInitUpdateExpr(const ASTContext &C, SourceLocation lBraceLoc, Expr *baseExprs, SourceLocation rBraceLoc)
Definition Expr.cpp:4977
SourceLocation getEndLoc() const LLVM_READONLY
Definition Expr.cpp:4998
InitListExpr * getUpdater() const
Definition Expr.h:5990
EmbedExpr(const ASTContext &Ctx, SourceLocation Loc, EmbedDataStorage *Data, unsigned Begin, unsigned NumOfElements)
Definition Expr.cpp:2431
An instance of this object exists for each enum constant that is defined.
Definition Decl.h:3562
ExplicitCastExpr - An explicit cast written in the source code.
Definition Expr.h:3976
QualType getTypeAsWritten() const
getTypeAsWritten - Returns the type that this expression is casting to, as written in the source code...
Definition Expr.h:4003
Represents an expression – generally a full-expression – that introduces cleanups to be run at the en...
Definition ExprCXX.h:3715
bool isPRValue() const
Definition Expr.h:394
This represents one expression.
Definition Expr.h:113
@ LV_MemberFunction
Definition Expr.h:298
bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer,...
EnumConstantDecl * getEnumConstantDecl()
If this expression refers to an enum constant, retrieve its declaration.
Definition Expr.cpp:4325
bool isReadIfDiscardedInCPlusPlus11() const
Determine whether an lvalue-to-rvalue conversion should implicitly be applied to this expression if i...
Definition Expr.cpp:2604
bool isIntegerConstantExpr(const ASTContext &Ctx) const
bool isGLValue() const
Definition Expr.h:288
Expr * IgnoreParenNoopCasts(const ASTContext &Ctx) LLVM_READONLY
Skip past any parentheses and casts which do not change the value (including ptr->int casts of the sa...
Definition Expr.cpp:3156
@ SE_AllowSideEffects
Allow any unmodeled side effect.
Definition Expr.h:695
@ SE_AllowUndefinedBehavior
Allow UB that we can give a value, but not arbitrary unmodeled side effects.
Definition Expr.h:693
static QualType findBoundMemberType(const Expr *expr)
Given an expression of bound-member type, find the type of the member.
Definition Expr.cpp:3085
static std::pair< const NamedDecl *, const WarnUnusedResultAttr * > getUnusedResultAttrImpl(const Decl *Callee, QualType ReturnType)
Returns the WarnUnusedResultAttr that is declared on the callee or its return type declaration,...
Definition Expr.cpp:1671
bool isImplicitCXXThis() const
Whether this expression is an implicit reference to 'this' in C++.
Definition Expr.cpp:3334
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition Expr.cpp:3134
void setType(QualType t)
Definition Expr.h:146
bool isUnusedResultAWarning(const Expr *&WarnExpr, SourceLocation &Loc, SourceRange &R1, SourceRange &R2, ASTContext &Ctx) const
isUnusedResultAWarning - Return true if this immediate expression should be warned about if the resul...
Definition Expr.cpp:2670
LValueClassification ClassifyLValue(ASTContext &Ctx) const
Reasons why an expression might not be an l-value.
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:178
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition Expr.h:448
bool refersToVectorElement() const
Returns whether this expression refers to a vector element.
Definition Expr.cpp:4332
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:195
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
Expr * IgnoreParenLValueCasts() LLVM_READONLY
Skip past any parentheses and lvalue casts which might surround this expression until reaching a fixe...
Definition Expr.cpp:3146
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Returns the set of floating point options that apply to this expression.
Definition Expr.cpp:4031
const CXXRecordDecl * getBestDynamicClassType() const
For an expression of class type or pointer to class type, return the most derived class decl the expr...
Definition Expr.cpp:70
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3129
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3117
Expr * IgnoreConversionOperatorSingleStep() LLVM_READONLY
Skip conversion operators.
Definition Expr.cpp:3138
bool containsErrors() const
Whether this expression contains subexpressions which had errors.
Definition Expr.h:247
bool isObjCSelfExpr() const
Check if this expression is the ObjC 'self' implicit parameter.
Definition Expr.cpp:4253
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3125
bool isFlexibleArrayMemberLike(const ASTContext &Context, LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel, bool IgnoreTemplateOrMacroSubstitution=false) const
Check whether this array fits the idiom of a flexible array member, depending on the value of -fstric...
Definition Expr.cpp:212
bool EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsLValue - Evaluate an expression to see if we can fold it to an lvalue with link time known ...
bool isEvaluatable(const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects) const
isEvaluatable - Call EvaluateAsRValue to see if this expression can be constant folded without side-e...
Expr * IgnoreParenBaseCasts() LLVM_READONLY
Skip past any parentheses and derived-to-base casts until reaching a fixed point.
Definition Expr.cpp:3151
bool isConstantInitializer(ASTContext &Ctx, bool ForRef=false, const Expr **Culprit=nullptr) const
Returns true if this expression can be emitted to IR as a constant, and thus can be used as a constan...
Definition Expr.cpp:3386
bool isPRValue() const
Definition Expr.h:286
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition Expr.h:285
static bool hasAnyTypeDependentArguments(ArrayRef< Expr * > Exprs)
hasAnyTypeDependentArguments - Determines if any of the expressions in Exprs is type-dependent.
Definition Expr.cpp:3378
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
Definition Expr.cpp:4271
NullPointerConstantValueDependence
Enumeration used to describe how isNullPointerConstant() should cope with value-dependent expressions...
Definition Expr.h:849
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition Expr.h:855
@ NPC_NeverValueDependent
Specifies that the expression should never be value-dependent.
Definition Expr.h:851
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition Expr.h:859
Expr * IgnoreUnlessSpelledInSource()
Skip past any invisible AST nodes which might surround this statement, such as ExprWithCleanups or Im...
Definition Expr.cpp:3182
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition Expr.h:455
Expr * IgnoreCasts() LLVM_READONLY
Skip past any casts which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3113
Decl * getReferencedDeclOfCallee()
Definition Expr.cpp:1578
Expr * IgnoreImplicitAsWritten() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3121
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
HasSideEffects - This routine returns true for all those expressions which have any effect other than...
Definition Expr.cpp:3728
bool EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx, ConstantExprKind Kind=ConstantExprKind::Normal) const
Evaluate an expression that is required to be a constant expression.
const Expr * getBestDynamicClassTypeExpr() const
Get the inner expression that determines the best dynamic class.
Definition Expr.cpp:45
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3109
NullPointerConstantKind
Enumeration used to describe the kind of Null pointer constant returned from isNullPointerConstant().
Definition Expr.h:826
@ NPCK_ZeroExpression
Expression is a Null pointer constant built from a zero integer expression that is not a simple,...
Definition Expr.h:835
@ NPCK_ZeroLiteral
Expression is a Null pointer constant built from a literal zero.
Definition Expr.h:838
@ NPCK_CXX11_nullptr
Expression is a C++11 nullptr.
Definition Expr.h:841
@ NPCK_GNUNull
Expression is a GNU-style __null constant.
Definition Expr.h:844
@ NPCK_NotNull
Expression is not a Null pointer constant.
Definition Expr.h:828
bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsBooleanCondition - Return true if this is a constant which we can fold and convert to a boo...
bool isTemporaryObject(ASTContext &Ctx, const CXXRecordDecl *TempTy) const
Determine whether the result of this expression is a temporary object of the given class type.
Definition Expr.cpp:3292
NullPointerConstantKind isNullPointerConstant(ASTContext &Ctx, NullPointerConstantValueDependence NPC) const
isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to a Null pointer constant.
Definition Expr.cpp:4110
QualType getEnumCoercedType(const ASTContext &Ctx) const
If this expression is an enumeration constant, return the enumeration type under which said constant ...
Definition Expr.cpp:272
bool isBoundMemberFunction(ASTContext &Ctx) const
Returns true if this expression is a bound member function.
Definition Expr.cpp:3079
Expr()=delete
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:283
static bool isSameComparisonOperand(const Expr *E1, const Expr *E2)
Checks that the two Expr's will refer to the same value as a comparison operand.
Definition Expr.cpp:4369
bool isDefaultArgument() const
Determine whether this expression is a default function argument.
Definition Expr.cpp:3253
Classification Classify(ASTContext &Ctx) const
Classify - Classify this expression according to the C++11 expression taxonomy.
Definition Expr.h:416
QualType getType() const
Definition Expr.h:145
bool hasNonTrivialCall(const ASTContext &Ctx) const
Determine whether this expression involves a call to any function that is not trivial.
Definition Expr.cpp:4098
bool refersToGlobalRegisterVar() const
Returns whether this expression refers to a global register variable.
Definition Expr.cpp:4357
bool isCXX98IntegralConstantExpr(const ASTContext &Ctx) const
isCXX98IntegralConstantExpr - Return true if this expression is an integral constant expression in C+...
const ValueDecl * getAsBuiltinConstantDeclRef(const ASTContext &Context) const
If this expression is an unambiguous reference to a single declaration, in the style of __builtin_fun...
Definition Expr.cpp:232
bool isOBJCGCCandidate(ASTContext &Ctx) const
isOBJCGCCandidate - Return true if this expression may be used in a read/ write barrier.
Definition Expr.cpp:3040
static ExprValueKind getValueKindForType(QualType T)
getValueKindForType - Given a formal return or parameter type, give its value kind.
Definition Expr.h:438
const Expr * skipRValueSubobjectAdjustments() const
Definition Expr.h:1044
bool isKnownToHaveBooleanValue(bool Semantic=true) const
isKnownToHaveBooleanValue - Return true if this is an integer expression that is known to return 0 or...
Definition Expr.cpp:138
void setDependence(ExprDependence Deps)
Each concrete expr subclass is expected to compute its dependence and call this in the constructor.
Definition Expr.h:138
const ObjCPropertyRefExpr * getObjCProperty() const
If this expression is an l-value for an Objective C property, find the underlying property reference ...
Definition Expr.cpp:4234
bool containsDuplicateElements() const
containsDuplicateElements - Return true if any element access is repeated.
Definition Expr.cpp:4503
bool isArrow() const
isArrow - Return true if the base expression is a pointer to vector, return false if the base express...
Definition Expr.cpp:4485
void getEncodedElementAccess(SmallVectorImpl< uint32_t > &Elts) const
getEncodedElementAccess - Encode the elements accessed into an llvm aggregate Constant of ConstantInt...
Definition Expr.cpp:4598
unsigned getNumElements() const
getNumElements - Get the number of components being selected.
Definition Expr.cpp:4489
static int getAccessorIdx(char c, bool isNumericAccessor)
Definition TypeBase.h:4411
Represents difference between two FPOptions values.
bool requiresTrailingStorage() const
static FPOptions defaultWithoutTrailingStorage(const LangOptions &LO)
Return the default value of FPOptions that's used when trailing storage isn't required.
Represents a member of a struct/union/class.
Definition Decl.h:3299
Expr * getInClassInitializer() const
Get the C++11 default member initializer for this member, or null if one has not been set.
Definition Decl.cpp:4798
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3402
static FixedPointLiteral * Create(const ASTContext &C, EmptyShell Empty)
Returns an empty fixed-point literal.
Definition Expr.cpp:1015
std::string getValueAsString(unsigned Radix) const
Definition Expr.cpp:1020
llvm::APInt getValue() const
Returns an internal integer representation of the literal.
Definition Expr.h:1599
static FixedPointLiteral * CreateFromRawInt(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l, unsigned Scale)
Definition Expr.cpp:1007
static FloatingLiteral * Create(const ASTContext &C, const llvm::APFloat &V, bool isexact, QualType Type, SourceLocation L)
Definition Expr.cpp:1086
double getValueAsApproximateDouble() const
getValueAsApproximateDouble - This returns the value as an inaccurate double.
Definition Expr.cpp:1099
llvm::APFloat getValue() const
Definition Expr.h:1690
FullExpr - Represents a "full-expression" node.
Definition Expr.h:1073
Represents a function declaration or definition.
Definition Decl.h:2059
FunctionDecl * getTemplateInstantiationPattern(bool ForDefinition=true) const
Retrieve the function declaration from which this function could be instantiated, if it is an instant...
Definition Decl.cpp:4311
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition Decl.h:2504
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5416
Provides information about a function template specialization, which is a FunctionDecl that has been ...
TemplateArgumentList * TemplateArguments
The template arguments used to produce the function template specialization from the function templat...
FunctionTemplateDecl * getTemplate() const
Retrieve the template from which this function was specialized.
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4612
CallingConv getCallConv() const
Definition TypeBase.h:4967
QualType getReturnType() const
Definition TypeBase.h:4952
Represents a C11 generic selection.
Definition Expr.h:6236
static GenericSelectionExpr * Create(const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr, ArrayRef< TypeSourceInfo * > AssocTypes, ArrayRef< Expr * > AssocExprs, SourceLocation DefaultLoc, SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack, unsigned ResultIndex)
Create a non-result-dependent generic selection expression accepting an expression predicate.
Definition Expr.cpp:4765
static GenericSelectionExpr * CreateEmpty(const ASTContext &Context, unsigned NumAssocs)
Create an empty generic selection expression for deserialization.
Definition Expr.cpp:4823
GlobalDecl - represents a global declaration.
Definition GlobalDecl.h:60
static HLSLOutArgExpr * CreateEmpty(const ASTContext &Ctx)
Definition Expr.cpp:5710
static HLSLOutArgExpr * Create(const ASTContext &C, QualType Ty, OpaqueValueExpr *Base, OpaqueValueExpr *OpV, Expr *WB, bool IsInOut)
Definition Expr.cpp:5703
One of these records is kept for each identifier that is lexed.
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition Expr.h:3901
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition Expr.cpp:2109
static ImplicitCastExpr * CreateEmpty(const ASTContext &Context, unsigned PathSize, bool HasFPFeatures)
Definition Expr.cpp:2132
Describes an C or C++ initializer list.
Definition Expr.h:5356
bool hasArrayFiller() const
Return true if this is an array initializer and its array "filler" has been set.
Definition Expr.h:5469
bool isTransparent() const
Is this a transparent initializer list (that is, an InitListExpr that is purely syntactic,...
Definition Expr.cpp:2501
void resizeInits(const ASTContext &Context, unsigned NumInits)
Specify the number of initializers.
Definition Expr.cpp:2461
bool isStringLiteralInit() const
Is this an initializer for an array of characters, initialized by a string literal or an @encode?
Definition Expr.cpp:2487
FieldDecl * getInitializedFieldInUnion()
If this initializes a union, specifies which field in the union to initialize.
Definition Expr.h:5483
unsigned getNumInits() const
Definition Expr.h:5389
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.cpp:2535
bool isSemanticForm() const
Definition Expr.h:5519
void setInit(unsigned Init, Expr *expr)
Definition Expr.h:5421
Expr * updateInit(const ASTContext &C, unsigned Init, Expr *expr)
Updates the initializer at index Init with the new expression expr, and returns the old expression at...
Definition Expr.cpp:2465
void setArrayFiller(Expr *filler)
Definition Expr.cpp:2477
InitListExpr * getSyntacticForm() const
Definition Expr.h:5526
bool isExplicit() const
Definition Expr.h:5499
InitListExpr(const ASTContext &C, SourceLocation lbraceloc, ArrayRef< Expr * > initExprs, SourceLocation rbraceloc, bool isExplicit)
Definition Expr.cpp:2443
const Expr * getInit(unsigned Init) const
Definition Expr.h:5411
bool isIdiomaticZeroInitializer(const LangOptions &LangOpts) const
Is this the zero initializer {0} in a language which considers it idiomatic?
Definition Expr.cpp:2524
SourceLocation getEndLoc() const LLVM_READONLY
Definition Expr.cpp:2553
bool isSyntacticForm() const
Definition Expr.h:5523
ArrayRef< Expr * > inits() const
Definition Expr.h:5409
void sawArrayRangeDesignator(bool ARD=true)
Definition Expr.h:5540
Expr ** getInits()
Retrieve the set of initializers.
Definition Expr.h:5402
void reserveInits(const ASTContext &C, unsigned NumInits)
Reserve space for some number of initializers.
Definition Expr.cpp:2456
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition Expr.cpp:985
static ItaniumMangleContext * create(ASTContext &Context, DiagnosticsEngine &Diags, bool IsAux=false)
LabelStmt - Represents a label, which has a substatement.
Definition Stmt.h:2158
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition ExprCXX.h:1973
@ AddUnsignedOverflowTest
if (a + b < a)
@ AddSignedOverflowTest
if (a + b < a)
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
bool isOverflowPatternExcluded(OverflowPatternExclusionKind Kind) const
void remapPathPrefix(SmallVectorImpl< char > &Path) const
Remap path prefix according to -fmacro-prefix-path option.
Lexer - This provides a simple interface that turns a text buffer into a stream of tokens.
Definition Lexer.h:79
bool LexFromRawLexer(Token &Result)
LexFromRawLexer - Lex a token from a designated raw lexer (one with no associated preprocessor object...
Definition Lexer.h:236
static SourceLocation AdvanceToTokenCharacter(SourceLocation TokStart, unsigned Characters, const SourceManager &SM, const LangOptions &LangOpts)
AdvanceToTokenCharacter - If the current SourceLocation specifies a location at the start of a token,...
Definition Lexer.h:409
Represents a prvalue temporary that is written into memory so that a reference can bind to it.
Definition ExprCXX.h:4974
bool containsDuplicateElements() const
containsDuplicateElements - Return true if any element access is repeated.
Definition Expr.cpp:4579
void getEncodedElementAccess(SmallVectorImpl< uint32_t > &Elts) const
getEncodedElementAccess - Encode the elements accessed into an llvm aggregate Constant of ConstantInt...
Definition Expr.cpp:4630
unsigned getNumElements() const
getNumElements - Get the number of components being selected.
Definition Expr.cpp:4495
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3412
static MemberExpr * CreateEmpty(const ASTContext &Context, bool HasQualifier, bool HasFoundDecl, bool HasTemplateKWAndArgsInfo, unsigned NumTemplateArgs)
Definition Expr.cpp:1808
void setMemberDecl(ValueDecl *D)
Definition Expr.cpp:1823
NestedNameSpecifierLoc getQualifierLoc() const
If the member name was qualified, retrieves the nested-name-specifier that precedes the member name,...
Definition Expr.h:3514
bool hasExplicitTemplateArgs() const
Determines whether the member name was followed by an explicit template argument list.
Definition Expr.h:3556
bool hasQualifier() const
Determines whether this member expression actually had a C++ nested-name-specifier prior to the name ...
Definition Expr.h:3509
static MemberExpr * Create(const ASTContext &C, Expr *Base, bool IsArrow, SourceLocation OperatorLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *MemberDecl, DeclAccessPair FoundDecl, DeclarationNameInfo MemberNameInfo, const TemplateArgumentListInfo *TemplateArgs, QualType T, ExprValueKind VK, ExprObjectKind OK, NonOdrUseReason NOUR)
Definition Expr.cpp:1786
bool isImplicitAccess() const
Determine whether the base of this explicit is implicit.
Definition Expr.h:3610
Expr * getBase() const
Definition Expr.h:3489
SourceLocation getRAngleLoc() const
Retrieve the location of the right angle bracket ending the explicit template argument list following...
Definition Expr.h:3545
SourceLocation getEndLoc() const LLVM_READONLY
Definition Expr.cpp:1844
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.cpp:1830
DeclarationNameInfo getMemberNameInfo() const
Retrieve the member declaration name info.
Definition Expr.h:3589
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3751
This represents a decl that may have a name.
Definition Decl.h:275
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:296
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:302
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:341
A C++ nested-name-specifier augmented with source location information.
SourceLocation getBeginLoc() const
Retrieve the location of the beginning of this nested-name-specifier.
bool hasQualifier() const
Evaluates true when this nested-name-specifier location is non-empty.
An explicit cast in C or a C-style cast in C++, which uses the syntax ([s1][s2]......
Definition ExprOpenMP.h:24
static OMPArrayShapingExpr * CreateEmpty(const ASTContext &Context, unsigned NumDims)
Definition Expr.cpp:5564
static OMPArrayShapingExpr * Create(const ASTContext &Context, QualType T, Expr *Op, SourceLocation L, SourceLocation R, ArrayRef< Expr * > Dims, ArrayRef< SourceRange > BracketRanges)
Definition Expr.cpp:5550
OpenMP 5.0 [2.1.6 Iterators] Iterators are identifiers that expand to multiple values in the clause o...
Definition ExprOpenMP.h:151
static OMPIteratorExpr * Create(const ASTContext &Context, QualType T, SourceLocation IteratorKwLoc, SourceLocation L, SourceLocation R, ArrayRef< IteratorDefinition > Data, ArrayRef< OMPIteratorHelperData > Helpers)
Definition Expr.cpp:5677
static OMPIteratorExpr * CreateEmpty(const ASTContext &Context, unsigned NumIterators)
Definition Expr.cpp:5693
SourceLocation getSecondColonLoc(unsigned I) const
Gets the location of the second ':' (if any) in the range for the given iteratori definition.
Definition Expr.cpp:5640
SourceLocation getColonLoc(unsigned I) const
Gets the location of the first ':' in the range for the given iterator definition.
Definition Expr.cpp:5634
IteratorRange getIteratorRange(unsigned I)
Gets the iterator range for the given iterator.
Definition Expr.cpp:5611
OMPIteratorHelperData & getHelper(unsigned I)
Fetches helper data for the specified iteration space.
Definition Expr.cpp:5650
SourceLocation getAssignLoc(unsigned I) const
Gets the location of '=' for the given iterator definition.
Definition Expr.cpp:5628
Decl * getIteratorDecl(unsigned I)
Gets the iterator declaration for the given iterator.
Definition Expr.cpp:5607
ObjCArrayLiteral - used for objective-c array containers; as in: @["Hello", NSApp,...
Definition ExprObjC.h:219
ObjCBoxedExpr - used for generalized expression boxing.
Definition ExprObjC.h:158
ObjCCategoryImplDecl - An object of this class encapsulates a category @implementation declaration.
Definition DeclObjC.h:2551
ObjCDictionaryLiteral - AST node to represent objective-c dictionary literals; as in:"name" : NSUserN...
Definition ExprObjC.h:341
Represents an ObjC class declaration.
Definition DeclObjC.h:1160
ObjCIvarRefExpr - A reference to an ObjC instance variable.
Definition ExprObjC.h:581
An expression that sends a message to the given Objective-C object or class.
Definition ExprObjC.h:972
ObjCMethodFamily getMethodFamily() const
Definition ExprObjC.h:1415
bool isInstanceMessage() const
Determine whether this is an instance message to either a computed object or to super.
Definition ExprObjC.h:1288
bool hasUnusedResultAttr(ASTContext &Ctx) const
Returns true if this message send should warn on unused results.
Definition ExprObjC.h:1279
ObjCMethodDecl - Represents an instance or class method declaration.
Definition DeclObjC.h:140
ImplicitParamDecl * getSelfDecl() const
Definition DeclObjC.h:421
bool isExpressibleAsConstantInitializer() const
Definition ExprObjC.h:67
ObjCPropertyRefExpr - A dot-syntax expression to access an ObjC property.
Definition ExprObjC.h:649
static OffsetOfExpr * CreateEmpty(const ASTContext &C, unsigned NumComps, unsigned NumExprs)
Definition Expr.cpp:1703
static OffsetOfExpr * Create(const ASTContext &C, QualType type, SourceLocation OperatorLoc, TypeSourceInfo *tsi, ArrayRef< OffsetOfNode > comps, ArrayRef< Expr * > exprs, SourceLocation RParenLoc)
Definition Expr.cpp:1690
void setIndexExpr(unsigned Idx, Expr *E)
Definition Expr.h:2642
void setComponent(unsigned Idx, OffsetOfNode ON)
Definition Expr.h:2626
const IdentifierInfo * getFieldName() const
For a field or identifier offsetof node, returns the name of the field.
Definition Expr.cpp:1725
FieldDecl * getField() const
For a field offsetof node, returns the field.
Definition Expr.h:2533
@ Identifier
A field in a dependent type, known only by its name.
Definition Expr.h:2478
@ Field
A field.
Definition Expr.h:2476
Kind getKind() const
Determine what kind of offsetof node this is.
Definition Expr.h:2523
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition Expr.h:1202
static const OpaqueValueExpr * findInCopyConstruct(const Expr *expr)
Given an expression which invokes a copy constructor — i.e.
Definition Expr.cpp:5213
OpaqueValueExpr(SourceLocation Loc, QualType T, ExprValueKind VK, ExprObjectKind OK=OK_Ordinary, Expr *SourceExpr=nullptr)
Definition Expr.h:1207
This expression type represents an asterisk in an OpenACC Size-Expr, used in the 'tile' and 'gang' cl...
Definition Expr.h:2138
static OpenACCAsteriskSizeExpr * Create(const ASTContext &C, SourceLocation Loc)
Definition Expr.cpp:5714
static OpenACCAsteriskSizeExpr * CreateEmpty(const ASTContext &C)
Definition Expr.cpp:5720
ParenExpr - This represents a parenthesized expression, e.g.
Definition Expr.h:2230
const Expr * getSubExpr() const
Definition Expr.h:2247
static ParenListExpr * CreateEmpty(const ASTContext &Ctx, unsigned NumExprs)
Create an empty paren list.
Definition Expr.cpp:5025
static ParenListExpr * Create(const ASTContext &Ctx, SourceLocation LParenLoc, ArrayRef< Expr * > Exprs, SourceLocation RParenLoc)
Create a paren list.
Definition Expr.cpp:5016
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3403
QualType getPointeeType() const
Definition TypeBase.h:3413
static PredefinedExpr * Create(const ASTContext &Ctx, SourceLocation L, QualType FNTy, PredefinedIdentKind IK, bool IsTransparent, StringLiteral *SL)
Create a PredefinedExpr.
Definition Expr.cpp:643
StringRef getIdentKindName() const
Definition Expr.h:2110
static PredefinedExpr * CreateEmpty(const ASTContext &Ctx, bool HasFunctionName)
Create an empty PredefinedExpr.
Definition Expr.cpp:652
static std::string ComputeName(PredefinedIdentKind IK, const Decl *CurrentDecl, bool ForceElaboratedPrinting=false)
Definition Expr.cpp:683
static void processPathToFileName(SmallVectorImpl< char > &FileName, const PresumedLoc &PLoc, const LangOptions &LangOpts, const TargetInfo &TI)
static void processPathForFileMacro(SmallVectorImpl< char > &Path, const LangOptions &LangOpts, const TargetInfo &TI)
Represents an unpacked "presumed" location which can be presented to the user.
unsigned getColumn() const
Return the presumed column number of this location.
const char * getFilename() const
Return the presumed filename of this location.
unsigned getLine() const
Return the presumed line number of this location.
Callbacks to use to customize the behavior of the pretty-printer.
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition Expr.h:6858
semantics_iterator semantics_end()
Definition Expr.h:6923
semantics_iterator semantics_begin()
Definition Expr.h:6919
const Expr *const * const_semantics_iterator
Definition Expr.h:6918
static PseudoObjectExpr * Create(const ASTContext &Context, Expr *syntactic, ArrayRef< Expr * > semantic, unsigned resultIndex)
Definition Expr.cpp:5238
ArrayRef< Expr * > semantics()
Definition Expr.h:6930
A (possibly-)qualified type.
Definition TypeBase.h:938
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8530
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1005
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8572
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8486
void getAsStringInternal(std::string &Str, const PrintingPolicy &Policy) const
QualType getCanonicalType() const
Definition TypeBase.h:8498
The collection of all-type qualifiers we support.
Definition TypeBase.h:332
void removeAddressSpace()
Definition TypeBase.h:597
bool empty() const
Definition TypeBase.h:648
Represents a struct/union/class.
Definition Decl.h:4464
field_iterator field_end() const
Definition Decl.h:4670
field_range fields() const
Definition Decl.h:4667
specific_decl_iterator< FieldDecl > field_iterator
Definition Decl.h:4664
field_iterator field_begin() const
Definition Decl.cpp:5354
static RecoveryExpr * Create(ASTContext &Ctx, QualType T, SourceLocation BeginLoc, SourceLocation EndLoc, ArrayRef< Expr * > SubExprs)
Definition Expr.cpp:5510
static RecoveryExpr * CreateEmpty(ASTContext &Ctx, unsigned NumSubExprs)
Definition Expr.cpp:5519
TypeSourceInfo * getTypeSourceInfo()
Definition Expr.h:2191
static SYCLUniqueStableNameExpr * Create(const ASTContext &Ctx, SourceLocation OpLoc, SourceLocation LParen, SourceLocation RParen, TypeSourceInfo *TSI)
Definition Expr.cpp:583
std::string ComputeName(ASTContext &Context) const
Definition Expr.cpp:597
static SYCLUniqueStableNameExpr * CreateEmpty(const ASTContext &Ctx)
Definition Expr.cpp:592
void setExprs(const ASTContext &C, ArrayRef< Expr * > Exprs)
Definition Expr.cpp:4653
ShuffleVectorExpr(const ASTContext &C, ArrayRef< Expr * > args, QualType Type, SourceLocation BLoc, SourceLocation RP)
Definition Expr.cpp:4640
APValue EvaluateInContext(const ASTContext &Ctx, const Expr *DefaultExpr) const
Return the result of evaluating this SourceLocExpr in the specified (and possibly null) default argum...
Definition Expr.cpp:2319
SourceLocExpr(const ASTContext &Ctx, SourceLocIdentKind Type, QualType ResultTy, SourceLocation BLoc, SourceLocation RParenLoc, DeclContext *Context)
Definition Expr.cpp:2286
SourceLocation getLocation() const
Definition Expr.h:5118
const DeclContext * getParentContext() const
If the SourceLocExpr has been resolved return the subexpression representing the resolved value.
Definition Expr.h:5115
StringRef getBuiltinStr() const
Return a string representing the name of the specific builtin function.
Definition Expr.cpp:2299
static bool MayBeDependent(SourceLocIdentKind Kind)
Definition Expr.h:5134
SourceLocIdentKind getIdentKind() const
Definition Expr.h:5094
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
This class handles loading and caching of source files into memory.
FileIDAndOffset getDecomposedLoc(SourceLocation Loc) const
Decompose the specified location into a raw FileID + Offset pair.
PresumedLoc getPresumedLoc(SourceLocation Loc, bool UseLineDirectives=true) const
Returns the "presumed" location of a SourceLocation specifies.
StringRef getBufferData(FileID FID, bool *Invalid=nullptr) const
Return a StringRef to the source buffer data for the specified FileID.
SourceLocation getSpellingLoc(SourceLocation Loc) const
Given a SourceLocation object, return the spelling location referenced by the ID.
CharSourceRange getExpansionRange(SourceLocation Loc) const
Given a SourceLocation object, return the range of tokens covered by the expansion in the ultimate fi...
SourceLocation getLocForStartOfFile(FileID FID) const
Return the source location corresponding to the first byte of the specified file.
A trivial tuple used to represent a source range.
StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
Definition Expr.h:4643
Stmt - This represents one statement.
Definition Stmt.h:85
SourceLocation getEndLoc() const LLVM_READONLY
Definition Stmt.cpp:367
@ NoStmtClass
Definition Stmt.h:88
UnaryExprOrTypeTraitExprBitfields UnaryExprOrTypeTraitExprBits
Definition Stmt.h:1363
GenericSelectionExprBitfields GenericSelectionExprBits
Definition Stmt.h:1371
InitListExprBitfields InitListExprBits
Definition Stmt.h:1369
ParenListExprBitfields ParenListExprBits
Definition Stmt.h:1370
StmtIterator child_iterator
Child Iterators: All subclasses must implement 'children' to permit easy iteration over the substatem...
Definition Stmt.h:1591
CallExprBitfields CallExprBits
Definition Stmt.h:1365
ShuffleVectorExprBitfields ShuffleVectorExprBits
Definition Stmt.h:1375
FloatingLiteralBitfields FloatingLiteralBits
Definition Stmt.h:1359
child_iterator child_begin()
Definition Stmt.h:1603
StmtClass getStmtClass() const
Definition Stmt.h:1505
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
UnaryOperatorBitfields UnaryOperatorBits
Definition Stmt.h:1362
SourceLocExprBitfields SourceLocExprBits
Definition Stmt.h:1373
ConstantExprBitfields ConstantExprBits
Definition Stmt.h:1356
llvm::iterator_range< child_iterator > child_range
Definition Stmt.h:1594
StringLiteralBitfields StringLiteralBits
Definition Stmt.h:1360
MemberExprBitfields MemberExprBits
Definition Stmt.h:1366
DeclRefExprBitfields DeclRefExprBits
Definition Stmt.h:1358
ConstStmtIterator const_child_iterator
Definition Stmt.h:1592
PredefinedExprBitfields PredefinedExprBits
Definition Stmt.h:1357
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:355
BinaryOperatorBitfields BinaryOperatorBits
Definition Stmt.h:1368
PseudoObjectExprBitfields PseudoObjectExprBits
Definition Stmt.h:1372
llvm::iterator_range< const_child_iterator > const_child_range
Definition Stmt.h:1595
StringLiteralParser - This decodes string escape characters and performs wide string analysis and Tra...
unsigned getOffsetOfStringByte(const Token &TheTok, unsigned ByteNo) const
getOffsetOfStringByte - This function returns the offset of the specified byte of the string data rep...
unsigned GetStringLength() const
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1823
UnsignedOrNone findZeroCodeUnit(unsigned StartIndex=0) const
Scan the string literal contents for a code unit with value 0.
Definition Expr.cpp:1414
SourceLocation getStrTokenLoc(unsigned TokNum) const
Get one of the string literal token.
Definition Expr.h:1994
unsigned getLength() const
Definition Expr.h:1948
uint32_t getCodeUnit(size_t I) const
Return the code unit at the given position.
Definition Expr.h:1910
StringLiteralKind getKind() const
Definition Expr.h:1952
static StringLiteral * Create(const ASTContext &Ctx, StringRef Str, StringLiteralKind Kind, bool Pascal, QualType Ty, ArrayRef< SourceLocation > Locs)
This is the "fully general" constructor that allows representation of strings formed from one or more...
Definition Expr.cpp:1198
SourceLocation getLocationOfByte(unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, const TargetInfo &Target, unsigned *StartToken=nullptr, unsigned *StartTokenByteOffset=nullptr) const
Return a source location that points to the specified byte of this string literal.
Definition Expr.cpp:1336
void outputString(raw_ostream &OS) const
Prints the contents of the string to OS.
Definition Expr.cpp:1219
StringRef getString() const
Definition Expr.h:1891
static StringLiteral * CreateEmpty(const ASTContext &Ctx, unsigned NumConcatenated, unsigned Length, unsigned CharByteWidth)
Construct an empty string literal.
Definition Expr.cpp:1208
unsigned getNumConcatenated() const
Get the number of string literal tokens that were concatenated in translation phase #6 to form this s...
Definition Expr.h:1989
unsigned getCharByteWidth() const
Definition Expr.h:1950
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3856
Exposes information about the current target.
Definition TargetInfo.h:228
A convenient class for passing around template argument information.
ArrayRef< TemplateArgumentLoc > arguments() const
A template argument list.
unsigned size() const
Retrieve the number of template arguments in this template argument list.
const TemplateArgument & get(unsigned Idx) const
Retrieve the template argument at a given index.
Location wrapper for a TemplateArgument.
void print(const PrintingPolicy &Policy, raw_ostream &Out, bool IncludeType) const
Print this template argument to the given output stream.
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Stores a list of template parameters for a TemplateDecl and its derived classes.
NamedDecl * getParam(unsigned Idx)
static bool shouldIncludeTypeForArgument(const PrintingPolicy &Policy, const TemplateParameterList *TPL, unsigned Idx)
Token - This structure provides full information about a lexed token.
Definition Token.h:36
A container of type source information.
Definition TypeBase.h:8417
The base class of the type hierarchy.
Definition TypeBase.h:1879
bool isVoidType() const
Definition TypeBase.h:9068
bool isBooleanType() const
Definition TypeBase.h:9209
bool hasAttr(attr::Kind AK) const
Determine whether this type had the specified attribute applied to it (looking through top-level type...
Definition Type.cpp:2122
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2392
const ArrayType * castAsArrayTypeUnsafe() const
A variant of castAs<> for array type which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9375
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
bool isArrayType() const
Definition TypeBase.h:8782
bool isCharType() const
Definition Type.cpp:2319
CXXRecordDecl * castAsCXXRecordDecl() const
Definition Type.h:36
bool isPointerType() const
Definition TypeBase.h:8683
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9116
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9366
bool isSpecificPlaceholderType(unsigned K) const
Test for a specific placeholder type.
Definition TypeBase.h:9057
bool isReferenceType() const
Definition TypeBase.h:8707
const CXXRecordDecl * getPointeeCXXRecordDecl() const
If this is a pointer or reference to a RecordType, return the CXXRecordDecl that the type refers to.
Definition Type.cpp:2080
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition Type.cpp:2282
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:885
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9194
TagDecl * getAsTagDecl() const
Retrieves the TagDecl that this type refers to, either because the type is a TagType or because it is...
Definition Type.h:63
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition TypeBase.h:2871
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2863
RecordDecl * castAsRecordDecl() const
Definition Type.h:48
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9352
bool isFunctionType() const
Definition TypeBase.h:8679
bool isUnsignedIntegerType() const
Return true if this is an integer type that is unsigned, according to C99 6.2.5p6 [which returns true...
Definition Type.cpp:2460
bool isAnyPointerType() const
Definition TypeBase.h:8691
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9299
bool isRecordType() const
Definition TypeBase.h:8810
QualType desugar() const
Definition Type.cpp:4377
QualType getArgumentType() const
Definition Expr.h:2716
UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, TypeSourceInfo *TInfo, QualType resultType, SourceLocation op, SourceLocation rp)
Definition Expr.h:2681
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2292
SourceLocation getOperatorLoc() const
getOperatorLoc - Return the location of the operator.
Definition Expr.h:2337
Expr * getSubExpr() const
Definition Expr.h:2333
Opcode getOpcode() const
Definition Expr.h:2328
bool hasStoredFPFeatures() const
Is FPFeatures in Trailing Storage?
Definition Expr.h:2429
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given unary opcode.
Definition Expr.cpp:1462
static UnaryOperator * Create(const ASTContext &C, Expr *input, Opcode opc, QualType type, ExprValueKind VK, ExprObjectKind OK, SourceLocation l, bool CanOverflow, FPOptionsOverride FPFeatures)
Definition Expr.cpp:5201
static Opcode getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix)
Retrieve the unary opcode that corresponds to the given overloaded operator.
Definition Expr.cpp:1447
void setStoredFPFeatures(FPOptionsOverride F)
Set FPFeatures in trailing storage, used by Serialization & ASTImporter.
Definition Expr.h:2443
UnaryOperatorKind Opcode
Definition Expr.h:2306
UnaryOperator(const ASTContext &Ctx, Expr *input, Opcode opc, QualType type, ExprValueKind VK, ExprObjectKind OK, SourceLocation l, bool CanOverflow, FPOptionsOverride FPFeatures)
Definition Expr.cpp:5187
static UnaryOperator * CreateEmpty(const ASTContext &C, bool hasFPFeatures)
Definition Expr.cpp:5180
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition Expr.cpp:1438
An artificial decl, representing a global anonymous constant value which is uniquified by value withi...
Definition DeclCXX.h:4508
A call to a literal operator (C++11 [over.literal]) written as a user-defined literal (C++11 [lit....
Definition ExprCXX.h:645
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:713
QualType getType() const
Definition Decl.h:724
Represents a statement that could possibly have a value and type.
Definition Stmt.h:2139
Stmt(StmtClass SC, EmptyShell)
Construct an empty statement.
Definition Stmt.h:1487
Kind getKind() const
Definition Value.h:137
Represents a variable declaration or definition.
Definition Decl.h:933
Represents a C array with a specified size that is not an integer-constant-expression.
Definition TypeBase.h:4064
Represents a GCC generic vector type.
Definition TypeBase.h:4273
Defines the clang::TargetInfo interface.
Definition SPIR.cpp:47
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
bool Comp(InterpState &S)
1) Pops the value from the stack.
Definition Interp.h:1183
Top level wrappers for InstallAPI frontend operations.
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
@ OO_None
Not an overloaded operator.
ConstantResultStorageKind
Describes the kind of result that can be tail-allocated.
Definition Expr.h:1100
@ Ctor_Base
Base object ctor.
Definition ABI.h:26
bool isa(CodeGen::Address addr)
Definition Address.h:330
LLVM_READONLY bool isPrintable(unsigned char c)
Return true if this character is an ASCII printable character; that is, a character that should take ...
Definition CharInfo.h:160
const Expr * findStructFieldAccess(const Expr *E, const Expr **OutArrayIndex=nullptr, QualType *OutArrayElementTy=nullptr)
Walk E through parens, implicit casts, unary &/*, array subscripts and comma operators to find the he...
Definition Expr.cpp:5807
LLVM_READONLY auto escapeCStyle(CharT Ch) -> StringRef
Return C-style escaped string for special characters, or an empty string if there is no such mapping.
Definition CharInfo.h:191
Expr * IgnoreExprNodes(Expr *E, FnTys &&... Fns)
Given an expression E and functions Fn_1,...,Fn_n : Expr * -> Expr *, Recursively apply each of the f...
Definition IgnoreExpr.h:24
RefQualifierKind
The kind of C++11 ref-qualifier associated with a function type.
Definition TypeBase.h:1799
@ RQ_LValue
An lvalue ref-qualifier was provided (&).
Definition TypeBase.h:1804
@ RQ_RValue
An rvalue ref-qualifier was provided (&&).
Definition TypeBase.h:1807
StmtIterator cast_away_const(const ConstStmtIterator &RHS)
ExprObjectKind
A further classification of the kind of object referenced by an l-value or x-value.
Definition Specifiers.h:153
@ OK_ObjCProperty
An Objective-C property is a logical field of an Objective-C object which is read and written via Obj...
Definition Specifiers.h:165
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition Specifiers.h:155
std::pair< FileID, unsigned > FileIDAndOffset
ExprDependence computeDependence(FullExpr *E)
@ Create
'create' clause, allowed on Compute and Combined constructs, plus 'data', 'enter data',...
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
@ SC_Register
Definition Specifiers.h:261
Expr * IgnoreImplicitCastsExtraSingleStep(Expr *E)
Definition IgnoreExpr.h:48
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition ASTLambda.h:28
@ Result
The result type of a method or function.
Definition TypeBase.h:906
OptionalUnsigned< unsigned > UnsignedOrNone
const FunctionProtoType * T
Expr * IgnoreImplicitCastsSingleStep(Expr *E)
Definition IgnoreExpr.h:38
@ Dtor_Base
Base object dtor.
Definition ABI.h:37
CastKind
CastKind - The kind of operation required for a conversion.
void FixedPointValueToString(SmallVectorImpl< char > &Str, llvm::APSInt Val, unsigned Scale)
Definition Type.cpp:5854
Expr * IgnoreImplicitSingleStep(Expr *E)
Definition IgnoreExpr.h:101
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition Specifiers.h:136
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:139
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition Specifiers.h:143
Expr * IgnoreParensSingleStep(Expr *E)
Definition IgnoreExpr.h:157
SmallVector< CXXBaseSpecifier *, 4 > CXXCastPath
A simple array of base specifiers.
Definition ASTContext.h:147
Expr * IgnoreImplicitAsWrittenSingleStep(Expr *E)
Definition IgnoreExpr.h:144
Expr * IgnoreCastsSingleStep(Expr *E)
Definition IgnoreExpr.h:65
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition DeclBase.h:1305
child_range children()
StringLiteralKind
Definition Expr.h:1787
@ Full
Match, but we didn't check for full match.
@ CC_X86ThisCall
Definition Specifiers.h:286
@ CC_X86RegCall
Definition Specifiers.h:291
@ CC_X86VectorCall
Definition Specifiers.h:287
@ CC_X86StdCall
Definition Specifiers.h:284
@ CC_X86FastCall
Definition Specifiers.h:285
U cast(CodeGen::Address addr)
Definition Address.h:327
SourceLocIdentKind
Definition Expr.h:5061
Expr * IgnoreLValueCastsSingleStep(Expr *E)
Definition IgnoreExpr.h:81
bool isLambdaMethod(const DeclContext *DC)
Definition ASTLambda.h:39
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
Expr * IgnoreParensOnlySingleStep(Expr *E)
Definition IgnoreExpr.h:151
PredefinedIdentKind
Definition Expr.h:2037
@ PrettyFunctionNoVirtual
The same as PrettyFunction, except that the 'virtual' keyword is omitted for virtual member functions...
Definition Expr.h:2047
CharacterLiteralKind
Definition Expr.h:1627
Expr * IgnoreBaseCastsSingleStep(Expr *E)
Definition IgnoreExpr.h:91
NonOdrUseReason
The reason why a DeclRefExpr does not constitute an odr-use.
Definition Specifiers.h:177
__UINTPTR_TYPE__ uintptr_t
An unsigned integer type with the property that any valid pointer to void can be converted to this ty...
#define false
Definition stdbool.h:26
#define true
Definition stdbool.h:25
Represents an explicit template argument list in C++, e.g., the "<int>" in "sort<int>".
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
SourceLocation getLoc() const
getLoc - Returns the main location of the declaration name.
DeclarationName getName() const
getName - Returns the embedded declaration name.
SourceLocation getEndLoc() const LLVM_READONLY
Stores data related to a single embed directive.
Definition Expr.h:5150
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:666
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:668
Iterator range representation begin:end[:step].
Definition ExprOpenMP.h:154
Helper expressions and declaration for OMPIteratorExpr class for each iteration space.
Definition ExprOpenMP.h:111
Describes how types, statements, expressions, and declarations should be printed.
unsigned SuppressTagKeyword
Whether type printing should skip printing the tag keyword.
const PrintingCallbacks * Callbacks
Callbacks to use to allow the behavior of printing to be customized.
A placeholder type used to construct an empty shell of a type, that will be filled in later (e....
Definition Stmt.h:1445
An adjustment to be made to the temporary created when emitting a reference binding,...
Definition Expr.h:69