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