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