[clang][modules] Don't prevent translation of FW_Private includes when explicitly...
[llvm-project.git] / clang / lib / AST / Expr.cpp
blob5d3b510df1ef9b3c8bb7c58163f52ca211640b38
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.
11 //===----------------------------------------------------------------------===//
13 #include "clang/AST/Expr.h"
14 #include "clang/AST/APValue.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/Attr.h"
17 #include "clang/AST/ComputeDependence.h"
18 #include "clang/AST/DeclCXX.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/DeclTemplate.h"
21 #include "clang/AST/DependenceFlags.h"
22 #include "clang/AST/EvaluatedExprVisitor.h"
23 #include "clang/AST/ExprCXX.h"
24 #include "clang/AST/IgnoreExpr.h"
25 #include "clang/AST/Mangle.h"
26 #include "clang/AST/RecordLayout.h"
27 #include "clang/AST/StmtVisitor.h"
28 #include "clang/Basic/Builtins.h"
29 #include "clang/Basic/CharInfo.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Lex/Lexer.h"
33 #include "clang/Lex/LiteralSupport.h"
34 #include "clang/Lex/Preprocessor.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/Format.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include <algorithm>
39 #include <cstring>
40 #include <optional>
41 using namespace clang;
43 const Expr *Expr::getBestDynamicClassTypeExpr() const {
44 const Expr *E = this;
45 while (true) {
46 E = E->IgnoreParenBaseCasts();
48 // Follow the RHS of a comma operator.
49 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
50 if (BO->getOpcode() == BO_Comma) {
51 E = BO->getRHS();
52 continue;
56 // Step into initializer for materialized temporaries.
57 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
58 E = MTE->getSubExpr();
59 continue;
62 break;
65 return E;
68 const CXXRecordDecl *Expr::getBestDynamicClassType() const {
69 const Expr *E = getBestDynamicClassTypeExpr();
70 QualType DerivedType = E->getType();
71 if (const PointerType *PTy = DerivedType->getAs<PointerType>())
72 DerivedType = PTy->getPointeeType();
74 if (DerivedType->isDependentType())
75 return nullptr;
77 const RecordType *Ty = DerivedType->castAs<RecordType>();
78 Decl *D = Ty->getDecl();
79 return cast<CXXRecordDecl>(D);
82 const Expr *Expr::skipRValueSubobjectAdjustments(
83 SmallVectorImpl<const Expr *> &CommaLHSs,
84 SmallVectorImpl<SubobjectAdjustment> &Adjustments) const {
85 const Expr *E = this;
86 while (true) {
87 E = E->IgnoreParens();
89 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
90 if ((CE->getCastKind() == CK_DerivedToBase ||
91 CE->getCastKind() == CK_UncheckedDerivedToBase) &&
92 E->getType()->isRecordType()) {
93 E = CE->getSubExpr();
94 auto *Derived =
95 cast<CXXRecordDecl>(E->getType()->castAs<RecordType>()->getDecl());
96 Adjustments.push_back(SubobjectAdjustment(CE, Derived));
97 continue;
100 if (CE->getCastKind() == CK_NoOp) {
101 E = CE->getSubExpr();
102 continue;
104 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
105 if (!ME->isArrow()) {
106 assert(ME->getBase()->getType()->isRecordType());
107 if (FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
108 if (!Field->isBitField() && !Field->getType()->isReferenceType()) {
109 E = ME->getBase();
110 Adjustments.push_back(SubobjectAdjustment(Field));
111 continue;
115 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
116 if (BO->getOpcode() == BO_PtrMemD) {
117 assert(BO->getRHS()->isPRValue());
118 E = BO->getLHS();
119 const MemberPointerType *MPT =
120 BO->getRHS()->getType()->getAs<MemberPointerType>();
121 Adjustments.push_back(SubobjectAdjustment(MPT, BO->getRHS()));
122 continue;
124 if (BO->getOpcode() == BO_Comma) {
125 CommaLHSs.push_back(BO->getLHS());
126 E = BO->getRHS();
127 continue;
131 // Nothing changed.
132 break;
134 return E;
137 bool Expr::isKnownToHaveBooleanValue(bool Semantic) const {
138 const Expr *E = IgnoreParens();
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;
145 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(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;
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>(E))
160 return CE->getSubExpr()->isKnownToHaveBooleanValue(Semantic);
162 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(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;
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);
182 case BO_Comma:
183 case BO_Assign:
184 return BO->getRHS()->isKnownToHaveBooleanValue(Semantic);
188 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
189 return CO->getTrueExpr()->isKnownToHaveBooleanValue(Semantic) &&
190 CO->getFalseExpr()->isKnownToHaveBooleanValue(Semantic);
192 if (isa<ObjCBoolLiteralExpr>(E))
193 return true;
195 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
196 return OVE->getSourceExpr()->isKnownToHaveBooleanValue(Semantic);
198 if (const FieldDecl *FD = E->getSourceBitField())
199 if (!Semantic && FD->getType()->isUnsignedIntegerType() &&
200 !FD->getBitWidth()->isValueDependent() &&
201 FD->getBitWidthValue(FD->getASTContext()) == 1)
202 return true;
204 return false;
207 bool Expr::isFlexibleArrayMemberLike(
208 ASTContext &Ctx,
209 LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel,
210 bool IgnoreTemplateOrMacroSubstitution) const {
211 const Expr *E = IgnoreParens();
212 const Decl *D = nullptr;
214 if (const auto *ME = dyn_cast<MemberExpr>(E))
215 D = ME->getMemberDecl();
216 else if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
217 D = DRE->getDecl();
218 else if (const auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
219 D = IRE->getDecl();
221 return Decl::isFlexibleArrayMemberLike(Ctx, D, E->getType(),
222 StrictFlexArraysLevel,
223 IgnoreTemplateOrMacroSubstitution);
226 const ValueDecl *
227 Expr::getAsBuiltinConstantDeclRef(const ASTContext &Context) const {
228 Expr::EvalResult Eval;
230 if (EvaluateAsConstantExpr(Eval, Context)) {
231 APValue &Value = Eval.Val;
233 if (Value.isMemberPointer())
234 return Value.getMemberPointerDecl();
236 if (Value.isLValue() && Value.getLValueOffset().isZero())
237 return Value.getLValueBase().dyn_cast<const ValueDecl *>();
240 return nullptr;
243 // Amusing macro metaprogramming hack: check whether a class provides
244 // a more specific implementation of getExprLoc().
246 // See also Stmt.cpp:{getBeginLoc(),getEndLoc()}.
247 namespace {
248 /// This implementation is used when a class provides a custom
249 /// implementation of getExprLoc.
250 template <class E, class T>
251 SourceLocation getExprLocImpl(const Expr *expr,
252 SourceLocation (T::*v)() const) {
253 return static_cast<const E*>(expr)->getExprLoc();
256 /// This implementation is used when a class doesn't provide
257 /// a custom implementation of getExprLoc. Overload resolution
258 /// should pick it over the implementation above because it's
259 /// more specialized according to function template partial ordering.
260 template <class E>
261 SourceLocation getExprLocImpl(const Expr *expr,
262 SourceLocation (Expr::*v)() const) {
263 return static_cast<const E *>(expr)->getBeginLoc();
267 SourceLocation Expr::getExprLoc() const {
268 switch (getStmtClass()) {
269 case Stmt::NoStmtClass: llvm_unreachable("statement without class");
270 #define ABSTRACT_STMT(type)
271 #define STMT(type, base) \
272 case Stmt::type##Class: break;
273 #define EXPR(type, base) \
274 case Stmt::type##Class: return getExprLocImpl<type>(this, &type::getExprLoc);
275 #include "clang/AST/StmtNodes.inc"
277 llvm_unreachable("unknown expression kind");
280 //===----------------------------------------------------------------------===//
281 // Primary Expressions.
282 //===----------------------------------------------------------------------===//
284 static void AssertResultStorageKind(ConstantExpr::ResultStorageKind Kind) {
285 assert((Kind == ConstantExpr::RSK_APValue ||
286 Kind == ConstantExpr::RSK_Int64 || Kind == ConstantExpr::RSK_None) &&
287 "Invalid StorageKind Value");
288 (void)Kind;
291 ConstantExpr::ResultStorageKind
292 ConstantExpr::getStorageKind(const APValue &Value) {
293 switch (Value.getKind()) {
294 case APValue::None:
295 case APValue::Indeterminate:
296 return ConstantExpr::RSK_None;
297 case APValue::Int:
298 if (!Value.getInt().needsCleanup())
299 return ConstantExpr::RSK_Int64;
300 [[fallthrough]];
301 default:
302 return ConstantExpr::RSK_APValue;
306 ConstantExpr::ResultStorageKind
307 ConstantExpr::getStorageKind(const Type *T, const ASTContext &Context) {
308 if (T->isIntegralOrEnumerationType() && Context.getTypeInfo(T).Width <= 64)
309 return ConstantExpr::RSK_Int64;
310 return ConstantExpr::RSK_APValue;
313 ConstantExpr::ConstantExpr(Expr *SubExpr, ResultStorageKind StorageKind,
314 bool IsImmediateInvocation)
315 : FullExpr(ConstantExprClass, SubExpr) {
316 ConstantExprBits.ResultKind = StorageKind;
317 ConstantExprBits.APValueKind = APValue::None;
318 ConstantExprBits.IsUnsigned = false;
319 ConstantExprBits.BitWidth = 0;
320 ConstantExprBits.HasCleanup = false;
321 ConstantExprBits.IsImmediateInvocation = IsImmediateInvocation;
323 if (StorageKind == ConstantExpr::RSK_APValue)
324 ::new (getTrailingObjects<APValue>()) APValue();
327 ConstantExpr *ConstantExpr::Create(const ASTContext &Context, Expr *E,
328 ResultStorageKind StorageKind,
329 bool IsImmediateInvocation) {
330 assert(!isa<ConstantExpr>(E));
331 AssertResultStorageKind(StorageKind);
333 unsigned Size = totalSizeToAlloc<APValue, uint64_t>(
334 StorageKind == ConstantExpr::RSK_APValue,
335 StorageKind == ConstantExpr::RSK_Int64);
336 void *Mem = Context.Allocate(Size, alignof(ConstantExpr));
337 return new (Mem) ConstantExpr(E, StorageKind, IsImmediateInvocation);
340 ConstantExpr *ConstantExpr::Create(const ASTContext &Context, Expr *E,
341 const APValue &Result) {
342 ResultStorageKind StorageKind = getStorageKind(Result);
343 ConstantExpr *Self = Create(Context, E, StorageKind);
344 Self->SetResult(Result, Context);
345 return Self;
348 ConstantExpr::ConstantExpr(EmptyShell Empty, ResultStorageKind StorageKind)
349 : FullExpr(ConstantExprClass, Empty) {
350 ConstantExprBits.ResultKind = StorageKind;
352 if (StorageKind == ConstantExpr::RSK_APValue)
353 ::new (getTrailingObjects<APValue>()) APValue();
356 ConstantExpr *ConstantExpr::CreateEmpty(const ASTContext &Context,
357 ResultStorageKind StorageKind) {
358 AssertResultStorageKind(StorageKind);
360 unsigned Size = totalSizeToAlloc<APValue, uint64_t>(
361 StorageKind == ConstantExpr::RSK_APValue,
362 StorageKind == ConstantExpr::RSK_Int64);
363 void *Mem = Context.Allocate(Size, alignof(ConstantExpr));
364 return new (Mem) ConstantExpr(EmptyShell(), StorageKind);
367 void ConstantExpr::MoveIntoResult(APValue &Value, const ASTContext &Context) {
368 assert((unsigned)getStorageKind(Value) <= ConstantExprBits.ResultKind &&
369 "Invalid storage for this value kind");
370 ConstantExprBits.APValueKind = Value.getKind();
371 switch (ConstantExprBits.ResultKind) {
372 case RSK_None:
373 return;
374 case RSK_Int64:
375 Int64Result() = *Value.getInt().getRawData();
376 ConstantExprBits.BitWidth = Value.getInt().getBitWidth();
377 ConstantExprBits.IsUnsigned = Value.getInt().isUnsigned();
378 return;
379 case RSK_APValue:
380 if (!ConstantExprBits.HasCleanup && Value.needsCleanup()) {
381 ConstantExprBits.HasCleanup = true;
382 Context.addDestruction(&APValueResult());
384 APValueResult() = std::move(Value);
385 return;
387 llvm_unreachable("Invalid ResultKind Bits");
390 llvm::APSInt ConstantExpr::getResultAsAPSInt() const {
391 switch (ConstantExprBits.ResultKind) {
392 case ConstantExpr::RSK_APValue:
393 return APValueResult().getInt();
394 case ConstantExpr::RSK_Int64:
395 return llvm::APSInt(llvm::APInt(ConstantExprBits.BitWidth, Int64Result()),
396 ConstantExprBits.IsUnsigned);
397 default:
398 llvm_unreachable("invalid Accessor");
402 APValue ConstantExpr::getAPValueResult() const {
404 switch (ConstantExprBits.ResultKind) {
405 case ConstantExpr::RSK_APValue:
406 return APValueResult();
407 case ConstantExpr::RSK_Int64:
408 return APValue(
409 llvm::APSInt(llvm::APInt(ConstantExprBits.BitWidth, Int64Result()),
410 ConstantExprBits.IsUnsigned));
411 case ConstantExpr::RSK_None:
412 if (ConstantExprBits.APValueKind == APValue::Indeterminate)
413 return APValue::IndeterminateValue();
414 return APValue();
416 llvm_unreachable("invalid ResultKind");
419 DeclRefExpr::DeclRefExpr(const ASTContext &Ctx, ValueDecl *D,
420 bool RefersToEnclosingVariableOrCapture, QualType T,
421 ExprValueKind VK, SourceLocation L,
422 const DeclarationNameLoc &LocInfo,
423 NonOdrUseReason NOUR)
424 : Expr(DeclRefExprClass, T, VK, OK_Ordinary), D(D), DNLoc(LocInfo) {
425 DeclRefExprBits.HasQualifier = false;
426 DeclRefExprBits.HasTemplateKWAndArgsInfo = false;
427 DeclRefExprBits.HasFoundDecl = false;
428 DeclRefExprBits.HadMultipleCandidates = false;
429 DeclRefExprBits.RefersToEnclosingVariableOrCapture =
430 RefersToEnclosingVariableOrCapture;
431 DeclRefExprBits.CapturedByCopyInLambdaWithExplicitObjectParameter = false;
432 DeclRefExprBits.NonOdrUseReason = NOUR;
433 DeclRefExprBits.IsImmediateEscalating = false;
434 DeclRefExprBits.Loc = L;
435 setDependence(computeDependence(this, Ctx));
438 DeclRefExpr::DeclRefExpr(const ASTContext &Ctx,
439 NestedNameSpecifierLoc QualifierLoc,
440 SourceLocation TemplateKWLoc, ValueDecl *D,
441 bool RefersToEnclosingVariableOrCapture,
442 const DeclarationNameInfo &NameInfo, NamedDecl *FoundD,
443 const TemplateArgumentListInfo *TemplateArgs,
444 QualType T, ExprValueKind VK, NonOdrUseReason NOUR)
445 : Expr(DeclRefExprClass, T, VK, OK_Ordinary), D(D),
446 DNLoc(NameInfo.getInfo()) {
447 DeclRefExprBits.Loc = NameInfo.getLoc();
448 DeclRefExprBits.HasQualifier = QualifierLoc ? 1 : 0;
449 if (QualifierLoc)
450 new (getTrailingObjects<NestedNameSpecifierLoc>())
451 NestedNameSpecifierLoc(QualifierLoc);
452 DeclRefExprBits.HasFoundDecl = FoundD ? 1 : 0;
453 if (FoundD)
454 *getTrailingObjects<NamedDecl *>() = FoundD;
455 DeclRefExprBits.HasTemplateKWAndArgsInfo
456 = (TemplateArgs || TemplateKWLoc.isValid()) ? 1 : 0;
457 DeclRefExprBits.RefersToEnclosingVariableOrCapture =
458 RefersToEnclosingVariableOrCapture;
459 DeclRefExprBits.CapturedByCopyInLambdaWithExplicitObjectParameter = false;
460 DeclRefExprBits.NonOdrUseReason = NOUR;
461 if (TemplateArgs) {
462 auto Deps = TemplateArgumentDependence::None;
463 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
464 TemplateKWLoc, *TemplateArgs, getTrailingObjects<TemplateArgumentLoc>(),
465 Deps);
466 assert(!(Deps & TemplateArgumentDependence::Dependent) &&
467 "built a DeclRefExpr with dependent template args");
468 } else if (TemplateKWLoc.isValid()) {
469 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
470 TemplateKWLoc);
472 DeclRefExprBits.IsImmediateEscalating = false;
473 DeclRefExprBits.HadMultipleCandidates = 0;
474 setDependence(computeDependence(this, Ctx));
477 DeclRefExpr *DeclRefExpr::Create(const ASTContext &Context,
478 NestedNameSpecifierLoc QualifierLoc,
479 SourceLocation TemplateKWLoc, ValueDecl *D,
480 bool RefersToEnclosingVariableOrCapture,
481 SourceLocation NameLoc, QualType T,
482 ExprValueKind VK, NamedDecl *FoundD,
483 const TemplateArgumentListInfo *TemplateArgs,
484 NonOdrUseReason NOUR) {
485 return Create(Context, QualifierLoc, TemplateKWLoc, D,
486 RefersToEnclosingVariableOrCapture,
487 DeclarationNameInfo(D->getDeclName(), NameLoc),
488 T, VK, FoundD, TemplateArgs, NOUR);
491 DeclRefExpr *DeclRefExpr::Create(const ASTContext &Context,
492 NestedNameSpecifierLoc QualifierLoc,
493 SourceLocation TemplateKWLoc, ValueDecl *D,
494 bool RefersToEnclosingVariableOrCapture,
495 const DeclarationNameInfo &NameInfo,
496 QualType T, ExprValueKind VK,
497 NamedDecl *FoundD,
498 const TemplateArgumentListInfo *TemplateArgs,
499 NonOdrUseReason NOUR) {
500 // Filter out cases where the found Decl is the same as the value refenenced.
501 if (D == FoundD)
502 FoundD = nullptr;
504 bool HasTemplateKWAndArgsInfo = TemplateArgs || TemplateKWLoc.isValid();
505 std::size_t Size =
506 totalSizeToAlloc<NestedNameSpecifierLoc, NamedDecl *,
507 ASTTemplateKWAndArgsInfo, TemplateArgumentLoc>(
508 QualifierLoc ? 1 : 0, FoundD ? 1 : 0,
509 HasTemplateKWAndArgsInfo ? 1 : 0,
510 TemplateArgs ? TemplateArgs->size() : 0);
512 void *Mem = Context.Allocate(Size, alignof(DeclRefExpr));
513 return new (Mem) DeclRefExpr(Context, QualifierLoc, TemplateKWLoc, D,
514 RefersToEnclosingVariableOrCapture, NameInfo,
515 FoundD, TemplateArgs, T, VK, NOUR);
518 DeclRefExpr *DeclRefExpr::CreateEmpty(const ASTContext &Context,
519 bool HasQualifier,
520 bool HasFoundDecl,
521 bool HasTemplateKWAndArgsInfo,
522 unsigned NumTemplateArgs) {
523 assert(NumTemplateArgs == 0 || HasTemplateKWAndArgsInfo);
524 std::size_t Size =
525 totalSizeToAlloc<NestedNameSpecifierLoc, NamedDecl *,
526 ASTTemplateKWAndArgsInfo, TemplateArgumentLoc>(
527 HasQualifier ? 1 : 0, HasFoundDecl ? 1 : 0, HasTemplateKWAndArgsInfo,
528 NumTemplateArgs);
529 void *Mem = Context.Allocate(Size, alignof(DeclRefExpr));
530 return new (Mem) DeclRefExpr(EmptyShell());
533 void DeclRefExpr::setDecl(ValueDecl *NewD) {
534 D = NewD;
535 if (getType()->isUndeducedType())
536 setType(NewD->getType());
537 setDependence(computeDependence(this, NewD->getASTContext()));
540 SourceLocation DeclRefExpr::getBeginLoc() const {
541 if (hasQualifier())
542 return getQualifierLoc().getBeginLoc();
543 return getNameInfo().getBeginLoc();
545 SourceLocation DeclRefExpr::getEndLoc() const {
546 if (hasExplicitTemplateArgs())
547 return getRAngleLoc();
548 return getNameInfo().getEndLoc();
551 SYCLUniqueStableNameExpr::SYCLUniqueStableNameExpr(SourceLocation OpLoc,
552 SourceLocation LParen,
553 SourceLocation RParen,
554 QualType ResultTy,
555 TypeSourceInfo *TSI)
556 : Expr(SYCLUniqueStableNameExprClass, ResultTy, VK_PRValue, OK_Ordinary),
557 OpLoc(OpLoc), LParen(LParen), RParen(RParen) {
558 setTypeSourceInfo(TSI);
559 setDependence(computeDependence(this));
562 SYCLUniqueStableNameExpr::SYCLUniqueStableNameExpr(EmptyShell Empty,
563 QualType ResultTy)
564 : Expr(SYCLUniqueStableNameExprClass, ResultTy, VK_PRValue, OK_Ordinary) {}
566 SYCLUniqueStableNameExpr *
567 SYCLUniqueStableNameExpr::Create(const ASTContext &Ctx, SourceLocation OpLoc,
568 SourceLocation LParen, SourceLocation RParen,
569 TypeSourceInfo *TSI) {
570 QualType ResultTy = Ctx.getPointerType(Ctx.CharTy.withConst());
571 return new (Ctx)
572 SYCLUniqueStableNameExpr(OpLoc, LParen, RParen, ResultTy, TSI);
575 SYCLUniqueStableNameExpr *
576 SYCLUniqueStableNameExpr::CreateEmpty(const ASTContext &Ctx) {
577 QualType ResultTy = Ctx.getPointerType(Ctx.CharTy.withConst());
578 return new (Ctx) SYCLUniqueStableNameExpr(EmptyShell(), ResultTy);
581 std::string SYCLUniqueStableNameExpr::ComputeName(ASTContext &Context) const {
582 return SYCLUniqueStableNameExpr::ComputeName(Context,
583 getTypeSourceInfo()->getType());
586 std::string SYCLUniqueStableNameExpr::ComputeName(ASTContext &Context,
587 QualType Ty) {
588 auto MangleCallback = [](ASTContext &Ctx,
589 const NamedDecl *ND) -> std::optional<unsigned> {
590 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND))
591 return RD->getDeviceLambdaManglingNumber();
592 return std::nullopt;
595 std::unique_ptr<MangleContext> Ctx{ItaniumMangleContext::create(
596 Context, Context.getDiagnostics(), MangleCallback)};
598 std::string Buffer;
599 Buffer.reserve(128);
600 llvm::raw_string_ostream Out(Buffer);
601 Ctx->mangleCanonicalTypeName(Ty, Out);
603 return Out.str();
606 PredefinedExpr::PredefinedExpr(SourceLocation L, QualType FNTy, IdentKind IK,
607 bool IsTransparent, StringLiteral *SL)
608 : Expr(PredefinedExprClass, FNTy, VK_LValue, OK_Ordinary) {
609 PredefinedExprBits.Kind = IK;
610 assert((getIdentKind() == IK) &&
611 "IdentKind do not fit in PredefinedExprBitfields!");
612 bool HasFunctionName = SL != nullptr;
613 PredefinedExprBits.HasFunctionName = HasFunctionName;
614 PredefinedExprBits.IsTransparent = IsTransparent;
615 PredefinedExprBits.Loc = L;
616 if (HasFunctionName)
617 setFunctionName(SL);
618 setDependence(computeDependence(this));
621 PredefinedExpr::PredefinedExpr(EmptyShell Empty, bool HasFunctionName)
622 : Expr(PredefinedExprClass, Empty) {
623 PredefinedExprBits.HasFunctionName = HasFunctionName;
626 PredefinedExpr *PredefinedExpr::Create(const ASTContext &Ctx, SourceLocation L,
627 QualType FNTy, IdentKind IK,
628 bool IsTransparent, StringLiteral *SL) {
629 bool HasFunctionName = SL != nullptr;
630 void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *>(HasFunctionName),
631 alignof(PredefinedExpr));
632 return new (Mem) PredefinedExpr(L, FNTy, IK, IsTransparent, SL);
635 PredefinedExpr *PredefinedExpr::CreateEmpty(const ASTContext &Ctx,
636 bool HasFunctionName) {
637 void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *>(HasFunctionName),
638 alignof(PredefinedExpr));
639 return new (Mem) PredefinedExpr(EmptyShell(), HasFunctionName);
642 StringRef PredefinedExpr::getIdentKindName(PredefinedExpr::IdentKind IK) {
643 switch (IK) {
644 case Func:
645 return "__func__";
646 case Function:
647 return "__FUNCTION__";
648 case FuncDName:
649 return "__FUNCDNAME__";
650 case LFunction:
651 return "L__FUNCTION__";
652 case PrettyFunction:
653 return "__PRETTY_FUNCTION__";
654 case FuncSig:
655 return "__FUNCSIG__";
656 case LFuncSig:
657 return "L__FUNCSIG__";
658 case PrettyFunctionNoVirtual:
659 break;
661 llvm_unreachable("Unknown ident kind for PredefinedExpr");
664 // FIXME: Maybe this should use DeclPrinter with a special "print predefined
665 // expr" policy instead.
666 std::string PredefinedExpr::ComputeName(IdentKind IK, const Decl *CurrentDecl) {
667 ASTContext &Context = CurrentDecl->getASTContext();
669 if (IK == PredefinedExpr::FuncDName) {
670 if (const NamedDecl *ND = dyn_cast<NamedDecl>(CurrentDecl)) {
671 std::unique_ptr<MangleContext> MC;
672 MC.reset(Context.createMangleContext());
674 if (MC->shouldMangleDeclName(ND)) {
675 SmallString<256> Buffer;
676 llvm::raw_svector_ostream Out(Buffer);
677 GlobalDecl GD;
678 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(ND))
679 GD = GlobalDecl(CD, Ctor_Base);
680 else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(ND))
681 GD = GlobalDecl(DD, Dtor_Base);
682 else if (ND->hasAttr<CUDAGlobalAttr>())
683 GD = GlobalDecl(cast<FunctionDecl>(ND));
684 else
685 GD = GlobalDecl(ND);
686 MC->mangleName(GD, Out);
688 if (!Buffer.empty() && Buffer.front() == '\01')
689 return std::string(Buffer.substr(1));
690 return std::string(Buffer.str());
692 return std::string(ND->getIdentifier()->getName());
694 return "";
696 if (isa<BlockDecl>(CurrentDecl)) {
697 // For blocks we only emit something if it is enclosed in a function
698 // For top-level block we'd like to include the name of variable, but we
699 // don't have it at this point.
700 auto DC = CurrentDecl->getDeclContext();
701 if (DC->isFileContext())
702 return "";
704 SmallString<256> Buffer;
705 llvm::raw_svector_ostream Out(Buffer);
706 if (auto *DCBlock = dyn_cast<BlockDecl>(DC))
707 // For nested blocks, propagate up to the parent.
708 Out << ComputeName(IK, DCBlock);
709 else if (auto *DCDecl = dyn_cast<Decl>(DC))
710 Out << ComputeName(IK, DCDecl) << "_block_invoke";
711 return std::string(Out.str());
713 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CurrentDecl)) {
714 if (IK != PrettyFunction && IK != PrettyFunctionNoVirtual &&
715 IK != FuncSig && IK != LFuncSig)
716 return FD->getNameAsString();
718 SmallString<256> Name;
719 llvm::raw_svector_ostream Out(Name);
721 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
722 if (MD->isVirtual() && IK != PrettyFunctionNoVirtual)
723 Out << "virtual ";
724 if (MD->isStatic())
725 Out << "static ";
728 class PrettyCallbacks final : public PrintingCallbacks {
729 public:
730 PrettyCallbacks(const LangOptions &LO) : LO(LO) {}
731 std::string remapPath(StringRef Path) const override {
732 SmallString<128> p(Path);
733 LO.remapPathPrefix(p);
734 return std::string(p);
737 private:
738 const LangOptions &LO;
740 PrintingPolicy Policy(Context.getLangOpts());
741 PrettyCallbacks PrettyCB(Context.getLangOpts());
742 Policy.Callbacks = &PrettyCB;
743 std::string Proto;
744 llvm::raw_string_ostream POut(Proto);
746 const FunctionDecl *Decl = FD;
747 if (const FunctionDecl* Pattern = FD->getTemplateInstantiationPattern())
748 Decl = Pattern;
749 const FunctionType *AFT = Decl->getType()->getAs<FunctionType>();
750 const FunctionProtoType *FT = nullptr;
751 if (FD->hasWrittenPrototype())
752 FT = dyn_cast<FunctionProtoType>(AFT);
754 if (IK == FuncSig || IK == LFuncSig) {
755 switch (AFT->getCallConv()) {
756 case CC_C: POut << "__cdecl "; break;
757 case CC_X86StdCall: POut << "__stdcall "; break;
758 case CC_X86FastCall: POut << "__fastcall "; break;
759 case CC_X86ThisCall: POut << "__thiscall "; break;
760 case CC_X86VectorCall: POut << "__vectorcall "; break;
761 case CC_X86RegCall: POut << "__regcall "; break;
762 // Only bother printing the conventions that MSVC knows about.
763 default: break;
767 FD->printQualifiedName(POut, Policy);
769 POut << "(";
770 if (FT) {
771 for (unsigned i = 0, e = Decl->getNumParams(); i != e; ++i) {
772 if (i) POut << ", ";
773 POut << Decl->getParamDecl(i)->getType().stream(Policy);
776 if (FT->isVariadic()) {
777 if (FD->getNumParams()) POut << ", ";
778 POut << "...";
779 } else if ((IK == FuncSig || IK == LFuncSig ||
780 !Context.getLangOpts().CPlusPlus) &&
781 !Decl->getNumParams()) {
782 POut << "void";
785 POut << ")";
787 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
788 assert(FT && "We must have a written prototype in this case.");
789 if (FT->isConst())
790 POut << " const";
791 if (FT->isVolatile())
792 POut << " volatile";
793 RefQualifierKind Ref = MD->getRefQualifier();
794 if (Ref == RQ_LValue)
795 POut << " &";
796 else if (Ref == RQ_RValue)
797 POut << " &&";
800 typedef SmallVector<const ClassTemplateSpecializationDecl *, 8> SpecsTy;
801 SpecsTy Specs;
802 const DeclContext *Ctx = FD->getDeclContext();
803 while (Ctx && isa<NamedDecl>(Ctx)) {
804 const ClassTemplateSpecializationDecl *Spec
805 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx);
806 if (Spec && !Spec->isExplicitSpecialization())
807 Specs.push_back(Spec);
808 Ctx = Ctx->getParent();
811 std::string TemplateParams;
812 llvm::raw_string_ostream TOut(TemplateParams);
813 for (const ClassTemplateSpecializationDecl *D : llvm::reverse(Specs)) {
814 const TemplateParameterList *Params =
815 D->getSpecializedTemplate()->getTemplateParameters();
816 const TemplateArgumentList &Args = D->getTemplateArgs();
817 assert(Params->size() == Args.size());
818 for (unsigned i = 0, numParams = Params->size(); i != numParams; ++i) {
819 StringRef Param = Params->getParam(i)->getName();
820 if (Param.empty()) continue;
821 TOut << Param << " = ";
822 Args.get(i).print(Policy, TOut,
823 TemplateParameterList::shouldIncludeTypeForArgument(
824 Policy, Params, i));
825 TOut << ", ";
829 FunctionTemplateSpecializationInfo *FSI
830 = FD->getTemplateSpecializationInfo();
831 if (FSI && !FSI->isExplicitSpecialization()) {
832 const TemplateParameterList* Params
833 = FSI->getTemplate()->getTemplateParameters();
834 const TemplateArgumentList* Args = FSI->TemplateArguments;
835 assert(Params->size() == Args->size());
836 for (unsigned i = 0, e = Params->size(); i != e; ++i) {
837 StringRef Param = Params->getParam(i)->getName();
838 if (Param.empty()) continue;
839 TOut << Param << " = ";
840 Args->get(i).print(Policy, TOut, /*IncludeType*/ true);
841 TOut << ", ";
845 TOut.flush();
846 if (!TemplateParams.empty()) {
847 // remove the trailing comma and space
848 TemplateParams.resize(TemplateParams.size() - 2);
849 POut << " [" << TemplateParams << "]";
852 POut.flush();
854 // Print "auto" for all deduced return types. This includes C++1y return
855 // type deduction and lambdas. For trailing return types resolve the
856 // decltype expression. Otherwise print the real type when this is
857 // not a constructor or destructor.
858 if (isa<CXXMethodDecl>(FD) &&
859 cast<CXXMethodDecl>(FD)->getParent()->isLambda())
860 Proto = "auto " + Proto;
861 else if (FT && FT->getReturnType()->getAs<DecltypeType>())
862 FT->getReturnType()
863 ->getAs<DecltypeType>()
864 ->getUnderlyingType()
865 .getAsStringInternal(Proto, Policy);
866 else if (!isa<CXXConstructorDecl>(FD) && !isa<CXXDestructorDecl>(FD))
867 AFT->getReturnType().getAsStringInternal(Proto, Policy);
869 Out << Proto;
871 return std::string(Name);
873 if (const CapturedDecl *CD = dyn_cast<CapturedDecl>(CurrentDecl)) {
874 for (const DeclContext *DC = CD->getParent(); DC; DC = DC->getParent())
875 // Skip to its enclosing function or method, but not its enclosing
876 // CapturedDecl.
877 if (DC->isFunctionOrMethod() && (DC->getDeclKind() != Decl::Captured)) {
878 const Decl *D = Decl::castFromDeclContext(DC);
879 return ComputeName(IK, D);
881 llvm_unreachable("CapturedDecl not inside a function or method");
883 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurrentDecl)) {
884 SmallString<256> Name;
885 llvm::raw_svector_ostream Out(Name);
886 Out << (MD->isInstanceMethod() ? '-' : '+');
887 Out << '[';
889 // For incorrect code, there might not be an ObjCInterfaceDecl. Do
890 // a null check to avoid a crash.
891 if (const ObjCInterfaceDecl *ID = MD->getClassInterface())
892 Out << *ID;
894 if (const ObjCCategoryImplDecl *CID =
895 dyn_cast<ObjCCategoryImplDecl>(MD->getDeclContext()))
896 Out << '(' << *CID << ')';
898 Out << ' ';
899 MD->getSelector().print(Out);
900 Out << ']';
902 return std::string(Name);
904 if (isa<TranslationUnitDecl>(CurrentDecl) && IK == PrettyFunction) {
905 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
906 return "top level";
908 return "";
911 void APNumericStorage::setIntValue(const ASTContext &C,
912 const llvm::APInt &Val) {
913 if (hasAllocation())
914 C.Deallocate(pVal);
916 BitWidth = Val.getBitWidth();
917 unsigned NumWords = Val.getNumWords();
918 const uint64_t* Words = Val.getRawData();
919 if (NumWords > 1) {
920 pVal = new (C) uint64_t[NumWords];
921 std::copy(Words, Words + NumWords, pVal);
922 } else if (NumWords == 1)
923 VAL = Words[0];
924 else
925 VAL = 0;
928 IntegerLiteral::IntegerLiteral(const ASTContext &C, const llvm::APInt &V,
929 QualType type, SourceLocation l)
930 : Expr(IntegerLiteralClass, type, VK_PRValue, OK_Ordinary), Loc(l) {
931 assert(type->isIntegerType() && "Illegal type in IntegerLiteral");
932 assert(V.getBitWidth() == C.getIntWidth(type) &&
933 "Integer type is not the correct size for constant.");
934 setValue(C, V);
935 setDependence(ExprDependence::None);
938 IntegerLiteral *
939 IntegerLiteral::Create(const ASTContext &C, const llvm::APInt &V,
940 QualType type, SourceLocation l) {
941 return new (C) IntegerLiteral(C, V, type, l);
944 IntegerLiteral *
945 IntegerLiteral::Create(const ASTContext &C, EmptyShell Empty) {
946 return new (C) IntegerLiteral(Empty);
949 FixedPointLiteral::FixedPointLiteral(const ASTContext &C, const llvm::APInt &V,
950 QualType type, SourceLocation l,
951 unsigned Scale)
952 : Expr(FixedPointLiteralClass, type, VK_PRValue, OK_Ordinary), Loc(l),
953 Scale(Scale) {
954 assert(type->isFixedPointType() && "Illegal type in FixedPointLiteral");
955 assert(V.getBitWidth() == C.getTypeInfo(type).Width &&
956 "Fixed point type is not the correct size for constant.");
957 setValue(C, V);
958 setDependence(ExprDependence::None);
961 FixedPointLiteral *FixedPointLiteral::CreateFromRawInt(const ASTContext &C,
962 const llvm::APInt &V,
963 QualType type,
964 SourceLocation l,
965 unsigned Scale) {
966 return new (C) FixedPointLiteral(C, V, type, l, Scale);
969 FixedPointLiteral *FixedPointLiteral::Create(const ASTContext &C,
970 EmptyShell Empty) {
971 return new (C) FixedPointLiteral(Empty);
974 std::string FixedPointLiteral::getValueAsString(unsigned Radix) const {
975 // Currently the longest decimal number that can be printed is the max for an
976 // unsigned long _Accum: 4294967295.99999999976716935634613037109375
977 // which is 43 characters.
978 SmallString<64> S;
979 FixedPointValueToString(
980 S, llvm::APSInt::getUnsigned(getValue().getZExtValue()), Scale);
981 return std::string(S.str());
984 void CharacterLiteral::print(unsigned Val, CharacterKind Kind,
985 raw_ostream &OS) {
986 switch (Kind) {
987 case CharacterLiteral::Ascii:
988 break; // no prefix.
989 case CharacterLiteral::Wide:
990 OS << 'L';
991 break;
992 case CharacterLiteral::UTF8:
993 OS << "u8";
994 break;
995 case CharacterLiteral::UTF16:
996 OS << 'u';
997 break;
998 case CharacterLiteral::UTF32:
999 OS << 'U';
1000 break;
1003 StringRef Escaped = escapeCStyle<EscapeChar::Single>(Val);
1004 if (!Escaped.empty()) {
1005 OS << "'" << Escaped << "'";
1006 } else {
1007 // A character literal might be sign-extended, which
1008 // would result in an invalid \U escape sequence.
1009 // FIXME: multicharacter literals such as '\xFF\xFF\xFF\xFF'
1010 // are not correctly handled.
1011 if ((Val & ~0xFFu) == ~0xFFu && Kind == CharacterLiteral::Ascii)
1012 Val &= 0xFFu;
1013 if (Val < 256 && isPrintable((unsigned char)Val))
1014 OS << "'" << (char)Val << "'";
1015 else if (Val < 256)
1016 OS << "'\\x" << llvm::format("%02x", Val) << "'";
1017 else if (Val <= 0xFFFF)
1018 OS << "'\\u" << llvm::format("%04x", Val) << "'";
1019 else
1020 OS << "'\\U" << llvm::format("%08x", Val) << "'";
1024 FloatingLiteral::FloatingLiteral(const ASTContext &C, const llvm::APFloat &V,
1025 bool isexact, QualType Type, SourceLocation L)
1026 : Expr(FloatingLiteralClass, Type, VK_PRValue, OK_Ordinary), Loc(L) {
1027 setSemantics(V.getSemantics());
1028 FloatingLiteralBits.IsExact = isexact;
1029 setValue(C, V);
1030 setDependence(ExprDependence::None);
1033 FloatingLiteral::FloatingLiteral(const ASTContext &C, EmptyShell Empty)
1034 : Expr(FloatingLiteralClass, Empty) {
1035 setRawSemantics(llvm::APFloatBase::S_IEEEhalf);
1036 FloatingLiteralBits.IsExact = false;
1039 FloatingLiteral *
1040 FloatingLiteral::Create(const ASTContext &C, const llvm::APFloat &V,
1041 bool isexact, QualType Type, SourceLocation L) {
1042 return new (C) FloatingLiteral(C, V, isexact, Type, L);
1045 FloatingLiteral *
1046 FloatingLiteral::Create(const ASTContext &C, EmptyShell Empty) {
1047 return new (C) FloatingLiteral(C, Empty);
1050 /// getValueAsApproximateDouble - This returns the value as an inaccurate
1051 /// double. Note that this may cause loss of precision, but is useful for
1052 /// debugging dumps, etc.
1053 double FloatingLiteral::getValueAsApproximateDouble() const {
1054 llvm::APFloat V = getValue();
1055 bool ignored;
1056 V.convert(llvm::APFloat::IEEEdouble(), llvm::APFloat::rmNearestTiesToEven,
1057 &ignored);
1058 return V.convertToDouble();
1061 unsigned StringLiteral::mapCharByteWidth(TargetInfo const &Target,
1062 StringKind SK) {
1063 unsigned CharByteWidth = 0;
1064 switch (SK) {
1065 case Ordinary:
1066 case UTF8:
1067 CharByteWidth = Target.getCharWidth();
1068 break;
1069 case Wide:
1070 CharByteWidth = Target.getWCharWidth();
1071 break;
1072 case UTF16:
1073 CharByteWidth = Target.getChar16Width();
1074 break;
1075 case UTF32:
1076 CharByteWidth = Target.getChar32Width();
1077 break;
1078 case Unevaluated:
1079 return sizeof(char); // Host;
1081 assert((CharByteWidth & 7) == 0 && "Assumes character size is byte multiple");
1082 CharByteWidth /= 8;
1083 assert((CharByteWidth == 1 || CharByteWidth == 2 || CharByteWidth == 4) &&
1084 "The only supported character byte widths are 1,2 and 4!");
1085 return CharByteWidth;
1088 StringLiteral::StringLiteral(const ASTContext &Ctx, StringRef Str,
1089 StringKind Kind, bool Pascal, QualType Ty,
1090 const SourceLocation *Loc,
1091 unsigned NumConcatenated)
1092 : Expr(StringLiteralClass, Ty, VK_LValue, OK_Ordinary) {
1094 unsigned Length = Str.size();
1096 StringLiteralBits.Kind = Kind;
1097 StringLiteralBits.NumConcatenated = NumConcatenated;
1099 if (Kind != StringKind::Unevaluated) {
1100 assert(Ctx.getAsConstantArrayType(Ty) &&
1101 "StringLiteral must be of constant array type!");
1102 unsigned CharByteWidth = mapCharByteWidth(Ctx.getTargetInfo(), Kind);
1103 unsigned ByteLength = Str.size();
1104 assert((ByteLength % CharByteWidth == 0) &&
1105 "The size of the data must be a multiple of CharByteWidth!");
1107 // Avoid the expensive division. The compiler should be able to figure it
1108 // out by itself. However as of clang 7, even with the appropriate
1109 // llvm_unreachable added just here, it is not able to do so.
1110 switch (CharByteWidth) {
1111 case 1:
1112 Length = ByteLength;
1113 break;
1114 case 2:
1115 Length = ByteLength / 2;
1116 break;
1117 case 4:
1118 Length = ByteLength / 4;
1119 break;
1120 default:
1121 llvm_unreachable("Unsupported character width!");
1124 StringLiteralBits.CharByteWidth = CharByteWidth;
1125 StringLiteralBits.IsPascal = Pascal;
1126 } else {
1127 assert(!Pascal && "Can't make an unevaluated Pascal string");
1128 StringLiteralBits.CharByteWidth = 1;
1129 StringLiteralBits.IsPascal = false;
1132 *getTrailingObjects<unsigned>() = Length;
1134 // Initialize the trailing array of SourceLocation.
1135 // This is safe since SourceLocation is POD-like.
1136 std::memcpy(getTrailingObjects<SourceLocation>(), Loc,
1137 NumConcatenated * sizeof(SourceLocation));
1139 // Initialize the trailing array of char holding the string data.
1140 std::memcpy(getTrailingObjects<char>(), Str.data(), Str.size());
1142 setDependence(ExprDependence::None);
1145 StringLiteral::StringLiteral(EmptyShell Empty, unsigned NumConcatenated,
1146 unsigned Length, unsigned CharByteWidth)
1147 : Expr(StringLiteralClass, Empty) {
1148 StringLiteralBits.CharByteWidth = CharByteWidth;
1149 StringLiteralBits.NumConcatenated = NumConcatenated;
1150 *getTrailingObjects<unsigned>() = Length;
1153 StringLiteral *StringLiteral::Create(const ASTContext &Ctx, StringRef Str,
1154 StringKind Kind, bool Pascal, QualType Ty,
1155 const SourceLocation *Loc,
1156 unsigned NumConcatenated) {
1157 void *Mem = Ctx.Allocate(totalSizeToAlloc<unsigned, SourceLocation, char>(
1158 1, NumConcatenated, Str.size()),
1159 alignof(StringLiteral));
1160 return new (Mem)
1161 StringLiteral(Ctx, Str, Kind, Pascal, Ty, Loc, NumConcatenated);
1164 StringLiteral *StringLiteral::CreateEmpty(const ASTContext &Ctx,
1165 unsigned NumConcatenated,
1166 unsigned Length,
1167 unsigned CharByteWidth) {
1168 void *Mem = Ctx.Allocate(totalSizeToAlloc<unsigned, SourceLocation, char>(
1169 1, NumConcatenated, Length * CharByteWidth),
1170 alignof(StringLiteral));
1171 return new (Mem)
1172 StringLiteral(EmptyShell(), NumConcatenated, Length, CharByteWidth);
1175 void StringLiteral::outputString(raw_ostream &OS) const {
1176 switch (getKind()) {
1177 case Unevaluated:
1178 case Ordinary:
1179 break; // no prefix.
1180 case Wide: OS << 'L'; break;
1181 case UTF8: OS << "u8"; break;
1182 case UTF16: OS << 'u'; break;
1183 case UTF32: OS << 'U'; break;
1185 OS << '"';
1186 static const char Hex[] = "0123456789ABCDEF";
1188 unsigned LastSlashX = getLength();
1189 for (unsigned I = 0, N = getLength(); I != N; ++I) {
1190 uint32_t Char = getCodeUnit(I);
1191 StringRef Escaped = escapeCStyle<EscapeChar::Double>(Char);
1192 if (Escaped.empty()) {
1193 // FIXME: Convert UTF-8 back to codepoints before rendering.
1195 // Convert UTF-16 surrogate pairs back to codepoints before rendering.
1196 // Leave invalid surrogates alone; we'll use \x for those.
1197 if (getKind() == UTF16 && I != N - 1 && Char >= 0xd800 &&
1198 Char <= 0xdbff) {
1199 uint32_t Trail = getCodeUnit(I + 1);
1200 if (Trail >= 0xdc00 && Trail <= 0xdfff) {
1201 Char = 0x10000 + ((Char - 0xd800) << 10) + (Trail - 0xdc00);
1202 ++I;
1206 if (Char > 0xff) {
1207 // If this is a wide string, output characters over 0xff using \x
1208 // escapes. Otherwise, this is a UTF-16 or UTF-32 string, and Char is a
1209 // codepoint: use \x escapes for invalid codepoints.
1210 if (getKind() == Wide ||
1211 (Char >= 0xd800 && Char <= 0xdfff) || Char >= 0x110000) {
1212 // FIXME: Is this the best way to print wchar_t?
1213 OS << "\\x";
1214 int Shift = 28;
1215 while ((Char >> Shift) == 0)
1216 Shift -= 4;
1217 for (/**/; Shift >= 0; Shift -= 4)
1218 OS << Hex[(Char >> Shift) & 15];
1219 LastSlashX = I;
1220 continue;
1223 if (Char > 0xffff)
1224 OS << "\\U00"
1225 << Hex[(Char >> 20) & 15]
1226 << Hex[(Char >> 16) & 15];
1227 else
1228 OS << "\\u";
1229 OS << Hex[(Char >> 12) & 15]
1230 << Hex[(Char >> 8) & 15]
1231 << Hex[(Char >> 4) & 15]
1232 << Hex[(Char >> 0) & 15];
1233 continue;
1236 // If we used \x... for the previous character, and this character is a
1237 // hexadecimal digit, prevent it being slurped as part of the \x.
1238 if (LastSlashX + 1 == I) {
1239 switch (Char) {
1240 case '0': case '1': case '2': case '3': case '4':
1241 case '5': case '6': case '7': case '8': case '9':
1242 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
1243 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
1244 OS << "\"\"";
1248 assert(Char <= 0xff &&
1249 "Characters above 0xff should already have been handled.");
1251 if (isPrintable(Char))
1252 OS << (char)Char;
1253 else // Output anything hard as an octal escape.
1254 OS << '\\'
1255 << (char)('0' + ((Char >> 6) & 7))
1256 << (char)('0' + ((Char >> 3) & 7))
1257 << (char)('0' + ((Char >> 0) & 7));
1258 } else {
1259 // Handle some common non-printable cases to make dumps prettier.
1260 OS << Escaped;
1263 OS << '"';
1266 /// getLocationOfByte - Return a source location that points to the specified
1267 /// byte of this string literal.
1269 /// Strings are amazingly complex. They can be formed from multiple tokens and
1270 /// can have escape sequences in them in addition to the usual trigraph and
1271 /// escaped newline business. This routine handles this complexity.
1273 /// The *StartToken sets the first token to be searched in this function and
1274 /// the *StartTokenByteOffset is the byte offset of the first token. Before
1275 /// returning, it updates the *StartToken to the TokNo of the token being found
1276 /// and sets *StartTokenByteOffset to the byte offset of the token in the
1277 /// string.
1278 /// Using these two parameters can reduce the time complexity from O(n^2) to
1279 /// O(n) if one wants to get the location of byte for all the tokens in a
1280 /// string.
1282 SourceLocation
1283 StringLiteral::getLocationOfByte(unsigned ByteNo, const SourceManager &SM,
1284 const LangOptions &Features,
1285 const TargetInfo &Target, unsigned *StartToken,
1286 unsigned *StartTokenByteOffset) const {
1287 assert((getKind() == StringLiteral::Ordinary ||
1288 getKind() == StringLiteral::UTF8 ||
1289 getKind() == StringLiteral::Unevaluated) &&
1290 "Only narrow string literals are currently supported");
1292 // Loop over all of the tokens in this string until we find the one that
1293 // contains the byte we're looking for.
1294 unsigned TokNo = 0;
1295 unsigned StringOffset = 0;
1296 if (StartToken)
1297 TokNo = *StartToken;
1298 if (StartTokenByteOffset) {
1299 StringOffset = *StartTokenByteOffset;
1300 ByteNo -= StringOffset;
1302 while (true) {
1303 assert(TokNo < getNumConcatenated() && "Invalid byte number!");
1304 SourceLocation StrTokLoc = getStrTokenLoc(TokNo);
1306 // Get the spelling of the string so that we can get the data that makes up
1307 // the string literal, not the identifier for the macro it is potentially
1308 // expanded through.
1309 SourceLocation StrTokSpellingLoc = SM.getSpellingLoc(StrTokLoc);
1311 // Re-lex the token to get its length and original spelling.
1312 std::pair<FileID, unsigned> LocInfo =
1313 SM.getDecomposedLoc(StrTokSpellingLoc);
1314 bool Invalid = false;
1315 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
1316 if (Invalid) {
1317 if (StartTokenByteOffset != nullptr)
1318 *StartTokenByteOffset = StringOffset;
1319 if (StartToken != nullptr)
1320 *StartToken = TokNo;
1321 return StrTokSpellingLoc;
1324 const char *StrData = Buffer.data()+LocInfo.second;
1326 // Create a lexer starting at the beginning of this token.
1327 Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), Features,
1328 Buffer.begin(), StrData, Buffer.end());
1329 Token TheTok;
1330 TheLexer.LexFromRawLexer(TheTok);
1332 // Use the StringLiteralParser to compute the length of the string in bytes.
1333 StringLiteralParser SLP(TheTok, SM, Features, Target);
1334 unsigned TokNumBytes = SLP.GetStringLength();
1336 // If the byte is in this token, return the location of the byte.
1337 if (ByteNo < TokNumBytes ||
1338 (ByteNo == TokNumBytes && TokNo == getNumConcatenated() - 1)) {
1339 unsigned Offset = SLP.getOffsetOfStringByte(TheTok, ByteNo);
1341 // Now that we know the offset of the token in the spelling, use the
1342 // preprocessor to get the offset in the original source.
1343 if (StartTokenByteOffset != nullptr)
1344 *StartTokenByteOffset = StringOffset;
1345 if (StartToken != nullptr)
1346 *StartToken = TokNo;
1347 return Lexer::AdvanceToTokenCharacter(StrTokLoc, Offset, SM, Features);
1350 // Move to the next string token.
1351 StringOffset += TokNumBytes;
1352 ++TokNo;
1353 ByteNo -= TokNumBytes;
1357 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1358 /// corresponds to, e.g. "sizeof" or "[pre]++".
1359 StringRef UnaryOperator::getOpcodeStr(Opcode Op) {
1360 switch (Op) {
1361 #define UNARY_OPERATION(Name, Spelling) case UO_##Name: return Spelling;
1362 #include "clang/AST/OperationKinds.def"
1364 llvm_unreachable("Unknown unary operator");
1367 UnaryOperatorKind
1368 UnaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix) {
1369 switch (OO) {
1370 default: llvm_unreachable("No unary operator for overloaded function");
1371 case OO_PlusPlus: return Postfix ? UO_PostInc : UO_PreInc;
1372 case OO_MinusMinus: return Postfix ? UO_PostDec : UO_PreDec;
1373 case OO_Amp: return UO_AddrOf;
1374 case OO_Star: return UO_Deref;
1375 case OO_Plus: return UO_Plus;
1376 case OO_Minus: return UO_Minus;
1377 case OO_Tilde: return UO_Not;
1378 case OO_Exclaim: return UO_LNot;
1379 case OO_Coawait: return UO_Coawait;
1383 OverloadedOperatorKind UnaryOperator::getOverloadedOperator(Opcode Opc) {
1384 switch (Opc) {
1385 case UO_PostInc: case UO_PreInc: return OO_PlusPlus;
1386 case UO_PostDec: case UO_PreDec: return OO_MinusMinus;
1387 case UO_AddrOf: return OO_Amp;
1388 case UO_Deref: return OO_Star;
1389 case UO_Plus: return OO_Plus;
1390 case UO_Minus: return OO_Minus;
1391 case UO_Not: return OO_Tilde;
1392 case UO_LNot: return OO_Exclaim;
1393 case UO_Coawait: return OO_Coawait;
1394 default: return OO_None;
1399 //===----------------------------------------------------------------------===//
1400 // Postfix Operators.
1401 //===----------------------------------------------------------------------===//
1403 CallExpr::CallExpr(StmtClass SC, Expr *Fn, ArrayRef<Expr *> PreArgs,
1404 ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,
1405 SourceLocation RParenLoc, FPOptionsOverride FPFeatures,
1406 unsigned MinNumArgs, ADLCallKind UsesADL)
1407 : Expr(SC, Ty, VK, OK_Ordinary), RParenLoc(RParenLoc) {
1408 NumArgs = std::max<unsigned>(Args.size(), MinNumArgs);
1409 unsigned NumPreArgs = PreArgs.size();
1410 CallExprBits.NumPreArgs = NumPreArgs;
1411 assert((NumPreArgs == getNumPreArgs()) && "NumPreArgs overflow!");
1413 unsigned OffsetToTrailingObjects = offsetToTrailingObjects(SC);
1414 CallExprBits.OffsetToTrailingObjects = OffsetToTrailingObjects;
1415 assert((CallExprBits.OffsetToTrailingObjects == OffsetToTrailingObjects) &&
1416 "OffsetToTrailingObjects overflow!");
1418 CallExprBits.UsesADL = static_cast<bool>(UsesADL);
1420 setCallee(Fn);
1421 for (unsigned I = 0; I != NumPreArgs; ++I)
1422 setPreArg(I, PreArgs[I]);
1423 for (unsigned I = 0; I != Args.size(); ++I)
1424 setArg(I, Args[I]);
1425 for (unsigned I = Args.size(); I != NumArgs; ++I)
1426 setArg(I, nullptr);
1428 this->computeDependence();
1430 CallExprBits.HasFPFeatures = FPFeatures.requiresTrailingStorage();
1431 if (hasStoredFPFeatures())
1432 setStoredFPFeatures(FPFeatures);
1435 CallExpr::CallExpr(StmtClass SC, unsigned NumPreArgs, unsigned NumArgs,
1436 bool HasFPFeatures, EmptyShell Empty)
1437 : Expr(SC, Empty), NumArgs(NumArgs) {
1438 CallExprBits.NumPreArgs = NumPreArgs;
1439 assert((NumPreArgs == getNumPreArgs()) && "NumPreArgs overflow!");
1441 unsigned OffsetToTrailingObjects = offsetToTrailingObjects(SC);
1442 CallExprBits.OffsetToTrailingObjects = OffsetToTrailingObjects;
1443 assert((CallExprBits.OffsetToTrailingObjects == OffsetToTrailingObjects) &&
1444 "OffsetToTrailingObjects overflow!");
1445 CallExprBits.HasFPFeatures = HasFPFeatures;
1448 CallExpr *CallExpr::Create(const ASTContext &Ctx, Expr *Fn,
1449 ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,
1450 SourceLocation RParenLoc,
1451 FPOptionsOverride FPFeatures, unsigned MinNumArgs,
1452 ADLCallKind UsesADL) {
1453 unsigned NumArgs = std::max<unsigned>(Args.size(), MinNumArgs);
1454 unsigned SizeOfTrailingObjects = CallExpr::sizeOfTrailingObjects(
1455 /*NumPreArgs=*/0, NumArgs, FPFeatures.requiresTrailingStorage());
1456 void *Mem =
1457 Ctx.Allocate(sizeof(CallExpr) + SizeOfTrailingObjects, alignof(CallExpr));
1458 return new (Mem) CallExpr(CallExprClass, Fn, /*PreArgs=*/{}, Args, Ty, VK,
1459 RParenLoc, FPFeatures, MinNumArgs, UsesADL);
1462 CallExpr *CallExpr::CreateTemporary(void *Mem, Expr *Fn, QualType Ty,
1463 ExprValueKind VK, SourceLocation RParenLoc,
1464 ADLCallKind UsesADL) {
1465 assert(!(reinterpret_cast<uintptr_t>(Mem) % alignof(CallExpr)) &&
1466 "Misaligned memory in CallExpr::CreateTemporary!");
1467 return new (Mem) CallExpr(CallExprClass, Fn, /*PreArgs=*/{}, /*Args=*/{}, Ty,
1468 VK, RParenLoc, FPOptionsOverride(),
1469 /*MinNumArgs=*/0, UsesADL);
1472 CallExpr *CallExpr::CreateEmpty(const ASTContext &Ctx, unsigned NumArgs,
1473 bool HasFPFeatures, EmptyShell Empty) {
1474 unsigned SizeOfTrailingObjects =
1475 CallExpr::sizeOfTrailingObjects(/*NumPreArgs=*/0, NumArgs, HasFPFeatures);
1476 void *Mem =
1477 Ctx.Allocate(sizeof(CallExpr) + SizeOfTrailingObjects, alignof(CallExpr));
1478 return new (Mem)
1479 CallExpr(CallExprClass, /*NumPreArgs=*/0, NumArgs, HasFPFeatures, Empty);
1482 unsigned CallExpr::offsetToTrailingObjects(StmtClass SC) {
1483 switch (SC) {
1484 case CallExprClass:
1485 return sizeof(CallExpr);
1486 case CXXOperatorCallExprClass:
1487 return sizeof(CXXOperatorCallExpr);
1488 case CXXMemberCallExprClass:
1489 return sizeof(CXXMemberCallExpr);
1490 case UserDefinedLiteralClass:
1491 return sizeof(UserDefinedLiteral);
1492 case CUDAKernelCallExprClass:
1493 return sizeof(CUDAKernelCallExpr);
1494 default:
1495 llvm_unreachable("unexpected class deriving from CallExpr!");
1499 Decl *Expr::getReferencedDeclOfCallee() {
1500 Expr *CEE = IgnoreParenImpCasts();
1502 while (auto *NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(CEE))
1503 CEE = NTTP->getReplacement()->IgnoreParenImpCasts();
1505 // If we're calling a dereference, look at the pointer instead.
1506 while (true) {
1507 if (auto *BO = dyn_cast<BinaryOperator>(CEE)) {
1508 if (BO->isPtrMemOp()) {
1509 CEE = BO->getRHS()->IgnoreParenImpCasts();
1510 continue;
1512 } else if (auto *UO = dyn_cast<UnaryOperator>(CEE)) {
1513 if (UO->getOpcode() == UO_Deref || UO->getOpcode() == UO_AddrOf ||
1514 UO->getOpcode() == UO_Plus) {
1515 CEE = UO->getSubExpr()->IgnoreParenImpCasts();
1516 continue;
1519 break;
1522 if (auto *DRE = dyn_cast<DeclRefExpr>(CEE))
1523 return DRE->getDecl();
1524 if (auto *ME = dyn_cast<MemberExpr>(CEE))
1525 return ME->getMemberDecl();
1526 if (auto *BE = dyn_cast<BlockExpr>(CEE))
1527 return BE->getBlockDecl();
1529 return nullptr;
1532 /// If this is a call to a builtin, return the builtin ID. If not, return 0.
1533 unsigned CallExpr::getBuiltinCallee() const {
1534 const auto *FDecl = getDirectCallee();
1535 return FDecl ? FDecl->getBuiltinID() : 0;
1538 bool CallExpr::isUnevaluatedBuiltinCall(const ASTContext &Ctx) const {
1539 if (unsigned BI = getBuiltinCallee())
1540 return Ctx.BuiltinInfo.isUnevaluated(BI);
1541 return false;
1544 QualType CallExpr::getCallReturnType(const ASTContext &Ctx) const {
1545 const Expr *Callee = getCallee();
1546 QualType CalleeType = Callee->getType();
1547 if (const auto *FnTypePtr = CalleeType->getAs<PointerType>()) {
1548 CalleeType = FnTypePtr->getPointeeType();
1549 } else if (const auto *BPT = CalleeType->getAs<BlockPointerType>()) {
1550 CalleeType = BPT->getPointeeType();
1551 } else if (CalleeType->isSpecificPlaceholderType(BuiltinType::BoundMember)) {
1552 if (isa<CXXPseudoDestructorExpr>(Callee->IgnoreParens()))
1553 return Ctx.VoidTy;
1555 if (isa<UnresolvedMemberExpr>(Callee->IgnoreParens()))
1556 return Ctx.DependentTy;
1558 // This should never be overloaded and so should never return null.
1559 CalleeType = Expr::findBoundMemberType(Callee);
1560 assert(!CalleeType.isNull());
1561 } else if (CalleeType->isRecordType()) {
1562 // If the Callee is a record type, then it is a not-yet-resolved
1563 // dependent call to the call operator of that type.
1564 return Ctx.DependentTy;
1565 } else if (CalleeType->isDependentType() ||
1566 CalleeType->isSpecificPlaceholderType(BuiltinType::Overload)) {
1567 return Ctx.DependentTy;
1570 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
1571 return FnType->getReturnType();
1574 const Attr *CallExpr::getUnusedResultAttr(const ASTContext &Ctx) const {
1575 // If the return type is a struct, union, or enum that is marked nodiscard,
1576 // then return the return type attribute.
1577 if (const TagDecl *TD = getCallReturnType(Ctx)->getAsTagDecl())
1578 if (const auto *A = TD->getAttr<WarnUnusedResultAttr>())
1579 return A;
1581 for (const auto *TD = getCallReturnType(Ctx)->getAs<TypedefType>(); TD;
1582 TD = TD->desugar()->getAs<TypedefType>())
1583 if (const auto *A = TD->getDecl()->getAttr<WarnUnusedResultAttr>())
1584 return A;
1586 // Otherwise, see if the callee is marked nodiscard and return that attribute
1587 // instead.
1588 const Decl *D = getCalleeDecl();
1589 return D ? D->getAttr<WarnUnusedResultAttr>() : nullptr;
1592 SourceLocation CallExpr::getBeginLoc() const {
1593 if (const auto *OCE = dyn_cast<CXXOperatorCallExpr>(this))
1594 return OCE->getBeginLoc();
1596 SourceLocation begin = getCallee()->getBeginLoc();
1597 if (begin.isInvalid() && getNumArgs() > 0 && getArg(0))
1598 begin = getArg(0)->getBeginLoc();
1599 return begin;
1601 SourceLocation CallExpr::getEndLoc() const {
1602 if (const auto *OCE = dyn_cast<CXXOperatorCallExpr>(this))
1603 return OCE->getEndLoc();
1605 SourceLocation end = getRParenLoc();
1606 if (end.isInvalid() && getNumArgs() > 0 && getArg(getNumArgs() - 1))
1607 end = getArg(getNumArgs() - 1)->getEndLoc();
1608 return end;
1611 OffsetOfExpr *OffsetOfExpr::Create(const ASTContext &C, QualType type,
1612 SourceLocation OperatorLoc,
1613 TypeSourceInfo *tsi,
1614 ArrayRef<OffsetOfNode> comps,
1615 ArrayRef<Expr*> exprs,
1616 SourceLocation RParenLoc) {
1617 void *Mem = C.Allocate(
1618 totalSizeToAlloc<OffsetOfNode, Expr *>(comps.size(), exprs.size()));
1620 return new (Mem) OffsetOfExpr(C, type, OperatorLoc, tsi, comps, exprs,
1621 RParenLoc);
1624 OffsetOfExpr *OffsetOfExpr::CreateEmpty(const ASTContext &C,
1625 unsigned numComps, unsigned numExprs) {
1626 void *Mem =
1627 C.Allocate(totalSizeToAlloc<OffsetOfNode, Expr *>(numComps, numExprs));
1628 return new (Mem) OffsetOfExpr(numComps, numExprs);
1631 OffsetOfExpr::OffsetOfExpr(const ASTContext &C, QualType type,
1632 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
1633 ArrayRef<OffsetOfNode> comps, ArrayRef<Expr *> exprs,
1634 SourceLocation RParenLoc)
1635 : Expr(OffsetOfExprClass, type, VK_PRValue, OK_Ordinary),
1636 OperatorLoc(OperatorLoc), RParenLoc(RParenLoc), TSInfo(tsi),
1637 NumComps(comps.size()), NumExprs(exprs.size()) {
1638 for (unsigned i = 0; i != comps.size(); ++i)
1639 setComponent(i, comps[i]);
1640 for (unsigned i = 0; i != exprs.size(); ++i)
1641 setIndexExpr(i, exprs[i]);
1643 setDependence(computeDependence(this));
1646 IdentifierInfo *OffsetOfNode::getFieldName() const {
1647 assert(getKind() == Field || getKind() == Identifier);
1648 if (getKind() == Field)
1649 return getField()->getIdentifier();
1651 return reinterpret_cast<IdentifierInfo *> (Data & ~(uintptr_t)Mask);
1654 UnaryExprOrTypeTraitExpr::UnaryExprOrTypeTraitExpr(
1655 UnaryExprOrTypeTrait ExprKind, Expr *E, QualType resultType,
1656 SourceLocation op, SourceLocation rp)
1657 : Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_PRValue, OK_Ordinary),
1658 OpLoc(op), RParenLoc(rp) {
1659 assert(ExprKind <= UETT_Last && "invalid enum value!");
1660 UnaryExprOrTypeTraitExprBits.Kind = ExprKind;
1661 assert(static_cast<unsigned>(ExprKind) == UnaryExprOrTypeTraitExprBits.Kind &&
1662 "UnaryExprOrTypeTraitExprBits.Kind overflow!");
1663 UnaryExprOrTypeTraitExprBits.IsType = false;
1664 Argument.Ex = E;
1665 setDependence(computeDependence(this));
1668 MemberExpr::MemberExpr(Expr *Base, bool IsArrow, SourceLocation OperatorLoc,
1669 ValueDecl *MemberDecl,
1670 const DeclarationNameInfo &NameInfo, QualType T,
1671 ExprValueKind VK, ExprObjectKind OK,
1672 NonOdrUseReason NOUR)
1673 : Expr(MemberExprClass, T, VK, OK), Base(Base), MemberDecl(MemberDecl),
1674 MemberDNLoc(NameInfo.getInfo()), MemberLoc(NameInfo.getLoc()) {
1675 assert(!NameInfo.getName() ||
1676 MemberDecl->getDeclName() == NameInfo.getName());
1677 MemberExprBits.IsArrow = IsArrow;
1678 MemberExprBits.HasQualifierOrFoundDecl = false;
1679 MemberExprBits.HasTemplateKWAndArgsInfo = false;
1680 MemberExprBits.HadMultipleCandidates = false;
1681 MemberExprBits.NonOdrUseReason = NOUR;
1682 MemberExprBits.OperatorLoc = OperatorLoc;
1683 setDependence(computeDependence(this));
1686 MemberExpr *MemberExpr::Create(
1687 const ASTContext &C, Expr *Base, bool IsArrow, SourceLocation OperatorLoc,
1688 NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,
1689 ValueDecl *MemberDecl, DeclAccessPair FoundDecl,
1690 DeclarationNameInfo NameInfo, const TemplateArgumentListInfo *TemplateArgs,
1691 QualType T, ExprValueKind VK, ExprObjectKind OK, NonOdrUseReason NOUR) {
1692 bool HasQualOrFound = QualifierLoc || FoundDecl.getDecl() != MemberDecl ||
1693 FoundDecl.getAccess() != MemberDecl->getAccess();
1694 bool HasTemplateKWAndArgsInfo = TemplateArgs || TemplateKWLoc.isValid();
1695 std::size_t Size =
1696 totalSizeToAlloc<MemberExprNameQualifier, ASTTemplateKWAndArgsInfo,
1697 TemplateArgumentLoc>(
1698 HasQualOrFound ? 1 : 0, HasTemplateKWAndArgsInfo ? 1 : 0,
1699 TemplateArgs ? TemplateArgs->size() : 0);
1701 void *Mem = C.Allocate(Size, alignof(MemberExpr));
1702 MemberExpr *E = new (Mem) MemberExpr(Base, IsArrow, OperatorLoc, MemberDecl,
1703 NameInfo, T, VK, OK, NOUR);
1705 if (HasQualOrFound) {
1706 E->MemberExprBits.HasQualifierOrFoundDecl = true;
1708 MemberExprNameQualifier *NQ =
1709 E->getTrailingObjects<MemberExprNameQualifier>();
1710 NQ->QualifierLoc = QualifierLoc;
1711 NQ->FoundDecl = FoundDecl;
1714 E->MemberExprBits.HasTemplateKWAndArgsInfo =
1715 TemplateArgs || TemplateKWLoc.isValid();
1717 // FIXME: remove remaining dependence computation to computeDependence().
1718 auto Deps = E->getDependence();
1719 if (TemplateArgs) {
1720 auto TemplateArgDeps = TemplateArgumentDependence::None;
1721 E->getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
1722 TemplateKWLoc, *TemplateArgs,
1723 E->getTrailingObjects<TemplateArgumentLoc>(), TemplateArgDeps);
1724 for (const TemplateArgumentLoc &ArgLoc : TemplateArgs->arguments()) {
1725 Deps |= toExprDependence(ArgLoc.getArgument().getDependence());
1727 } else if (TemplateKWLoc.isValid()) {
1728 E->getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
1729 TemplateKWLoc);
1731 E->setDependence(Deps);
1733 return E;
1736 MemberExpr *MemberExpr::CreateEmpty(const ASTContext &Context,
1737 bool HasQualifier, bool HasFoundDecl,
1738 bool HasTemplateKWAndArgsInfo,
1739 unsigned NumTemplateArgs) {
1740 assert((!NumTemplateArgs || HasTemplateKWAndArgsInfo) &&
1741 "template args but no template arg info?");
1742 bool HasQualOrFound = HasQualifier || HasFoundDecl;
1743 std::size_t Size =
1744 totalSizeToAlloc<MemberExprNameQualifier, ASTTemplateKWAndArgsInfo,
1745 TemplateArgumentLoc>(HasQualOrFound ? 1 : 0,
1746 HasTemplateKWAndArgsInfo ? 1 : 0,
1747 NumTemplateArgs);
1748 void *Mem = Context.Allocate(Size, alignof(MemberExpr));
1749 return new (Mem) MemberExpr(EmptyShell());
1752 void MemberExpr::setMemberDecl(ValueDecl *NewD) {
1753 MemberDecl = NewD;
1754 if (getType()->isUndeducedType())
1755 setType(NewD->getType());
1756 setDependence(computeDependence(this));
1759 SourceLocation MemberExpr::getBeginLoc() const {
1760 if (isImplicitAccess()) {
1761 if (hasQualifier())
1762 return getQualifierLoc().getBeginLoc();
1763 return MemberLoc;
1766 // FIXME: We don't want this to happen. Rather, we should be able to
1767 // detect all kinds of implicit accesses more cleanly.
1768 SourceLocation BaseStartLoc = getBase()->getBeginLoc();
1769 if (BaseStartLoc.isValid())
1770 return BaseStartLoc;
1771 return MemberLoc;
1773 SourceLocation MemberExpr::getEndLoc() const {
1774 SourceLocation EndLoc = getMemberNameInfo().getEndLoc();
1775 if (hasExplicitTemplateArgs())
1776 EndLoc = getRAngleLoc();
1777 else if (EndLoc.isInvalid())
1778 EndLoc = getBase()->getEndLoc();
1779 return EndLoc;
1782 bool CastExpr::CastConsistency() const {
1783 switch (getCastKind()) {
1784 case CK_DerivedToBase:
1785 case CK_UncheckedDerivedToBase:
1786 case CK_DerivedToBaseMemberPointer:
1787 case CK_BaseToDerived:
1788 case CK_BaseToDerivedMemberPointer:
1789 assert(!path_empty() && "Cast kind should have a base path!");
1790 break;
1792 case CK_CPointerToObjCPointerCast:
1793 assert(getType()->isObjCObjectPointerType());
1794 assert(getSubExpr()->getType()->isPointerType());
1795 goto CheckNoBasePath;
1797 case CK_BlockPointerToObjCPointerCast:
1798 assert(getType()->isObjCObjectPointerType());
1799 assert(getSubExpr()->getType()->isBlockPointerType());
1800 goto CheckNoBasePath;
1802 case CK_ReinterpretMemberPointer:
1803 assert(getType()->isMemberPointerType());
1804 assert(getSubExpr()->getType()->isMemberPointerType());
1805 goto CheckNoBasePath;
1807 case CK_BitCast:
1808 // Arbitrary casts to C pointer types count as bitcasts.
1809 // Otherwise, we should only have block and ObjC pointer casts
1810 // here if they stay within the type kind.
1811 if (!getType()->isPointerType()) {
1812 assert(getType()->isObjCObjectPointerType() ==
1813 getSubExpr()->getType()->isObjCObjectPointerType());
1814 assert(getType()->isBlockPointerType() ==
1815 getSubExpr()->getType()->isBlockPointerType());
1817 goto CheckNoBasePath;
1819 case CK_AnyPointerToBlockPointerCast:
1820 assert(getType()->isBlockPointerType());
1821 assert(getSubExpr()->getType()->isAnyPointerType() &&
1822 !getSubExpr()->getType()->isBlockPointerType());
1823 goto CheckNoBasePath;
1825 case CK_CopyAndAutoreleaseBlockObject:
1826 assert(getType()->isBlockPointerType());
1827 assert(getSubExpr()->getType()->isBlockPointerType());
1828 goto CheckNoBasePath;
1830 case CK_FunctionToPointerDecay:
1831 assert(getType()->isPointerType());
1832 assert(getSubExpr()->getType()->isFunctionType());
1833 goto CheckNoBasePath;
1835 case CK_AddressSpaceConversion: {
1836 auto Ty = getType();
1837 auto SETy = getSubExpr()->getType();
1838 assert(getValueKindForType(Ty) == Expr::getValueKindForType(SETy));
1839 if (isPRValue() && !Ty->isDependentType() && !SETy->isDependentType()) {
1840 Ty = Ty->getPointeeType();
1841 SETy = SETy->getPointeeType();
1843 assert((Ty->isDependentType() || SETy->isDependentType()) ||
1844 (!Ty.isNull() && !SETy.isNull() &&
1845 Ty.getAddressSpace() != SETy.getAddressSpace()));
1846 goto CheckNoBasePath;
1848 // These should not have an inheritance path.
1849 case CK_Dynamic:
1850 case CK_ToUnion:
1851 case CK_ArrayToPointerDecay:
1852 case CK_NullToMemberPointer:
1853 case CK_NullToPointer:
1854 case CK_ConstructorConversion:
1855 case CK_IntegralToPointer:
1856 case CK_PointerToIntegral:
1857 case CK_ToVoid:
1858 case CK_VectorSplat:
1859 case CK_IntegralCast:
1860 case CK_BooleanToSignedIntegral:
1861 case CK_IntegralToFloating:
1862 case CK_FloatingToIntegral:
1863 case CK_FloatingCast:
1864 case CK_ObjCObjectLValueCast:
1865 case CK_FloatingRealToComplex:
1866 case CK_FloatingComplexToReal:
1867 case CK_FloatingComplexCast:
1868 case CK_FloatingComplexToIntegralComplex:
1869 case CK_IntegralRealToComplex:
1870 case CK_IntegralComplexToReal:
1871 case CK_IntegralComplexCast:
1872 case CK_IntegralComplexToFloatingComplex:
1873 case CK_ARCProduceObject:
1874 case CK_ARCConsumeObject:
1875 case CK_ARCReclaimReturnedObject:
1876 case CK_ARCExtendBlockObject:
1877 case CK_ZeroToOCLOpaqueType:
1878 case CK_IntToOCLSampler:
1879 case CK_FloatingToFixedPoint:
1880 case CK_FixedPointToFloating:
1881 case CK_FixedPointCast:
1882 case CK_FixedPointToIntegral:
1883 case CK_IntegralToFixedPoint:
1884 case CK_MatrixCast:
1885 assert(!getType()->isBooleanType() && "unheralded conversion to bool");
1886 goto CheckNoBasePath;
1888 case CK_Dependent:
1889 case CK_LValueToRValue:
1890 case CK_NoOp:
1891 case CK_AtomicToNonAtomic:
1892 case CK_NonAtomicToAtomic:
1893 case CK_PointerToBoolean:
1894 case CK_IntegralToBoolean:
1895 case CK_FloatingToBoolean:
1896 case CK_MemberPointerToBoolean:
1897 case CK_FloatingComplexToBoolean:
1898 case CK_IntegralComplexToBoolean:
1899 case CK_LValueBitCast: // -> bool&
1900 case CK_LValueToRValueBitCast:
1901 case CK_UserDefinedConversion: // operator bool()
1902 case CK_BuiltinFnToFnPtr:
1903 case CK_FixedPointToBoolean:
1904 CheckNoBasePath:
1905 assert(path_empty() && "Cast kind should not have a base path!");
1906 break;
1908 return true;
1911 const char *CastExpr::getCastKindName(CastKind CK) {
1912 switch (CK) {
1913 #define CAST_OPERATION(Name) case CK_##Name: return #Name;
1914 #include "clang/AST/OperationKinds.def"
1916 llvm_unreachable("Unhandled cast kind!");
1919 namespace {
1920 // Skip over implicit nodes produced as part of semantic analysis.
1921 // Designed for use with IgnoreExprNodes.
1922 static Expr *ignoreImplicitSemaNodes(Expr *E) {
1923 if (auto *Materialize = dyn_cast<MaterializeTemporaryExpr>(E))
1924 return Materialize->getSubExpr();
1926 if (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
1927 return Binder->getSubExpr();
1929 if (auto *Full = dyn_cast<FullExpr>(E))
1930 return Full->getSubExpr();
1932 if (auto *CPLIE = dyn_cast<CXXParenListInitExpr>(E);
1933 CPLIE && CPLIE->getInitExprs().size() == 1)
1934 return CPLIE->getInitExprs()[0];
1936 return E;
1938 } // namespace
1940 Expr *CastExpr::getSubExprAsWritten() {
1941 const Expr *SubExpr = nullptr;
1943 for (const CastExpr *E = this; E; E = dyn_cast<ImplicitCastExpr>(SubExpr)) {
1944 SubExpr = IgnoreExprNodes(E->getSubExpr(), ignoreImplicitSemaNodes);
1946 // Conversions by constructor and conversion functions have a
1947 // subexpression describing the call; strip it off.
1948 if (E->getCastKind() == CK_ConstructorConversion) {
1949 SubExpr = IgnoreExprNodes(cast<CXXConstructExpr>(SubExpr)->getArg(0),
1950 ignoreImplicitSemaNodes);
1951 } else if (E->getCastKind() == CK_UserDefinedConversion) {
1952 assert((isa<CXXMemberCallExpr>(SubExpr) || isa<BlockExpr>(SubExpr)) &&
1953 "Unexpected SubExpr for CK_UserDefinedConversion.");
1954 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SubExpr))
1955 SubExpr = MCE->getImplicitObjectArgument();
1959 return const_cast<Expr *>(SubExpr);
1962 NamedDecl *CastExpr::getConversionFunction() const {
1963 const Expr *SubExpr = nullptr;
1965 for (const CastExpr *E = this; E; E = dyn_cast<ImplicitCastExpr>(SubExpr)) {
1966 SubExpr = IgnoreExprNodes(E->getSubExpr(), ignoreImplicitSemaNodes);
1968 if (E->getCastKind() == CK_ConstructorConversion)
1969 return cast<CXXConstructExpr>(SubExpr)->getConstructor();
1971 if (E->getCastKind() == CK_UserDefinedConversion) {
1972 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SubExpr))
1973 return MCE->getMethodDecl();
1977 return nullptr;
1980 CXXBaseSpecifier **CastExpr::path_buffer() {
1981 switch (getStmtClass()) {
1982 #define ABSTRACT_STMT(x)
1983 #define CASTEXPR(Type, Base) \
1984 case Stmt::Type##Class: \
1985 return static_cast<Type *>(this)->getTrailingObjects<CXXBaseSpecifier *>();
1986 #define STMT(Type, Base)
1987 #include "clang/AST/StmtNodes.inc"
1988 default:
1989 llvm_unreachable("non-cast expressions not possible here");
1993 const FieldDecl *CastExpr::getTargetFieldForToUnionCast(QualType unionType,
1994 QualType opType) {
1995 auto RD = unionType->castAs<RecordType>()->getDecl();
1996 return getTargetFieldForToUnionCast(RD, opType);
1999 const FieldDecl *CastExpr::getTargetFieldForToUnionCast(const RecordDecl *RD,
2000 QualType OpType) {
2001 auto &Ctx = RD->getASTContext();
2002 RecordDecl::field_iterator Field, FieldEnd;
2003 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
2004 Field != FieldEnd; ++Field) {
2005 if (Ctx.hasSameUnqualifiedType(Field->getType(), OpType) &&
2006 !Field->isUnnamedBitfield()) {
2007 return *Field;
2010 return nullptr;
2013 FPOptionsOverride *CastExpr::getTrailingFPFeatures() {
2014 assert(hasStoredFPFeatures());
2015 switch (getStmtClass()) {
2016 case ImplicitCastExprClass:
2017 return static_cast<ImplicitCastExpr *>(this)
2018 ->getTrailingObjects<FPOptionsOverride>();
2019 case CStyleCastExprClass:
2020 return static_cast<CStyleCastExpr *>(this)
2021 ->getTrailingObjects<FPOptionsOverride>();
2022 case CXXFunctionalCastExprClass:
2023 return static_cast<CXXFunctionalCastExpr *>(this)
2024 ->getTrailingObjects<FPOptionsOverride>();
2025 case CXXStaticCastExprClass:
2026 return static_cast<CXXStaticCastExpr *>(this)
2027 ->getTrailingObjects<FPOptionsOverride>();
2028 default:
2029 llvm_unreachable("Cast does not have FPFeatures");
2033 ImplicitCastExpr *ImplicitCastExpr::Create(const ASTContext &C, QualType T,
2034 CastKind Kind, Expr *Operand,
2035 const CXXCastPath *BasePath,
2036 ExprValueKind VK,
2037 FPOptionsOverride FPO) {
2038 unsigned PathSize = (BasePath ? BasePath->size() : 0);
2039 void *Buffer =
2040 C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *, FPOptionsOverride>(
2041 PathSize, FPO.requiresTrailingStorage()));
2042 // Per C++ [conv.lval]p3, lvalue-to-rvalue conversions on class and
2043 // std::nullptr_t have special semantics not captured by CK_LValueToRValue.
2044 assert((Kind != CK_LValueToRValue ||
2045 !(T->isNullPtrType() || T->getAsCXXRecordDecl())) &&
2046 "invalid type for lvalue-to-rvalue conversion");
2047 ImplicitCastExpr *E =
2048 new (Buffer) ImplicitCastExpr(T, Kind, Operand, PathSize, FPO, VK);
2049 if (PathSize)
2050 std::uninitialized_copy_n(BasePath->data(), BasePath->size(),
2051 E->getTrailingObjects<CXXBaseSpecifier *>());
2052 return E;
2055 ImplicitCastExpr *ImplicitCastExpr::CreateEmpty(const ASTContext &C,
2056 unsigned PathSize,
2057 bool HasFPFeatures) {
2058 void *Buffer =
2059 C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *, FPOptionsOverride>(
2060 PathSize, HasFPFeatures));
2061 return new (Buffer) ImplicitCastExpr(EmptyShell(), PathSize, HasFPFeatures);
2064 CStyleCastExpr *CStyleCastExpr::Create(const ASTContext &C, QualType T,
2065 ExprValueKind VK, CastKind K, Expr *Op,
2066 const CXXCastPath *BasePath,
2067 FPOptionsOverride FPO,
2068 TypeSourceInfo *WrittenTy,
2069 SourceLocation L, SourceLocation R) {
2070 unsigned PathSize = (BasePath ? BasePath->size() : 0);
2071 void *Buffer =
2072 C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *, FPOptionsOverride>(
2073 PathSize, FPO.requiresTrailingStorage()));
2074 CStyleCastExpr *E =
2075 new (Buffer) CStyleCastExpr(T, VK, K, Op, PathSize, FPO, WrittenTy, L, R);
2076 if (PathSize)
2077 std::uninitialized_copy_n(BasePath->data(), BasePath->size(),
2078 E->getTrailingObjects<CXXBaseSpecifier *>());
2079 return E;
2082 CStyleCastExpr *CStyleCastExpr::CreateEmpty(const ASTContext &C,
2083 unsigned PathSize,
2084 bool HasFPFeatures) {
2085 void *Buffer =
2086 C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *, FPOptionsOverride>(
2087 PathSize, HasFPFeatures));
2088 return new (Buffer) CStyleCastExpr(EmptyShell(), PathSize, HasFPFeatures);
2091 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
2092 /// corresponds to, e.g. "<<=".
2093 StringRef BinaryOperator::getOpcodeStr(Opcode Op) {
2094 switch (Op) {
2095 #define BINARY_OPERATION(Name, Spelling) case BO_##Name: return Spelling;
2096 #include "clang/AST/OperationKinds.def"
2098 llvm_unreachable("Invalid OpCode!");
2101 BinaryOperatorKind
2102 BinaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO) {
2103 switch (OO) {
2104 default: llvm_unreachable("Not an overloadable binary operator");
2105 case OO_Plus: return BO_Add;
2106 case OO_Minus: return BO_Sub;
2107 case OO_Star: return BO_Mul;
2108 case OO_Slash: return BO_Div;
2109 case OO_Percent: return BO_Rem;
2110 case OO_Caret: return BO_Xor;
2111 case OO_Amp: return BO_And;
2112 case OO_Pipe: return BO_Or;
2113 case OO_Equal: return BO_Assign;
2114 case OO_Spaceship: return BO_Cmp;
2115 case OO_Less: return BO_LT;
2116 case OO_Greater: return BO_GT;
2117 case OO_PlusEqual: return BO_AddAssign;
2118 case OO_MinusEqual: return BO_SubAssign;
2119 case OO_StarEqual: return BO_MulAssign;
2120 case OO_SlashEqual: return BO_DivAssign;
2121 case OO_PercentEqual: return BO_RemAssign;
2122 case OO_CaretEqual: return BO_XorAssign;
2123 case OO_AmpEqual: return BO_AndAssign;
2124 case OO_PipeEqual: return BO_OrAssign;
2125 case OO_LessLess: return BO_Shl;
2126 case OO_GreaterGreater: return BO_Shr;
2127 case OO_LessLessEqual: return BO_ShlAssign;
2128 case OO_GreaterGreaterEqual: return BO_ShrAssign;
2129 case OO_EqualEqual: return BO_EQ;
2130 case OO_ExclaimEqual: return BO_NE;
2131 case OO_LessEqual: return BO_LE;
2132 case OO_GreaterEqual: return BO_GE;
2133 case OO_AmpAmp: return BO_LAnd;
2134 case OO_PipePipe: return BO_LOr;
2135 case OO_Comma: return BO_Comma;
2136 case OO_ArrowStar: return BO_PtrMemI;
2140 OverloadedOperatorKind BinaryOperator::getOverloadedOperator(Opcode Opc) {
2141 static const OverloadedOperatorKind OverOps[] = {
2142 /* .* Cannot be overloaded */OO_None, OO_ArrowStar,
2143 OO_Star, OO_Slash, OO_Percent,
2144 OO_Plus, OO_Minus,
2145 OO_LessLess, OO_GreaterGreater,
2146 OO_Spaceship,
2147 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
2148 OO_EqualEqual, OO_ExclaimEqual,
2149 OO_Amp,
2150 OO_Caret,
2151 OO_Pipe,
2152 OO_AmpAmp,
2153 OO_PipePipe,
2154 OO_Equal, OO_StarEqual,
2155 OO_SlashEqual, OO_PercentEqual,
2156 OO_PlusEqual, OO_MinusEqual,
2157 OO_LessLessEqual, OO_GreaterGreaterEqual,
2158 OO_AmpEqual, OO_CaretEqual,
2159 OO_PipeEqual,
2160 OO_Comma
2162 return OverOps[Opc];
2165 bool BinaryOperator::isNullPointerArithmeticExtension(ASTContext &Ctx,
2166 Opcode Opc,
2167 const Expr *LHS,
2168 const Expr *RHS) {
2169 if (Opc != BO_Add)
2170 return false;
2172 // Check that we have one pointer and one integer operand.
2173 const Expr *PExp;
2174 if (LHS->getType()->isPointerType()) {
2175 if (!RHS->getType()->isIntegerType())
2176 return false;
2177 PExp = LHS;
2178 } else if (RHS->getType()->isPointerType()) {
2179 if (!LHS->getType()->isIntegerType())
2180 return false;
2181 PExp = RHS;
2182 } else {
2183 return false;
2186 // Check that the pointer is a nullptr.
2187 if (!PExp->IgnoreParenCasts()
2188 ->isNullPointerConstant(Ctx, Expr::NPC_ValueDependentIsNotNull))
2189 return false;
2191 // Check that the pointee type is char-sized.
2192 const PointerType *PTy = PExp->getType()->getAs<PointerType>();
2193 if (!PTy || !PTy->getPointeeType()->isCharType())
2194 return false;
2196 return true;
2199 SourceLocExpr::SourceLocExpr(const ASTContext &Ctx, IdentKind Kind,
2200 QualType ResultTy, SourceLocation BLoc,
2201 SourceLocation RParenLoc,
2202 DeclContext *ParentContext)
2203 : Expr(SourceLocExprClass, ResultTy, VK_PRValue, OK_Ordinary),
2204 BuiltinLoc(BLoc), RParenLoc(RParenLoc), ParentContext(ParentContext) {
2205 SourceLocExprBits.Kind = Kind;
2206 setDependence(ExprDependence::None);
2209 StringRef SourceLocExpr::getBuiltinStr() const {
2210 switch (getIdentKind()) {
2211 case File:
2212 return "__builtin_FILE";
2213 case FileName:
2214 return "__builtin_FILE_NAME";
2215 case Function:
2216 return "__builtin_FUNCTION";
2217 case FuncSig:
2218 return "__builtin_FUNCSIG";
2219 case Line:
2220 return "__builtin_LINE";
2221 case Column:
2222 return "__builtin_COLUMN";
2223 case SourceLocStruct:
2224 return "__builtin_source_location";
2226 llvm_unreachable("unexpected IdentKind!");
2229 APValue SourceLocExpr::EvaluateInContext(const ASTContext &Ctx,
2230 const Expr *DefaultExpr) const {
2231 SourceLocation Loc;
2232 const DeclContext *Context;
2234 if (const auto *DIE = dyn_cast_if_present<CXXDefaultInitExpr>(DefaultExpr)) {
2235 Loc = DIE->getUsedLocation();
2236 Context = DIE->getUsedContext();
2237 } else if (const auto *DAE =
2238 dyn_cast_if_present<CXXDefaultArgExpr>(DefaultExpr)) {
2239 Loc = DAE->getUsedLocation();
2240 Context = DAE->getUsedContext();
2241 } else {
2242 Loc = getLocation();
2243 Context = getParentContext();
2246 PresumedLoc PLoc = Ctx.getSourceManager().getPresumedLoc(
2247 Ctx.getSourceManager().getExpansionRange(Loc).getEnd());
2249 auto MakeStringLiteral = [&](StringRef Tmp) {
2250 using LValuePathEntry = APValue::LValuePathEntry;
2251 StringLiteral *Res = Ctx.getPredefinedStringLiteralFromCache(Tmp);
2252 // Decay the string to a pointer to the first character.
2253 LValuePathEntry Path[1] = {LValuePathEntry::ArrayIndex(0)};
2254 return APValue(Res, CharUnits::Zero(), Path, /*OnePastTheEnd=*/false);
2257 switch (getIdentKind()) {
2258 case SourceLocExpr::FileName: {
2259 // __builtin_FILE_NAME() is a Clang-specific extension that expands to the
2260 // the last part of __builtin_FILE().
2261 SmallString<256> FileName;
2262 clang::Preprocessor::processPathToFileName(
2263 FileName, PLoc, Ctx.getLangOpts(), Ctx.getTargetInfo());
2264 return MakeStringLiteral(FileName);
2266 case SourceLocExpr::File: {
2267 SmallString<256> Path(PLoc.getFilename());
2268 clang::Preprocessor::processPathForFileMacro(Path, Ctx.getLangOpts(),
2269 Ctx.getTargetInfo());
2270 return MakeStringLiteral(Path);
2272 case SourceLocExpr::Function:
2273 case SourceLocExpr::FuncSig: {
2274 const auto *CurDecl = dyn_cast<Decl>(Context);
2275 const auto Kind = getIdentKind() == SourceLocExpr::Function
2276 ? PredefinedExpr::Function
2277 : PredefinedExpr::FuncSig;
2278 return MakeStringLiteral(
2279 CurDecl ? PredefinedExpr::ComputeName(Kind, CurDecl) : std::string(""));
2281 case SourceLocExpr::Line:
2282 return APValue(Ctx.MakeIntValue(PLoc.getLine(), Ctx.UnsignedIntTy));
2283 case SourceLocExpr::Column:
2284 return APValue(Ctx.MakeIntValue(PLoc.getColumn(), Ctx.UnsignedIntTy));
2285 case SourceLocExpr::SourceLocStruct: {
2286 // Fill in a std::source_location::__impl structure, by creating an
2287 // artificial file-scoped CompoundLiteralExpr, and returning a pointer to
2288 // that.
2289 const CXXRecordDecl *ImplDecl = getType()->getPointeeCXXRecordDecl();
2290 assert(ImplDecl);
2292 // Construct an APValue for the __impl struct, and get or create a Decl
2293 // corresponding to that. Note that we've already verified that the shape of
2294 // the ImplDecl type is as expected.
2296 APValue Value(APValue::UninitStruct(), 0, 4);
2297 for (const FieldDecl *F : ImplDecl->fields()) {
2298 StringRef Name = F->getName();
2299 if (Name == "_M_file_name") {
2300 SmallString<256> Path(PLoc.getFilename());
2301 clang::Preprocessor::processPathForFileMacro(Path, Ctx.getLangOpts(),
2302 Ctx.getTargetInfo());
2303 Value.getStructField(F->getFieldIndex()) = MakeStringLiteral(Path);
2304 } else if (Name == "_M_function_name") {
2305 // Note: this emits the PrettyFunction name -- different than what
2306 // __builtin_FUNCTION() above returns!
2307 const auto *CurDecl = dyn_cast<Decl>(Context);
2308 Value.getStructField(F->getFieldIndex()) = MakeStringLiteral(
2309 CurDecl && !isa<TranslationUnitDecl>(CurDecl)
2310 ? StringRef(PredefinedExpr::ComputeName(
2311 PredefinedExpr::PrettyFunction, CurDecl))
2312 : "");
2313 } else if (Name == "_M_line") {
2314 llvm::APSInt IntVal = Ctx.MakeIntValue(PLoc.getLine(), F->getType());
2315 Value.getStructField(F->getFieldIndex()) = APValue(IntVal);
2316 } else if (Name == "_M_column") {
2317 llvm::APSInt IntVal = Ctx.MakeIntValue(PLoc.getColumn(), F->getType());
2318 Value.getStructField(F->getFieldIndex()) = APValue(IntVal);
2322 UnnamedGlobalConstantDecl *GV =
2323 Ctx.getUnnamedGlobalConstantDecl(getType()->getPointeeType(), Value);
2325 return APValue(GV, CharUnits::Zero(), ArrayRef<APValue::LValuePathEntry>{},
2326 false);
2329 llvm_unreachable("unhandled case");
2332 InitListExpr::InitListExpr(const ASTContext &C, SourceLocation lbraceloc,
2333 ArrayRef<Expr *> initExprs, SourceLocation rbraceloc)
2334 : Expr(InitListExprClass, QualType(), VK_PRValue, OK_Ordinary),
2335 InitExprs(C, initExprs.size()), LBraceLoc(lbraceloc),
2336 RBraceLoc(rbraceloc), AltForm(nullptr, true) {
2337 sawArrayRangeDesignator(false);
2338 InitExprs.insert(C, InitExprs.end(), initExprs.begin(), initExprs.end());
2340 setDependence(computeDependence(this));
2343 void InitListExpr::reserveInits(const ASTContext &C, unsigned NumInits) {
2344 if (NumInits > InitExprs.size())
2345 InitExprs.reserve(C, NumInits);
2348 void InitListExpr::resizeInits(const ASTContext &C, unsigned NumInits) {
2349 InitExprs.resize(C, NumInits, nullptr);
2352 Expr *InitListExpr::updateInit(const ASTContext &C, unsigned Init, Expr *expr) {
2353 if (Init >= InitExprs.size()) {
2354 InitExprs.insert(C, InitExprs.end(), Init - InitExprs.size() + 1, nullptr);
2355 setInit(Init, expr);
2356 return nullptr;
2359 Expr *Result = cast_or_null<Expr>(InitExprs[Init]);
2360 setInit(Init, expr);
2361 return Result;
2364 void InitListExpr::setArrayFiller(Expr *filler) {
2365 assert(!hasArrayFiller() && "Filler already set!");
2366 ArrayFillerOrUnionFieldInit = filler;
2367 // Fill out any "holes" in the array due to designated initializers.
2368 Expr **inits = getInits();
2369 for (unsigned i = 0, e = getNumInits(); i != e; ++i)
2370 if (inits[i] == nullptr)
2371 inits[i] = filler;
2374 bool InitListExpr::isStringLiteralInit() const {
2375 if (getNumInits() != 1)
2376 return false;
2377 const ArrayType *AT = getType()->getAsArrayTypeUnsafe();
2378 if (!AT || !AT->getElementType()->isIntegerType())
2379 return false;
2380 // It is possible for getInit() to return null.
2381 const Expr *Init = getInit(0);
2382 if (!Init)
2383 return false;
2384 Init = Init->IgnoreParenImpCasts();
2385 return isa<StringLiteral>(Init) || isa<ObjCEncodeExpr>(Init);
2388 bool InitListExpr::isTransparent() const {
2389 assert(isSemanticForm() && "syntactic form never semantically transparent");
2391 // A glvalue InitListExpr is always just sugar.
2392 if (isGLValue()) {
2393 assert(getNumInits() == 1 && "multiple inits in glvalue init list");
2394 return true;
2397 // Otherwise, we're sugar if and only if we have exactly one initializer that
2398 // is of the same type.
2399 if (getNumInits() != 1 || !getInit(0))
2400 return false;
2402 // Don't confuse aggregate initialization of a struct X { X &x; }; with a
2403 // transparent struct copy.
2404 if (!getInit(0)->isPRValue() && getType()->isRecordType())
2405 return false;
2407 return getType().getCanonicalType() ==
2408 getInit(0)->getType().getCanonicalType();
2411 bool InitListExpr::isIdiomaticZeroInitializer(const LangOptions &LangOpts) const {
2412 assert(isSyntacticForm() && "only test syntactic form as zero initializer");
2414 if (LangOpts.CPlusPlus || getNumInits() != 1 || !getInit(0)) {
2415 return false;
2418 const IntegerLiteral *Lit = dyn_cast<IntegerLiteral>(getInit(0)->IgnoreImplicit());
2419 return Lit && Lit->getValue() == 0;
2422 SourceLocation InitListExpr::getBeginLoc() const {
2423 if (InitListExpr *SyntacticForm = getSyntacticForm())
2424 return SyntacticForm->getBeginLoc();
2425 SourceLocation Beg = LBraceLoc;
2426 if (Beg.isInvalid()) {
2427 // Find the first non-null initializer.
2428 for (InitExprsTy::const_iterator I = InitExprs.begin(),
2429 E = InitExprs.end();
2430 I != E; ++I) {
2431 if (Stmt *S = *I) {
2432 Beg = S->getBeginLoc();
2433 break;
2437 return Beg;
2440 SourceLocation InitListExpr::getEndLoc() const {
2441 if (InitListExpr *SyntacticForm = getSyntacticForm())
2442 return SyntacticForm->getEndLoc();
2443 SourceLocation End = RBraceLoc;
2444 if (End.isInvalid()) {
2445 // Find the first non-null initializer from the end.
2446 for (Stmt *S : llvm::reverse(InitExprs)) {
2447 if (S) {
2448 End = S->getEndLoc();
2449 break;
2453 return End;
2456 /// getFunctionType - Return the underlying function type for this block.
2458 const FunctionProtoType *BlockExpr::getFunctionType() const {
2459 // The block pointer is never sugared, but the function type might be.
2460 return cast<BlockPointerType>(getType())
2461 ->getPointeeType()->castAs<FunctionProtoType>();
2464 SourceLocation BlockExpr::getCaretLocation() const {
2465 return TheBlock->getCaretLocation();
2467 const Stmt *BlockExpr::getBody() const {
2468 return TheBlock->getBody();
2470 Stmt *BlockExpr::getBody() {
2471 return TheBlock->getBody();
2475 //===----------------------------------------------------------------------===//
2476 // Generic Expression Routines
2477 //===----------------------------------------------------------------------===//
2479 bool Expr::isReadIfDiscardedInCPlusPlus11() const {
2480 // In C++11, discarded-value expressions of a certain form are special,
2481 // according to [expr]p10:
2482 // The lvalue-to-rvalue conversion (4.1) is applied only if the
2483 // expression is a glvalue of volatile-qualified type and it has
2484 // one of the following forms:
2485 if (!isGLValue() || !getType().isVolatileQualified())
2486 return false;
2488 const Expr *E = IgnoreParens();
2490 // - id-expression (5.1.1),
2491 if (isa<DeclRefExpr>(E))
2492 return true;
2494 // - subscripting (5.2.1),
2495 if (isa<ArraySubscriptExpr>(E))
2496 return true;
2498 // - class member access (5.2.5),
2499 if (isa<MemberExpr>(E))
2500 return true;
2502 // - indirection (5.3.1),
2503 if (auto *UO = dyn_cast<UnaryOperator>(E))
2504 if (UO->getOpcode() == UO_Deref)
2505 return true;
2507 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
2508 // - pointer-to-member operation (5.5),
2509 if (BO->isPtrMemOp())
2510 return true;
2512 // - comma expression (5.18) where the right operand is one of the above.
2513 if (BO->getOpcode() == BO_Comma)
2514 return BO->getRHS()->isReadIfDiscardedInCPlusPlus11();
2517 // - conditional expression (5.16) where both the second and the third
2518 // operands are one of the above, or
2519 if (auto *CO = dyn_cast<ConditionalOperator>(E))
2520 return CO->getTrueExpr()->isReadIfDiscardedInCPlusPlus11() &&
2521 CO->getFalseExpr()->isReadIfDiscardedInCPlusPlus11();
2522 // The related edge case of "*x ?: *x".
2523 if (auto *BCO =
2524 dyn_cast<BinaryConditionalOperator>(E)) {
2525 if (auto *OVE = dyn_cast<OpaqueValueExpr>(BCO->getTrueExpr()))
2526 return OVE->getSourceExpr()->isReadIfDiscardedInCPlusPlus11() &&
2527 BCO->getFalseExpr()->isReadIfDiscardedInCPlusPlus11();
2530 // Objective-C++ extensions to the rule.
2531 if (isa<ObjCIvarRefExpr>(E))
2532 return true;
2533 if (const auto *POE = dyn_cast<PseudoObjectExpr>(E)) {
2534 if (isa<ObjCPropertyRefExpr, ObjCSubscriptRefExpr>(POE->getSyntacticForm()))
2535 return true;
2538 return false;
2541 /// isUnusedResultAWarning - Return true if this immediate expression should
2542 /// be warned about if the result is unused. If so, fill in Loc and Ranges
2543 /// with location to warn on and the source range[s] to report with the
2544 /// warning.
2545 bool Expr::isUnusedResultAWarning(const Expr *&WarnE, SourceLocation &Loc,
2546 SourceRange &R1, SourceRange &R2,
2547 ASTContext &Ctx) const {
2548 // Don't warn if the expr is type dependent. The type could end up
2549 // instantiating to void.
2550 if (isTypeDependent())
2551 return false;
2553 switch (getStmtClass()) {
2554 default:
2555 if (getType()->isVoidType())
2556 return false;
2557 WarnE = this;
2558 Loc = getExprLoc();
2559 R1 = getSourceRange();
2560 return true;
2561 case ParenExprClass:
2562 return cast<ParenExpr>(this)->getSubExpr()->
2563 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2564 case GenericSelectionExprClass:
2565 return cast<GenericSelectionExpr>(this)->getResultExpr()->
2566 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2567 case CoawaitExprClass:
2568 case CoyieldExprClass:
2569 return cast<CoroutineSuspendExpr>(this)->getResumeExpr()->
2570 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2571 case ChooseExprClass:
2572 return cast<ChooseExpr>(this)->getChosenSubExpr()->
2573 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2574 case UnaryOperatorClass: {
2575 const UnaryOperator *UO = cast<UnaryOperator>(this);
2577 switch (UO->getOpcode()) {
2578 case UO_Plus:
2579 case UO_Minus:
2580 case UO_AddrOf:
2581 case UO_Not:
2582 case UO_LNot:
2583 case UO_Deref:
2584 break;
2585 case UO_Coawait:
2586 // This is just the 'operator co_await' call inside the guts of a
2587 // dependent co_await call.
2588 case UO_PostInc:
2589 case UO_PostDec:
2590 case UO_PreInc:
2591 case UO_PreDec: // ++/--
2592 return false; // Not a warning.
2593 case UO_Real:
2594 case UO_Imag:
2595 // accessing a piece of a volatile complex is a side-effect.
2596 if (Ctx.getCanonicalType(UO->getSubExpr()->getType())
2597 .isVolatileQualified())
2598 return false;
2599 break;
2600 case UO_Extension:
2601 return UO->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2603 WarnE = this;
2604 Loc = UO->getOperatorLoc();
2605 R1 = UO->getSubExpr()->getSourceRange();
2606 return true;
2608 case BinaryOperatorClass: {
2609 const BinaryOperator *BO = cast<BinaryOperator>(this);
2610 switch (BO->getOpcode()) {
2611 default:
2612 break;
2613 // Consider the RHS of comma for side effects. LHS was checked by
2614 // Sema::CheckCommaOperands.
2615 case BO_Comma:
2616 // ((foo = <blah>), 0) is an idiom for hiding the result (and
2617 // lvalue-ness) of an assignment written in a macro.
2618 if (IntegerLiteral *IE =
2619 dyn_cast<IntegerLiteral>(BO->getRHS()->IgnoreParens()))
2620 if (IE->getValue() == 0)
2621 return false;
2622 return BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2623 // Consider '||', '&&' to have side effects if the LHS or RHS does.
2624 case BO_LAnd:
2625 case BO_LOr:
2626 if (!BO->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx) ||
2627 !BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx))
2628 return false;
2629 break;
2631 if (BO->isAssignmentOp())
2632 return false;
2633 WarnE = this;
2634 Loc = BO->getOperatorLoc();
2635 R1 = BO->getLHS()->getSourceRange();
2636 R2 = BO->getRHS()->getSourceRange();
2637 return true;
2639 case CompoundAssignOperatorClass:
2640 case VAArgExprClass:
2641 case AtomicExprClass:
2642 return false;
2644 case ConditionalOperatorClass: {
2645 // If only one of the LHS or RHS is a warning, the operator might
2646 // be being used for control flow. Only warn if both the LHS and
2647 // RHS are warnings.
2648 const auto *Exp = cast<ConditionalOperator>(this);
2649 return Exp->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx) &&
2650 Exp->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2652 case BinaryConditionalOperatorClass: {
2653 const auto *Exp = cast<BinaryConditionalOperator>(this);
2654 return Exp->getFalseExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2657 case MemberExprClass:
2658 WarnE = this;
2659 Loc = cast<MemberExpr>(this)->getMemberLoc();
2660 R1 = SourceRange(Loc, Loc);
2661 R2 = cast<MemberExpr>(this)->getBase()->getSourceRange();
2662 return true;
2664 case ArraySubscriptExprClass:
2665 WarnE = this;
2666 Loc = cast<ArraySubscriptExpr>(this)->getRBracketLoc();
2667 R1 = cast<ArraySubscriptExpr>(this)->getLHS()->getSourceRange();
2668 R2 = cast<ArraySubscriptExpr>(this)->getRHS()->getSourceRange();
2669 return true;
2671 case CXXOperatorCallExprClass: {
2672 // Warn about operator ==,!=,<,>,<=, and >= even when user-defined operator
2673 // overloads as there is no reasonable way to define these such that they
2674 // have non-trivial, desirable side-effects. See the -Wunused-comparison
2675 // warning: operators == and != are commonly typo'ed, and so warning on them
2676 // provides additional value as well. If this list is updated,
2677 // DiagnoseUnusedComparison should be as well.
2678 const CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(this);
2679 switch (Op->getOperator()) {
2680 default:
2681 break;
2682 case OO_EqualEqual:
2683 case OO_ExclaimEqual:
2684 case OO_Less:
2685 case OO_Greater:
2686 case OO_GreaterEqual:
2687 case OO_LessEqual:
2688 if (Op->getCallReturnType(Ctx)->isReferenceType() ||
2689 Op->getCallReturnType(Ctx)->isVoidType())
2690 break;
2691 WarnE = this;
2692 Loc = Op->getOperatorLoc();
2693 R1 = Op->getSourceRange();
2694 return true;
2697 // Fallthrough for generic call handling.
2698 [[fallthrough]];
2700 case CallExprClass:
2701 case CXXMemberCallExprClass:
2702 case UserDefinedLiteralClass: {
2703 // If this is a direct call, get the callee.
2704 const CallExpr *CE = cast<CallExpr>(this);
2705 if (const Decl *FD = CE->getCalleeDecl()) {
2706 // If the callee has attribute pure, const, or warn_unused_result, warn
2707 // about it. void foo() { strlen("bar"); } should warn.
2709 // Note: If new cases are added here, DiagnoseUnusedExprResult should be
2710 // updated to match for QoI.
2711 if (CE->hasUnusedResultAttr(Ctx) ||
2712 FD->hasAttr<PureAttr>() || FD->hasAttr<ConstAttr>()) {
2713 WarnE = this;
2714 Loc = CE->getCallee()->getBeginLoc();
2715 R1 = CE->getCallee()->getSourceRange();
2717 if (unsigned NumArgs = CE->getNumArgs())
2718 R2 = SourceRange(CE->getArg(0)->getBeginLoc(),
2719 CE->getArg(NumArgs - 1)->getEndLoc());
2720 return true;
2723 return false;
2726 // If we don't know precisely what we're looking at, let's not warn.
2727 case UnresolvedLookupExprClass:
2728 case CXXUnresolvedConstructExprClass:
2729 case RecoveryExprClass:
2730 return false;
2732 case CXXTemporaryObjectExprClass:
2733 case CXXConstructExprClass: {
2734 if (const CXXRecordDecl *Type = getType()->getAsCXXRecordDecl()) {
2735 const auto *WarnURAttr = Type->getAttr<WarnUnusedResultAttr>();
2736 if (Type->hasAttr<WarnUnusedAttr>() ||
2737 (WarnURAttr && WarnURAttr->IsCXX11NoDiscard())) {
2738 WarnE = this;
2739 Loc = getBeginLoc();
2740 R1 = getSourceRange();
2741 return true;
2745 const auto *CE = cast<CXXConstructExpr>(this);
2746 if (const CXXConstructorDecl *Ctor = CE->getConstructor()) {
2747 const auto *WarnURAttr = Ctor->getAttr<WarnUnusedResultAttr>();
2748 if (WarnURAttr && WarnURAttr->IsCXX11NoDiscard()) {
2749 WarnE = this;
2750 Loc = getBeginLoc();
2751 R1 = getSourceRange();
2753 if (unsigned NumArgs = CE->getNumArgs())
2754 R2 = SourceRange(CE->getArg(0)->getBeginLoc(),
2755 CE->getArg(NumArgs - 1)->getEndLoc());
2756 return true;
2760 return false;
2763 case ObjCMessageExprClass: {
2764 const ObjCMessageExpr *ME = cast<ObjCMessageExpr>(this);
2765 if (Ctx.getLangOpts().ObjCAutoRefCount &&
2766 ME->isInstanceMessage() &&
2767 !ME->getType()->isVoidType() &&
2768 ME->getMethodFamily() == OMF_init) {
2769 WarnE = this;
2770 Loc = getExprLoc();
2771 R1 = ME->getSourceRange();
2772 return true;
2775 if (const ObjCMethodDecl *MD = ME->getMethodDecl())
2776 if (MD->hasAttr<WarnUnusedResultAttr>()) {
2777 WarnE = this;
2778 Loc = getExprLoc();
2779 return true;
2782 return false;
2785 case ObjCPropertyRefExprClass:
2786 case ObjCSubscriptRefExprClass:
2787 WarnE = this;
2788 Loc = getExprLoc();
2789 R1 = getSourceRange();
2790 return true;
2792 case PseudoObjectExprClass: {
2793 const auto *POE = cast<PseudoObjectExpr>(this);
2795 // For some syntactic forms, we should always warn.
2796 if (isa<ObjCPropertyRefExpr, ObjCSubscriptRefExpr>(
2797 POE->getSyntacticForm())) {
2798 WarnE = this;
2799 Loc = getExprLoc();
2800 R1 = getSourceRange();
2801 return true;
2804 // For others, we should never warn.
2805 if (auto *BO = dyn_cast<BinaryOperator>(POE->getSyntacticForm()))
2806 if (BO->isAssignmentOp())
2807 return false;
2808 if (auto *UO = dyn_cast<UnaryOperator>(POE->getSyntacticForm()))
2809 if (UO->isIncrementDecrementOp())
2810 return false;
2812 // Otherwise, warn if the result expression would warn.
2813 const Expr *Result = POE->getResultExpr();
2814 return Result && Result->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2817 case StmtExprClass: {
2818 // Statement exprs don't logically have side effects themselves, but are
2819 // sometimes used in macros in ways that give them a type that is unused.
2820 // For example ({ blah; foo(); }) will end up with a type if foo has a type.
2821 // however, if the result of the stmt expr is dead, we don't want to emit a
2822 // warning.
2823 const CompoundStmt *CS = cast<StmtExpr>(this)->getSubStmt();
2824 if (!CS->body_empty()) {
2825 if (const Expr *E = dyn_cast<Expr>(CS->body_back()))
2826 return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2827 if (const LabelStmt *Label = dyn_cast<LabelStmt>(CS->body_back()))
2828 if (const Expr *E = dyn_cast<Expr>(Label->getSubStmt()))
2829 return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2832 if (getType()->isVoidType())
2833 return false;
2834 WarnE = this;
2835 Loc = cast<StmtExpr>(this)->getLParenLoc();
2836 R1 = getSourceRange();
2837 return true;
2839 case CXXFunctionalCastExprClass:
2840 case CStyleCastExprClass: {
2841 // Ignore an explicit cast to void, except in C++98 if the operand is a
2842 // volatile glvalue for which we would trigger an implicit read in any
2843 // other language mode. (Such an implicit read always happens as part of
2844 // the lvalue conversion in C, and happens in C++ for expressions of all
2845 // forms where it seems likely the user intended to trigger a volatile
2846 // load.)
2847 const CastExpr *CE = cast<CastExpr>(this);
2848 const Expr *SubE = CE->getSubExpr()->IgnoreParens();
2849 if (CE->getCastKind() == CK_ToVoid) {
2850 if (Ctx.getLangOpts().CPlusPlus && !Ctx.getLangOpts().CPlusPlus11 &&
2851 SubE->isReadIfDiscardedInCPlusPlus11()) {
2852 // Suppress the "unused value" warning for idiomatic usage of
2853 // '(void)var;' used to suppress "unused variable" warnings.
2854 if (auto *DRE = dyn_cast<DeclRefExpr>(SubE))
2855 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
2856 if (!VD->isExternallyVisible())
2857 return false;
2859 // The lvalue-to-rvalue conversion would have no effect for an array.
2860 // It's implausible that the programmer expected this to result in a
2861 // volatile array load, so don't warn.
2862 if (SubE->getType()->isArrayType())
2863 return false;
2865 return SubE->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2867 return false;
2870 // If this is a cast to a constructor conversion, check the operand.
2871 // Otherwise, the result of the cast is unused.
2872 if (CE->getCastKind() == CK_ConstructorConversion)
2873 return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2874 if (CE->getCastKind() == CK_Dependent)
2875 return false;
2877 WarnE = this;
2878 if (const CXXFunctionalCastExpr *CXXCE =
2879 dyn_cast<CXXFunctionalCastExpr>(this)) {
2880 Loc = CXXCE->getBeginLoc();
2881 R1 = CXXCE->getSubExpr()->getSourceRange();
2882 } else {
2883 const CStyleCastExpr *CStyleCE = cast<CStyleCastExpr>(this);
2884 Loc = CStyleCE->getLParenLoc();
2885 R1 = CStyleCE->getSubExpr()->getSourceRange();
2887 return true;
2889 case ImplicitCastExprClass: {
2890 const CastExpr *ICE = cast<ImplicitCastExpr>(this);
2892 // lvalue-to-rvalue conversion on a volatile lvalue is a side-effect.
2893 if (ICE->getCastKind() == CK_LValueToRValue &&
2894 ICE->getSubExpr()->getType().isVolatileQualified())
2895 return false;
2897 return ICE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2899 case CXXDefaultArgExprClass:
2900 return (cast<CXXDefaultArgExpr>(this)
2901 ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
2902 case CXXDefaultInitExprClass:
2903 return (cast<CXXDefaultInitExpr>(this)
2904 ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
2906 case CXXNewExprClass:
2907 // FIXME: In theory, there might be new expressions that don't have side
2908 // effects (e.g. a placement new with an uninitialized POD).
2909 case CXXDeleteExprClass:
2910 return false;
2911 case MaterializeTemporaryExprClass:
2912 return cast<MaterializeTemporaryExpr>(this)
2913 ->getSubExpr()
2914 ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2915 case CXXBindTemporaryExprClass:
2916 return cast<CXXBindTemporaryExpr>(this)->getSubExpr()
2917 ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2918 case ExprWithCleanupsClass:
2919 return cast<ExprWithCleanups>(this)->getSubExpr()
2920 ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2924 /// isOBJCGCCandidate - Check if an expression is objc gc'able.
2925 /// returns true, if it is; false otherwise.
2926 bool Expr::isOBJCGCCandidate(ASTContext &Ctx) const {
2927 const Expr *E = IgnoreParens();
2928 switch (E->getStmtClass()) {
2929 default:
2930 return false;
2931 case ObjCIvarRefExprClass:
2932 return true;
2933 case Expr::UnaryOperatorClass:
2934 return cast<UnaryOperator>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
2935 case ImplicitCastExprClass:
2936 return cast<ImplicitCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
2937 case MaterializeTemporaryExprClass:
2938 return cast<MaterializeTemporaryExpr>(E)->getSubExpr()->isOBJCGCCandidate(
2939 Ctx);
2940 case CStyleCastExprClass:
2941 return cast<CStyleCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
2942 case DeclRefExprClass: {
2943 const Decl *D = cast<DeclRefExpr>(E)->getDecl();
2945 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2946 if (VD->hasGlobalStorage())
2947 return true;
2948 QualType T = VD->getType();
2949 // dereferencing to a pointer is always a gc'able candidate,
2950 // unless it is __weak.
2951 return T->isPointerType() &&
2952 (Ctx.getObjCGCAttrKind(T) != Qualifiers::Weak);
2954 return false;
2956 case MemberExprClass: {
2957 const MemberExpr *M = cast<MemberExpr>(E);
2958 return M->getBase()->isOBJCGCCandidate(Ctx);
2960 case ArraySubscriptExprClass:
2961 return cast<ArraySubscriptExpr>(E)->getBase()->isOBJCGCCandidate(Ctx);
2965 bool Expr::isBoundMemberFunction(ASTContext &Ctx) const {
2966 if (isTypeDependent())
2967 return false;
2968 return ClassifyLValue(Ctx) == Expr::LV_MemberFunction;
2971 QualType Expr::findBoundMemberType(const Expr *expr) {
2972 assert(expr->hasPlaceholderType(BuiltinType::BoundMember));
2974 // Bound member expressions are always one of these possibilities:
2975 // x->m x.m x->*y x.*y
2976 // (possibly parenthesized)
2978 expr = expr->IgnoreParens();
2979 if (const MemberExpr *mem = dyn_cast<MemberExpr>(expr)) {
2980 assert(isa<CXXMethodDecl>(mem->getMemberDecl()));
2981 return mem->getMemberDecl()->getType();
2984 if (const BinaryOperator *op = dyn_cast<BinaryOperator>(expr)) {
2985 QualType type = op->getRHS()->getType()->castAs<MemberPointerType>()
2986 ->getPointeeType();
2987 assert(type->isFunctionType());
2988 return type;
2991 assert(isa<UnresolvedMemberExpr>(expr) || isa<CXXPseudoDestructorExpr>(expr));
2992 return QualType();
2995 Expr *Expr::IgnoreImpCasts() {
2996 return IgnoreExprNodes(this, IgnoreImplicitCastsSingleStep);
2999 Expr *Expr::IgnoreCasts() {
3000 return IgnoreExprNodes(this, IgnoreCastsSingleStep);
3003 Expr *Expr::IgnoreImplicit() {
3004 return IgnoreExprNodes(this, IgnoreImplicitSingleStep);
3007 Expr *Expr::IgnoreImplicitAsWritten() {
3008 return IgnoreExprNodes(this, IgnoreImplicitAsWrittenSingleStep);
3011 Expr *Expr::IgnoreParens() {
3012 return IgnoreExprNodes(this, IgnoreParensSingleStep);
3015 Expr *Expr::IgnoreParenImpCasts() {
3016 return IgnoreExprNodes(this, IgnoreParensSingleStep,
3017 IgnoreImplicitCastsExtraSingleStep);
3020 Expr *Expr::IgnoreParenCasts() {
3021 return IgnoreExprNodes(this, IgnoreParensSingleStep, IgnoreCastsSingleStep);
3024 Expr *Expr::IgnoreConversionOperatorSingleStep() {
3025 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(this)) {
3026 if (MCE->getMethodDecl() && isa<CXXConversionDecl>(MCE->getMethodDecl()))
3027 return MCE->getImplicitObjectArgument();
3029 return this;
3032 Expr *Expr::IgnoreParenLValueCasts() {
3033 return IgnoreExprNodes(this, IgnoreParensSingleStep,
3034 IgnoreLValueCastsSingleStep);
3037 Expr *Expr::IgnoreParenBaseCasts() {
3038 return IgnoreExprNodes(this, IgnoreParensSingleStep,
3039 IgnoreBaseCastsSingleStep);
3042 Expr *Expr::IgnoreParenNoopCasts(const ASTContext &Ctx) {
3043 auto IgnoreNoopCastsSingleStep = [&Ctx](Expr *E) {
3044 if (auto *CE = dyn_cast<CastExpr>(E)) {
3045 // We ignore integer <-> casts that are of the same width, ptr<->ptr and
3046 // ptr<->int casts of the same width. We also ignore all identity casts.
3047 Expr *SubExpr = CE->getSubExpr();
3048 bool IsIdentityCast =
3049 Ctx.hasSameUnqualifiedType(E->getType(), SubExpr->getType());
3050 bool IsSameWidthCast = (E->getType()->isPointerType() ||
3051 E->getType()->isIntegralType(Ctx)) &&
3052 (SubExpr->getType()->isPointerType() ||
3053 SubExpr->getType()->isIntegralType(Ctx)) &&
3054 (Ctx.getTypeSize(E->getType()) ==
3055 Ctx.getTypeSize(SubExpr->getType()));
3057 if (IsIdentityCast || IsSameWidthCast)
3058 return SubExpr;
3059 } else if (auto *NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E))
3060 return NTTP->getReplacement();
3062 return E;
3064 return IgnoreExprNodes(this, IgnoreParensSingleStep,
3065 IgnoreNoopCastsSingleStep);
3068 Expr *Expr::IgnoreUnlessSpelledInSource() {
3069 auto IgnoreImplicitConstructorSingleStep = [](Expr *E) {
3070 if (auto *Cast = dyn_cast<CXXFunctionalCastExpr>(E)) {
3071 auto *SE = Cast->getSubExpr();
3072 if (SE->getSourceRange() == E->getSourceRange())
3073 return SE;
3076 if (auto *C = dyn_cast<CXXConstructExpr>(E)) {
3077 auto NumArgs = C->getNumArgs();
3078 if (NumArgs == 1 ||
3079 (NumArgs > 1 && isa<CXXDefaultArgExpr>(C->getArg(1)))) {
3080 Expr *A = C->getArg(0);
3081 if (A->getSourceRange() == E->getSourceRange() || C->isElidable())
3082 return A;
3085 return E;
3087 auto IgnoreImplicitMemberCallSingleStep = [](Expr *E) {
3088 if (auto *C = dyn_cast<CXXMemberCallExpr>(E)) {
3089 Expr *ExprNode = C->getImplicitObjectArgument();
3090 if (ExprNode->getSourceRange() == E->getSourceRange()) {
3091 return ExprNode;
3093 if (auto *PE = dyn_cast<ParenExpr>(ExprNode)) {
3094 if (PE->getSourceRange() == C->getSourceRange()) {
3095 return cast<Expr>(PE);
3098 ExprNode = ExprNode->IgnoreParenImpCasts();
3099 if (ExprNode->getSourceRange() == E->getSourceRange())
3100 return ExprNode;
3102 return E;
3104 return IgnoreExprNodes(
3105 this, IgnoreImplicitSingleStep, IgnoreImplicitCastsExtraSingleStep,
3106 IgnoreParensOnlySingleStep, IgnoreImplicitConstructorSingleStep,
3107 IgnoreImplicitMemberCallSingleStep);
3110 bool Expr::isDefaultArgument() const {
3111 const Expr *E = this;
3112 if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
3113 E = M->getSubExpr();
3115 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3116 E = ICE->getSubExprAsWritten();
3118 return isa<CXXDefaultArgExpr>(E);
3121 /// Skip over any no-op casts and any temporary-binding
3122 /// expressions.
3123 static const Expr *skipTemporaryBindingsNoOpCastsAndParens(const Expr *E) {
3124 if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
3125 E = M->getSubExpr();
3127 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3128 if (ICE->getCastKind() == CK_NoOp)
3129 E = ICE->getSubExpr();
3130 else
3131 break;
3134 while (const CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
3135 E = BE->getSubExpr();
3137 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3138 if (ICE->getCastKind() == CK_NoOp)
3139 E = ICE->getSubExpr();
3140 else
3141 break;
3144 return E->IgnoreParens();
3147 /// isTemporaryObject - Determines if this expression produces a
3148 /// temporary of the given class type.
3149 bool Expr::isTemporaryObject(ASTContext &C, const CXXRecordDecl *TempTy) const {
3150 if (!C.hasSameUnqualifiedType(getType(), C.getTypeDeclType(TempTy)))
3151 return false;
3153 const Expr *E = skipTemporaryBindingsNoOpCastsAndParens(this);
3155 // Temporaries are by definition pr-values of class type.
3156 if (!E->Classify(C).isPRValue()) {
3157 // In this context, property reference is a message call and is pr-value.
3158 if (!isa<ObjCPropertyRefExpr>(E))
3159 return false;
3162 // Black-list a few cases which yield pr-values of class type that don't
3163 // refer to temporaries of that type:
3165 // - implicit derived-to-base conversions
3166 if (isa<ImplicitCastExpr>(E)) {
3167 switch (cast<ImplicitCastExpr>(E)->getCastKind()) {
3168 case CK_DerivedToBase:
3169 case CK_UncheckedDerivedToBase:
3170 return false;
3171 default:
3172 break;
3176 // - member expressions (all)
3177 if (isa<MemberExpr>(E))
3178 return false;
3180 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E))
3181 if (BO->isPtrMemOp())
3182 return false;
3184 // - opaque values (all)
3185 if (isa<OpaqueValueExpr>(E))
3186 return false;
3188 return true;
3191 bool Expr::isImplicitCXXThis() const {
3192 const Expr *E = this;
3194 // Strip away parentheses and casts we don't care about.
3195 while (true) {
3196 if (const ParenExpr *Paren = dyn_cast<ParenExpr>(E)) {
3197 E = Paren->getSubExpr();
3198 continue;
3201 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3202 if (ICE->getCastKind() == CK_NoOp ||
3203 ICE->getCastKind() == CK_LValueToRValue ||
3204 ICE->getCastKind() == CK_DerivedToBase ||
3205 ICE->getCastKind() == CK_UncheckedDerivedToBase) {
3206 E = ICE->getSubExpr();
3207 continue;
3211 if (const UnaryOperator* UnOp = dyn_cast<UnaryOperator>(E)) {
3212 if (UnOp->getOpcode() == UO_Extension) {
3213 E = UnOp->getSubExpr();
3214 continue;
3218 if (const MaterializeTemporaryExpr *M
3219 = dyn_cast<MaterializeTemporaryExpr>(E)) {
3220 E = M->getSubExpr();
3221 continue;
3224 break;
3227 if (const CXXThisExpr *This = dyn_cast<CXXThisExpr>(E))
3228 return This->isImplicit();
3230 return false;
3233 /// hasAnyTypeDependentArguments - Determines if any of the expressions
3234 /// in Exprs is type-dependent.
3235 bool Expr::hasAnyTypeDependentArguments(ArrayRef<Expr *> Exprs) {
3236 for (unsigned I = 0; I < Exprs.size(); ++I)
3237 if (Exprs[I]->isTypeDependent())
3238 return true;
3240 return false;
3243 bool Expr::isConstantInitializer(ASTContext &Ctx, bool IsForRef,
3244 const Expr **Culprit) const {
3245 assert(!isValueDependent() &&
3246 "Expression evaluator can't be called on a dependent expression.");
3248 // This function is attempting whether an expression is an initializer
3249 // which can be evaluated at compile-time. It very closely parallels
3250 // ConstExprEmitter in CGExprConstant.cpp; if they don't match, it
3251 // will lead to unexpected results. Like ConstExprEmitter, it falls back
3252 // to isEvaluatable most of the time.
3254 // If we ever capture reference-binding directly in the AST, we can
3255 // kill the second parameter.
3257 if (IsForRef) {
3258 if (auto *EWC = dyn_cast<ExprWithCleanups>(this))
3259 return EWC->getSubExpr()->isConstantInitializer(Ctx, true, Culprit);
3260 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(this))
3261 return MTE->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
3262 EvalResult Result;
3263 if (EvaluateAsLValue(Result, Ctx) && !Result.HasSideEffects)
3264 return true;
3265 if (Culprit)
3266 *Culprit = this;
3267 return false;
3270 switch (getStmtClass()) {
3271 default: break;
3272 case Stmt::ExprWithCleanupsClass:
3273 return cast<ExprWithCleanups>(this)->getSubExpr()->isConstantInitializer(
3274 Ctx, IsForRef, Culprit);
3275 case StringLiteralClass:
3276 case ObjCEncodeExprClass:
3277 return true;
3278 case CXXTemporaryObjectExprClass:
3279 case CXXConstructExprClass: {
3280 const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
3282 if (CE->getConstructor()->isTrivial() &&
3283 CE->getConstructor()->getParent()->hasTrivialDestructor()) {
3284 // Trivial default constructor
3285 if (!CE->getNumArgs()) return true;
3287 // Trivial copy constructor
3288 assert(CE->getNumArgs() == 1 && "trivial ctor with > 1 argument");
3289 return CE->getArg(0)->isConstantInitializer(Ctx, false, Culprit);
3292 break;
3294 case ConstantExprClass: {
3295 // FIXME: We should be able to return "true" here, but it can lead to extra
3296 // error messages. E.g. in Sema/array-init.c.
3297 const Expr *Exp = cast<ConstantExpr>(this)->getSubExpr();
3298 return Exp->isConstantInitializer(Ctx, false, Culprit);
3300 case CompoundLiteralExprClass: {
3301 // This handles gcc's extension that allows global initializers like
3302 // "struct x {int x;} x = (struct x) {};".
3303 // FIXME: This accepts other cases it shouldn't!
3304 const Expr *Exp = cast<CompoundLiteralExpr>(this)->getInitializer();
3305 return Exp->isConstantInitializer(Ctx, false, Culprit);
3307 case DesignatedInitUpdateExprClass: {
3308 const DesignatedInitUpdateExpr *DIUE = cast<DesignatedInitUpdateExpr>(this);
3309 return DIUE->getBase()->isConstantInitializer(Ctx, false, Culprit) &&
3310 DIUE->getUpdater()->isConstantInitializer(Ctx, false, Culprit);
3312 case InitListExprClass: {
3313 const InitListExpr *ILE = cast<InitListExpr>(this);
3314 assert(ILE->isSemanticForm() && "InitListExpr must be in semantic form");
3315 if (ILE->getType()->isArrayType()) {
3316 unsigned numInits = ILE->getNumInits();
3317 for (unsigned i = 0; i < numInits; i++) {
3318 if (!ILE->getInit(i)->isConstantInitializer(Ctx, false, Culprit))
3319 return false;
3321 return true;
3324 if (ILE->getType()->isRecordType()) {
3325 unsigned ElementNo = 0;
3326 RecordDecl *RD = ILE->getType()->castAs<RecordType>()->getDecl();
3327 for (const auto *Field : RD->fields()) {
3328 // If this is a union, skip all the fields that aren't being initialized.
3329 if (RD->isUnion() && ILE->getInitializedFieldInUnion() != Field)
3330 continue;
3332 // Don't emit anonymous bitfields, they just affect layout.
3333 if (Field->isUnnamedBitfield())
3334 continue;
3336 if (ElementNo < ILE->getNumInits()) {
3337 const Expr *Elt = ILE->getInit(ElementNo++);
3338 if (Field->isBitField()) {
3339 // Bitfields have to evaluate to an integer.
3340 EvalResult Result;
3341 if (!Elt->EvaluateAsInt(Result, Ctx)) {
3342 if (Culprit)
3343 *Culprit = Elt;
3344 return false;
3346 } else {
3347 bool RefType = Field->getType()->isReferenceType();
3348 if (!Elt->isConstantInitializer(Ctx, RefType, Culprit))
3349 return false;
3353 return true;
3356 break;
3358 case ImplicitValueInitExprClass:
3359 case NoInitExprClass:
3360 return true;
3361 case ParenExprClass:
3362 return cast<ParenExpr>(this)->getSubExpr()
3363 ->isConstantInitializer(Ctx, IsForRef, Culprit);
3364 case GenericSelectionExprClass:
3365 return cast<GenericSelectionExpr>(this)->getResultExpr()
3366 ->isConstantInitializer(Ctx, IsForRef, Culprit);
3367 case ChooseExprClass:
3368 if (cast<ChooseExpr>(this)->isConditionDependent()) {
3369 if (Culprit)
3370 *Culprit = this;
3371 return false;
3373 return cast<ChooseExpr>(this)->getChosenSubExpr()
3374 ->isConstantInitializer(Ctx, IsForRef, Culprit);
3375 case UnaryOperatorClass: {
3376 const UnaryOperator* Exp = cast<UnaryOperator>(this);
3377 if (Exp->getOpcode() == UO_Extension)
3378 return Exp->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
3379 break;
3381 case CXXFunctionalCastExprClass:
3382 case CXXStaticCastExprClass:
3383 case ImplicitCastExprClass:
3384 case CStyleCastExprClass:
3385 case ObjCBridgedCastExprClass:
3386 case CXXDynamicCastExprClass:
3387 case CXXReinterpretCastExprClass:
3388 case CXXAddrspaceCastExprClass:
3389 case CXXConstCastExprClass: {
3390 const CastExpr *CE = cast<CastExpr>(this);
3392 // Handle misc casts we want to ignore.
3393 if (CE->getCastKind() == CK_NoOp ||
3394 CE->getCastKind() == CK_LValueToRValue ||
3395 CE->getCastKind() == CK_ToUnion ||
3396 CE->getCastKind() == CK_ConstructorConversion ||
3397 CE->getCastKind() == CK_NonAtomicToAtomic ||
3398 CE->getCastKind() == CK_AtomicToNonAtomic ||
3399 CE->getCastKind() == CK_NullToPointer ||
3400 CE->getCastKind() == CK_IntToOCLSampler)
3401 return CE->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
3403 break;
3405 case MaterializeTemporaryExprClass:
3406 return cast<MaterializeTemporaryExpr>(this)
3407 ->getSubExpr()
3408 ->isConstantInitializer(Ctx, false, Culprit);
3410 case SubstNonTypeTemplateParmExprClass:
3411 return cast<SubstNonTypeTemplateParmExpr>(this)->getReplacement()
3412 ->isConstantInitializer(Ctx, false, Culprit);
3413 case CXXDefaultArgExprClass:
3414 return cast<CXXDefaultArgExpr>(this)->getExpr()
3415 ->isConstantInitializer(Ctx, false, Culprit);
3416 case CXXDefaultInitExprClass:
3417 return cast<CXXDefaultInitExpr>(this)->getExpr()
3418 ->isConstantInitializer(Ctx, false, Culprit);
3420 // Allow certain forms of UB in constant initializers: signed integer
3421 // overflow and floating-point division by zero. We'll give a warning on
3422 // these, but they're common enough that we have to accept them.
3423 if (isEvaluatable(Ctx, SE_AllowUndefinedBehavior))
3424 return true;
3425 if (Culprit)
3426 *Culprit = this;
3427 return false;
3430 bool CallExpr::isBuiltinAssumeFalse(const ASTContext &Ctx) const {
3431 unsigned BuiltinID = getBuiltinCallee();
3432 if (BuiltinID != Builtin::BI__assume &&
3433 BuiltinID != Builtin::BI__builtin_assume)
3434 return false;
3436 const Expr* Arg = getArg(0);
3437 bool ArgVal;
3438 return !Arg->isValueDependent() &&
3439 Arg->EvaluateAsBooleanCondition(ArgVal, Ctx) && !ArgVal;
3442 bool CallExpr::isCallToStdMove() const {
3443 return getBuiltinCallee() == Builtin::BImove;
3446 namespace {
3447 /// Look for any side effects within a Stmt.
3448 class SideEffectFinder : public ConstEvaluatedExprVisitor<SideEffectFinder> {
3449 typedef ConstEvaluatedExprVisitor<SideEffectFinder> Inherited;
3450 const bool IncludePossibleEffects;
3451 bool HasSideEffects;
3453 public:
3454 explicit SideEffectFinder(const ASTContext &Context, bool IncludePossible)
3455 : Inherited(Context),
3456 IncludePossibleEffects(IncludePossible), HasSideEffects(false) { }
3458 bool hasSideEffects() const { return HasSideEffects; }
3460 void VisitDecl(const Decl *D) {
3461 if (!D)
3462 return;
3464 // We assume the caller checks subexpressions (eg, the initializer, VLA
3465 // bounds) for side-effects on our behalf.
3466 if (auto *VD = dyn_cast<VarDecl>(D)) {
3467 // Registering a destructor is a side-effect.
3468 if (IncludePossibleEffects && VD->isThisDeclarationADefinition() &&
3469 VD->needsDestruction(Context))
3470 HasSideEffects = true;
3474 void VisitDeclStmt(const DeclStmt *DS) {
3475 for (auto *D : DS->decls())
3476 VisitDecl(D);
3477 Inherited::VisitDeclStmt(DS);
3480 void VisitExpr(const Expr *E) {
3481 if (!HasSideEffects &&
3482 E->HasSideEffects(Context, IncludePossibleEffects))
3483 HasSideEffects = true;
3488 bool Expr::HasSideEffects(const ASTContext &Ctx,
3489 bool IncludePossibleEffects) const {
3490 // In circumstances where we care about definite side effects instead of
3491 // potential side effects, we want to ignore expressions that are part of a
3492 // macro expansion as a potential side effect.
3493 if (!IncludePossibleEffects && getExprLoc().isMacroID())
3494 return false;
3496 switch (getStmtClass()) {
3497 case NoStmtClass:
3498 #define ABSTRACT_STMT(Type)
3499 #define STMT(Type, Base) case Type##Class:
3500 #define EXPR(Type, Base)
3501 #include "clang/AST/StmtNodes.inc"
3502 llvm_unreachable("unexpected Expr kind");
3504 case DependentScopeDeclRefExprClass:
3505 case CXXUnresolvedConstructExprClass:
3506 case CXXDependentScopeMemberExprClass:
3507 case UnresolvedLookupExprClass:
3508 case UnresolvedMemberExprClass:
3509 case PackExpansionExprClass:
3510 case SubstNonTypeTemplateParmPackExprClass:
3511 case FunctionParmPackExprClass:
3512 case TypoExprClass:
3513 case RecoveryExprClass:
3514 case CXXFoldExprClass:
3515 // Make a conservative assumption for dependent nodes.
3516 return IncludePossibleEffects;
3518 case DeclRefExprClass:
3519 case ObjCIvarRefExprClass:
3520 case PredefinedExprClass:
3521 case IntegerLiteralClass:
3522 case FixedPointLiteralClass:
3523 case FloatingLiteralClass:
3524 case ImaginaryLiteralClass:
3525 case StringLiteralClass:
3526 case CharacterLiteralClass:
3527 case OffsetOfExprClass:
3528 case ImplicitValueInitExprClass:
3529 case UnaryExprOrTypeTraitExprClass:
3530 case AddrLabelExprClass:
3531 case GNUNullExprClass:
3532 case ArrayInitIndexExprClass:
3533 case NoInitExprClass:
3534 case CXXBoolLiteralExprClass:
3535 case CXXNullPtrLiteralExprClass:
3536 case CXXThisExprClass:
3537 case CXXScalarValueInitExprClass:
3538 case TypeTraitExprClass:
3539 case ArrayTypeTraitExprClass:
3540 case ExpressionTraitExprClass:
3541 case CXXNoexceptExprClass:
3542 case SizeOfPackExprClass:
3543 case ObjCStringLiteralClass:
3544 case ObjCEncodeExprClass:
3545 case ObjCBoolLiteralExprClass:
3546 case ObjCAvailabilityCheckExprClass:
3547 case CXXUuidofExprClass:
3548 case OpaqueValueExprClass:
3549 case SourceLocExprClass:
3550 case ConceptSpecializationExprClass:
3551 case RequiresExprClass:
3552 case SYCLUniqueStableNameExprClass:
3553 // These never have a side-effect.
3554 return false;
3556 case ConstantExprClass:
3557 // FIXME: Move this into the "return false;" block above.
3558 return cast<ConstantExpr>(this)->getSubExpr()->HasSideEffects(
3559 Ctx, IncludePossibleEffects);
3561 case CallExprClass:
3562 case CXXOperatorCallExprClass:
3563 case CXXMemberCallExprClass:
3564 case CUDAKernelCallExprClass:
3565 case UserDefinedLiteralClass: {
3566 // We don't know a call definitely has side effects, except for calls
3567 // to pure/const functions that definitely don't.
3568 // If the call itself is considered side-effect free, check the operands.
3569 const Decl *FD = cast<CallExpr>(this)->getCalleeDecl();
3570 bool IsPure = FD && (FD->hasAttr<ConstAttr>() || FD->hasAttr<PureAttr>());
3571 if (IsPure || !IncludePossibleEffects)
3572 break;
3573 return true;
3576 case BlockExprClass:
3577 case CXXBindTemporaryExprClass:
3578 if (!IncludePossibleEffects)
3579 break;
3580 return true;
3582 case MSPropertyRefExprClass:
3583 case MSPropertySubscriptExprClass:
3584 case CompoundAssignOperatorClass:
3585 case VAArgExprClass:
3586 case AtomicExprClass:
3587 case CXXThrowExprClass:
3588 case CXXNewExprClass:
3589 case CXXDeleteExprClass:
3590 case CoawaitExprClass:
3591 case DependentCoawaitExprClass:
3592 case CoyieldExprClass:
3593 // These always have a side-effect.
3594 return true;
3596 case StmtExprClass: {
3597 // StmtExprs have a side-effect if any substatement does.
3598 SideEffectFinder Finder(Ctx, IncludePossibleEffects);
3599 Finder.Visit(cast<StmtExpr>(this)->getSubStmt());
3600 return Finder.hasSideEffects();
3603 case ExprWithCleanupsClass:
3604 if (IncludePossibleEffects)
3605 if (cast<ExprWithCleanups>(this)->cleanupsHaveSideEffects())
3606 return true;
3607 break;
3609 case ParenExprClass:
3610 case ArraySubscriptExprClass:
3611 case MatrixSubscriptExprClass:
3612 case OMPArraySectionExprClass:
3613 case OMPArrayShapingExprClass:
3614 case OMPIteratorExprClass:
3615 case MemberExprClass:
3616 case ConditionalOperatorClass:
3617 case BinaryConditionalOperatorClass:
3618 case CompoundLiteralExprClass:
3619 case ExtVectorElementExprClass:
3620 case DesignatedInitExprClass:
3621 case DesignatedInitUpdateExprClass:
3622 case ArrayInitLoopExprClass:
3623 case ParenListExprClass:
3624 case CXXPseudoDestructorExprClass:
3625 case CXXRewrittenBinaryOperatorClass:
3626 case CXXStdInitializerListExprClass:
3627 case SubstNonTypeTemplateParmExprClass:
3628 case MaterializeTemporaryExprClass:
3629 case ShuffleVectorExprClass:
3630 case ConvertVectorExprClass:
3631 case AsTypeExprClass:
3632 case CXXParenListInitExprClass:
3633 // These have a side-effect if any subexpression does.
3634 break;
3636 case UnaryOperatorClass:
3637 if (cast<UnaryOperator>(this)->isIncrementDecrementOp())
3638 return true;
3639 break;
3641 case BinaryOperatorClass:
3642 if (cast<BinaryOperator>(this)->isAssignmentOp())
3643 return true;
3644 break;
3646 case InitListExprClass:
3647 // FIXME: The children for an InitListExpr doesn't include the array filler.
3648 if (const Expr *E = cast<InitListExpr>(this)->getArrayFiller())
3649 if (E->HasSideEffects(Ctx, IncludePossibleEffects))
3650 return true;
3651 break;
3653 case GenericSelectionExprClass:
3654 return cast<GenericSelectionExpr>(this)->getResultExpr()->
3655 HasSideEffects(Ctx, IncludePossibleEffects);
3657 case ChooseExprClass:
3658 return cast<ChooseExpr>(this)->getChosenSubExpr()->HasSideEffects(
3659 Ctx, IncludePossibleEffects);
3661 case CXXDefaultArgExprClass:
3662 return cast<CXXDefaultArgExpr>(this)->getExpr()->HasSideEffects(
3663 Ctx, IncludePossibleEffects);
3665 case CXXDefaultInitExprClass: {
3666 const FieldDecl *FD = cast<CXXDefaultInitExpr>(this)->getField();
3667 if (const Expr *E = FD->getInClassInitializer())
3668 return E->HasSideEffects(Ctx, IncludePossibleEffects);
3669 // If we've not yet parsed the initializer, assume it has side-effects.
3670 return true;
3673 case CXXDynamicCastExprClass: {
3674 // A dynamic_cast expression has side-effects if it can throw.
3675 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(this);
3676 if (DCE->getTypeAsWritten()->isReferenceType() &&
3677 DCE->getCastKind() == CK_Dynamic)
3678 return true;
3680 [[fallthrough]];
3681 case ImplicitCastExprClass:
3682 case CStyleCastExprClass:
3683 case CXXStaticCastExprClass:
3684 case CXXReinterpretCastExprClass:
3685 case CXXConstCastExprClass:
3686 case CXXAddrspaceCastExprClass:
3687 case CXXFunctionalCastExprClass:
3688 case BuiltinBitCastExprClass: {
3689 // While volatile reads are side-effecting in both C and C++, we treat them
3690 // as having possible (not definite) side-effects. This allows idiomatic
3691 // code to behave without warning, such as sizeof(*v) for a volatile-
3692 // qualified pointer.
3693 if (!IncludePossibleEffects)
3694 break;
3696 const CastExpr *CE = cast<CastExpr>(this);
3697 if (CE->getCastKind() == CK_LValueToRValue &&
3698 CE->getSubExpr()->getType().isVolatileQualified())
3699 return true;
3700 break;
3703 case CXXTypeidExprClass:
3704 // typeid might throw if its subexpression is potentially-evaluated, so has
3705 // side-effects in that case whether or not its subexpression does.
3706 return cast<CXXTypeidExpr>(this)->isPotentiallyEvaluated();
3708 case CXXConstructExprClass:
3709 case CXXTemporaryObjectExprClass: {
3710 const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
3711 if (!CE->getConstructor()->isTrivial() && IncludePossibleEffects)
3712 return true;
3713 // A trivial constructor does not add any side-effects of its own. Just look
3714 // at its arguments.
3715 break;
3718 case CXXInheritedCtorInitExprClass: {
3719 const auto *ICIE = cast<CXXInheritedCtorInitExpr>(this);
3720 if (!ICIE->getConstructor()->isTrivial() && IncludePossibleEffects)
3721 return true;
3722 break;
3725 case LambdaExprClass: {
3726 const LambdaExpr *LE = cast<LambdaExpr>(this);
3727 for (Expr *E : LE->capture_inits())
3728 if (E && E->HasSideEffects(Ctx, IncludePossibleEffects))
3729 return true;
3730 return false;
3733 case PseudoObjectExprClass: {
3734 // Only look for side-effects in the semantic form, and look past
3735 // OpaqueValueExpr bindings in that form.
3736 const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this);
3737 for (PseudoObjectExpr::const_semantics_iterator I = PO->semantics_begin(),
3738 E = PO->semantics_end();
3739 I != E; ++I) {
3740 const Expr *Subexpr = *I;
3741 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Subexpr))
3742 Subexpr = OVE->getSourceExpr();
3743 if (Subexpr->HasSideEffects(Ctx, IncludePossibleEffects))
3744 return true;
3746 return false;
3749 case ObjCBoxedExprClass:
3750 case ObjCArrayLiteralClass:
3751 case ObjCDictionaryLiteralClass:
3752 case ObjCSelectorExprClass:
3753 case ObjCProtocolExprClass:
3754 case ObjCIsaExprClass:
3755 case ObjCIndirectCopyRestoreExprClass:
3756 case ObjCSubscriptRefExprClass:
3757 case ObjCBridgedCastExprClass:
3758 case ObjCMessageExprClass:
3759 case ObjCPropertyRefExprClass:
3760 // FIXME: Classify these cases better.
3761 if (IncludePossibleEffects)
3762 return true;
3763 break;
3766 // Recurse to children.
3767 for (const Stmt *SubStmt : children())
3768 if (SubStmt &&
3769 cast<Expr>(SubStmt)->HasSideEffects(Ctx, IncludePossibleEffects))
3770 return true;
3772 return false;
3775 FPOptions Expr::getFPFeaturesInEffect(const LangOptions &LO) const {
3776 if (auto Call = dyn_cast<CallExpr>(this))
3777 return Call->getFPFeaturesInEffect(LO);
3778 if (auto UO = dyn_cast<UnaryOperator>(this))
3779 return UO->getFPFeaturesInEffect(LO);
3780 if (auto BO = dyn_cast<BinaryOperator>(this))
3781 return BO->getFPFeaturesInEffect(LO);
3782 if (auto Cast = dyn_cast<CastExpr>(this))
3783 return Cast->getFPFeaturesInEffect(LO);
3784 return FPOptions::defaultWithoutTrailingStorage(LO);
3787 namespace {
3788 /// Look for a call to a non-trivial function within an expression.
3789 class NonTrivialCallFinder : public ConstEvaluatedExprVisitor<NonTrivialCallFinder>
3791 typedef ConstEvaluatedExprVisitor<NonTrivialCallFinder> Inherited;
3793 bool NonTrivial;
3795 public:
3796 explicit NonTrivialCallFinder(const ASTContext &Context)
3797 : Inherited(Context), NonTrivial(false) { }
3799 bool hasNonTrivialCall() const { return NonTrivial; }
3801 void VisitCallExpr(const CallExpr *E) {
3802 if (const CXXMethodDecl *Method
3803 = dyn_cast_or_null<const CXXMethodDecl>(E->getCalleeDecl())) {
3804 if (Method->isTrivial()) {
3805 // Recurse to children of the call.
3806 Inherited::VisitStmt(E);
3807 return;
3811 NonTrivial = true;
3814 void VisitCXXConstructExpr(const CXXConstructExpr *E) {
3815 if (E->getConstructor()->isTrivial()) {
3816 // Recurse to children of the call.
3817 Inherited::VisitStmt(E);
3818 return;
3821 NonTrivial = true;
3824 void VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
3825 if (E->getTemporary()->getDestructor()->isTrivial()) {
3826 Inherited::VisitStmt(E);
3827 return;
3830 NonTrivial = true;
3835 bool Expr::hasNonTrivialCall(const ASTContext &Ctx) const {
3836 NonTrivialCallFinder Finder(Ctx);
3837 Finder.Visit(this);
3838 return Finder.hasNonTrivialCall();
3841 /// isNullPointerConstant - C99 6.3.2.3p3 - Return whether this is a null
3842 /// pointer constant or not, as well as the specific kind of constant detected.
3843 /// Null pointer constants can be integer constant expressions with the
3844 /// value zero, casts of zero to void*, nullptr (C++0X), or __null
3845 /// (a GNU extension).
3846 Expr::NullPointerConstantKind
3847 Expr::isNullPointerConstant(ASTContext &Ctx,
3848 NullPointerConstantValueDependence NPC) const {
3849 if (isValueDependent() &&
3850 (!Ctx.getLangOpts().CPlusPlus11 || Ctx.getLangOpts().MSVCCompat)) {
3851 // Error-dependent expr should never be a null pointer.
3852 if (containsErrors())
3853 return NPCK_NotNull;
3854 switch (NPC) {
3855 case NPC_NeverValueDependent:
3856 llvm_unreachable("Unexpected value dependent expression!");
3857 case NPC_ValueDependentIsNull:
3858 if (isTypeDependent() || getType()->isIntegralType(Ctx))
3859 return NPCK_ZeroExpression;
3860 else
3861 return NPCK_NotNull;
3863 case NPC_ValueDependentIsNotNull:
3864 return NPCK_NotNull;
3868 // Strip off a cast to void*, if it exists. Except in C++.
3869 if (const ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(this)) {
3870 if (!Ctx.getLangOpts().CPlusPlus) {
3871 // Check that it is a cast to void*.
3872 if (const PointerType *PT = CE->getType()->getAs<PointerType>()) {
3873 QualType Pointee = PT->getPointeeType();
3874 Qualifiers Qs = Pointee.getQualifiers();
3875 // Only (void*)0 or equivalent are treated as nullptr. If pointee type
3876 // has non-default address space it is not treated as nullptr.
3877 // (__generic void*)0 in OpenCL 2.0 should not be treated as nullptr
3878 // since it cannot be assigned to a pointer to constant address space.
3879 if (Ctx.getLangOpts().OpenCL &&
3880 Pointee.getAddressSpace() == Ctx.getDefaultOpenCLPointeeAddrSpace())
3881 Qs.removeAddressSpace();
3883 if (Pointee->isVoidType() && Qs.empty() && // to void*
3884 CE->getSubExpr()->getType()->isIntegerType()) // from int
3885 return CE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
3888 } else if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(this)) {
3889 // Ignore the ImplicitCastExpr type entirely.
3890 return ICE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
3891 } else if (const ParenExpr *PE = dyn_cast<ParenExpr>(this)) {
3892 // Accept ((void*)0) as a null pointer constant, as many other
3893 // implementations do.
3894 return PE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
3895 } else if (const GenericSelectionExpr *GE =
3896 dyn_cast<GenericSelectionExpr>(this)) {
3897 if (GE->isResultDependent())
3898 return NPCK_NotNull;
3899 return GE->getResultExpr()->isNullPointerConstant(Ctx, NPC);
3900 } else if (const ChooseExpr *CE = dyn_cast<ChooseExpr>(this)) {
3901 if (CE->isConditionDependent())
3902 return NPCK_NotNull;
3903 return CE->getChosenSubExpr()->isNullPointerConstant(Ctx, NPC);
3904 } else if (const CXXDefaultArgExpr *DefaultArg
3905 = dyn_cast<CXXDefaultArgExpr>(this)) {
3906 // See through default argument expressions.
3907 return DefaultArg->getExpr()->isNullPointerConstant(Ctx, NPC);
3908 } else if (const CXXDefaultInitExpr *DefaultInit
3909 = dyn_cast<CXXDefaultInitExpr>(this)) {
3910 // See through default initializer expressions.
3911 return DefaultInit->getExpr()->isNullPointerConstant(Ctx, NPC);
3912 } else if (isa<GNUNullExpr>(this)) {
3913 // The GNU __null extension is always a null pointer constant.
3914 return NPCK_GNUNull;
3915 } else if (const MaterializeTemporaryExpr *M
3916 = dyn_cast<MaterializeTemporaryExpr>(this)) {
3917 return M->getSubExpr()->isNullPointerConstant(Ctx, NPC);
3918 } else if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(this)) {
3919 if (const Expr *Source = OVE->getSourceExpr())
3920 return Source->isNullPointerConstant(Ctx, NPC);
3923 // If the expression has no type information, it cannot be a null pointer
3924 // constant.
3925 if (getType().isNull())
3926 return NPCK_NotNull;
3928 // C++11/C23 nullptr_t is always a null pointer constant.
3929 if (getType()->isNullPtrType())
3930 return NPCK_CXX11_nullptr;
3932 if (const RecordType *UT = getType()->getAsUnionType())
3933 if (!Ctx.getLangOpts().CPlusPlus11 &&
3934 UT && UT->getDecl()->hasAttr<TransparentUnionAttr>())
3935 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(this)){
3936 const Expr *InitExpr = CLE->getInitializer();
3937 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(InitExpr))
3938 return ILE->getInit(0)->isNullPointerConstant(Ctx, NPC);
3940 // This expression must be an integer type.
3941 if (!getType()->isIntegerType() ||
3942 (Ctx.getLangOpts().CPlusPlus && getType()->isEnumeralType()))
3943 return NPCK_NotNull;
3945 if (Ctx.getLangOpts().CPlusPlus11) {
3946 // C++11 [conv.ptr]p1: A null pointer constant is an integer literal with
3947 // value zero or a prvalue of type std::nullptr_t.
3948 // Microsoft mode permits C++98 rules reflecting MSVC behavior.
3949 const IntegerLiteral *Lit = dyn_cast<IntegerLiteral>(this);
3950 if (Lit && !Lit->getValue())
3951 return NPCK_ZeroLiteral;
3952 if (!Ctx.getLangOpts().MSVCCompat || !isCXX98IntegralConstantExpr(Ctx))
3953 return NPCK_NotNull;
3954 } else {
3955 // If we have an integer constant expression, we need to *evaluate* it and
3956 // test for the value 0.
3957 if (!isIntegerConstantExpr(Ctx))
3958 return NPCK_NotNull;
3961 if (EvaluateKnownConstInt(Ctx) != 0)
3962 return NPCK_NotNull;
3964 if (isa<IntegerLiteral>(this))
3965 return NPCK_ZeroLiteral;
3966 return NPCK_ZeroExpression;
3969 /// If this expression is an l-value for an Objective C
3970 /// property, find the underlying property reference expression.
3971 const ObjCPropertyRefExpr *Expr::getObjCProperty() const {
3972 const Expr *E = this;
3973 while (true) {
3974 assert((E->isLValue() && E->getObjectKind() == OK_ObjCProperty) &&
3975 "expression is not a property reference");
3976 E = E->IgnoreParenCasts();
3977 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3978 if (BO->getOpcode() == BO_Comma) {
3979 E = BO->getRHS();
3980 continue;
3984 break;
3987 return cast<ObjCPropertyRefExpr>(E);
3990 bool Expr::isObjCSelfExpr() const {
3991 const Expr *E = IgnoreParenImpCasts();
3993 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
3994 if (!DRE)
3995 return false;
3997 const ImplicitParamDecl *Param = dyn_cast<ImplicitParamDecl>(DRE->getDecl());
3998 if (!Param)
3999 return false;
4001 const ObjCMethodDecl *M = dyn_cast<ObjCMethodDecl>(Param->getDeclContext());
4002 if (!M)
4003 return false;
4005 return M->getSelfDecl() == Param;
4008 FieldDecl *Expr::getSourceBitField() {
4009 Expr *E = this->IgnoreParens();
4011 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
4012 if (ICE->getCastKind() == CK_LValueToRValue ||
4013 (ICE->isGLValue() && ICE->getCastKind() == CK_NoOp))
4014 E = ICE->getSubExpr()->IgnoreParens();
4015 else
4016 break;
4019 if (MemberExpr *MemRef = dyn_cast<MemberExpr>(E))
4020 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemRef->getMemberDecl()))
4021 if (Field->isBitField())
4022 return Field;
4024 if (ObjCIvarRefExpr *IvarRef = dyn_cast<ObjCIvarRefExpr>(E)) {
4025 FieldDecl *Ivar = IvarRef->getDecl();
4026 if (Ivar->isBitField())
4027 return Ivar;
4030 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E)) {
4031 if (FieldDecl *Field = dyn_cast<FieldDecl>(DeclRef->getDecl()))
4032 if (Field->isBitField())
4033 return Field;
4035 if (BindingDecl *BD = dyn_cast<BindingDecl>(DeclRef->getDecl()))
4036 if (Expr *E = BD->getBinding())
4037 return E->getSourceBitField();
4040 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(E)) {
4041 if (BinOp->isAssignmentOp() && BinOp->getLHS())
4042 return BinOp->getLHS()->getSourceBitField();
4044 if (BinOp->getOpcode() == BO_Comma && BinOp->getRHS())
4045 return BinOp->getRHS()->getSourceBitField();
4048 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E))
4049 if (UnOp->isPrefix() && UnOp->isIncrementDecrementOp())
4050 return UnOp->getSubExpr()->getSourceBitField();
4052 return nullptr;
4055 bool Expr::refersToVectorElement() const {
4056 // FIXME: Why do we not just look at the ObjectKind here?
4057 const Expr *E = this->IgnoreParens();
4059 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
4060 if (ICE->isGLValue() && ICE->getCastKind() == CK_NoOp)
4061 E = ICE->getSubExpr()->IgnoreParens();
4062 else
4063 break;
4066 if (const ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(E))
4067 return ASE->getBase()->getType()->isVectorType();
4069 if (isa<ExtVectorElementExpr>(E))
4070 return true;
4072 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
4073 if (auto *BD = dyn_cast<BindingDecl>(DRE->getDecl()))
4074 if (auto *E = BD->getBinding())
4075 return E->refersToVectorElement();
4077 return false;
4080 bool Expr::refersToGlobalRegisterVar() const {
4081 const Expr *E = this->IgnoreParenImpCasts();
4083 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
4084 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
4085 if (VD->getStorageClass() == SC_Register &&
4086 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
4087 return true;
4089 return false;
4092 bool Expr::isSameComparisonOperand(const Expr* E1, const Expr* E2) {
4093 E1 = E1->IgnoreParens();
4094 E2 = E2->IgnoreParens();
4096 if (E1->getStmtClass() != E2->getStmtClass())
4097 return false;
4099 switch (E1->getStmtClass()) {
4100 default:
4101 return false;
4102 case CXXThisExprClass:
4103 return true;
4104 case DeclRefExprClass: {
4105 // DeclRefExpr without an ImplicitCastExpr can happen for integral
4106 // template parameters.
4107 const auto *DRE1 = cast<DeclRefExpr>(E1);
4108 const auto *DRE2 = cast<DeclRefExpr>(E2);
4109 return DRE1->isPRValue() && DRE2->isPRValue() &&
4110 DRE1->getDecl() == DRE2->getDecl();
4112 case ImplicitCastExprClass: {
4113 // Peel off implicit casts.
4114 while (true) {
4115 const auto *ICE1 = dyn_cast<ImplicitCastExpr>(E1);
4116 const auto *ICE2 = dyn_cast<ImplicitCastExpr>(E2);
4117 if (!ICE1 || !ICE2)
4118 return false;
4119 if (ICE1->getCastKind() != ICE2->getCastKind())
4120 return false;
4121 E1 = ICE1->getSubExpr()->IgnoreParens();
4122 E2 = ICE2->getSubExpr()->IgnoreParens();
4123 // The final cast must be one of these types.
4124 if (ICE1->getCastKind() == CK_LValueToRValue ||
4125 ICE1->getCastKind() == CK_ArrayToPointerDecay ||
4126 ICE1->getCastKind() == CK_FunctionToPointerDecay) {
4127 break;
4131 const auto *DRE1 = dyn_cast<DeclRefExpr>(E1);
4132 const auto *DRE2 = dyn_cast<DeclRefExpr>(E2);
4133 if (DRE1 && DRE2)
4134 return declaresSameEntity(DRE1->getDecl(), DRE2->getDecl());
4136 const auto *Ivar1 = dyn_cast<ObjCIvarRefExpr>(E1);
4137 const auto *Ivar2 = dyn_cast<ObjCIvarRefExpr>(E2);
4138 if (Ivar1 && Ivar2) {
4139 return Ivar1->isFreeIvar() && Ivar2->isFreeIvar() &&
4140 declaresSameEntity(Ivar1->getDecl(), Ivar2->getDecl());
4143 const auto *Array1 = dyn_cast<ArraySubscriptExpr>(E1);
4144 const auto *Array2 = dyn_cast<ArraySubscriptExpr>(E2);
4145 if (Array1 && Array2) {
4146 if (!isSameComparisonOperand(Array1->getBase(), Array2->getBase()))
4147 return false;
4149 auto Idx1 = Array1->getIdx();
4150 auto Idx2 = Array2->getIdx();
4151 const auto Integer1 = dyn_cast<IntegerLiteral>(Idx1);
4152 const auto Integer2 = dyn_cast<IntegerLiteral>(Idx2);
4153 if (Integer1 && Integer2) {
4154 if (!llvm::APInt::isSameValue(Integer1->getValue(),
4155 Integer2->getValue()))
4156 return false;
4157 } else {
4158 if (!isSameComparisonOperand(Idx1, Idx2))
4159 return false;
4162 return true;
4165 // Walk the MemberExpr chain.
4166 while (isa<MemberExpr>(E1) && isa<MemberExpr>(E2)) {
4167 const auto *ME1 = cast<MemberExpr>(E1);
4168 const auto *ME2 = cast<MemberExpr>(E2);
4169 if (!declaresSameEntity(ME1->getMemberDecl(), ME2->getMemberDecl()))
4170 return false;
4171 if (const auto *D = dyn_cast<VarDecl>(ME1->getMemberDecl()))
4172 if (D->isStaticDataMember())
4173 return true;
4174 E1 = ME1->getBase()->IgnoreParenImpCasts();
4175 E2 = ME2->getBase()->IgnoreParenImpCasts();
4178 if (isa<CXXThisExpr>(E1) && isa<CXXThisExpr>(E2))
4179 return true;
4181 // A static member variable can end the MemberExpr chain with either
4182 // a MemberExpr or a DeclRefExpr.
4183 auto getAnyDecl = [](const Expr *E) -> const ValueDecl * {
4184 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
4185 return DRE->getDecl();
4186 if (const auto *ME = dyn_cast<MemberExpr>(E))
4187 return ME->getMemberDecl();
4188 return nullptr;
4191 const ValueDecl *VD1 = getAnyDecl(E1);
4192 const ValueDecl *VD2 = getAnyDecl(E2);
4193 return declaresSameEntity(VD1, VD2);
4198 /// isArrow - Return true if the base expression is a pointer to vector,
4199 /// return false if the base expression is a vector.
4200 bool ExtVectorElementExpr::isArrow() const {
4201 return getBase()->getType()->isPointerType();
4204 unsigned ExtVectorElementExpr::getNumElements() const {
4205 if (const VectorType *VT = getType()->getAs<VectorType>())
4206 return VT->getNumElements();
4207 return 1;
4210 /// containsDuplicateElements - Return true if any element access is repeated.
4211 bool ExtVectorElementExpr::containsDuplicateElements() const {
4212 // FIXME: Refactor this code to an accessor on the AST node which returns the
4213 // "type" of component access, and share with code below and in Sema.
4214 StringRef Comp = Accessor->getName();
4216 // Halving swizzles do not contain duplicate elements.
4217 if (Comp == "hi" || Comp == "lo" || Comp == "even" || Comp == "odd")
4218 return false;
4220 // Advance past s-char prefix on hex swizzles.
4221 if (Comp[0] == 's' || Comp[0] == 'S')
4222 Comp = Comp.substr(1);
4224 for (unsigned i = 0, e = Comp.size(); i != e; ++i)
4225 if (Comp.substr(i + 1).contains(Comp[i]))
4226 return true;
4228 return false;
4231 /// getEncodedElementAccess - We encode the fields as a llvm ConstantArray.
4232 void ExtVectorElementExpr::getEncodedElementAccess(
4233 SmallVectorImpl<uint32_t> &Elts) const {
4234 StringRef Comp = Accessor->getName();
4235 bool isNumericAccessor = false;
4236 if (Comp[0] == 's' || Comp[0] == 'S') {
4237 Comp = Comp.substr(1);
4238 isNumericAccessor = true;
4241 bool isHi = Comp == "hi";
4242 bool isLo = Comp == "lo";
4243 bool isEven = Comp == "even";
4244 bool isOdd = Comp == "odd";
4246 for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
4247 uint64_t Index;
4249 if (isHi)
4250 Index = e + i;
4251 else if (isLo)
4252 Index = i;
4253 else if (isEven)
4254 Index = 2 * i;
4255 else if (isOdd)
4256 Index = 2 * i + 1;
4257 else
4258 Index = ExtVectorType::getAccessorIdx(Comp[i], isNumericAccessor);
4260 Elts.push_back(Index);
4264 ShuffleVectorExpr::ShuffleVectorExpr(const ASTContext &C, ArrayRef<Expr *> args,
4265 QualType Type, SourceLocation BLoc,
4266 SourceLocation RP)
4267 : Expr(ShuffleVectorExprClass, Type, VK_PRValue, OK_Ordinary),
4268 BuiltinLoc(BLoc), RParenLoc(RP), NumExprs(args.size()) {
4269 SubExprs = new (C) Stmt*[args.size()];
4270 for (unsigned i = 0; i != args.size(); i++)
4271 SubExprs[i] = args[i];
4273 setDependence(computeDependence(this));
4276 void ShuffleVectorExpr::setExprs(const ASTContext &C, ArrayRef<Expr *> Exprs) {
4277 if (SubExprs) C.Deallocate(SubExprs);
4279 this->NumExprs = Exprs.size();
4280 SubExprs = new (C) Stmt*[NumExprs];
4281 memcpy(SubExprs, Exprs.data(), sizeof(Expr *) * Exprs.size());
4284 GenericSelectionExpr::GenericSelectionExpr(
4285 const ASTContext &, SourceLocation GenericLoc, Expr *ControllingExpr,
4286 ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
4287 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4288 bool ContainsUnexpandedParameterPack, unsigned ResultIndex)
4289 : Expr(GenericSelectionExprClass, AssocExprs[ResultIndex]->getType(),
4290 AssocExprs[ResultIndex]->getValueKind(),
4291 AssocExprs[ResultIndex]->getObjectKind()),
4292 NumAssocs(AssocExprs.size()), ResultIndex(ResultIndex),
4293 IsExprPredicate(true), DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
4294 assert(AssocTypes.size() == AssocExprs.size() &&
4295 "Must have the same number of association expressions"
4296 " and TypeSourceInfo!");
4297 assert(ResultIndex < NumAssocs && "ResultIndex is out-of-bounds!");
4299 GenericSelectionExprBits.GenericLoc = GenericLoc;
4300 getTrailingObjects<Stmt *>()[getIndexOfControllingExpression()] =
4301 ControllingExpr;
4302 std::copy(AssocExprs.begin(), AssocExprs.end(),
4303 getTrailingObjects<Stmt *>() + getIndexOfStartOfAssociatedExprs());
4304 std::copy(AssocTypes.begin(), AssocTypes.end(),
4305 getTrailingObjects<TypeSourceInfo *>() +
4306 getIndexOfStartOfAssociatedTypes());
4308 setDependence(computeDependence(this, ContainsUnexpandedParameterPack));
4311 GenericSelectionExpr::GenericSelectionExpr(
4312 const ASTContext &, SourceLocation GenericLoc,
4313 TypeSourceInfo *ControllingType, ArrayRef<TypeSourceInfo *> AssocTypes,
4314 ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,
4315 SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack,
4316 unsigned ResultIndex)
4317 : Expr(GenericSelectionExprClass, AssocExprs[ResultIndex]->getType(),
4318 AssocExprs[ResultIndex]->getValueKind(),
4319 AssocExprs[ResultIndex]->getObjectKind()),
4320 NumAssocs(AssocExprs.size()), ResultIndex(ResultIndex),
4321 IsExprPredicate(false), DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
4322 assert(AssocTypes.size() == AssocExprs.size() &&
4323 "Must have the same number of association expressions"
4324 " and TypeSourceInfo!");
4325 assert(ResultIndex < NumAssocs && "ResultIndex is out-of-bounds!");
4327 GenericSelectionExprBits.GenericLoc = GenericLoc;
4328 getTrailingObjects<TypeSourceInfo *>()[getIndexOfControllingType()] =
4329 ControllingType;
4330 std::copy(AssocExprs.begin(), AssocExprs.end(),
4331 getTrailingObjects<Stmt *>() + getIndexOfStartOfAssociatedExprs());
4332 std::copy(AssocTypes.begin(), AssocTypes.end(),
4333 getTrailingObjects<TypeSourceInfo *>() +
4334 getIndexOfStartOfAssociatedTypes());
4336 setDependence(computeDependence(this, ContainsUnexpandedParameterPack));
4339 GenericSelectionExpr::GenericSelectionExpr(
4340 const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,
4341 ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
4342 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4343 bool ContainsUnexpandedParameterPack)
4344 : Expr(GenericSelectionExprClass, Context.DependentTy, VK_PRValue,
4345 OK_Ordinary),
4346 NumAssocs(AssocExprs.size()), ResultIndex(ResultDependentIndex),
4347 IsExprPredicate(true), DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
4348 assert(AssocTypes.size() == AssocExprs.size() &&
4349 "Must have the same number of association expressions"
4350 " and TypeSourceInfo!");
4352 GenericSelectionExprBits.GenericLoc = GenericLoc;
4353 getTrailingObjects<Stmt *>()[getIndexOfControllingExpression()] =
4354 ControllingExpr;
4355 std::copy(AssocExprs.begin(), AssocExprs.end(),
4356 getTrailingObjects<Stmt *>() + getIndexOfStartOfAssociatedExprs());
4357 std::copy(AssocTypes.begin(), AssocTypes.end(),
4358 getTrailingObjects<TypeSourceInfo *>() +
4359 getIndexOfStartOfAssociatedTypes());
4361 setDependence(computeDependence(this, ContainsUnexpandedParameterPack));
4364 GenericSelectionExpr::GenericSelectionExpr(
4365 const ASTContext &Context, SourceLocation GenericLoc,
4366 TypeSourceInfo *ControllingType, ArrayRef<TypeSourceInfo *> AssocTypes,
4367 ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,
4368 SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack)
4369 : Expr(GenericSelectionExprClass, Context.DependentTy, VK_PRValue,
4370 OK_Ordinary),
4371 NumAssocs(AssocExprs.size()), ResultIndex(ResultDependentIndex),
4372 IsExprPredicate(false), DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
4373 assert(AssocTypes.size() == AssocExprs.size() &&
4374 "Must have the same number of association expressions"
4375 " and TypeSourceInfo!");
4377 GenericSelectionExprBits.GenericLoc = GenericLoc;
4378 getTrailingObjects<TypeSourceInfo *>()[getIndexOfControllingType()] =
4379 ControllingType;
4380 std::copy(AssocExprs.begin(), AssocExprs.end(),
4381 getTrailingObjects<Stmt *>() + getIndexOfStartOfAssociatedExprs());
4382 std::copy(AssocTypes.begin(), AssocTypes.end(),
4383 getTrailingObjects<TypeSourceInfo *>() +
4384 getIndexOfStartOfAssociatedTypes());
4386 setDependence(computeDependence(this, ContainsUnexpandedParameterPack));
4389 GenericSelectionExpr::GenericSelectionExpr(EmptyShell Empty, unsigned NumAssocs)
4390 : Expr(GenericSelectionExprClass, Empty), NumAssocs(NumAssocs) {}
4392 GenericSelectionExpr *GenericSelectionExpr::Create(
4393 const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,
4394 ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
4395 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4396 bool ContainsUnexpandedParameterPack, unsigned ResultIndex) {
4397 unsigned NumAssocs = AssocExprs.size();
4398 void *Mem = Context.Allocate(
4399 totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
4400 alignof(GenericSelectionExpr));
4401 return new (Mem) GenericSelectionExpr(
4402 Context, GenericLoc, ControllingExpr, AssocTypes, AssocExprs, DefaultLoc,
4403 RParenLoc, ContainsUnexpandedParameterPack, ResultIndex);
4406 GenericSelectionExpr *GenericSelectionExpr::Create(
4407 const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,
4408 ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
4409 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4410 bool ContainsUnexpandedParameterPack) {
4411 unsigned NumAssocs = AssocExprs.size();
4412 void *Mem = Context.Allocate(
4413 totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
4414 alignof(GenericSelectionExpr));
4415 return new (Mem) GenericSelectionExpr(
4416 Context, GenericLoc, ControllingExpr, AssocTypes, AssocExprs, DefaultLoc,
4417 RParenLoc, ContainsUnexpandedParameterPack);
4420 GenericSelectionExpr *GenericSelectionExpr::Create(
4421 const ASTContext &Context, SourceLocation GenericLoc,
4422 TypeSourceInfo *ControllingType, ArrayRef<TypeSourceInfo *> AssocTypes,
4423 ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,
4424 SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack,
4425 unsigned ResultIndex) {
4426 unsigned NumAssocs = AssocExprs.size();
4427 void *Mem = Context.Allocate(
4428 totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
4429 alignof(GenericSelectionExpr));
4430 return new (Mem) GenericSelectionExpr(
4431 Context, GenericLoc, ControllingType, AssocTypes, AssocExprs, DefaultLoc,
4432 RParenLoc, ContainsUnexpandedParameterPack, ResultIndex);
4435 GenericSelectionExpr *GenericSelectionExpr::Create(
4436 const ASTContext &Context, SourceLocation GenericLoc,
4437 TypeSourceInfo *ControllingType, ArrayRef<TypeSourceInfo *> AssocTypes,
4438 ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,
4439 SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack) {
4440 unsigned NumAssocs = AssocExprs.size();
4441 void *Mem = Context.Allocate(
4442 totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
4443 alignof(GenericSelectionExpr));
4444 return new (Mem) GenericSelectionExpr(
4445 Context, GenericLoc, ControllingType, AssocTypes, AssocExprs, DefaultLoc,
4446 RParenLoc, ContainsUnexpandedParameterPack);
4449 GenericSelectionExpr *
4450 GenericSelectionExpr::CreateEmpty(const ASTContext &Context,
4451 unsigned NumAssocs) {
4452 void *Mem = Context.Allocate(
4453 totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
4454 alignof(GenericSelectionExpr));
4455 return new (Mem) GenericSelectionExpr(EmptyShell(), NumAssocs);
4458 //===----------------------------------------------------------------------===//
4459 // DesignatedInitExpr
4460 //===----------------------------------------------------------------------===//
4462 const IdentifierInfo *DesignatedInitExpr::Designator::getFieldName() const {
4463 assert(isFieldDesignator() && "Only valid on a field designator");
4464 if (FieldInfo.NameOrField & 0x01)
4465 return reinterpret_cast<IdentifierInfo *>(FieldInfo.NameOrField & ~0x01);
4466 return getFieldDecl()->getIdentifier();
4469 DesignatedInitExpr::DesignatedInitExpr(const ASTContext &C, QualType Ty,
4470 llvm::ArrayRef<Designator> Designators,
4471 SourceLocation EqualOrColonLoc,
4472 bool GNUSyntax,
4473 ArrayRef<Expr *> IndexExprs, Expr *Init)
4474 : Expr(DesignatedInitExprClass, Ty, Init->getValueKind(),
4475 Init->getObjectKind()),
4476 EqualOrColonLoc(EqualOrColonLoc), GNUSyntax(GNUSyntax),
4477 NumDesignators(Designators.size()), NumSubExprs(IndexExprs.size() + 1) {
4478 this->Designators = new (C) Designator[NumDesignators];
4480 // Record the initializer itself.
4481 child_iterator Child = child_begin();
4482 *Child++ = Init;
4484 // Copy the designators and their subexpressions, computing
4485 // value-dependence along the way.
4486 unsigned IndexIdx = 0;
4487 for (unsigned I = 0; I != NumDesignators; ++I) {
4488 this->Designators[I] = Designators[I];
4489 if (this->Designators[I].isArrayDesignator()) {
4490 // Copy the index expressions into permanent storage.
4491 *Child++ = IndexExprs[IndexIdx++];
4492 } else if (this->Designators[I].isArrayRangeDesignator()) {
4493 // Copy the start/end expressions into permanent storage.
4494 *Child++ = IndexExprs[IndexIdx++];
4495 *Child++ = IndexExprs[IndexIdx++];
4499 assert(IndexIdx == IndexExprs.size() && "Wrong number of index expressions");
4500 setDependence(computeDependence(this));
4503 DesignatedInitExpr *
4504 DesignatedInitExpr::Create(const ASTContext &C,
4505 llvm::ArrayRef<Designator> Designators,
4506 ArrayRef<Expr*> IndexExprs,
4507 SourceLocation ColonOrEqualLoc,
4508 bool UsesColonSyntax, Expr *Init) {
4509 void *Mem = C.Allocate(totalSizeToAlloc<Stmt *>(IndexExprs.size() + 1),
4510 alignof(DesignatedInitExpr));
4511 return new (Mem) DesignatedInitExpr(C, C.VoidTy, Designators,
4512 ColonOrEqualLoc, UsesColonSyntax,
4513 IndexExprs, Init);
4516 DesignatedInitExpr *DesignatedInitExpr::CreateEmpty(const ASTContext &C,
4517 unsigned NumIndexExprs) {
4518 void *Mem = C.Allocate(totalSizeToAlloc<Stmt *>(NumIndexExprs + 1),
4519 alignof(DesignatedInitExpr));
4520 return new (Mem) DesignatedInitExpr(NumIndexExprs + 1);
4523 void DesignatedInitExpr::setDesignators(const ASTContext &C,
4524 const Designator *Desigs,
4525 unsigned NumDesigs) {
4526 Designators = new (C) Designator[NumDesigs];
4527 NumDesignators = NumDesigs;
4528 for (unsigned I = 0; I != NumDesigs; ++I)
4529 Designators[I] = Desigs[I];
4532 SourceRange DesignatedInitExpr::getDesignatorsSourceRange() const {
4533 DesignatedInitExpr *DIE = const_cast<DesignatedInitExpr*>(this);
4534 if (size() == 1)
4535 return DIE->getDesignator(0)->getSourceRange();
4536 return SourceRange(DIE->getDesignator(0)->getBeginLoc(),
4537 DIE->getDesignator(size() - 1)->getEndLoc());
4540 SourceLocation DesignatedInitExpr::getBeginLoc() const {
4541 auto *DIE = const_cast<DesignatedInitExpr *>(this);
4542 Designator &First = *DIE->getDesignator(0);
4543 if (First.isFieldDesignator())
4544 return GNUSyntax ? First.getFieldLoc() : First.getDotLoc();
4545 return First.getLBracketLoc();
4548 SourceLocation DesignatedInitExpr::getEndLoc() const {
4549 return getInit()->getEndLoc();
4552 Expr *DesignatedInitExpr::getArrayIndex(const Designator& D) const {
4553 assert(D.isArrayDesignator() && "Requires array designator");
4554 return getSubExpr(D.getArrayIndex() + 1);
4557 Expr *DesignatedInitExpr::getArrayRangeStart(const Designator &D) const {
4558 assert(D.isArrayRangeDesignator() && "Requires array range designator");
4559 return getSubExpr(D.getArrayIndex() + 1);
4562 Expr *DesignatedInitExpr::getArrayRangeEnd(const Designator &D) const {
4563 assert(D.isArrayRangeDesignator() && "Requires array range designator");
4564 return getSubExpr(D.getArrayIndex() + 2);
4567 /// Replaces the designator at index @p Idx with the series
4568 /// of designators in [First, Last).
4569 void DesignatedInitExpr::ExpandDesignator(const ASTContext &C, unsigned Idx,
4570 const Designator *First,
4571 const Designator *Last) {
4572 unsigned NumNewDesignators = Last - First;
4573 if (NumNewDesignators == 0) {
4574 std::copy_backward(Designators + Idx + 1,
4575 Designators + NumDesignators,
4576 Designators + Idx);
4577 --NumNewDesignators;
4578 return;
4580 if (NumNewDesignators == 1) {
4581 Designators[Idx] = *First;
4582 return;
4585 Designator *NewDesignators
4586 = new (C) Designator[NumDesignators - 1 + NumNewDesignators];
4587 std::copy(Designators, Designators + Idx, NewDesignators);
4588 std::copy(First, Last, NewDesignators + Idx);
4589 std::copy(Designators + Idx + 1, Designators + NumDesignators,
4590 NewDesignators + Idx + NumNewDesignators);
4591 Designators = NewDesignators;
4592 NumDesignators = NumDesignators - 1 + NumNewDesignators;
4595 DesignatedInitUpdateExpr::DesignatedInitUpdateExpr(const ASTContext &C,
4596 SourceLocation lBraceLoc,
4597 Expr *baseExpr,
4598 SourceLocation rBraceLoc)
4599 : Expr(DesignatedInitUpdateExprClass, baseExpr->getType(), VK_PRValue,
4600 OK_Ordinary) {
4601 BaseAndUpdaterExprs[0] = baseExpr;
4603 InitListExpr *ILE =
4604 new (C) InitListExpr(C, lBraceLoc, std::nullopt, rBraceLoc);
4605 ILE->setType(baseExpr->getType());
4606 BaseAndUpdaterExprs[1] = ILE;
4608 // FIXME: this is wrong, set it correctly.
4609 setDependence(ExprDependence::None);
4612 SourceLocation DesignatedInitUpdateExpr::getBeginLoc() const {
4613 return getBase()->getBeginLoc();
4616 SourceLocation DesignatedInitUpdateExpr::getEndLoc() const {
4617 return getBase()->getEndLoc();
4620 ParenListExpr::ParenListExpr(SourceLocation LParenLoc, ArrayRef<Expr *> Exprs,
4621 SourceLocation RParenLoc)
4622 : Expr(ParenListExprClass, QualType(), VK_PRValue, OK_Ordinary),
4623 LParenLoc(LParenLoc), RParenLoc(RParenLoc) {
4624 ParenListExprBits.NumExprs = Exprs.size();
4626 for (unsigned I = 0, N = Exprs.size(); I != N; ++I)
4627 getTrailingObjects<Stmt *>()[I] = Exprs[I];
4628 setDependence(computeDependence(this));
4631 ParenListExpr::ParenListExpr(EmptyShell Empty, unsigned NumExprs)
4632 : Expr(ParenListExprClass, Empty) {
4633 ParenListExprBits.NumExprs = NumExprs;
4636 ParenListExpr *ParenListExpr::Create(const ASTContext &Ctx,
4637 SourceLocation LParenLoc,
4638 ArrayRef<Expr *> Exprs,
4639 SourceLocation RParenLoc) {
4640 void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *>(Exprs.size()),
4641 alignof(ParenListExpr));
4642 return new (Mem) ParenListExpr(LParenLoc, Exprs, RParenLoc);
4645 ParenListExpr *ParenListExpr::CreateEmpty(const ASTContext &Ctx,
4646 unsigned NumExprs) {
4647 void *Mem =
4648 Ctx.Allocate(totalSizeToAlloc<Stmt *>(NumExprs), alignof(ParenListExpr));
4649 return new (Mem) ParenListExpr(EmptyShell(), NumExprs);
4652 BinaryOperator::BinaryOperator(const ASTContext &Ctx, Expr *lhs, Expr *rhs,
4653 Opcode opc, QualType ResTy, ExprValueKind VK,
4654 ExprObjectKind OK, SourceLocation opLoc,
4655 FPOptionsOverride FPFeatures)
4656 : Expr(BinaryOperatorClass, ResTy, VK, OK) {
4657 BinaryOperatorBits.Opc = opc;
4658 assert(!isCompoundAssignmentOp() &&
4659 "Use CompoundAssignOperator for compound assignments");
4660 BinaryOperatorBits.OpLoc = opLoc;
4661 SubExprs[LHS] = lhs;
4662 SubExprs[RHS] = rhs;
4663 BinaryOperatorBits.HasFPFeatures = FPFeatures.requiresTrailingStorage();
4664 if (hasStoredFPFeatures())
4665 setStoredFPFeatures(FPFeatures);
4666 setDependence(computeDependence(this));
4669 BinaryOperator::BinaryOperator(const ASTContext &Ctx, Expr *lhs, Expr *rhs,
4670 Opcode opc, QualType ResTy, ExprValueKind VK,
4671 ExprObjectKind OK, SourceLocation opLoc,
4672 FPOptionsOverride FPFeatures, bool dead2)
4673 : Expr(CompoundAssignOperatorClass, ResTy, VK, OK) {
4674 BinaryOperatorBits.Opc = opc;
4675 assert(isCompoundAssignmentOp() &&
4676 "Use CompoundAssignOperator for compound assignments");
4677 BinaryOperatorBits.OpLoc = opLoc;
4678 SubExprs[LHS] = lhs;
4679 SubExprs[RHS] = rhs;
4680 BinaryOperatorBits.HasFPFeatures = FPFeatures.requiresTrailingStorage();
4681 if (hasStoredFPFeatures())
4682 setStoredFPFeatures(FPFeatures);
4683 setDependence(computeDependence(this));
4686 BinaryOperator *BinaryOperator::CreateEmpty(const ASTContext &C,
4687 bool HasFPFeatures) {
4688 unsigned Extra = sizeOfTrailingObjects(HasFPFeatures);
4689 void *Mem =
4690 C.Allocate(sizeof(BinaryOperator) + Extra, alignof(BinaryOperator));
4691 return new (Mem) BinaryOperator(EmptyShell());
4694 BinaryOperator *BinaryOperator::Create(const ASTContext &C, Expr *lhs,
4695 Expr *rhs, Opcode opc, QualType ResTy,
4696 ExprValueKind VK, ExprObjectKind OK,
4697 SourceLocation opLoc,
4698 FPOptionsOverride FPFeatures) {
4699 bool HasFPFeatures = FPFeatures.requiresTrailingStorage();
4700 unsigned Extra = sizeOfTrailingObjects(HasFPFeatures);
4701 void *Mem =
4702 C.Allocate(sizeof(BinaryOperator) + Extra, alignof(BinaryOperator));
4703 return new (Mem)
4704 BinaryOperator(C, lhs, rhs, opc, ResTy, VK, OK, opLoc, FPFeatures);
4707 CompoundAssignOperator *
4708 CompoundAssignOperator::CreateEmpty(const ASTContext &C, bool HasFPFeatures) {
4709 unsigned Extra = sizeOfTrailingObjects(HasFPFeatures);
4710 void *Mem = C.Allocate(sizeof(CompoundAssignOperator) + Extra,
4711 alignof(CompoundAssignOperator));
4712 return new (Mem) CompoundAssignOperator(C, EmptyShell(), HasFPFeatures);
4715 CompoundAssignOperator *
4716 CompoundAssignOperator::Create(const ASTContext &C, Expr *lhs, Expr *rhs,
4717 Opcode opc, QualType ResTy, ExprValueKind VK,
4718 ExprObjectKind OK, SourceLocation opLoc,
4719 FPOptionsOverride FPFeatures,
4720 QualType CompLHSType, QualType CompResultType) {
4721 bool HasFPFeatures = FPFeatures.requiresTrailingStorage();
4722 unsigned Extra = sizeOfTrailingObjects(HasFPFeatures);
4723 void *Mem = C.Allocate(sizeof(CompoundAssignOperator) + Extra,
4724 alignof(CompoundAssignOperator));
4725 return new (Mem)
4726 CompoundAssignOperator(C, lhs, rhs, opc, ResTy, VK, OK, opLoc, FPFeatures,
4727 CompLHSType, CompResultType);
4730 UnaryOperator *UnaryOperator::CreateEmpty(const ASTContext &C,
4731 bool hasFPFeatures) {
4732 void *Mem = C.Allocate(totalSizeToAlloc<FPOptionsOverride>(hasFPFeatures),
4733 alignof(UnaryOperator));
4734 return new (Mem) UnaryOperator(hasFPFeatures, EmptyShell());
4737 UnaryOperator::UnaryOperator(const ASTContext &Ctx, Expr *input, Opcode opc,
4738 QualType type, ExprValueKind VK, ExprObjectKind OK,
4739 SourceLocation l, bool CanOverflow,
4740 FPOptionsOverride FPFeatures)
4741 : Expr(UnaryOperatorClass, type, VK, OK), Val(input) {
4742 UnaryOperatorBits.Opc = opc;
4743 UnaryOperatorBits.CanOverflow = CanOverflow;
4744 UnaryOperatorBits.Loc = l;
4745 UnaryOperatorBits.HasFPFeatures = FPFeatures.requiresTrailingStorage();
4746 if (hasStoredFPFeatures())
4747 setStoredFPFeatures(FPFeatures);
4748 setDependence(computeDependence(this, Ctx));
4751 UnaryOperator *UnaryOperator::Create(const ASTContext &C, Expr *input,
4752 Opcode opc, QualType type,
4753 ExprValueKind VK, ExprObjectKind OK,
4754 SourceLocation l, bool CanOverflow,
4755 FPOptionsOverride FPFeatures) {
4756 bool HasFPFeatures = FPFeatures.requiresTrailingStorage();
4757 unsigned Size = totalSizeToAlloc<FPOptionsOverride>(HasFPFeatures);
4758 void *Mem = C.Allocate(Size, alignof(UnaryOperator));
4759 return new (Mem)
4760 UnaryOperator(C, input, opc, type, VK, OK, l, CanOverflow, FPFeatures);
4763 const OpaqueValueExpr *OpaqueValueExpr::findInCopyConstruct(const Expr *e) {
4764 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(e))
4765 e = ewc->getSubExpr();
4766 if (const MaterializeTemporaryExpr *m = dyn_cast<MaterializeTemporaryExpr>(e))
4767 e = m->getSubExpr();
4768 e = cast<CXXConstructExpr>(e)->getArg(0);
4769 while (const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
4770 e = ice->getSubExpr();
4771 return cast<OpaqueValueExpr>(e);
4774 PseudoObjectExpr *PseudoObjectExpr::Create(const ASTContext &Context,
4775 EmptyShell sh,
4776 unsigned numSemanticExprs) {
4777 void *buffer =
4778 Context.Allocate(totalSizeToAlloc<Expr *>(1 + numSemanticExprs),
4779 alignof(PseudoObjectExpr));
4780 return new(buffer) PseudoObjectExpr(sh, numSemanticExprs);
4783 PseudoObjectExpr::PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs)
4784 : Expr(PseudoObjectExprClass, shell) {
4785 PseudoObjectExprBits.NumSubExprs = numSemanticExprs + 1;
4788 PseudoObjectExpr *PseudoObjectExpr::Create(const ASTContext &C, Expr *syntax,
4789 ArrayRef<Expr*> semantics,
4790 unsigned resultIndex) {
4791 assert(syntax && "no syntactic expression!");
4792 assert(semantics.size() && "no semantic expressions!");
4794 QualType type;
4795 ExprValueKind VK;
4796 if (resultIndex == NoResult) {
4797 type = C.VoidTy;
4798 VK = VK_PRValue;
4799 } else {
4800 assert(resultIndex < semantics.size());
4801 type = semantics[resultIndex]->getType();
4802 VK = semantics[resultIndex]->getValueKind();
4803 assert(semantics[resultIndex]->getObjectKind() == OK_Ordinary);
4806 void *buffer = C.Allocate(totalSizeToAlloc<Expr *>(semantics.size() + 1),
4807 alignof(PseudoObjectExpr));
4808 return new(buffer) PseudoObjectExpr(type, VK, syntax, semantics,
4809 resultIndex);
4812 PseudoObjectExpr::PseudoObjectExpr(QualType type, ExprValueKind VK,
4813 Expr *syntax, ArrayRef<Expr *> semantics,
4814 unsigned resultIndex)
4815 : Expr(PseudoObjectExprClass, type, VK, OK_Ordinary) {
4816 PseudoObjectExprBits.NumSubExprs = semantics.size() + 1;
4817 PseudoObjectExprBits.ResultIndex = resultIndex + 1;
4819 for (unsigned i = 0, e = semantics.size() + 1; i != e; ++i) {
4820 Expr *E = (i == 0 ? syntax : semantics[i-1]);
4821 getSubExprsBuffer()[i] = E;
4823 if (isa<OpaqueValueExpr>(E))
4824 assert(cast<OpaqueValueExpr>(E)->getSourceExpr() != nullptr &&
4825 "opaque-value semantic expressions for pseudo-object "
4826 "operations must have sources");
4829 setDependence(computeDependence(this));
4832 //===----------------------------------------------------------------------===//
4833 // Child Iterators for iterating over subexpressions/substatements
4834 //===----------------------------------------------------------------------===//
4836 // UnaryExprOrTypeTraitExpr
4837 Stmt::child_range UnaryExprOrTypeTraitExpr::children() {
4838 const_child_range CCR =
4839 const_cast<const UnaryExprOrTypeTraitExpr *>(this)->children();
4840 return child_range(cast_away_const(CCR.begin()), cast_away_const(CCR.end()));
4843 Stmt::const_child_range UnaryExprOrTypeTraitExpr::children() const {
4844 // If this is of a type and the type is a VLA type (and not a typedef), the
4845 // size expression of the VLA needs to be treated as an executable expression.
4846 // Why isn't this weirdness documented better in StmtIterator?
4847 if (isArgumentType()) {
4848 if (const VariableArrayType *T =
4849 dyn_cast<VariableArrayType>(getArgumentType().getTypePtr()))
4850 return const_child_range(const_child_iterator(T), const_child_iterator());
4851 return const_child_range(const_child_iterator(), const_child_iterator());
4853 return const_child_range(&Argument.Ex, &Argument.Ex + 1);
4856 AtomicExpr::AtomicExpr(SourceLocation BLoc, ArrayRef<Expr *> args, QualType t,
4857 AtomicOp op, SourceLocation RP)
4858 : Expr(AtomicExprClass, t, VK_PRValue, OK_Ordinary),
4859 NumSubExprs(args.size()), BuiltinLoc(BLoc), RParenLoc(RP), Op(op) {
4860 assert(args.size() == getNumSubExprs(op) && "wrong number of subexpressions");
4861 for (unsigned i = 0; i != args.size(); i++)
4862 SubExprs[i] = args[i];
4863 setDependence(computeDependence(this));
4866 unsigned AtomicExpr::getNumSubExprs(AtomicOp Op) {
4867 switch (Op) {
4868 case AO__c11_atomic_init:
4869 case AO__opencl_atomic_init:
4870 case AO__c11_atomic_load:
4871 case AO__atomic_load_n:
4872 return 2;
4874 case AO__opencl_atomic_load:
4875 case AO__hip_atomic_load:
4876 case AO__c11_atomic_store:
4877 case AO__c11_atomic_exchange:
4878 case AO__atomic_load:
4879 case AO__atomic_store:
4880 case AO__atomic_store_n:
4881 case AO__atomic_exchange_n:
4882 case AO__c11_atomic_fetch_add:
4883 case AO__c11_atomic_fetch_sub:
4884 case AO__c11_atomic_fetch_and:
4885 case AO__c11_atomic_fetch_or:
4886 case AO__c11_atomic_fetch_xor:
4887 case AO__c11_atomic_fetch_nand:
4888 case AO__c11_atomic_fetch_max:
4889 case AO__c11_atomic_fetch_min:
4890 case AO__atomic_fetch_add:
4891 case AO__atomic_fetch_sub:
4892 case AO__atomic_fetch_and:
4893 case AO__atomic_fetch_or:
4894 case AO__atomic_fetch_xor:
4895 case AO__atomic_fetch_nand:
4896 case AO__atomic_add_fetch:
4897 case AO__atomic_sub_fetch:
4898 case AO__atomic_and_fetch:
4899 case AO__atomic_or_fetch:
4900 case AO__atomic_xor_fetch:
4901 case AO__atomic_nand_fetch:
4902 case AO__atomic_min_fetch:
4903 case AO__atomic_max_fetch:
4904 case AO__atomic_fetch_min:
4905 case AO__atomic_fetch_max:
4906 return 3;
4908 case AO__hip_atomic_exchange:
4909 case AO__hip_atomic_fetch_add:
4910 case AO__hip_atomic_fetch_sub:
4911 case AO__hip_atomic_fetch_and:
4912 case AO__hip_atomic_fetch_or:
4913 case AO__hip_atomic_fetch_xor:
4914 case AO__hip_atomic_fetch_min:
4915 case AO__hip_atomic_fetch_max:
4916 case AO__opencl_atomic_store:
4917 case AO__hip_atomic_store:
4918 case AO__opencl_atomic_exchange:
4919 case AO__opencl_atomic_fetch_add:
4920 case AO__opencl_atomic_fetch_sub:
4921 case AO__opencl_atomic_fetch_and:
4922 case AO__opencl_atomic_fetch_or:
4923 case AO__opencl_atomic_fetch_xor:
4924 case AO__opencl_atomic_fetch_min:
4925 case AO__opencl_atomic_fetch_max:
4926 case AO__atomic_exchange:
4927 return 4;
4929 case AO__c11_atomic_compare_exchange_strong:
4930 case AO__c11_atomic_compare_exchange_weak:
4931 return 5;
4932 case AO__hip_atomic_compare_exchange_strong:
4933 case AO__opencl_atomic_compare_exchange_strong:
4934 case AO__opencl_atomic_compare_exchange_weak:
4935 case AO__hip_atomic_compare_exchange_weak:
4936 case AO__atomic_compare_exchange:
4937 case AO__atomic_compare_exchange_n:
4938 return 6;
4940 llvm_unreachable("unknown atomic op");
4943 QualType AtomicExpr::getValueType() const {
4944 auto T = getPtr()->getType()->castAs<PointerType>()->getPointeeType();
4945 if (auto AT = T->getAs<AtomicType>())
4946 return AT->getValueType();
4947 return T;
4950 QualType OMPArraySectionExpr::getBaseOriginalType(const Expr *Base) {
4951 unsigned ArraySectionCount = 0;
4952 while (auto *OASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParens())) {
4953 Base = OASE->getBase();
4954 ++ArraySectionCount;
4956 while (auto *ASE =
4957 dyn_cast<ArraySubscriptExpr>(Base->IgnoreParenImpCasts())) {
4958 Base = ASE->getBase();
4959 ++ArraySectionCount;
4961 Base = Base->IgnoreParenImpCasts();
4962 auto OriginalTy = Base->getType();
4963 if (auto *DRE = dyn_cast<DeclRefExpr>(Base))
4964 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
4965 OriginalTy = PVD->getOriginalType().getNonReferenceType();
4967 for (unsigned Cnt = 0; Cnt < ArraySectionCount; ++Cnt) {
4968 if (OriginalTy->isAnyPointerType())
4969 OriginalTy = OriginalTy->getPointeeType();
4970 else {
4971 assert (OriginalTy->isArrayType());
4972 OriginalTy = OriginalTy->castAsArrayTypeUnsafe()->getElementType();
4975 return OriginalTy;
4978 RecoveryExpr::RecoveryExpr(ASTContext &Ctx, QualType T, SourceLocation BeginLoc,
4979 SourceLocation EndLoc, ArrayRef<Expr *> SubExprs)
4980 : Expr(RecoveryExprClass, T.getNonReferenceType(),
4981 T->isDependentType() ? VK_LValue : getValueKindForType(T),
4982 OK_Ordinary),
4983 BeginLoc(BeginLoc), EndLoc(EndLoc), NumExprs(SubExprs.size()) {
4984 assert(!T.isNull());
4985 assert(!llvm::is_contained(SubExprs, nullptr));
4987 llvm::copy(SubExprs, getTrailingObjects<Expr *>());
4988 setDependence(computeDependence(this));
4991 RecoveryExpr *RecoveryExpr::Create(ASTContext &Ctx, QualType T,
4992 SourceLocation BeginLoc,
4993 SourceLocation EndLoc,
4994 ArrayRef<Expr *> SubExprs) {
4995 void *Mem = Ctx.Allocate(totalSizeToAlloc<Expr *>(SubExprs.size()),
4996 alignof(RecoveryExpr));
4997 return new (Mem) RecoveryExpr(Ctx, T, BeginLoc, EndLoc, SubExprs);
5000 RecoveryExpr *RecoveryExpr::CreateEmpty(ASTContext &Ctx, unsigned NumSubExprs) {
5001 void *Mem = Ctx.Allocate(totalSizeToAlloc<Expr *>(NumSubExprs),
5002 alignof(RecoveryExpr));
5003 return new (Mem) RecoveryExpr(EmptyShell(), NumSubExprs);
5006 void OMPArrayShapingExpr::setDimensions(ArrayRef<Expr *> Dims) {
5007 assert(
5008 NumDims == Dims.size() &&
5009 "Preallocated number of dimensions is different from the provided one.");
5010 llvm::copy(Dims, getTrailingObjects<Expr *>());
5013 void OMPArrayShapingExpr::setBracketsRanges(ArrayRef<SourceRange> BR) {
5014 assert(
5015 NumDims == BR.size() &&
5016 "Preallocated number of dimensions is different from the provided one.");
5017 llvm::copy(BR, getTrailingObjects<SourceRange>());
5020 OMPArrayShapingExpr::OMPArrayShapingExpr(QualType ExprTy, Expr *Op,
5021 SourceLocation L, SourceLocation R,
5022 ArrayRef<Expr *> Dims)
5023 : Expr(OMPArrayShapingExprClass, ExprTy, VK_LValue, OK_Ordinary), LPLoc(L),
5024 RPLoc(R), NumDims(Dims.size()) {
5025 setBase(Op);
5026 setDimensions(Dims);
5027 setDependence(computeDependence(this));
5030 OMPArrayShapingExpr *
5031 OMPArrayShapingExpr::Create(const ASTContext &Context, QualType T, Expr *Op,
5032 SourceLocation L, SourceLocation R,
5033 ArrayRef<Expr *> Dims,
5034 ArrayRef<SourceRange> BracketRanges) {
5035 assert(Dims.size() == BracketRanges.size() &&
5036 "Different number of dimensions and brackets ranges.");
5037 void *Mem = Context.Allocate(
5038 totalSizeToAlloc<Expr *, SourceRange>(Dims.size() + 1, Dims.size()),
5039 alignof(OMPArrayShapingExpr));
5040 auto *E = new (Mem) OMPArrayShapingExpr(T, Op, L, R, Dims);
5041 E->setBracketsRanges(BracketRanges);
5042 return E;
5045 OMPArrayShapingExpr *OMPArrayShapingExpr::CreateEmpty(const ASTContext &Context,
5046 unsigned NumDims) {
5047 void *Mem = Context.Allocate(
5048 totalSizeToAlloc<Expr *, SourceRange>(NumDims + 1, NumDims),
5049 alignof(OMPArrayShapingExpr));
5050 return new (Mem) OMPArrayShapingExpr(EmptyShell(), NumDims);
5053 void OMPIteratorExpr::setIteratorDeclaration(unsigned I, Decl *D) {
5054 assert(I < NumIterators &&
5055 "Idx is greater or equal the number of iterators definitions.");
5056 getTrailingObjects<Decl *>()[I] = D;
5059 void OMPIteratorExpr::setAssignmentLoc(unsigned I, SourceLocation Loc) {
5060 assert(I < NumIterators &&
5061 "Idx is greater or equal the number of iterators definitions.");
5062 getTrailingObjects<
5063 SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +
5064 static_cast<int>(RangeLocOffset::AssignLoc)] = Loc;
5067 void OMPIteratorExpr::setIteratorRange(unsigned I, Expr *Begin,
5068 SourceLocation ColonLoc, Expr *End,
5069 SourceLocation SecondColonLoc,
5070 Expr *Step) {
5071 assert(I < NumIterators &&
5072 "Idx is greater or equal the number of iterators definitions.");
5073 getTrailingObjects<Expr *>()[I * static_cast<int>(RangeExprOffset::Total) +
5074 static_cast<int>(RangeExprOffset::Begin)] =
5075 Begin;
5076 getTrailingObjects<Expr *>()[I * static_cast<int>(RangeExprOffset::Total) +
5077 static_cast<int>(RangeExprOffset::End)] = End;
5078 getTrailingObjects<Expr *>()[I * static_cast<int>(RangeExprOffset::Total) +
5079 static_cast<int>(RangeExprOffset::Step)] = Step;
5080 getTrailingObjects<
5081 SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +
5082 static_cast<int>(RangeLocOffset::FirstColonLoc)] =
5083 ColonLoc;
5084 getTrailingObjects<
5085 SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +
5086 static_cast<int>(RangeLocOffset::SecondColonLoc)] =
5087 SecondColonLoc;
5090 Decl *OMPIteratorExpr::getIteratorDecl(unsigned I) {
5091 return getTrailingObjects<Decl *>()[I];
5094 OMPIteratorExpr::IteratorRange OMPIteratorExpr::getIteratorRange(unsigned I) {
5095 IteratorRange Res;
5096 Res.Begin =
5097 getTrailingObjects<Expr *>()[I * static_cast<int>(
5098 RangeExprOffset::Total) +
5099 static_cast<int>(RangeExprOffset::Begin)];
5100 Res.End =
5101 getTrailingObjects<Expr *>()[I * static_cast<int>(
5102 RangeExprOffset::Total) +
5103 static_cast<int>(RangeExprOffset::End)];
5104 Res.Step =
5105 getTrailingObjects<Expr *>()[I * static_cast<int>(
5106 RangeExprOffset::Total) +
5107 static_cast<int>(RangeExprOffset::Step)];
5108 return Res;
5111 SourceLocation OMPIteratorExpr::getAssignLoc(unsigned I) const {
5112 return getTrailingObjects<
5113 SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +
5114 static_cast<int>(RangeLocOffset::AssignLoc)];
5117 SourceLocation OMPIteratorExpr::getColonLoc(unsigned I) const {
5118 return getTrailingObjects<
5119 SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +
5120 static_cast<int>(RangeLocOffset::FirstColonLoc)];
5123 SourceLocation OMPIteratorExpr::getSecondColonLoc(unsigned I) const {
5124 return getTrailingObjects<
5125 SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +
5126 static_cast<int>(RangeLocOffset::SecondColonLoc)];
5129 void OMPIteratorExpr::setHelper(unsigned I, const OMPIteratorHelperData &D) {
5130 getTrailingObjects<OMPIteratorHelperData>()[I] = D;
5133 OMPIteratorHelperData &OMPIteratorExpr::getHelper(unsigned I) {
5134 return getTrailingObjects<OMPIteratorHelperData>()[I];
5137 const OMPIteratorHelperData &OMPIteratorExpr::getHelper(unsigned I) const {
5138 return getTrailingObjects<OMPIteratorHelperData>()[I];
5141 OMPIteratorExpr::OMPIteratorExpr(
5142 QualType ExprTy, SourceLocation IteratorKwLoc, SourceLocation L,
5143 SourceLocation R, ArrayRef<OMPIteratorExpr::IteratorDefinition> Data,
5144 ArrayRef<OMPIteratorHelperData> Helpers)
5145 : Expr(OMPIteratorExprClass, ExprTy, VK_LValue, OK_Ordinary),
5146 IteratorKwLoc(IteratorKwLoc), LPLoc(L), RPLoc(R),
5147 NumIterators(Data.size()) {
5148 for (unsigned I = 0, E = Data.size(); I < E; ++I) {
5149 const IteratorDefinition &D = Data[I];
5150 setIteratorDeclaration(I, D.IteratorDecl);
5151 setAssignmentLoc(I, D.AssignmentLoc);
5152 setIteratorRange(I, D.Range.Begin, D.ColonLoc, D.Range.End,
5153 D.SecondColonLoc, D.Range.Step);
5154 setHelper(I, Helpers[I]);
5156 setDependence(computeDependence(this));
5159 OMPIteratorExpr *
5160 OMPIteratorExpr::Create(const ASTContext &Context, QualType T,
5161 SourceLocation IteratorKwLoc, SourceLocation L,
5162 SourceLocation R,
5163 ArrayRef<OMPIteratorExpr::IteratorDefinition> Data,
5164 ArrayRef<OMPIteratorHelperData> Helpers) {
5165 assert(Data.size() == Helpers.size() &&
5166 "Data and helpers must have the same size.");
5167 void *Mem = Context.Allocate(
5168 totalSizeToAlloc<Decl *, Expr *, SourceLocation, OMPIteratorHelperData>(
5169 Data.size(), Data.size() * static_cast<int>(RangeExprOffset::Total),
5170 Data.size() * static_cast<int>(RangeLocOffset::Total),
5171 Helpers.size()),
5172 alignof(OMPIteratorExpr));
5173 return new (Mem) OMPIteratorExpr(T, IteratorKwLoc, L, R, Data, Helpers);
5176 OMPIteratorExpr *OMPIteratorExpr::CreateEmpty(const ASTContext &Context,
5177 unsigned NumIterators) {
5178 void *Mem = Context.Allocate(
5179 totalSizeToAlloc<Decl *, Expr *, SourceLocation, OMPIteratorHelperData>(
5180 NumIterators, NumIterators * static_cast<int>(RangeExprOffset::Total),
5181 NumIterators * static_cast<int>(RangeLocOffset::Total), NumIterators),
5182 alignof(OMPIteratorExpr));
5183 return new (Mem) OMPIteratorExpr(EmptyShell(), NumIterators);