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