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