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