1 //===--- Expr.cpp - Expression AST Node Implementation --------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Expr class and subclasses.
12 //===----------------------------------------------------------------------===//
14 #include "clang/AST/Expr.h"
15 #include "clang/AST/ExprCXX.h"
16 #include "clang/AST/APValue.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/AST/DeclCXX.h"
20 #include "clang/AST/DeclTemplate.h"
21 #include "clang/AST/RecordLayout.h"
22 #include "clang/AST/StmtVisitor.h"
23 #include "clang/Lex/LiteralSupport.h"
24 #include "clang/Lex/Lexer.h"
25 #include "clang/Sema/SemaDiagnostic.h"
26 #include "clang/Basic/Builtins.h"
27 #include "clang/Basic/SourceManager.h"
28 #include "clang/Basic/TargetInfo.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/raw_ostream.h"
32 using namespace clang;
34 /// isKnownToHaveBooleanValue - Return true if this is an integer expression
35 /// that is known to return 0 or 1. This happens for _Bool/bool expressions
36 /// but also int expressions which are produced by things like comparisons in
38 bool Expr::isKnownToHaveBooleanValue() const {
39 const Expr *E = IgnoreParens();
41 // If this value has _Bool type, it is obvious 0/1.
42 if (E->getType()->isBooleanType()) return true;
43 // If this is a non-scalar-integer type, we don't care enough to try.
44 if (!E->getType()->isIntegralOrEnumerationType()) return false;
46 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
47 switch (UO->getOpcode()) {
49 return UO->getSubExpr()->isKnownToHaveBooleanValue();
55 // Only look through implicit casts. If the user writes
56 // '(int) (a && b)' treat it as an arbitrary int.
57 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
58 return CE->getSubExpr()->isKnownToHaveBooleanValue();
60 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
61 switch (BO->getOpcode()) {
62 default: return false;
63 case BO_LT: // Relational operators.
67 case BO_EQ: // Equality operators.
69 case BO_LAnd: // AND operator.
70 case BO_LOr: // Logical OR operator.
73 case BO_And: // Bitwise AND operator.
74 case BO_Xor: // Bitwise XOR operator.
75 case BO_Or: // Bitwise OR operator.
76 // Handle things like (x==2)|(y==12).
77 return BO->getLHS()->isKnownToHaveBooleanValue() &&
78 BO->getRHS()->isKnownToHaveBooleanValue();
82 return BO->getRHS()->isKnownToHaveBooleanValue();
86 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
87 return CO->getTrueExpr()->isKnownToHaveBooleanValue() &&
88 CO->getFalseExpr()->isKnownToHaveBooleanValue();
93 // Amusing macro metaprogramming hack: check whether a class provides
94 // a more specific implementation of getExprLoc().
96 /// This implementation is used when a class provides a custom
97 /// implementation of getExprLoc.
98 template <class E, class T>
99 SourceLocation getExprLocImpl(const Expr *expr,
100 SourceLocation (T::*v)() const) {
101 return static_cast<const E*>(expr)->getExprLoc();
104 /// This implementation is used when a class doesn't provide
105 /// a custom implementation of getExprLoc. Overload resolution
106 /// should pick it over the implementation above because it's
107 /// more specialized according to function template partial ordering.
109 SourceLocation getExprLocImpl(const Expr *expr,
110 SourceLocation (Expr::*v)() const) {
111 return static_cast<const E*>(expr)->getSourceRange().getBegin();
115 SourceLocation Expr::getExprLoc() const {
116 switch (getStmtClass()) {
117 case Stmt::NoStmtClass: llvm_unreachable("statement without class");
118 #define ABSTRACT_STMT(type)
119 #define STMT(type, base) \
120 case Stmt::type##Class: llvm_unreachable(#type " is not an Expr"); break;
121 #define EXPR(type, base) \
122 case Stmt::type##Class: return getExprLocImpl<type>(this, &type::getExprLoc);
123 #include "clang/AST/StmtNodes.inc"
125 llvm_unreachable("unknown statement kind");
126 return SourceLocation();
129 //===----------------------------------------------------------------------===//
130 // Primary Expressions.
131 //===----------------------------------------------------------------------===//
133 void ExplicitTemplateArgumentList::initializeFrom(
134 const TemplateArgumentListInfo &Info) {
135 LAngleLoc = Info.getLAngleLoc();
136 RAngleLoc = Info.getRAngleLoc();
137 NumTemplateArgs = Info.size();
139 TemplateArgumentLoc *ArgBuffer = getTemplateArgs();
140 for (unsigned i = 0; i != NumTemplateArgs; ++i)
141 new (&ArgBuffer[i]) TemplateArgumentLoc(Info[i]);
144 void ExplicitTemplateArgumentList::initializeFrom(
145 const TemplateArgumentListInfo &Info,
147 bool &InstantiationDependent,
148 bool &ContainsUnexpandedParameterPack) {
149 LAngleLoc = Info.getLAngleLoc();
150 RAngleLoc = Info.getRAngleLoc();
151 NumTemplateArgs = Info.size();
153 TemplateArgumentLoc *ArgBuffer = getTemplateArgs();
154 for (unsigned i = 0; i != NumTemplateArgs; ++i) {
155 Dependent = Dependent || Info[i].getArgument().isDependent();
156 InstantiationDependent = InstantiationDependent ||
157 Info[i].getArgument().isInstantiationDependent();
158 ContainsUnexpandedParameterPack
159 = ContainsUnexpandedParameterPack ||
160 Info[i].getArgument().containsUnexpandedParameterPack();
162 new (&ArgBuffer[i]) TemplateArgumentLoc(Info[i]);
166 void ExplicitTemplateArgumentList::copyInto(
167 TemplateArgumentListInfo &Info) const {
168 Info.setLAngleLoc(LAngleLoc);
169 Info.setRAngleLoc(RAngleLoc);
170 for (unsigned I = 0; I != NumTemplateArgs; ++I)
171 Info.addArgument(getTemplateArgs()[I]);
174 std::size_t ExplicitTemplateArgumentList::sizeFor(unsigned NumTemplateArgs) {
175 return sizeof(ExplicitTemplateArgumentList) +
176 sizeof(TemplateArgumentLoc) * NumTemplateArgs;
179 std::size_t ExplicitTemplateArgumentList::sizeFor(
180 const TemplateArgumentListInfo &Info) {
181 return sizeFor(Info.size());
184 /// \brief Compute the type-, value-, and instantiation-dependence of a
185 /// declaration reference
186 /// based on the declaration being referenced.
187 static void computeDeclRefDependence(NamedDecl *D, QualType T,
189 bool &ValueDependent,
190 bool &InstantiationDependent) {
191 TypeDependent = false;
192 ValueDependent = false;
193 InstantiationDependent = false;
195 // (TD) C++ [temp.dep.expr]p3:
196 // An id-expression is type-dependent if it contains:
200 // (VD) C++ [temp.dep.constexpr]p2:
201 // An identifier is value-dependent if it is:
203 // (TD) - an identifier that was declared with dependent type
204 // (VD) - a name declared with a dependent type,
205 if (T->isDependentType()) {
206 TypeDependent = true;
207 ValueDependent = true;
208 InstantiationDependent = true;
210 } else if (T->isInstantiationDependentType()) {
211 InstantiationDependent = true;
214 // (TD) - a conversion-function-id that specifies a dependent type
215 if (D->getDeclName().getNameKind()
216 == DeclarationName::CXXConversionFunctionName) {
217 QualType T = D->getDeclName().getCXXNameType();
218 if (T->isDependentType()) {
219 TypeDependent = true;
220 ValueDependent = true;
221 InstantiationDependent = true;
225 if (T->isInstantiationDependentType())
226 InstantiationDependent = true;
229 // (VD) - the name of a non-type template parameter,
230 if (isa<NonTypeTemplateParmDecl>(D)) {
231 ValueDependent = true;
232 InstantiationDependent = true;
236 // (VD) - a constant with integral or enumeration type and is
237 // initialized with an expression that is value-dependent.
238 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
239 if (Var->getType()->isIntegralOrEnumerationType() &&
240 Var->getType().getCVRQualifiers() == Qualifiers::Const) {
241 if (const Expr *Init = Var->getAnyInitializer())
242 if (Init->isValueDependent()) {
243 ValueDependent = true;
244 InstantiationDependent = true;
248 // (VD) - FIXME: Missing from the standard:
249 // - a member function or a static data member of the current
251 else if (Var->isStaticDataMember() &&
252 Var->getDeclContext()->isDependentContext()) {
253 ValueDependent = true;
254 InstantiationDependent = true;
260 // (VD) - FIXME: Missing from the standard:
261 // - a member function or a static data member of the current
263 if (isa<CXXMethodDecl>(D) && D->getDeclContext()->isDependentContext()) {
264 ValueDependent = true;
265 InstantiationDependent = true;
270 void DeclRefExpr::computeDependence() {
271 bool TypeDependent = false;
272 bool ValueDependent = false;
273 bool InstantiationDependent = false;
274 computeDeclRefDependence(getDecl(), getType(), TypeDependent, ValueDependent,
275 InstantiationDependent);
277 // (TD) C++ [temp.dep.expr]p3:
278 // An id-expression is type-dependent if it contains:
282 // (VD) C++ [temp.dep.constexpr]p2:
283 // An identifier is value-dependent if it is:
284 if (!TypeDependent && !ValueDependent &&
285 hasExplicitTemplateArgs() &&
286 TemplateSpecializationType::anyDependentTemplateArguments(
288 getNumTemplateArgs(),
289 InstantiationDependent)) {
290 TypeDependent = true;
291 ValueDependent = true;
292 InstantiationDependent = true;
295 ExprBits.TypeDependent = TypeDependent;
296 ExprBits.ValueDependent = ValueDependent;
297 ExprBits.InstantiationDependent = InstantiationDependent;
299 // Is the declaration a parameter pack?
300 if (getDecl()->isParameterPack())
301 ExprBits.ContainsUnexpandedParameterPack = true;
304 DeclRefExpr::DeclRefExpr(NestedNameSpecifierLoc QualifierLoc,
305 ValueDecl *D, const DeclarationNameInfo &NameInfo,
307 const TemplateArgumentListInfo *TemplateArgs,
308 QualType T, ExprValueKind VK)
309 : Expr(DeclRefExprClass, T, VK, OK_Ordinary, false, false, false, false),
310 D(D), Loc(NameInfo.getLoc()), DNLoc(NameInfo.getInfo()) {
311 DeclRefExprBits.HasQualifier = QualifierLoc ? 1 : 0;
313 getInternalQualifierLoc() = QualifierLoc;
314 DeclRefExprBits.HasFoundDecl = FoundD ? 1 : 0;
316 getInternalFoundDecl() = FoundD;
317 DeclRefExprBits.HasExplicitTemplateArgs = TemplateArgs ? 1 : 0;
319 bool Dependent = false;
320 bool InstantiationDependent = false;
321 bool ContainsUnexpandedParameterPack = false;
322 getExplicitTemplateArgs().initializeFrom(*TemplateArgs, Dependent,
323 InstantiationDependent,
324 ContainsUnexpandedParameterPack);
325 if (InstantiationDependent)
326 setInstantiationDependent(true);
332 DeclRefExpr *DeclRefExpr::Create(ASTContext &Context,
333 NestedNameSpecifierLoc QualifierLoc,
335 SourceLocation NameLoc,
339 const TemplateArgumentListInfo *TemplateArgs) {
340 return Create(Context, QualifierLoc, D,
341 DeclarationNameInfo(D->getDeclName(), NameLoc),
342 T, VK, FoundD, TemplateArgs);
345 DeclRefExpr *DeclRefExpr::Create(ASTContext &Context,
346 NestedNameSpecifierLoc QualifierLoc,
348 const DeclarationNameInfo &NameInfo,
352 const TemplateArgumentListInfo *TemplateArgs) {
353 // Filter out cases where the found Decl is the same as the value refenenced.
357 std::size_t Size = sizeof(DeclRefExpr);
358 if (QualifierLoc != 0)
359 Size += sizeof(NestedNameSpecifierLoc);
361 Size += sizeof(NamedDecl *);
363 Size += ExplicitTemplateArgumentList::sizeFor(*TemplateArgs);
365 void *Mem = Context.Allocate(Size, llvm::alignOf<DeclRefExpr>());
366 return new (Mem) DeclRefExpr(QualifierLoc, D, NameInfo, FoundD, TemplateArgs,
370 DeclRefExpr *DeclRefExpr::CreateEmpty(ASTContext &Context,
373 bool HasExplicitTemplateArgs,
374 unsigned NumTemplateArgs) {
375 std::size_t Size = sizeof(DeclRefExpr);
377 Size += sizeof(NestedNameSpecifierLoc);
379 Size += sizeof(NamedDecl *);
380 if (HasExplicitTemplateArgs)
381 Size += ExplicitTemplateArgumentList::sizeFor(NumTemplateArgs);
383 void *Mem = Context.Allocate(Size, llvm::alignOf<DeclRefExpr>());
384 return new (Mem) DeclRefExpr(EmptyShell());
387 SourceRange DeclRefExpr::getSourceRange() const {
388 SourceRange R = getNameInfo().getSourceRange();
390 R.setBegin(getQualifierLoc().getBeginLoc());
391 if (hasExplicitTemplateArgs())
392 R.setEnd(getRAngleLoc());
396 // FIXME: Maybe this should use DeclPrinter with a special "print predefined
397 // expr" policy instead.
398 std::string PredefinedExpr::ComputeName(IdentType IT, const Decl *CurrentDecl) {
399 ASTContext &Context = CurrentDecl->getASTContext();
401 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CurrentDecl)) {
402 if (IT != PrettyFunction && IT != PrettyFunctionNoVirtual)
403 return FD->getNameAsString();
405 llvm::SmallString<256> Name;
406 llvm::raw_svector_ostream Out(Name);
408 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
409 if (MD->isVirtual() && IT != PrettyFunctionNoVirtual)
415 PrintingPolicy Policy(Context.getLangOptions());
417 std::string Proto = FD->getQualifiedNameAsString(Policy);
419 const FunctionType *AFT = FD->getType()->getAs<FunctionType>();
420 const FunctionProtoType *FT = 0;
421 if (FD->hasWrittenPrototype())
422 FT = dyn_cast<FunctionProtoType>(AFT);
426 llvm::raw_string_ostream POut(Proto);
427 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) {
430 FD->getParamDecl(i)->getType().getAsStringInternal(Param, Policy);
434 if (FT->isVariadic()) {
435 if (FD->getNumParams()) POut << ", ";
441 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
442 Qualifiers ThisQuals = Qualifiers::fromCVRMask(MD->getTypeQualifiers());
443 if (ThisQuals.hasConst())
445 if (ThisQuals.hasVolatile())
446 Proto += " volatile";
449 if (!isa<CXXConstructorDecl>(FD) && !isa<CXXDestructorDecl>(FD))
450 AFT->getResultType().getAsStringInternal(Proto, Policy);
455 return Name.str().str();
457 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurrentDecl)) {
458 llvm::SmallString<256> Name;
459 llvm::raw_svector_ostream Out(Name);
460 Out << (MD->isInstanceMethod() ? '-' : '+');
463 // For incorrect code, there might not be an ObjCInterfaceDecl. Do
464 // a null check to avoid a crash.
465 if (const ObjCInterfaceDecl *ID = MD->getClassInterface())
468 if (const ObjCCategoryImplDecl *CID =
469 dyn_cast<ObjCCategoryImplDecl>(MD->getDeclContext()))
470 Out << '(' << CID << ')';
473 Out << MD->getSelector().getAsString();
477 return Name.str().str();
479 if (isa<TranslationUnitDecl>(CurrentDecl) && IT == PrettyFunction) {
480 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
486 void APNumericStorage::setIntValue(ASTContext &C, const llvm::APInt &Val) {
490 BitWidth = Val.getBitWidth();
491 unsigned NumWords = Val.getNumWords();
492 const uint64_t* Words = Val.getRawData();
494 pVal = new (C) uint64_t[NumWords];
495 std::copy(Words, Words + NumWords, pVal);
496 } else if (NumWords == 1)
503 IntegerLiteral::Create(ASTContext &C, const llvm::APInt &V,
504 QualType type, SourceLocation l) {
505 return new (C) IntegerLiteral(C, V, type, l);
509 IntegerLiteral::Create(ASTContext &C, EmptyShell Empty) {
510 return new (C) IntegerLiteral(Empty);
514 FloatingLiteral::Create(ASTContext &C, const llvm::APFloat &V,
515 bool isexact, QualType Type, SourceLocation L) {
516 return new (C) FloatingLiteral(C, V, isexact, Type, L);
520 FloatingLiteral::Create(ASTContext &C, EmptyShell Empty) {
521 return new (C) FloatingLiteral(Empty);
524 /// getValueAsApproximateDouble - This returns the value as an inaccurate
525 /// double. Note that this may cause loss of precision, but is useful for
526 /// debugging dumps, etc.
527 double FloatingLiteral::getValueAsApproximateDouble() const {
528 llvm::APFloat V = getValue();
530 V.convert(llvm::APFloat::IEEEdouble, llvm::APFloat::rmNearestTiesToEven,
532 return V.convertToDouble();
535 StringLiteral *StringLiteral::Create(ASTContext &C, llvm::StringRef Str,
537 bool Pascal, QualType Ty,
538 const SourceLocation *Loc,
540 // Allocate enough space for the StringLiteral plus an array of locations for
541 // any concatenated string tokens.
542 void *Mem = C.Allocate(sizeof(StringLiteral)+
543 sizeof(SourceLocation)*(NumStrs-1),
544 llvm::alignOf<StringLiteral>());
545 StringLiteral *SL = new (Mem) StringLiteral(Ty);
547 // OPTIMIZE: could allocate this appended to the StringLiteral.
548 char *AStrData = new (C, 1) char[Str.size()];
549 memcpy(AStrData, Str.data(), Str.size());
550 SL->StrData = AStrData;
551 SL->ByteLength = Str.size();
553 SL->IsPascal = Pascal;
554 SL->TokLocs[0] = Loc[0];
555 SL->NumConcatenated = NumStrs;
558 memcpy(&SL->TokLocs[1], Loc+1, sizeof(SourceLocation)*(NumStrs-1));
562 StringLiteral *StringLiteral::CreateEmpty(ASTContext &C, unsigned NumStrs) {
563 void *Mem = C.Allocate(sizeof(StringLiteral)+
564 sizeof(SourceLocation)*(NumStrs-1),
565 llvm::alignOf<StringLiteral>());
566 StringLiteral *SL = new (Mem) StringLiteral(QualType());
569 SL->NumConcatenated = NumStrs;
573 void StringLiteral::setString(ASTContext &C, llvm::StringRef Str) {
574 char *AStrData = new (C, 1) char[Str.size()];
575 memcpy(AStrData, Str.data(), Str.size());
577 ByteLength = Str.size();
580 /// getLocationOfByte - Return a source location that points to the specified
581 /// byte of this string literal.
583 /// Strings are amazingly complex. They can be formed from multiple tokens and
584 /// can have escape sequences in them in addition to the usual trigraph and
585 /// escaped newline business. This routine handles this complexity.
587 SourceLocation StringLiteral::
588 getLocationOfByte(unsigned ByteNo, const SourceManager &SM,
589 const LangOptions &Features, const TargetInfo &Target) const {
590 assert(!isWide() && "This doesn't work for wide strings yet");
592 // Loop over all of the tokens in this string until we find the one that
593 // contains the byte we're looking for.
596 assert(TokNo < getNumConcatenated() && "Invalid byte number!");
597 SourceLocation StrTokLoc = getStrTokenLoc(TokNo);
599 // Get the spelling of the string so that we can get the data that makes up
600 // the string literal, not the identifier for the macro it is potentially
602 SourceLocation StrTokSpellingLoc = SM.getSpellingLoc(StrTokLoc);
604 // Re-lex the token to get its length and original spelling.
605 std::pair<FileID, unsigned> LocInfo =SM.getDecomposedLoc(StrTokSpellingLoc);
606 bool Invalid = false;
607 llvm::StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
609 return StrTokSpellingLoc;
611 const char *StrData = Buffer.data()+LocInfo.second;
613 // Create a langops struct and enable trigraphs. This is sufficient for
615 LangOptions LangOpts;
616 LangOpts.Trigraphs = true;
618 // Create a lexer starting at the beginning of this token.
619 Lexer TheLexer(StrTokSpellingLoc, Features, Buffer.begin(), StrData,
622 TheLexer.LexFromRawLexer(TheTok);
624 // Use the StringLiteralParser to compute the length of the string in bytes.
625 StringLiteralParser SLP(&TheTok, 1, SM, Features, Target);
626 unsigned TokNumBytes = SLP.GetStringLength();
628 // If the byte is in this token, return the location of the byte.
629 if (ByteNo < TokNumBytes ||
630 (ByteNo == TokNumBytes && TokNo == getNumConcatenated() - 1)) {
631 unsigned Offset = SLP.getOffsetOfStringByte(TheTok, ByteNo);
633 // Now that we know the offset of the token in the spelling, use the
634 // preprocessor to get the offset in the original source.
635 return Lexer::AdvanceToTokenCharacter(StrTokLoc, Offset, SM, Features);
638 // Move to the next string token.
640 ByteNo -= TokNumBytes;
646 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
647 /// corresponds to, e.g. "sizeof" or "[pre]++".
648 const char *UnaryOperator::getOpcodeStr(Opcode Op) {
650 default: assert(0 && "Unknown unary operator");
651 case UO_PostInc: return "++";
652 case UO_PostDec: return "--";
653 case UO_PreInc: return "++";
654 case UO_PreDec: return "--";
655 case UO_AddrOf: return "&";
656 case UO_Deref: return "*";
657 case UO_Plus: return "+";
658 case UO_Minus: return "-";
659 case UO_Not: return "~";
660 case UO_LNot: return "!";
661 case UO_Real: return "__real";
662 case UO_Imag: return "__imag";
663 case UO_Extension: return "__extension__";
668 UnaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix) {
670 default: assert(false && "No unary operator for overloaded function");
671 case OO_PlusPlus: return Postfix ? UO_PostInc : UO_PreInc;
672 case OO_MinusMinus: return Postfix ? UO_PostDec : UO_PreDec;
673 case OO_Amp: return UO_AddrOf;
674 case OO_Star: return UO_Deref;
675 case OO_Plus: return UO_Plus;
676 case OO_Minus: return UO_Minus;
677 case OO_Tilde: return UO_Not;
678 case OO_Exclaim: return UO_LNot;
682 OverloadedOperatorKind UnaryOperator::getOverloadedOperator(Opcode Opc) {
684 case UO_PostInc: case UO_PreInc: return OO_PlusPlus;
685 case UO_PostDec: case UO_PreDec: return OO_MinusMinus;
686 case UO_AddrOf: return OO_Amp;
687 case UO_Deref: return OO_Star;
688 case UO_Plus: return OO_Plus;
689 case UO_Minus: return OO_Minus;
690 case UO_Not: return OO_Tilde;
691 case UO_LNot: return OO_Exclaim;
692 default: return OO_None;
697 //===----------------------------------------------------------------------===//
698 // Postfix Operators.
699 //===----------------------------------------------------------------------===//
701 CallExpr::CallExpr(ASTContext& C, StmtClass SC, Expr *fn, unsigned NumPreArgs,
702 Expr **args, unsigned numargs, QualType t, ExprValueKind VK,
703 SourceLocation rparenloc)
704 : Expr(SC, t, VK, OK_Ordinary,
705 fn->isTypeDependent(),
706 fn->isValueDependent(),
707 fn->isInstantiationDependent(),
708 fn->containsUnexpandedParameterPack()),
711 SubExprs = new (C) Stmt*[numargs+PREARGS_START+NumPreArgs];
713 for (unsigned i = 0; i != numargs; ++i) {
714 if (args[i]->isTypeDependent())
715 ExprBits.TypeDependent = true;
716 if (args[i]->isValueDependent())
717 ExprBits.ValueDependent = true;
718 if (args[i]->isInstantiationDependent())
719 ExprBits.InstantiationDependent = true;
720 if (args[i]->containsUnexpandedParameterPack())
721 ExprBits.ContainsUnexpandedParameterPack = true;
723 SubExprs[i+PREARGS_START+NumPreArgs] = args[i];
726 CallExprBits.NumPreArgs = NumPreArgs;
727 RParenLoc = rparenloc;
730 CallExpr::CallExpr(ASTContext& C, Expr *fn, Expr **args, unsigned numargs,
731 QualType t, ExprValueKind VK, SourceLocation rparenloc)
732 : Expr(CallExprClass, t, VK, OK_Ordinary,
733 fn->isTypeDependent(),
734 fn->isValueDependent(),
735 fn->isInstantiationDependent(),
736 fn->containsUnexpandedParameterPack()),
739 SubExprs = new (C) Stmt*[numargs+PREARGS_START];
741 for (unsigned i = 0; i != numargs; ++i) {
742 if (args[i]->isTypeDependent())
743 ExprBits.TypeDependent = true;
744 if (args[i]->isValueDependent())
745 ExprBits.ValueDependent = true;
746 if (args[i]->isInstantiationDependent())
747 ExprBits.InstantiationDependent = true;
748 if (args[i]->containsUnexpandedParameterPack())
749 ExprBits.ContainsUnexpandedParameterPack = true;
751 SubExprs[i+PREARGS_START] = args[i];
754 CallExprBits.NumPreArgs = 0;
755 RParenLoc = rparenloc;
758 CallExpr::CallExpr(ASTContext &C, StmtClass SC, EmptyShell Empty)
759 : Expr(SC, Empty), SubExprs(0), NumArgs(0) {
760 // FIXME: Why do we allocate this?
761 SubExprs = new (C) Stmt*[PREARGS_START];
762 CallExprBits.NumPreArgs = 0;
765 CallExpr::CallExpr(ASTContext &C, StmtClass SC, unsigned NumPreArgs,
767 : Expr(SC, Empty), SubExprs(0), NumArgs(0) {
768 // FIXME: Why do we allocate this?
769 SubExprs = new (C) Stmt*[PREARGS_START+NumPreArgs];
770 CallExprBits.NumPreArgs = NumPreArgs;
773 Decl *CallExpr::getCalleeDecl() {
774 Expr *CEE = getCallee()->IgnoreParenCasts();
775 // If we're calling a dereference, look at the pointer instead.
776 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CEE)) {
777 if (BO->isPtrMemOp())
778 CEE = BO->getRHS()->IgnoreParenCasts();
779 } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(CEE)) {
780 if (UO->getOpcode() == UO_Deref)
781 CEE = UO->getSubExpr()->IgnoreParenCasts();
783 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CEE))
784 return DRE->getDecl();
785 if (MemberExpr *ME = dyn_cast<MemberExpr>(CEE))
786 return ME->getMemberDecl();
791 FunctionDecl *CallExpr::getDirectCallee() {
792 return dyn_cast_or_null<FunctionDecl>(getCalleeDecl());
795 /// setNumArgs - This changes the number of arguments present in this call.
796 /// Any orphaned expressions are deleted by this, and any new operands are set
798 void CallExpr::setNumArgs(ASTContext& C, unsigned NumArgs) {
799 // No change, just return.
800 if (NumArgs == getNumArgs()) return;
802 // If shrinking # arguments, just delete the extras and forgot them.
803 if (NumArgs < getNumArgs()) {
804 this->NumArgs = NumArgs;
808 // Otherwise, we are growing the # arguments. New an bigger argument array.
809 unsigned NumPreArgs = getNumPreArgs();
810 Stmt **NewSubExprs = new (C) Stmt*[NumArgs+PREARGS_START+NumPreArgs];
812 for (unsigned i = 0; i != getNumArgs()+PREARGS_START+NumPreArgs; ++i)
813 NewSubExprs[i] = SubExprs[i];
814 // Null out new args.
815 for (unsigned i = getNumArgs()+PREARGS_START+NumPreArgs;
816 i != NumArgs+PREARGS_START+NumPreArgs; ++i)
819 if (SubExprs) C.Deallocate(SubExprs);
820 SubExprs = NewSubExprs;
821 this->NumArgs = NumArgs;
824 /// isBuiltinCall - If this is a call to a builtin, return the builtin ID. If
826 unsigned CallExpr::isBuiltinCall(const ASTContext &Context) const {
827 // All simple function calls (e.g. func()) are implicitly cast to pointer to
828 // function. As a result, we try and obtain the DeclRefExpr from the
830 const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(getCallee());
831 if (!ICE) // FIXME: deal with more complex calls (e.g. (func)(), (*func)()).
834 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr());
838 const FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
842 if (!FDecl->getIdentifier())
845 return FDecl->getBuiltinID();
848 QualType CallExpr::getCallReturnType() const {
849 QualType CalleeType = getCallee()->getType();
850 if (const PointerType *FnTypePtr = CalleeType->getAs<PointerType>())
851 CalleeType = FnTypePtr->getPointeeType();
852 else if (const BlockPointerType *BPT = CalleeType->getAs<BlockPointerType>())
853 CalleeType = BPT->getPointeeType();
854 else if (CalleeType->isSpecificPlaceholderType(BuiltinType::BoundMember))
855 // This should never be overloaded and so should never return null.
856 CalleeType = Expr::findBoundMemberType(getCallee());
858 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
859 return FnType->getResultType();
862 SourceRange CallExpr::getSourceRange() const {
863 if (isa<CXXOperatorCallExpr>(this))
864 return cast<CXXOperatorCallExpr>(this)->getSourceRange();
866 SourceLocation begin = getCallee()->getLocStart();
867 if (begin.isInvalid() && getNumArgs() > 0)
868 begin = getArg(0)->getLocStart();
869 SourceLocation end = getRParenLoc();
870 if (end.isInvalid() && getNumArgs() > 0)
871 end = getArg(getNumArgs() - 1)->getLocEnd();
872 return SourceRange(begin, end);
875 OffsetOfExpr *OffsetOfExpr::Create(ASTContext &C, QualType type,
876 SourceLocation OperatorLoc,
878 OffsetOfNode* compsPtr, unsigned numComps,
879 Expr** exprsPtr, unsigned numExprs,
880 SourceLocation RParenLoc) {
881 void *Mem = C.Allocate(sizeof(OffsetOfExpr) +
882 sizeof(OffsetOfNode) * numComps +
883 sizeof(Expr*) * numExprs);
885 return new (Mem) OffsetOfExpr(C, type, OperatorLoc, tsi, compsPtr, numComps,
886 exprsPtr, numExprs, RParenLoc);
889 OffsetOfExpr *OffsetOfExpr::CreateEmpty(ASTContext &C,
890 unsigned numComps, unsigned numExprs) {
891 void *Mem = C.Allocate(sizeof(OffsetOfExpr) +
892 sizeof(OffsetOfNode) * numComps +
893 sizeof(Expr*) * numExprs);
894 return new (Mem) OffsetOfExpr(numComps, numExprs);
897 OffsetOfExpr::OffsetOfExpr(ASTContext &C, QualType type,
898 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
899 OffsetOfNode* compsPtr, unsigned numComps,
900 Expr** exprsPtr, unsigned numExprs,
901 SourceLocation RParenLoc)
902 : Expr(OffsetOfExprClass, type, VK_RValue, OK_Ordinary,
903 /*TypeDependent=*/false,
904 /*ValueDependent=*/tsi->getType()->isDependentType(),
905 tsi->getType()->isInstantiationDependentType(),
906 tsi->getType()->containsUnexpandedParameterPack()),
907 OperatorLoc(OperatorLoc), RParenLoc(RParenLoc), TSInfo(tsi),
908 NumComps(numComps), NumExprs(numExprs)
910 for(unsigned i = 0; i < numComps; ++i) {
911 setComponent(i, compsPtr[i]);
914 for(unsigned i = 0; i < numExprs; ++i) {
915 if (exprsPtr[i]->isTypeDependent() || exprsPtr[i]->isValueDependent())
916 ExprBits.ValueDependent = true;
917 if (exprsPtr[i]->containsUnexpandedParameterPack())
918 ExprBits.ContainsUnexpandedParameterPack = true;
920 setIndexExpr(i, exprsPtr[i]);
924 IdentifierInfo *OffsetOfExpr::OffsetOfNode::getFieldName() const {
925 assert(getKind() == Field || getKind() == Identifier);
926 if (getKind() == Field)
927 return getField()->getIdentifier();
929 return reinterpret_cast<IdentifierInfo *> (Data & ~(uintptr_t)Mask);
932 MemberExpr *MemberExpr::Create(ASTContext &C, Expr *base, bool isarrow,
933 NestedNameSpecifierLoc QualifierLoc,
934 ValueDecl *memberdecl,
935 DeclAccessPair founddecl,
936 DeclarationNameInfo nameinfo,
937 const TemplateArgumentListInfo *targs,
941 std::size_t Size = sizeof(MemberExpr);
943 bool hasQualOrFound = (QualifierLoc ||
944 founddecl.getDecl() != memberdecl ||
945 founddecl.getAccess() != memberdecl->getAccess());
947 Size += sizeof(MemberNameQualifier);
950 Size += ExplicitTemplateArgumentList::sizeFor(*targs);
952 void *Mem = C.Allocate(Size, llvm::alignOf<MemberExpr>());
953 MemberExpr *E = new (Mem) MemberExpr(base, isarrow, memberdecl, nameinfo,
956 if (hasQualOrFound) {
957 // FIXME: Wrong. We should be looking at the member declaration we found.
958 if (QualifierLoc && QualifierLoc.getNestedNameSpecifier()->isDependent()) {
959 E->setValueDependent(true);
960 E->setTypeDependent(true);
961 E->setInstantiationDependent(true);
963 else if (QualifierLoc &&
964 QualifierLoc.getNestedNameSpecifier()->isInstantiationDependent())
965 E->setInstantiationDependent(true);
967 E->HasQualifierOrFoundDecl = true;
969 MemberNameQualifier *NQ = E->getMemberQualifier();
970 NQ->QualifierLoc = QualifierLoc;
971 NQ->FoundDecl = founddecl;
975 bool Dependent = false;
976 bool InstantiationDependent = false;
977 bool ContainsUnexpandedParameterPack = false;
978 E->HasExplicitTemplateArgumentList = true;
979 E->getExplicitTemplateArgs().initializeFrom(*targs, Dependent,
980 InstantiationDependent,
981 ContainsUnexpandedParameterPack);
982 if (InstantiationDependent)
983 E->setInstantiationDependent(true);
989 SourceRange MemberExpr::getSourceRange() const {
990 SourceLocation StartLoc;
991 if (isImplicitAccess()) {
993 StartLoc = getQualifierLoc().getBeginLoc();
995 StartLoc = MemberLoc;
997 // FIXME: We don't want this to happen. Rather, we should be able to
998 // detect all kinds of implicit accesses more cleanly.
999 StartLoc = getBase()->getLocStart();
1000 if (StartLoc.isInvalid())
1001 StartLoc = MemberLoc;
1004 SourceLocation EndLoc =
1005 HasExplicitTemplateArgumentList? getRAngleLoc()
1006 : getMemberNameInfo().getEndLoc();
1008 return SourceRange(StartLoc, EndLoc);
1011 const char *CastExpr::getCastKindName() const {
1012 switch (getCastKind()) {
1017 case CK_LValueBitCast:
1018 return "LValueBitCast";
1019 case CK_LValueToRValue:
1020 return "LValueToRValue";
1021 case CK_GetObjCProperty:
1022 return "GetObjCProperty";
1025 case CK_BaseToDerived:
1026 return "BaseToDerived";
1027 case CK_DerivedToBase:
1028 return "DerivedToBase";
1029 case CK_UncheckedDerivedToBase:
1030 return "UncheckedDerivedToBase";
1035 case CK_ArrayToPointerDecay:
1036 return "ArrayToPointerDecay";
1037 case CK_FunctionToPointerDecay:
1038 return "FunctionToPointerDecay";
1039 case CK_NullToMemberPointer:
1040 return "NullToMemberPointer";
1041 case CK_NullToPointer:
1042 return "NullToPointer";
1043 case CK_BaseToDerivedMemberPointer:
1044 return "BaseToDerivedMemberPointer";
1045 case CK_DerivedToBaseMemberPointer:
1046 return "DerivedToBaseMemberPointer";
1047 case CK_UserDefinedConversion:
1048 return "UserDefinedConversion";
1049 case CK_ConstructorConversion:
1050 return "ConstructorConversion";
1051 case CK_IntegralToPointer:
1052 return "IntegralToPointer";
1053 case CK_PointerToIntegral:
1054 return "PointerToIntegral";
1055 case CK_PointerToBoolean:
1056 return "PointerToBoolean";
1059 case CK_VectorSplat:
1060 return "VectorSplat";
1061 case CK_IntegralCast:
1062 return "IntegralCast";
1063 case CK_IntegralToBoolean:
1064 return "IntegralToBoolean";
1065 case CK_IntegralToFloating:
1066 return "IntegralToFloating";
1067 case CK_FloatingToIntegral:
1068 return "FloatingToIntegral";
1069 case CK_FloatingCast:
1070 return "FloatingCast";
1071 case CK_FloatingToBoolean:
1072 return "FloatingToBoolean";
1073 case CK_MemberPointerToBoolean:
1074 return "MemberPointerToBoolean";
1075 case CK_AnyPointerToObjCPointerCast:
1076 return "AnyPointerToObjCPointerCast";
1077 case CK_AnyPointerToBlockPointerCast:
1078 return "AnyPointerToBlockPointerCast";
1079 case CK_ObjCObjectLValueCast:
1080 return "ObjCObjectLValueCast";
1081 case CK_FloatingRealToComplex:
1082 return "FloatingRealToComplex";
1083 case CK_FloatingComplexToReal:
1084 return "FloatingComplexToReal";
1085 case CK_FloatingComplexToBoolean:
1086 return "FloatingComplexToBoolean";
1087 case CK_FloatingComplexCast:
1088 return "FloatingComplexCast";
1089 case CK_FloatingComplexToIntegralComplex:
1090 return "FloatingComplexToIntegralComplex";
1091 case CK_IntegralRealToComplex:
1092 return "IntegralRealToComplex";
1093 case CK_IntegralComplexToReal:
1094 return "IntegralComplexToReal";
1095 case CK_IntegralComplexToBoolean:
1096 return "IntegralComplexToBoolean";
1097 case CK_IntegralComplexCast:
1098 return "IntegralComplexCast";
1099 case CK_IntegralComplexToFloatingComplex:
1100 return "IntegralComplexToFloatingComplex";
1101 case CK_ObjCConsumeObject:
1102 return "ObjCConsumeObject";
1103 case CK_ObjCProduceObject:
1104 return "ObjCProduceObject";
1105 case CK_ObjCReclaimReturnedObject:
1106 return "ObjCReclaimReturnedObject";
1109 llvm_unreachable("Unhandled cast kind!");
1113 Expr *CastExpr::getSubExprAsWritten() {
1117 SubExpr = E->getSubExpr();
1119 // Skip through reference binding to temporary.
1120 if (MaterializeTemporaryExpr *Materialize
1121 = dyn_cast<MaterializeTemporaryExpr>(SubExpr))
1122 SubExpr = Materialize->GetTemporaryExpr();
1124 // Skip any temporary bindings; they're implicit.
1125 if (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(SubExpr))
1126 SubExpr = Binder->getSubExpr();
1128 // Conversions by constructor and conversion functions have a
1129 // subexpression describing the call; strip it off.
1130 if (E->getCastKind() == CK_ConstructorConversion)
1131 SubExpr = cast<CXXConstructExpr>(SubExpr)->getArg(0);
1132 else if (E->getCastKind() == CK_UserDefinedConversion)
1133 SubExpr = cast<CXXMemberCallExpr>(SubExpr)->getImplicitObjectArgument();
1135 // If the subexpression we're left with is an implicit cast, look
1136 // through that, too.
1137 } while ((E = dyn_cast<ImplicitCastExpr>(SubExpr)));
1142 CXXBaseSpecifier **CastExpr::path_buffer() {
1143 switch (getStmtClass()) {
1144 #define ABSTRACT_STMT(x)
1145 #define CASTEXPR(Type, Base) \
1146 case Stmt::Type##Class: \
1147 return reinterpret_cast<CXXBaseSpecifier**>(static_cast<Type*>(this)+1);
1148 #define STMT(Type, Base)
1149 #include "clang/AST/StmtNodes.inc"
1151 llvm_unreachable("non-cast expressions not possible here");
1156 void CastExpr::setCastPath(const CXXCastPath &Path) {
1157 assert(Path.size() == path_size());
1158 memcpy(path_buffer(), Path.data(), Path.size() * sizeof(CXXBaseSpecifier*));
1161 ImplicitCastExpr *ImplicitCastExpr::Create(ASTContext &C, QualType T,
1162 CastKind Kind, Expr *Operand,
1163 const CXXCastPath *BasePath,
1165 unsigned PathSize = (BasePath ? BasePath->size() : 0);
1167 C.Allocate(sizeof(ImplicitCastExpr) + PathSize * sizeof(CXXBaseSpecifier*));
1168 ImplicitCastExpr *E =
1169 new (Buffer) ImplicitCastExpr(T, Kind, Operand, PathSize, VK);
1170 if (PathSize) E->setCastPath(*BasePath);
1174 ImplicitCastExpr *ImplicitCastExpr::CreateEmpty(ASTContext &C,
1175 unsigned PathSize) {
1177 C.Allocate(sizeof(ImplicitCastExpr) + PathSize * sizeof(CXXBaseSpecifier*));
1178 return new (Buffer) ImplicitCastExpr(EmptyShell(), PathSize);
1182 CStyleCastExpr *CStyleCastExpr::Create(ASTContext &C, QualType T,
1183 ExprValueKind VK, CastKind K, Expr *Op,
1184 const CXXCastPath *BasePath,
1185 TypeSourceInfo *WrittenTy,
1186 SourceLocation L, SourceLocation R) {
1187 unsigned PathSize = (BasePath ? BasePath->size() : 0);
1189 C.Allocate(sizeof(CStyleCastExpr) + PathSize * sizeof(CXXBaseSpecifier*));
1191 new (Buffer) CStyleCastExpr(T, VK, K, Op, PathSize, WrittenTy, L, R);
1192 if (PathSize) E->setCastPath(*BasePath);
1196 CStyleCastExpr *CStyleCastExpr::CreateEmpty(ASTContext &C, unsigned PathSize) {
1198 C.Allocate(sizeof(CStyleCastExpr) + PathSize * sizeof(CXXBaseSpecifier*));
1199 return new (Buffer) CStyleCastExpr(EmptyShell(), PathSize);
1202 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1203 /// corresponds to, e.g. "<<=".
1204 const char *BinaryOperator::getOpcodeStr(Opcode Op) {
1206 case BO_PtrMemD: return ".*";
1207 case BO_PtrMemI: return "->*";
1208 case BO_Mul: return "*";
1209 case BO_Div: return "/";
1210 case BO_Rem: return "%";
1211 case BO_Add: return "+";
1212 case BO_Sub: return "-";
1213 case BO_Shl: return "<<";
1214 case BO_Shr: return ">>";
1215 case BO_LT: return "<";
1216 case BO_GT: return ">";
1217 case BO_LE: return "<=";
1218 case BO_GE: return ">=";
1219 case BO_EQ: return "==";
1220 case BO_NE: return "!=";
1221 case BO_And: return "&";
1222 case BO_Xor: return "^";
1223 case BO_Or: return "|";
1224 case BO_LAnd: return "&&";
1225 case BO_LOr: return "||";
1226 case BO_Assign: return "=";
1227 case BO_MulAssign: return "*=";
1228 case BO_DivAssign: return "/=";
1229 case BO_RemAssign: return "%=";
1230 case BO_AddAssign: return "+=";
1231 case BO_SubAssign: return "-=";
1232 case BO_ShlAssign: return "<<=";
1233 case BO_ShrAssign: return ">>=";
1234 case BO_AndAssign: return "&=";
1235 case BO_XorAssign: return "^=";
1236 case BO_OrAssign: return "|=";
1237 case BO_Comma: return ",";
1244 BinaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO) {
1246 default: assert(false && "Not an overloadable binary operator");
1247 case OO_Plus: return BO_Add;
1248 case OO_Minus: return BO_Sub;
1249 case OO_Star: return BO_Mul;
1250 case OO_Slash: return BO_Div;
1251 case OO_Percent: return BO_Rem;
1252 case OO_Caret: return BO_Xor;
1253 case OO_Amp: return BO_And;
1254 case OO_Pipe: return BO_Or;
1255 case OO_Equal: return BO_Assign;
1256 case OO_Less: return BO_LT;
1257 case OO_Greater: return BO_GT;
1258 case OO_PlusEqual: return BO_AddAssign;
1259 case OO_MinusEqual: return BO_SubAssign;
1260 case OO_StarEqual: return BO_MulAssign;
1261 case OO_SlashEqual: return BO_DivAssign;
1262 case OO_PercentEqual: return BO_RemAssign;
1263 case OO_CaretEqual: return BO_XorAssign;
1264 case OO_AmpEqual: return BO_AndAssign;
1265 case OO_PipeEqual: return BO_OrAssign;
1266 case OO_LessLess: return BO_Shl;
1267 case OO_GreaterGreater: return BO_Shr;
1268 case OO_LessLessEqual: return BO_ShlAssign;
1269 case OO_GreaterGreaterEqual: return BO_ShrAssign;
1270 case OO_EqualEqual: return BO_EQ;
1271 case OO_ExclaimEqual: return BO_NE;
1272 case OO_LessEqual: return BO_LE;
1273 case OO_GreaterEqual: return BO_GE;
1274 case OO_AmpAmp: return BO_LAnd;
1275 case OO_PipePipe: return BO_LOr;
1276 case OO_Comma: return BO_Comma;
1277 case OO_ArrowStar: return BO_PtrMemI;
1281 OverloadedOperatorKind BinaryOperator::getOverloadedOperator(Opcode Opc) {
1282 static const OverloadedOperatorKind OverOps[] = {
1283 /* .* Cannot be overloaded */OO_None, OO_ArrowStar,
1284 OO_Star, OO_Slash, OO_Percent,
1286 OO_LessLess, OO_GreaterGreater,
1287 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
1288 OO_EqualEqual, OO_ExclaimEqual,
1294 OO_Equal, OO_StarEqual,
1295 OO_SlashEqual, OO_PercentEqual,
1296 OO_PlusEqual, OO_MinusEqual,
1297 OO_LessLessEqual, OO_GreaterGreaterEqual,
1298 OO_AmpEqual, OO_CaretEqual,
1302 return OverOps[Opc];
1305 InitListExpr::InitListExpr(ASTContext &C, SourceLocation lbraceloc,
1306 Expr **initExprs, unsigned numInits,
1307 SourceLocation rbraceloc)
1308 : Expr(InitListExprClass, QualType(), VK_RValue, OK_Ordinary, false, false,
1310 InitExprs(C, numInits),
1311 LBraceLoc(lbraceloc), RBraceLoc(rbraceloc), SyntacticForm(0),
1312 HadArrayRangeDesignator(false)
1314 for (unsigned I = 0; I != numInits; ++I) {
1315 if (initExprs[I]->isTypeDependent())
1316 ExprBits.TypeDependent = true;
1317 if (initExprs[I]->isValueDependent())
1318 ExprBits.ValueDependent = true;
1319 if (initExprs[I]->isInstantiationDependent())
1320 ExprBits.InstantiationDependent = true;
1321 if (initExprs[I]->containsUnexpandedParameterPack())
1322 ExprBits.ContainsUnexpandedParameterPack = true;
1325 InitExprs.insert(C, InitExprs.end(), initExprs, initExprs+numInits);
1328 void InitListExpr::reserveInits(ASTContext &C, unsigned NumInits) {
1329 if (NumInits > InitExprs.size())
1330 InitExprs.reserve(C, NumInits);
1333 void InitListExpr::resizeInits(ASTContext &C, unsigned NumInits) {
1334 InitExprs.resize(C, NumInits, 0);
1337 Expr *InitListExpr::updateInit(ASTContext &C, unsigned Init, Expr *expr) {
1338 if (Init >= InitExprs.size()) {
1339 InitExprs.insert(C, InitExprs.end(), Init - InitExprs.size() + 1, 0);
1340 InitExprs.back() = expr;
1344 Expr *Result = cast_or_null<Expr>(InitExprs[Init]);
1345 InitExprs[Init] = expr;
1349 void InitListExpr::setArrayFiller(Expr *filler) {
1350 ArrayFillerOrUnionFieldInit = filler;
1351 // Fill out any "holes" in the array due to designated initializers.
1352 Expr **inits = getInits();
1353 for (unsigned i = 0, e = getNumInits(); i != e; ++i)
1358 SourceRange InitListExpr::getSourceRange() const {
1360 return SyntacticForm->getSourceRange();
1361 SourceLocation Beg = LBraceLoc, End = RBraceLoc;
1362 if (Beg.isInvalid()) {
1363 // Find the first non-null initializer.
1364 for (InitExprsTy::const_iterator I = InitExprs.begin(),
1365 E = InitExprs.end();
1368 Beg = S->getLocStart();
1373 if (End.isInvalid()) {
1374 // Find the first non-null initializer from the end.
1375 for (InitExprsTy::const_reverse_iterator I = InitExprs.rbegin(),
1376 E = InitExprs.rend();
1379 End = S->getSourceRange().getEnd();
1384 return SourceRange(Beg, End);
1387 /// getFunctionType - Return the underlying function type for this block.
1389 const FunctionType *BlockExpr::getFunctionType() const {
1390 return getType()->getAs<BlockPointerType>()->
1391 getPointeeType()->getAs<FunctionType>();
1394 SourceLocation BlockExpr::getCaretLocation() const {
1395 return TheBlock->getCaretLocation();
1397 const Stmt *BlockExpr::getBody() const {
1398 return TheBlock->getBody();
1400 Stmt *BlockExpr::getBody() {
1401 return TheBlock->getBody();
1405 //===----------------------------------------------------------------------===//
1406 // Generic Expression Routines
1407 //===----------------------------------------------------------------------===//
1409 /// isUnusedResultAWarning - Return true if this immediate expression should
1410 /// be warned about if the result is unused. If so, fill in Loc and Ranges
1411 /// with location to warn on and the source range[s] to report with the
1413 bool Expr::isUnusedResultAWarning(SourceLocation &Loc, SourceRange &R1,
1414 SourceRange &R2, ASTContext &Ctx) const {
1415 // Don't warn if the expr is type dependent. The type could end up
1416 // instantiating to void.
1417 if (isTypeDependent())
1420 switch (getStmtClass()) {
1422 if (getType()->isVoidType())
1425 R1 = getSourceRange();
1427 case ParenExprClass:
1428 return cast<ParenExpr>(this)->getSubExpr()->
1429 isUnusedResultAWarning(Loc, R1, R2, Ctx);
1430 case GenericSelectionExprClass:
1431 return cast<GenericSelectionExpr>(this)->getResultExpr()->
1432 isUnusedResultAWarning(Loc, R1, R2, Ctx);
1433 case UnaryOperatorClass: {
1434 const UnaryOperator *UO = cast<UnaryOperator>(this);
1436 switch (UO->getOpcode()) {
1441 case UO_PreDec: // ++/--
1442 return false; // Not a warning.
1444 // Dereferencing a volatile pointer is a side-effect.
1445 if (Ctx.getCanonicalType(getType()).isVolatileQualified())
1450 // accessing a piece of a volatile complex is a side-effect.
1451 if (Ctx.getCanonicalType(UO->getSubExpr()->getType())
1452 .isVolatileQualified())
1456 return UO->getSubExpr()->isUnusedResultAWarning(Loc, R1, R2, Ctx);
1458 Loc = UO->getOperatorLoc();
1459 R1 = UO->getSubExpr()->getSourceRange();
1462 case BinaryOperatorClass: {
1463 const BinaryOperator *BO = cast<BinaryOperator>(this);
1464 switch (BO->getOpcode()) {
1467 // Consider the RHS of comma for side effects. LHS was checked by
1468 // Sema::CheckCommaOperands.
1470 // ((foo = <blah>), 0) is an idiom for hiding the result (and
1471 // lvalue-ness) of an assignment written in a macro.
1472 if (IntegerLiteral *IE =
1473 dyn_cast<IntegerLiteral>(BO->getRHS()->IgnoreParens()))
1474 if (IE->getValue() == 0)
1476 return BO->getRHS()->isUnusedResultAWarning(Loc, R1, R2, Ctx);
1477 // Consider '||', '&&' to have side effects if the LHS or RHS does.
1480 if (!BO->getLHS()->isUnusedResultAWarning(Loc, R1, R2, Ctx) ||
1481 !BO->getRHS()->isUnusedResultAWarning(Loc, R1, R2, Ctx))
1485 if (BO->isAssignmentOp())
1487 Loc = BO->getOperatorLoc();
1488 R1 = BO->getLHS()->getSourceRange();
1489 R2 = BO->getRHS()->getSourceRange();
1492 case CompoundAssignOperatorClass:
1493 case VAArgExprClass:
1496 case ConditionalOperatorClass: {
1497 // If only one of the LHS or RHS is a warning, the operator might
1498 // be being used for control flow. Only warn if both the LHS and
1499 // RHS are warnings.
1500 const ConditionalOperator *Exp = cast<ConditionalOperator>(this);
1501 if (!Exp->getRHS()->isUnusedResultAWarning(Loc, R1, R2, Ctx))
1505 return Exp->getLHS()->isUnusedResultAWarning(Loc, R1, R2, Ctx);
1508 case MemberExprClass:
1509 // If the base pointer or element is to a volatile pointer/field, accessing
1510 // it is a side effect.
1511 if (Ctx.getCanonicalType(getType()).isVolatileQualified())
1513 Loc = cast<MemberExpr>(this)->getMemberLoc();
1514 R1 = SourceRange(Loc, Loc);
1515 R2 = cast<MemberExpr>(this)->getBase()->getSourceRange();
1518 case ArraySubscriptExprClass:
1519 // If the base pointer or element is to a volatile pointer/field, accessing
1520 // it is a side effect.
1521 if (Ctx.getCanonicalType(getType()).isVolatileQualified())
1523 Loc = cast<ArraySubscriptExpr>(this)->getRBracketLoc();
1524 R1 = cast<ArraySubscriptExpr>(this)->getLHS()->getSourceRange();
1525 R2 = cast<ArraySubscriptExpr>(this)->getRHS()->getSourceRange();
1529 case CXXOperatorCallExprClass:
1530 case CXXMemberCallExprClass: {
1531 // If this is a direct call, get the callee.
1532 const CallExpr *CE = cast<CallExpr>(this);
1533 if (const Decl *FD = CE->getCalleeDecl()) {
1534 // If the callee has attribute pure, const, or warn_unused_result, warn
1535 // about it. void foo() { strlen("bar"); } should warn.
1537 // Note: If new cases are added here, DiagnoseUnusedExprResult should be
1538 // updated to match for QoI.
1539 if (FD->getAttr<WarnUnusedResultAttr>() ||
1540 FD->getAttr<PureAttr>() || FD->getAttr<ConstAttr>()) {
1541 Loc = CE->getCallee()->getLocStart();
1542 R1 = CE->getCallee()->getSourceRange();
1544 if (unsigned NumArgs = CE->getNumArgs())
1545 R2 = SourceRange(CE->getArg(0)->getLocStart(),
1546 CE->getArg(NumArgs-1)->getLocEnd());
1553 case CXXTemporaryObjectExprClass:
1554 case CXXConstructExprClass:
1557 case ObjCMessageExprClass: {
1558 const ObjCMessageExpr *ME = cast<ObjCMessageExpr>(this);
1559 if (Ctx.getLangOptions().ObjCAutoRefCount &&
1560 ME->isInstanceMessage() &&
1561 !ME->getType()->isVoidType() &&
1562 ME->getSelector().getIdentifierInfoForSlot(0) &&
1563 ME->getSelector().getIdentifierInfoForSlot(0)
1564 ->getName().startswith("init")) {
1566 R1 = ME->getSourceRange();
1570 const ObjCMethodDecl *MD = ME->getMethodDecl();
1571 if (MD && MD->getAttr<WarnUnusedResultAttr>()) {
1578 case ObjCPropertyRefExprClass:
1580 R1 = getSourceRange();
1583 case StmtExprClass: {
1584 // Statement exprs don't logically have side effects themselves, but are
1585 // sometimes used in macros in ways that give them a type that is unused.
1586 // For example ({ blah; foo(); }) will end up with a type if foo has a type.
1587 // however, if the result of the stmt expr is dead, we don't want to emit a
1589 const CompoundStmt *CS = cast<StmtExpr>(this)->getSubStmt();
1590 if (!CS->body_empty()) {
1591 if (const Expr *E = dyn_cast<Expr>(CS->body_back()))
1592 return E->isUnusedResultAWarning(Loc, R1, R2, Ctx);
1593 if (const LabelStmt *Label = dyn_cast<LabelStmt>(CS->body_back()))
1594 if (const Expr *E = dyn_cast<Expr>(Label->getSubStmt()))
1595 return E->isUnusedResultAWarning(Loc, R1, R2, Ctx);
1598 if (getType()->isVoidType())
1600 Loc = cast<StmtExpr>(this)->getLParenLoc();
1601 R1 = getSourceRange();
1604 case CStyleCastExprClass:
1605 // If this is an explicit cast to void, allow it. People do this when they
1606 // think they know what they're doing :).
1607 if (getType()->isVoidType())
1609 Loc = cast<CStyleCastExpr>(this)->getLParenLoc();
1610 R1 = cast<CStyleCastExpr>(this)->getSubExpr()->getSourceRange();
1612 case CXXFunctionalCastExprClass: {
1613 if (getType()->isVoidType())
1615 const CastExpr *CE = cast<CastExpr>(this);
1617 // If this is a cast to void or a constructor conversion, check the operand.
1618 // Otherwise, the result of the cast is unused.
1619 if (CE->getCastKind() == CK_ToVoid ||
1620 CE->getCastKind() == CK_ConstructorConversion)
1621 return (cast<CastExpr>(this)->getSubExpr()
1622 ->isUnusedResultAWarning(Loc, R1, R2, Ctx));
1623 Loc = cast<CXXFunctionalCastExpr>(this)->getTypeBeginLoc();
1624 R1 = cast<CXXFunctionalCastExpr>(this)->getSubExpr()->getSourceRange();
1628 case ImplicitCastExprClass:
1629 // Check the operand, since implicit casts are inserted by Sema
1630 return (cast<ImplicitCastExpr>(this)
1631 ->getSubExpr()->isUnusedResultAWarning(Loc, R1, R2, Ctx));
1633 case CXXDefaultArgExprClass:
1634 return (cast<CXXDefaultArgExpr>(this)
1635 ->getExpr()->isUnusedResultAWarning(Loc, R1, R2, Ctx));
1637 case CXXNewExprClass:
1638 // FIXME: In theory, there might be new expressions that don't have side
1639 // effects (e.g. a placement new with an uninitialized POD).
1640 case CXXDeleteExprClass:
1642 case CXXBindTemporaryExprClass:
1643 return (cast<CXXBindTemporaryExpr>(this)
1644 ->getSubExpr()->isUnusedResultAWarning(Loc, R1, R2, Ctx));
1645 case ExprWithCleanupsClass:
1646 return (cast<ExprWithCleanups>(this)
1647 ->getSubExpr()->isUnusedResultAWarning(Loc, R1, R2, Ctx));
1651 /// isOBJCGCCandidate - Check if an expression is objc gc'able.
1652 /// returns true, if it is; false otherwise.
1653 bool Expr::isOBJCGCCandidate(ASTContext &Ctx) const {
1654 const Expr *E = IgnoreParens();
1655 switch (E->getStmtClass()) {
1658 case ObjCIvarRefExprClass:
1660 case Expr::UnaryOperatorClass:
1661 return cast<UnaryOperator>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
1662 case ImplicitCastExprClass:
1663 return cast<ImplicitCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
1664 case MaterializeTemporaryExprClass:
1665 return cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr()
1666 ->isOBJCGCCandidate(Ctx);
1667 case CStyleCastExprClass:
1668 return cast<CStyleCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
1669 case DeclRefExprClass: {
1670 const Decl *D = cast<DeclRefExpr>(E)->getDecl();
1671 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1672 if (VD->hasGlobalStorage())
1674 QualType T = VD->getType();
1675 // dereferencing to a pointer is always a gc'able candidate,
1676 // unless it is __weak.
1677 return T->isPointerType() &&
1678 (Ctx.getObjCGCAttrKind(T) != Qualifiers::Weak);
1682 case MemberExprClass: {
1683 const MemberExpr *M = cast<MemberExpr>(E);
1684 return M->getBase()->isOBJCGCCandidate(Ctx);
1686 case ArraySubscriptExprClass:
1687 return cast<ArraySubscriptExpr>(E)->getBase()->isOBJCGCCandidate(Ctx);
1691 bool Expr::isBoundMemberFunction(ASTContext &Ctx) const {
1692 if (isTypeDependent())
1694 return ClassifyLValue(Ctx) == Expr::LV_MemberFunction;
1697 QualType Expr::findBoundMemberType(const Expr *expr) {
1698 assert(expr->getType()->isSpecificPlaceholderType(BuiltinType::BoundMember));
1700 // Bound member expressions are always one of these possibilities:
1701 // x->m x.m x->*y x.*y
1702 // (possibly parenthesized)
1704 expr = expr->IgnoreParens();
1705 if (const MemberExpr *mem = dyn_cast<MemberExpr>(expr)) {
1706 assert(isa<CXXMethodDecl>(mem->getMemberDecl()));
1707 return mem->getMemberDecl()->getType();
1710 if (const BinaryOperator *op = dyn_cast<BinaryOperator>(expr)) {
1711 QualType type = op->getRHS()->getType()->castAs<MemberPointerType>()
1713 assert(type->isFunctionType());
1717 assert(isa<UnresolvedMemberExpr>(expr));
1721 static Expr::CanThrowResult MergeCanThrow(Expr::CanThrowResult CT1,
1722 Expr::CanThrowResult CT2) {
1723 // CanThrowResult constants are ordered so that the maximum is the correct
1725 return CT1 > CT2 ? CT1 : CT2;
1728 static Expr::CanThrowResult CanSubExprsThrow(ASTContext &C, const Expr *CE) {
1729 Expr *E = const_cast<Expr*>(CE);
1730 Expr::CanThrowResult R = Expr::CT_Cannot;
1731 for (Expr::child_range I = E->children(); I && R != Expr::CT_Can; ++I) {
1732 R = MergeCanThrow(R, cast<Expr>(*I)->CanThrow(C));
1737 static Expr::CanThrowResult CanCalleeThrow(ASTContext &Ctx, const Expr *E,
1739 bool NullThrows = true) {
1741 return NullThrows ? Expr::CT_Can : Expr::CT_Cannot;
1743 // See if we can get a function type from the decl somehow.
1744 const ValueDecl *VD = dyn_cast<ValueDecl>(D);
1745 if (!VD) // If we have no clue what we're calling, assume the worst.
1746 return Expr::CT_Can;
1748 // As an extension, we assume that __attribute__((nothrow)) functions don't
1750 if (isa<FunctionDecl>(D) && D->hasAttr<NoThrowAttr>())
1751 return Expr::CT_Cannot;
1753 QualType T = VD->getType();
1754 const FunctionProtoType *FT;
1755 if ((FT = T->getAs<FunctionProtoType>())) {
1756 } else if (const PointerType *PT = T->getAs<PointerType>())
1757 FT = PT->getPointeeType()->getAs<FunctionProtoType>();
1758 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
1759 FT = RT->getPointeeType()->getAs<FunctionProtoType>();
1760 else if (const MemberPointerType *MT = T->getAs<MemberPointerType>())
1761 FT = MT->getPointeeType()->getAs<FunctionProtoType>();
1762 else if (const BlockPointerType *BT = T->getAs<BlockPointerType>())
1763 FT = BT->getPointeeType()->getAs<FunctionProtoType>();
1766 return Expr::CT_Can;
1768 if (FT->getExceptionSpecType() == EST_Delayed) {
1769 assert(isa<CXXConstructorDecl>(D) &&
1770 "only constructor exception specs can be unknown");
1771 Ctx.getDiagnostics().Report(E->getLocStart(),
1772 diag::err_exception_spec_unknown)
1773 << E->getSourceRange();
1774 return Expr::CT_Can;
1777 return FT->isNothrow(Ctx) ? Expr::CT_Cannot : Expr::CT_Can;
1780 static Expr::CanThrowResult CanDynamicCastThrow(const CXXDynamicCastExpr *DC) {
1781 if (DC->isTypeDependent())
1782 return Expr::CT_Dependent;
1784 if (!DC->getTypeAsWritten()->isReferenceType())
1785 return Expr::CT_Cannot;
1787 if (DC->getSubExpr()->isTypeDependent())
1788 return Expr::CT_Dependent;
1790 return DC->getCastKind() == clang::CK_Dynamic? Expr::CT_Can : Expr::CT_Cannot;
1793 static Expr::CanThrowResult CanTypeidThrow(ASTContext &C,
1794 const CXXTypeidExpr *DC) {
1795 if (DC->isTypeOperand())
1796 return Expr::CT_Cannot;
1798 Expr *Op = DC->getExprOperand();
1799 if (Op->isTypeDependent())
1800 return Expr::CT_Dependent;
1802 const RecordType *RT = Op->getType()->getAs<RecordType>();
1804 return Expr::CT_Cannot;
1806 if (!cast<CXXRecordDecl>(RT->getDecl())->isPolymorphic())
1807 return Expr::CT_Cannot;
1809 if (Op->Classify(C).isPRValue())
1810 return Expr::CT_Cannot;
1812 return Expr::CT_Can;
1815 Expr::CanThrowResult Expr::CanThrow(ASTContext &C) const {
1816 // C++ [expr.unary.noexcept]p3:
1817 // [Can throw] if in a potentially-evaluated context the expression would
1819 switch (getStmtClass()) {
1820 case CXXThrowExprClass:
1821 // - a potentially evaluated throw-expression
1824 case CXXDynamicCastExprClass: {
1825 // - a potentially evaluated dynamic_cast expression dynamic_cast<T>(v),
1826 // where T is a reference type, that requires a run-time check
1827 CanThrowResult CT = CanDynamicCastThrow(cast<CXXDynamicCastExpr>(this));
1830 return MergeCanThrow(CT, CanSubExprsThrow(C, this));
1833 case CXXTypeidExprClass:
1834 // - a potentially evaluated typeid expression applied to a glvalue
1835 // expression whose type is a polymorphic class type
1836 return CanTypeidThrow(C, cast<CXXTypeidExpr>(this));
1838 // - a potentially evaluated call to a function, member function, function
1839 // pointer, or member function pointer that does not have a non-throwing
1840 // exception-specification
1842 case CXXOperatorCallExprClass:
1843 case CXXMemberCallExprClass: {
1844 const CallExpr *CE = cast<CallExpr>(this);
1846 if (isTypeDependent())
1848 else if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens()))
1851 CT = CanCalleeThrow(C, this, CE->getCalleeDecl());
1854 return MergeCanThrow(CT, CanSubExprsThrow(C, this));
1857 case CXXConstructExprClass:
1858 case CXXTemporaryObjectExprClass: {
1859 CanThrowResult CT = CanCalleeThrow(C, this,
1860 cast<CXXConstructExpr>(this)->getConstructor());
1863 return MergeCanThrow(CT, CanSubExprsThrow(C, this));
1866 case CXXNewExprClass: {
1868 if (isTypeDependent())
1872 CanCalleeThrow(C, this, cast<CXXNewExpr>(this)->getOperatorNew()),
1873 CanCalleeThrow(C, this, cast<CXXNewExpr>(this)->getConstructor(),
1874 /*NullThrows*/false));
1877 return MergeCanThrow(CT, CanSubExprsThrow(C, this));
1880 case CXXDeleteExprClass: {
1882 QualType DTy = cast<CXXDeleteExpr>(this)->getDestroyedType();
1883 if (DTy.isNull() || DTy->isDependentType()) {
1886 CT = CanCalleeThrow(C, this,
1887 cast<CXXDeleteExpr>(this)->getOperatorDelete());
1888 if (const RecordType *RT = DTy->getAs<RecordType>()) {
1889 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1890 CT = MergeCanThrow(CT, CanCalleeThrow(C, this, RD->getDestructor()));
1895 return MergeCanThrow(CT, CanSubExprsThrow(C, this));
1898 case CXXBindTemporaryExprClass: {
1899 // The bound temporary has to be destroyed again, which might throw.
1900 CanThrowResult CT = CanCalleeThrow(C, this,
1901 cast<CXXBindTemporaryExpr>(this)->getTemporary()->getDestructor());
1904 return MergeCanThrow(CT, CanSubExprsThrow(C, this));
1907 // ObjC message sends are like function calls, but never have exception
1909 case ObjCMessageExprClass:
1910 case ObjCPropertyRefExprClass:
1913 // Many other things have subexpressions, so we have to test those.
1915 case ParenExprClass:
1916 case MemberExprClass:
1917 case CXXReinterpretCastExprClass:
1918 case CXXConstCastExprClass:
1919 case ConditionalOperatorClass:
1920 case CompoundLiteralExprClass:
1921 case ExtVectorElementExprClass:
1922 case InitListExprClass:
1923 case DesignatedInitExprClass:
1924 case ParenListExprClass:
1925 case VAArgExprClass:
1926 case CXXDefaultArgExprClass:
1927 case ExprWithCleanupsClass:
1928 case ObjCIvarRefExprClass:
1929 case ObjCIsaExprClass:
1930 case ShuffleVectorExprClass:
1931 return CanSubExprsThrow(C, this);
1933 // Some might be dependent for other reasons.
1934 case UnaryOperatorClass:
1935 case ArraySubscriptExprClass:
1936 case ImplicitCastExprClass:
1937 case CStyleCastExprClass:
1938 case CXXStaticCastExprClass:
1939 case CXXFunctionalCastExprClass:
1940 case BinaryOperatorClass:
1941 case CompoundAssignOperatorClass:
1942 case MaterializeTemporaryExprClass: {
1943 CanThrowResult CT = isTypeDependent() ? CT_Dependent : CT_Cannot;
1944 return MergeCanThrow(CT, CanSubExprsThrow(C, this));
1947 // FIXME: We should handle StmtExpr, but that opens a MASSIVE can of worms.
1951 case ChooseExprClass:
1952 if (isTypeDependent() || isValueDependent())
1953 return CT_Dependent;
1954 return cast<ChooseExpr>(this)->getChosenSubExpr(C)->CanThrow(C);
1956 case GenericSelectionExprClass:
1957 if (cast<GenericSelectionExpr>(this)->isResultDependent())
1958 return CT_Dependent;
1959 return cast<GenericSelectionExpr>(this)->getResultExpr()->CanThrow(C);
1961 // Some expressions are always dependent.
1962 case DependentScopeDeclRefExprClass:
1963 case CXXUnresolvedConstructExprClass:
1964 case CXXDependentScopeMemberExprClass:
1965 return CT_Dependent;
1968 // All other expressions don't have subexpressions, or else they are
1974 Expr* Expr::IgnoreParens() {
1977 if (ParenExpr* P = dyn_cast<ParenExpr>(E)) {
1978 E = P->getSubExpr();
1981 if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) {
1982 if (P->getOpcode() == UO_Extension) {
1983 E = P->getSubExpr();
1987 if (GenericSelectionExpr* P = dyn_cast<GenericSelectionExpr>(E)) {
1988 if (!P->isResultDependent()) {
1989 E = P->getResultExpr();
1997 /// IgnoreParenCasts - Ignore parentheses and casts. Strip off any ParenExpr
1998 /// or CastExprs or ImplicitCastExprs, returning their operand.
1999 Expr *Expr::IgnoreParenCasts() {
2002 if (ParenExpr* P = dyn_cast<ParenExpr>(E)) {
2003 E = P->getSubExpr();
2006 if (CastExpr *P = dyn_cast<CastExpr>(E)) {
2007 E = P->getSubExpr();
2010 if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) {
2011 if (P->getOpcode() == UO_Extension) {
2012 E = P->getSubExpr();
2016 if (GenericSelectionExpr* P = dyn_cast<GenericSelectionExpr>(E)) {
2017 if (!P->isResultDependent()) {
2018 E = P->getResultExpr();
2022 if (MaterializeTemporaryExpr *Materialize
2023 = dyn_cast<MaterializeTemporaryExpr>(E)) {
2024 E = Materialize->GetTemporaryExpr();
2032 /// IgnoreParenLValueCasts - Ignore parentheses and lvalue-to-rvalue
2033 /// casts. This is intended purely as a temporary workaround for code
2034 /// that hasn't yet been rewritten to do the right thing about those
2035 /// casts, and may disappear along with the last internal use.
2036 Expr *Expr::IgnoreParenLValueCasts() {
2039 if (ParenExpr *P = dyn_cast<ParenExpr>(E)) {
2040 E = P->getSubExpr();
2042 } else if (CastExpr *P = dyn_cast<CastExpr>(E)) {
2043 if (P->getCastKind() == CK_LValueToRValue) {
2044 E = P->getSubExpr();
2047 } else if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) {
2048 if (P->getOpcode() == UO_Extension) {
2049 E = P->getSubExpr();
2052 } else if (GenericSelectionExpr* P = dyn_cast<GenericSelectionExpr>(E)) {
2053 if (!P->isResultDependent()) {
2054 E = P->getResultExpr();
2057 } else if (MaterializeTemporaryExpr *Materialize
2058 = dyn_cast<MaterializeTemporaryExpr>(E)) {
2059 E = Materialize->GetTemporaryExpr();
2067 Expr *Expr::IgnoreParenImpCasts() {
2070 if (ParenExpr *P = dyn_cast<ParenExpr>(E)) {
2071 E = P->getSubExpr();
2074 if (ImplicitCastExpr *P = dyn_cast<ImplicitCastExpr>(E)) {
2075 E = P->getSubExpr();
2078 if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) {
2079 if (P->getOpcode() == UO_Extension) {
2080 E = P->getSubExpr();
2084 if (GenericSelectionExpr* P = dyn_cast<GenericSelectionExpr>(E)) {
2085 if (!P->isResultDependent()) {
2086 E = P->getResultExpr();
2090 if (MaterializeTemporaryExpr *Materialize
2091 = dyn_cast<MaterializeTemporaryExpr>(E)) {
2092 E = Materialize->GetTemporaryExpr();
2099 Expr *Expr::IgnoreConversionOperator() {
2100 if (CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(this)) {
2101 if (MCE->getMethodDecl() && isa<CXXConversionDecl>(MCE->getMethodDecl()))
2102 return MCE->getImplicitObjectArgument();
2107 /// IgnoreParenNoopCasts - Ignore parentheses and casts that do not change the
2108 /// value (including ptr->int casts of the same size). Strip off any
2109 /// ParenExpr or CastExprs, returning their operand.
2110 Expr *Expr::IgnoreParenNoopCasts(ASTContext &Ctx) {
2113 if (ParenExpr *P = dyn_cast<ParenExpr>(E)) {
2114 E = P->getSubExpr();
2118 if (CastExpr *P = dyn_cast<CastExpr>(E)) {
2119 // We ignore integer <-> casts that are of the same width, ptr<->ptr and
2120 // ptr<->int casts of the same width. We also ignore all identity casts.
2121 Expr *SE = P->getSubExpr();
2123 if (Ctx.hasSameUnqualifiedType(E->getType(), SE->getType())) {
2128 if ((E->getType()->isPointerType() ||
2129 E->getType()->isIntegralType(Ctx)) &&
2130 (SE->getType()->isPointerType() ||
2131 SE->getType()->isIntegralType(Ctx)) &&
2132 Ctx.getTypeSize(E->getType()) == Ctx.getTypeSize(SE->getType())) {
2138 if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) {
2139 if (P->getOpcode() == UO_Extension) {
2140 E = P->getSubExpr();
2145 if (GenericSelectionExpr* P = dyn_cast<GenericSelectionExpr>(E)) {
2146 if (!P->isResultDependent()) {
2147 E = P->getResultExpr();
2156 bool Expr::isDefaultArgument() const {
2157 const Expr *E = this;
2158 if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
2159 E = M->GetTemporaryExpr();
2161 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
2162 E = ICE->getSubExprAsWritten();
2164 return isa<CXXDefaultArgExpr>(E);
2167 /// \brief Skip over any no-op casts and any temporary-binding
2169 static const Expr *skipTemporaryBindingsNoOpCastsAndParens(const Expr *E) {
2170 if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
2171 E = M->GetTemporaryExpr();
2173 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2174 if (ICE->getCastKind() == CK_NoOp)
2175 E = ICE->getSubExpr();
2180 while (const CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
2181 E = BE->getSubExpr();
2183 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2184 if (ICE->getCastKind() == CK_NoOp)
2185 E = ICE->getSubExpr();
2190 return E->IgnoreParens();
2193 /// isTemporaryObject - Determines if this expression produces a
2194 /// temporary of the given class type.
2195 bool Expr::isTemporaryObject(ASTContext &C, const CXXRecordDecl *TempTy) const {
2196 if (!C.hasSameUnqualifiedType(getType(), C.getTypeDeclType(TempTy)))
2199 const Expr *E = skipTemporaryBindingsNoOpCastsAndParens(this);
2201 // Temporaries are by definition pr-values of class type.
2202 if (!E->Classify(C).isPRValue()) {
2203 // In this context, property reference is a message call and is pr-value.
2204 if (!isa<ObjCPropertyRefExpr>(E))
2208 // Black-list a few cases which yield pr-values of class type that don't
2209 // refer to temporaries of that type:
2211 // - implicit derived-to-base conversions
2212 if (isa<ImplicitCastExpr>(E)) {
2213 switch (cast<ImplicitCastExpr>(E)->getCastKind()) {
2214 case CK_DerivedToBase:
2215 case CK_UncheckedDerivedToBase:
2222 // - member expressions (all)
2223 if (isa<MemberExpr>(E))
2226 // - opaque values (all)
2227 if (isa<OpaqueValueExpr>(E))
2233 bool Expr::isImplicitCXXThis() const {
2234 const Expr *E = this;
2236 // Strip away parentheses and casts we don't care about.
2238 if (const ParenExpr *Paren = dyn_cast<ParenExpr>(E)) {
2239 E = Paren->getSubExpr();
2243 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2244 if (ICE->getCastKind() == CK_NoOp ||
2245 ICE->getCastKind() == CK_LValueToRValue ||
2246 ICE->getCastKind() == CK_DerivedToBase ||
2247 ICE->getCastKind() == CK_UncheckedDerivedToBase) {
2248 E = ICE->getSubExpr();
2253 if (const UnaryOperator* UnOp = dyn_cast<UnaryOperator>(E)) {
2254 if (UnOp->getOpcode() == UO_Extension) {
2255 E = UnOp->getSubExpr();
2260 if (const MaterializeTemporaryExpr *M
2261 = dyn_cast<MaterializeTemporaryExpr>(E)) {
2262 E = M->GetTemporaryExpr();
2269 if (const CXXThisExpr *This = dyn_cast<CXXThisExpr>(E))
2270 return This->isImplicit();
2275 /// hasAnyTypeDependentArguments - Determines if any of the expressions
2276 /// in Exprs is type-dependent.
2277 bool Expr::hasAnyTypeDependentArguments(Expr** Exprs, unsigned NumExprs) {
2278 for (unsigned I = 0; I < NumExprs; ++I)
2279 if (Exprs[I]->isTypeDependent())
2285 /// hasAnyValueDependentArguments - Determines if any of the expressions
2286 /// in Exprs is value-dependent.
2287 bool Expr::hasAnyValueDependentArguments(Expr** Exprs, unsigned NumExprs) {
2288 for (unsigned I = 0; I < NumExprs; ++I)
2289 if (Exprs[I]->isValueDependent())
2295 bool Expr::isConstantInitializer(ASTContext &Ctx, bool IsForRef) const {
2296 // This function is attempting whether an expression is an initializer
2297 // which can be evaluated at compile-time. isEvaluatable handles most
2298 // of the cases, but it can't deal with some initializer-specific
2299 // expressions, and it can't deal with aggregates; we deal with those here,
2300 // and fall back to isEvaluatable for the other cases.
2302 // If we ever capture reference-binding directly in the AST, we can
2303 // kill the second parameter.
2307 return EvaluateAsLValue(Result, Ctx) && !Result.HasSideEffects;
2310 switch (getStmtClass()) {
2312 case StringLiteralClass:
2313 case ObjCStringLiteralClass:
2314 case ObjCEncodeExprClass:
2316 case CXXTemporaryObjectExprClass:
2317 case CXXConstructExprClass: {
2318 const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
2321 // 1) an application of the trivial default constructor or
2322 if (!CE->getConstructor()->isTrivial()) return false;
2323 if (!CE->getNumArgs()) return true;
2325 // 2) an elidable trivial copy construction of an operand which is
2326 // itself a constant initializer. Note that we consider the
2327 // operand on its own, *not* as a reference binding.
2328 return CE->isElidable() &&
2329 CE->getArg(0)->isConstantInitializer(Ctx, false);
2331 case CompoundLiteralExprClass: {
2332 // This handles gcc's extension that allows global initializers like
2333 // "struct x {int x;} x = (struct x) {};".
2334 // FIXME: This accepts other cases it shouldn't!
2335 const Expr *Exp = cast<CompoundLiteralExpr>(this)->getInitializer();
2336 return Exp->isConstantInitializer(Ctx, false);
2338 case InitListExprClass: {
2339 // FIXME: This doesn't deal with fields with reference types correctly.
2340 // FIXME: This incorrectly allows pointers cast to integers to be assigned
2342 const InitListExpr *Exp = cast<InitListExpr>(this);
2343 unsigned numInits = Exp->getNumInits();
2344 for (unsigned i = 0; i < numInits; i++) {
2345 if (!Exp->getInit(i)->isConstantInitializer(Ctx, false))
2350 case ImplicitValueInitExprClass:
2352 case ParenExprClass:
2353 return cast<ParenExpr>(this)->getSubExpr()
2354 ->isConstantInitializer(Ctx, IsForRef);
2355 case GenericSelectionExprClass:
2356 if (cast<GenericSelectionExpr>(this)->isResultDependent())
2358 return cast<GenericSelectionExpr>(this)->getResultExpr()
2359 ->isConstantInitializer(Ctx, IsForRef);
2360 case ChooseExprClass:
2361 return cast<ChooseExpr>(this)->getChosenSubExpr(Ctx)
2362 ->isConstantInitializer(Ctx, IsForRef);
2363 case UnaryOperatorClass: {
2364 const UnaryOperator* Exp = cast<UnaryOperator>(this);
2365 if (Exp->getOpcode() == UO_Extension)
2366 return Exp->getSubExpr()->isConstantInitializer(Ctx, false);
2369 case BinaryOperatorClass: {
2370 // Special case &&foo - &&bar. It would be nice to generalize this somehow
2371 // but this handles the common case.
2372 const BinaryOperator *Exp = cast<BinaryOperator>(this);
2373 if (Exp->getOpcode() == BO_Sub &&
2374 isa<AddrLabelExpr>(Exp->getLHS()->IgnoreParenNoopCasts(Ctx)) &&
2375 isa<AddrLabelExpr>(Exp->getRHS()->IgnoreParenNoopCasts(Ctx)))
2379 case CXXFunctionalCastExprClass:
2380 case CXXStaticCastExprClass:
2381 case ImplicitCastExprClass:
2382 case CStyleCastExprClass:
2383 // Handle casts with a destination that's a struct or union; this
2384 // deals with both the gcc no-op struct cast extension and the
2385 // cast-to-union extension.
2386 if (getType()->isRecordType())
2387 return cast<CastExpr>(this)->getSubExpr()
2388 ->isConstantInitializer(Ctx, false);
2390 // Integer->integer casts can be handled here, which is important for
2391 // things like (int)(&&x-&&y). Scary but true.
2392 if (getType()->isIntegerType() &&
2393 cast<CastExpr>(this)->getSubExpr()->getType()->isIntegerType())
2394 return cast<CastExpr>(this)->getSubExpr()
2395 ->isConstantInitializer(Ctx, false);
2399 case MaterializeTemporaryExprClass:
2400 return llvm::cast<MaterializeTemporaryExpr>(this)->GetTemporaryExpr()
2401 ->isConstantInitializer(Ctx, false);
2403 return isEvaluatable(Ctx);
2406 /// isNullPointerConstant - C99 6.3.2.3p3 - Return whether this is a null
2407 /// pointer constant or not, as well as the specific kind of constant detected.
2408 /// Null pointer constants can be integer constant expressions with the
2409 /// value zero, casts of zero to void*, nullptr (C++0X), or __null
2410 /// (a GNU extension).
2411 Expr::NullPointerConstantKind
2412 Expr::isNullPointerConstant(ASTContext &Ctx,
2413 NullPointerConstantValueDependence NPC) const {
2414 if (isValueDependent()) {
2416 case NPC_NeverValueDependent:
2417 assert(false && "Unexpected value dependent expression!");
2418 // If the unthinkable happens, fall through to the safest alternative.
2420 case NPC_ValueDependentIsNull:
2421 if (isTypeDependent() || getType()->isIntegralType(Ctx))
2422 return NPCK_ZeroInteger;
2424 return NPCK_NotNull;
2426 case NPC_ValueDependentIsNotNull:
2427 return NPCK_NotNull;
2431 // Strip off a cast to void*, if it exists. Except in C++.
2432 if (const ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(this)) {
2433 if (!Ctx.getLangOptions().CPlusPlus) {
2434 // Check that it is a cast to void*.
2435 if (const PointerType *PT = CE->getType()->getAs<PointerType>()) {
2436 QualType Pointee = PT->getPointeeType();
2437 if (!Pointee.hasQualifiers() &&
2438 Pointee->isVoidType() && // to void*
2439 CE->getSubExpr()->getType()->isIntegerType()) // from int.
2440 return CE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
2443 } else if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(this)) {
2444 // Ignore the ImplicitCastExpr type entirely.
2445 return ICE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
2446 } else if (const ParenExpr *PE = dyn_cast<ParenExpr>(this)) {
2447 // Accept ((void*)0) as a null pointer constant, as many other
2448 // implementations do.
2449 return PE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
2450 } else if (const GenericSelectionExpr *GE =
2451 dyn_cast<GenericSelectionExpr>(this)) {
2452 return GE->getResultExpr()->isNullPointerConstant(Ctx, NPC);
2453 } else if (const CXXDefaultArgExpr *DefaultArg
2454 = dyn_cast<CXXDefaultArgExpr>(this)) {
2455 // See through default argument expressions
2456 return DefaultArg->getExpr()->isNullPointerConstant(Ctx, NPC);
2457 } else if (isa<GNUNullExpr>(this)) {
2458 // The GNU __null extension is always a null pointer constant.
2459 return NPCK_GNUNull;
2460 } else if (const MaterializeTemporaryExpr *M
2461 = dyn_cast<MaterializeTemporaryExpr>(this)) {
2462 return M->GetTemporaryExpr()->isNullPointerConstant(Ctx, NPC);
2465 // C++0x nullptr_t is always a null pointer constant.
2466 if (getType()->isNullPtrType())
2467 return NPCK_CXX0X_nullptr;
2469 if (const RecordType *UT = getType()->getAsUnionType())
2470 if (UT && UT->getDecl()->hasAttr<TransparentUnionAttr>())
2471 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(this)){
2472 const Expr *InitExpr = CLE->getInitializer();
2473 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(InitExpr))
2474 return ILE->getInit(0)->isNullPointerConstant(Ctx, NPC);
2476 // This expression must be an integer type.
2477 if (!getType()->isIntegerType() ||
2478 (Ctx.getLangOptions().CPlusPlus && getType()->isEnumeralType()))
2479 return NPCK_NotNull;
2481 // If we have an integer constant expression, we need to *evaluate* it and
2482 // test for the value 0.
2483 llvm::APSInt Result;
2484 bool IsNull = isIntegerConstantExpr(Result, Ctx) && Result == 0;
2486 return (IsNull ? NPCK_ZeroInteger : NPCK_NotNull);
2489 /// \brief If this expression is an l-value for an Objective C
2490 /// property, find the underlying property reference expression.
2491 const ObjCPropertyRefExpr *Expr::getObjCProperty() const {
2492 const Expr *E = this;
2494 assert((E->getValueKind() == VK_LValue &&
2495 E->getObjectKind() == OK_ObjCProperty) &&
2496 "expression is not a property reference");
2497 E = E->IgnoreParenCasts();
2498 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2499 if (BO->getOpcode() == BO_Comma) {
2508 return cast<ObjCPropertyRefExpr>(E);
2511 FieldDecl *Expr::getBitField() {
2512 Expr *E = this->IgnoreParens();
2514 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2515 if (ICE->getCastKind() == CK_LValueToRValue ||
2516 (ICE->getValueKind() != VK_RValue && ICE->getCastKind() == CK_NoOp))
2517 E = ICE->getSubExpr()->IgnoreParens();
2522 if (MemberExpr *MemRef = dyn_cast<MemberExpr>(E))
2523 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemRef->getMemberDecl()))
2524 if (Field->isBitField())
2527 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E))
2528 if (FieldDecl *Field = dyn_cast<FieldDecl>(DeclRef->getDecl()))
2529 if (Field->isBitField())
2532 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(E)) {
2533 if (BinOp->isAssignmentOp() && BinOp->getLHS())
2534 return BinOp->getLHS()->getBitField();
2536 if (BinOp->getOpcode() == BO_Comma && BinOp->getRHS())
2537 return BinOp->getRHS()->getBitField();
2543 bool Expr::refersToVectorElement() const {
2544 const Expr *E = this->IgnoreParens();
2546 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2547 if (ICE->getValueKind() != VK_RValue &&
2548 ICE->getCastKind() == CK_NoOp)
2549 E = ICE->getSubExpr()->IgnoreParens();
2554 if (const ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(E))
2555 return ASE->getBase()->getType()->isVectorType();
2557 if (isa<ExtVectorElementExpr>(E))
2563 /// isArrow - Return true if the base expression is a pointer to vector,
2564 /// return false if the base expression is a vector.
2565 bool ExtVectorElementExpr::isArrow() const {
2566 return getBase()->getType()->isPointerType();
2569 unsigned ExtVectorElementExpr::getNumElements() const {
2570 if (const VectorType *VT = getType()->getAs<VectorType>())
2571 return VT->getNumElements();
2575 /// containsDuplicateElements - Return true if any element access is repeated.
2576 bool ExtVectorElementExpr::containsDuplicateElements() const {
2577 // FIXME: Refactor this code to an accessor on the AST node which returns the
2578 // "type" of component access, and share with code below and in Sema.
2579 llvm::StringRef Comp = Accessor->getName();
2581 // Halving swizzles do not contain duplicate elements.
2582 if (Comp == "hi" || Comp == "lo" || Comp == "even" || Comp == "odd")
2585 // Advance past s-char prefix on hex swizzles.
2586 if (Comp[0] == 's' || Comp[0] == 'S')
2587 Comp = Comp.substr(1);
2589 for (unsigned i = 0, e = Comp.size(); i != e; ++i)
2590 if (Comp.substr(i + 1).find(Comp[i]) != llvm::StringRef::npos)
2596 /// getEncodedElementAccess - We encode the fields as a llvm ConstantArray.
2597 void ExtVectorElementExpr::getEncodedElementAccess(
2598 llvm::SmallVectorImpl<unsigned> &Elts) const {
2599 llvm::StringRef Comp = Accessor->getName();
2600 if (Comp[0] == 's' || Comp[0] == 'S')
2601 Comp = Comp.substr(1);
2603 bool isHi = Comp == "hi";
2604 bool isLo = Comp == "lo";
2605 bool isEven = Comp == "even";
2606 bool isOdd = Comp == "odd";
2608 for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
2620 Index = ExtVectorType::getAccessorIdx(Comp[i]);
2622 Elts.push_back(Index);
2626 ObjCMessageExpr::ObjCMessageExpr(QualType T,
2628 SourceLocation LBracLoc,
2629 SourceLocation SuperLoc,
2630 bool IsInstanceSuper,
2633 SourceLocation SelLoc,
2634 ObjCMethodDecl *Method,
2635 Expr **Args, unsigned NumArgs,
2636 SourceLocation RBracLoc)
2637 : Expr(ObjCMessageExprClass, T, VK, OK_Ordinary,
2638 /*TypeDependent=*/false, /*ValueDependent=*/false,
2639 /*InstantiationDependent=*/false,
2640 /*ContainsUnexpandedParameterPack=*/false),
2641 NumArgs(NumArgs), Kind(IsInstanceSuper? SuperInstance : SuperClass),
2642 HasMethod(Method != 0), IsDelegateInitCall(false), SuperLoc(SuperLoc),
2643 SelectorOrMethod(reinterpret_cast<uintptr_t>(Method? Method
2644 : Sel.getAsOpaquePtr())),
2645 SelectorLoc(SelLoc), LBracLoc(LBracLoc), RBracLoc(RBracLoc)
2647 setReceiverPointer(SuperType.getAsOpaquePtr());
2649 memcpy(getArgs(), Args, NumArgs * sizeof(Expr *));
2652 ObjCMessageExpr::ObjCMessageExpr(QualType T,
2654 SourceLocation LBracLoc,
2655 TypeSourceInfo *Receiver,
2657 SourceLocation SelLoc,
2658 ObjCMethodDecl *Method,
2659 Expr **Args, unsigned NumArgs,
2660 SourceLocation RBracLoc)
2661 : Expr(ObjCMessageExprClass, T, VK, OK_Ordinary, T->isDependentType(),
2662 T->isDependentType(), T->isInstantiationDependentType(),
2663 T->containsUnexpandedParameterPack()),
2664 NumArgs(NumArgs), Kind(Class),
2665 HasMethod(Method != 0), IsDelegateInitCall(false),
2666 SelectorOrMethod(reinterpret_cast<uintptr_t>(Method? Method
2667 : Sel.getAsOpaquePtr())),
2668 SelectorLoc(SelLoc), LBracLoc(LBracLoc), RBracLoc(RBracLoc)
2670 setReceiverPointer(Receiver);
2671 Expr **MyArgs = getArgs();
2672 for (unsigned I = 0; I != NumArgs; ++I) {
2673 if (Args[I]->isTypeDependent())
2674 ExprBits.TypeDependent = true;
2675 if (Args[I]->isValueDependent())
2676 ExprBits.ValueDependent = true;
2677 if (Args[I]->isInstantiationDependent())
2678 ExprBits.InstantiationDependent = true;
2679 if (Args[I]->containsUnexpandedParameterPack())
2680 ExprBits.ContainsUnexpandedParameterPack = true;
2682 MyArgs[I] = Args[I];
2686 ObjCMessageExpr::ObjCMessageExpr(QualType T,
2688 SourceLocation LBracLoc,
2691 SourceLocation SelLoc,
2692 ObjCMethodDecl *Method,
2693 Expr **Args, unsigned NumArgs,
2694 SourceLocation RBracLoc)
2695 : Expr(ObjCMessageExprClass, T, VK, OK_Ordinary, Receiver->isTypeDependent(),
2696 Receiver->isTypeDependent(),
2697 Receiver->isInstantiationDependent(),
2698 Receiver->containsUnexpandedParameterPack()),
2699 NumArgs(NumArgs), Kind(Instance),
2700 HasMethod(Method != 0), IsDelegateInitCall(false),
2701 SelectorOrMethod(reinterpret_cast<uintptr_t>(Method? Method
2702 : Sel.getAsOpaquePtr())),
2703 SelectorLoc(SelLoc), LBracLoc(LBracLoc), RBracLoc(RBracLoc)
2705 setReceiverPointer(Receiver);
2706 Expr **MyArgs = getArgs();
2707 for (unsigned I = 0; I != NumArgs; ++I) {
2708 if (Args[I]->isTypeDependent())
2709 ExprBits.TypeDependent = true;
2710 if (Args[I]->isValueDependent())
2711 ExprBits.ValueDependent = true;
2712 if (Args[I]->isInstantiationDependent())
2713 ExprBits.InstantiationDependent = true;
2714 if (Args[I]->containsUnexpandedParameterPack())
2715 ExprBits.ContainsUnexpandedParameterPack = true;
2717 MyArgs[I] = Args[I];
2721 ObjCMessageExpr *ObjCMessageExpr::Create(ASTContext &Context, QualType T,
2723 SourceLocation LBracLoc,
2724 SourceLocation SuperLoc,
2725 bool IsInstanceSuper,
2728 SourceLocation SelLoc,
2729 ObjCMethodDecl *Method,
2730 Expr **Args, unsigned NumArgs,
2731 SourceLocation RBracLoc) {
2732 unsigned Size = sizeof(ObjCMessageExpr) + sizeof(void *) +
2733 NumArgs * sizeof(Expr *);
2734 void *Mem = Context.Allocate(Size, llvm::AlignOf<ObjCMessageExpr>::Alignment);
2735 return new (Mem) ObjCMessageExpr(T, VK, LBracLoc, SuperLoc, IsInstanceSuper,
2736 SuperType, Sel, SelLoc, Method, Args,NumArgs,
2740 ObjCMessageExpr *ObjCMessageExpr::Create(ASTContext &Context, QualType T,
2742 SourceLocation LBracLoc,
2743 TypeSourceInfo *Receiver,
2745 SourceLocation SelLoc,
2746 ObjCMethodDecl *Method,
2747 Expr **Args, unsigned NumArgs,
2748 SourceLocation RBracLoc) {
2749 unsigned Size = sizeof(ObjCMessageExpr) + sizeof(void *) +
2750 NumArgs * sizeof(Expr *);
2751 void *Mem = Context.Allocate(Size, llvm::AlignOf<ObjCMessageExpr>::Alignment);
2752 return new (Mem) ObjCMessageExpr(T, VK, LBracLoc, Receiver, Sel, SelLoc,
2753 Method, Args, NumArgs, RBracLoc);
2756 ObjCMessageExpr *ObjCMessageExpr::Create(ASTContext &Context, QualType T,
2758 SourceLocation LBracLoc,
2761 SourceLocation SelLoc,
2762 ObjCMethodDecl *Method,
2763 Expr **Args, unsigned NumArgs,
2764 SourceLocation RBracLoc) {
2765 unsigned Size = sizeof(ObjCMessageExpr) + sizeof(void *) +
2766 NumArgs * sizeof(Expr *);
2767 void *Mem = Context.Allocate(Size, llvm::AlignOf<ObjCMessageExpr>::Alignment);
2768 return new (Mem) ObjCMessageExpr(T, VK, LBracLoc, Receiver, Sel, SelLoc,
2769 Method, Args, NumArgs, RBracLoc);
2772 ObjCMessageExpr *ObjCMessageExpr::CreateEmpty(ASTContext &Context,
2774 unsigned Size = sizeof(ObjCMessageExpr) + sizeof(void *) +
2775 NumArgs * sizeof(Expr *);
2776 void *Mem = Context.Allocate(Size, llvm::AlignOf<ObjCMessageExpr>::Alignment);
2777 return new (Mem) ObjCMessageExpr(EmptyShell(), NumArgs);
2780 SourceRange ObjCMessageExpr::getReceiverRange() const {
2781 switch (getReceiverKind()) {
2783 return getInstanceReceiver()->getSourceRange();
2786 return getClassReceiverTypeInfo()->getTypeLoc().getSourceRange();
2790 return getSuperLoc();
2793 return SourceLocation();
2796 Selector ObjCMessageExpr::getSelector() const {
2798 return reinterpret_cast<const ObjCMethodDecl *>(SelectorOrMethod)
2800 return Selector(SelectorOrMethod);
2803 ObjCInterfaceDecl *ObjCMessageExpr::getReceiverInterface() const {
2804 switch (getReceiverKind()) {
2806 if (const ObjCObjectPointerType *Ptr
2807 = getInstanceReceiver()->getType()->getAs<ObjCObjectPointerType>())
2808 return Ptr->getInterfaceDecl();
2812 if (const ObjCObjectType *Ty
2813 = getClassReceiver()->getAs<ObjCObjectType>())
2814 return Ty->getInterface();
2818 if (const ObjCObjectPointerType *Ptr
2819 = getSuperType()->getAs<ObjCObjectPointerType>())
2820 return Ptr->getInterfaceDecl();
2824 if (const ObjCObjectType *Iface
2825 = getSuperType()->getAs<ObjCObjectType>())
2826 return Iface->getInterface();
2833 llvm::StringRef ObjCBridgedCastExpr::getBridgeKindName() const {
2834 switch (getBridgeKind()) {
2837 case OBC_BridgeTransfer:
2838 return "__bridge_transfer";
2839 case OBC_BridgeRetained:
2840 return "__bridge_retained";
2846 bool ChooseExpr::isConditionTrue(const ASTContext &C) const {
2847 return getCond()->EvaluateAsInt(C) != 0;
2850 ShuffleVectorExpr::ShuffleVectorExpr(ASTContext &C, Expr **args, unsigned nexpr,
2851 QualType Type, SourceLocation BLoc,
2853 : Expr(ShuffleVectorExprClass, Type, VK_RValue, OK_Ordinary,
2854 Type->isDependentType(), Type->isDependentType(),
2855 Type->isInstantiationDependentType(),
2856 Type->containsUnexpandedParameterPack()),
2857 BuiltinLoc(BLoc), RParenLoc(RP), NumExprs(nexpr)
2859 SubExprs = new (C) Stmt*[nexpr];
2860 for (unsigned i = 0; i < nexpr; i++) {
2861 if (args[i]->isTypeDependent())
2862 ExprBits.TypeDependent = true;
2863 if (args[i]->isValueDependent())
2864 ExprBits.ValueDependent = true;
2865 if (args[i]->isInstantiationDependent())
2866 ExprBits.InstantiationDependent = true;
2867 if (args[i]->containsUnexpandedParameterPack())
2868 ExprBits.ContainsUnexpandedParameterPack = true;
2870 SubExprs[i] = args[i];
2874 void ShuffleVectorExpr::setExprs(ASTContext &C, Expr ** Exprs,
2875 unsigned NumExprs) {
2876 if (SubExprs) C.Deallocate(SubExprs);
2878 SubExprs = new (C) Stmt* [NumExprs];
2879 this->NumExprs = NumExprs;
2880 memcpy(SubExprs, Exprs, sizeof(Expr *) * NumExprs);
2883 GenericSelectionExpr::GenericSelectionExpr(ASTContext &Context,
2884 SourceLocation GenericLoc, Expr *ControllingExpr,
2885 TypeSourceInfo **AssocTypes, Expr **AssocExprs,
2886 unsigned NumAssocs, SourceLocation DefaultLoc,
2887 SourceLocation RParenLoc,
2888 bool ContainsUnexpandedParameterPack,
2889 unsigned ResultIndex)
2890 : Expr(GenericSelectionExprClass,
2891 AssocExprs[ResultIndex]->getType(),
2892 AssocExprs[ResultIndex]->getValueKind(),
2893 AssocExprs[ResultIndex]->getObjectKind(),
2894 AssocExprs[ResultIndex]->isTypeDependent(),
2895 AssocExprs[ResultIndex]->isValueDependent(),
2896 AssocExprs[ResultIndex]->isInstantiationDependent(),
2897 ContainsUnexpandedParameterPack),
2898 AssocTypes(new (Context) TypeSourceInfo*[NumAssocs]),
2899 SubExprs(new (Context) Stmt*[END_EXPR+NumAssocs]), NumAssocs(NumAssocs),
2900 ResultIndex(ResultIndex), GenericLoc(GenericLoc), DefaultLoc(DefaultLoc),
2901 RParenLoc(RParenLoc) {
2902 SubExprs[CONTROLLING] = ControllingExpr;
2903 std::copy(AssocTypes, AssocTypes+NumAssocs, this->AssocTypes);
2904 std::copy(AssocExprs, AssocExprs+NumAssocs, SubExprs+END_EXPR);
2907 GenericSelectionExpr::GenericSelectionExpr(ASTContext &Context,
2908 SourceLocation GenericLoc, Expr *ControllingExpr,
2909 TypeSourceInfo **AssocTypes, Expr **AssocExprs,
2910 unsigned NumAssocs, SourceLocation DefaultLoc,
2911 SourceLocation RParenLoc,
2912 bool ContainsUnexpandedParameterPack)
2913 : Expr(GenericSelectionExprClass,
2914 Context.DependentTy,
2917 /*isTypeDependent=*/true,
2918 /*isValueDependent=*/true,
2919 /*isInstantiationDependent=*/true,
2920 ContainsUnexpandedParameterPack),
2921 AssocTypes(new (Context) TypeSourceInfo*[NumAssocs]),
2922 SubExprs(new (Context) Stmt*[END_EXPR+NumAssocs]), NumAssocs(NumAssocs),
2923 ResultIndex(-1U), GenericLoc(GenericLoc), DefaultLoc(DefaultLoc),
2924 RParenLoc(RParenLoc) {
2925 SubExprs[CONTROLLING] = ControllingExpr;
2926 std::copy(AssocTypes, AssocTypes+NumAssocs, this->AssocTypes);
2927 std::copy(AssocExprs, AssocExprs+NumAssocs, SubExprs+END_EXPR);
2930 //===----------------------------------------------------------------------===//
2931 // DesignatedInitExpr
2932 //===----------------------------------------------------------------------===//
2934 IdentifierInfo *DesignatedInitExpr::Designator::getFieldName() const {
2935 assert(Kind == FieldDesignator && "Only valid on a field designator");
2936 if (Field.NameOrField & 0x01)
2937 return reinterpret_cast<IdentifierInfo *>(Field.NameOrField&~0x01);
2939 return getField()->getIdentifier();
2942 DesignatedInitExpr::DesignatedInitExpr(ASTContext &C, QualType Ty,
2943 unsigned NumDesignators,
2944 const Designator *Designators,
2945 SourceLocation EqualOrColonLoc,
2948 unsigned NumIndexExprs,
2950 : Expr(DesignatedInitExprClass, Ty,
2951 Init->getValueKind(), Init->getObjectKind(),
2952 Init->isTypeDependent(), Init->isValueDependent(),
2953 Init->isInstantiationDependent(),
2954 Init->containsUnexpandedParameterPack()),
2955 EqualOrColonLoc(EqualOrColonLoc), GNUSyntax(GNUSyntax),
2956 NumDesignators(NumDesignators), NumSubExprs(NumIndexExprs + 1) {
2957 this->Designators = new (C) Designator[NumDesignators];
2959 // Record the initializer itself.
2960 child_range Child = children();
2963 // Copy the designators and their subexpressions, computing
2964 // value-dependence along the way.
2965 unsigned IndexIdx = 0;
2966 for (unsigned I = 0; I != NumDesignators; ++I) {
2967 this->Designators[I] = Designators[I];
2969 if (this->Designators[I].isArrayDesignator()) {
2970 // Compute type- and value-dependence.
2971 Expr *Index = IndexExprs[IndexIdx];
2972 if (Index->isTypeDependent() || Index->isValueDependent())
2973 ExprBits.ValueDependent = true;
2974 if (Index->isInstantiationDependent())
2975 ExprBits.InstantiationDependent = true;
2976 // Propagate unexpanded parameter packs.
2977 if (Index->containsUnexpandedParameterPack())
2978 ExprBits.ContainsUnexpandedParameterPack = true;
2980 // Copy the index expressions into permanent storage.
2981 *Child++ = IndexExprs[IndexIdx++];
2982 } else if (this->Designators[I].isArrayRangeDesignator()) {
2983 // Compute type- and value-dependence.
2984 Expr *Start = IndexExprs[IndexIdx];
2985 Expr *End = IndexExprs[IndexIdx + 1];
2986 if (Start->isTypeDependent() || Start->isValueDependent() ||
2987 End->isTypeDependent() || End->isValueDependent()) {
2988 ExprBits.ValueDependent = true;
2989 ExprBits.InstantiationDependent = true;
2990 } else if (Start->isInstantiationDependent() ||
2991 End->isInstantiationDependent()) {
2992 ExprBits.InstantiationDependent = true;
2995 // Propagate unexpanded parameter packs.
2996 if (Start->containsUnexpandedParameterPack() ||
2997 End->containsUnexpandedParameterPack())
2998 ExprBits.ContainsUnexpandedParameterPack = true;
3000 // Copy the start/end expressions into permanent storage.
3001 *Child++ = IndexExprs[IndexIdx++];
3002 *Child++ = IndexExprs[IndexIdx++];
3006 assert(IndexIdx == NumIndexExprs && "Wrong number of index expressions");
3009 DesignatedInitExpr *
3010 DesignatedInitExpr::Create(ASTContext &C, Designator *Designators,
3011 unsigned NumDesignators,
3012 Expr **IndexExprs, unsigned NumIndexExprs,
3013 SourceLocation ColonOrEqualLoc,
3014 bool UsesColonSyntax, Expr *Init) {
3015 void *Mem = C.Allocate(sizeof(DesignatedInitExpr) +
3016 sizeof(Stmt *) * (NumIndexExprs + 1), 8);
3017 return new (Mem) DesignatedInitExpr(C, C.VoidTy, NumDesignators, Designators,
3018 ColonOrEqualLoc, UsesColonSyntax,
3019 IndexExprs, NumIndexExprs, Init);
3022 DesignatedInitExpr *DesignatedInitExpr::CreateEmpty(ASTContext &C,
3023 unsigned NumIndexExprs) {
3024 void *Mem = C.Allocate(sizeof(DesignatedInitExpr) +
3025 sizeof(Stmt *) * (NumIndexExprs + 1), 8);
3026 return new (Mem) DesignatedInitExpr(NumIndexExprs + 1);
3029 void DesignatedInitExpr::setDesignators(ASTContext &C,
3030 const Designator *Desigs,
3031 unsigned NumDesigs) {
3032 Designators = new (C) Designator[NumDesigs];
3033 NumDesignators = NumDesigs;
3034 for (unsigned I = 0; I != NumDesigs; ++I)
3035 Designators[I] = Desigs[I];
3038 SourceRange DesignatedInitExpr::getDesignatorsSourceRange() const {
3039 DesignatedInitExpr *DIE = const_cast<DesignatedInitExpr*>(this);
3041 return DIE->getDesignator(0)->getSourceRange();
3042 return SourceRange(DIE->getDesignator(0)->getStartLocation(),
3043 DIE->getDesignator(size()-1)->getEndLocation());
3046 SourceRange DesignatedInitExpr::getSourceRange() const {
3047 SourceLocation StartLoc;
3049 *const_cast<DesignatedInitExpr*>(this)->designators_begin();
3050 if (First.isFieldDesignator()) {
3052 StartLoc = SourceLocation::getFromRawEncoding(First.Field.FieldLoc);
3054 StartLoc = SourceLocation::getFromRawEncoding(First.Field.DotLoc);
3057 SourceLocation::getFromRawEncoding(First.ArrayOrRange.LBracketLoc);
3058 return SourceRange(StartLoc, getInit()->getSourceRange().getEnd());
3061 Expr *DesignatedInitExpr::getArrayIndex(const Designator& D) {
3062 assert(D.Kind == Designator::ArrayDesignator && "Requires array designator");
3063 char* Ptr = static_cast<char*>(static_cast<void *>(this));
3064 Ptr += sizeof(DesignatedInitExpr);
3065 Stmt **SubExprs = reinterpret_cast<Stmt**>(reinterpret_cast<void**>(Ptr));
3066 return cast<Expr>(*(SubExprs + D.ArrayOrRange.Index + 1));
3069 Expr *DesignatedInitExpr::getArrayRangeStart(const Designator& D) {
3070 assert(D.Kind == Designator::ArrayRangeDesignator &&
3071 "Requires array range designator");
3072 char* Ptr = static_cast<char*>(static_cast<void *>(this));
3073 Ptr += sizeof(DesignatedInitExpr);
3074 Stmt **SubExprs = reinterpret_cast<Stmt**>(reinterpret_cast<void**>(Ptr));
3075 return cast<Expr>(*(SubExprs + D.ArrayOrRange.Index + 1));
3078 Expr *DesignatedInitExpr::getArrayRangeEnd(const Designator& D) {
3079 assert(D.Kind == Designator::ArrayRangeDesignator &&
3080 "Requires array range designator");
3081 char* Ptr = static_cast<char*>(static_cast<void *>(this));
3082 Ptr += sizeof(DesignatedInitExpr);
3083 Stmt **SubExprs = reinterpret_cast<Stmt**>(reinterpret_cast<void**>(Ptr));
3084 return cast<Expr>(*(SubExprs + D.ArrayOrRange.Index + 2));
3087 /// \brief Replaces the designator at index @p Idx with the series
3088 /// of designators in [First, Last).
3089 void DesignatedInitExpr::ExpandDesignator(ASTContext &C, unsigned Idx,
3090 const Designator *First,
3091 const Designator *Last) {
3092 unsigned NumNewDesignators = Last - First;
3093 if (NumNewDesignators == 0) {
3094 std::copy_backward(Designators + Idx + 1,
3095 Designators + NumDesignators,
3097 --NumNewDesignators;
3099 } else if (NumNewDesignators == 1) {
3100 Designators[Idx] = *First;
3104 Designator *NewDesignators
3105 = new (C) Designator[NumDesignators - 1 + NumNewDesignators];
3106 std::copy(Designators, Designators + Idx, NewDesignators);
3107 std::copy(First, Last, NewDesignators + Idx);
3108 std::copy(Designators + Idx + 1, Designators + NumDesignators,
3109 NewDesignators + Idx + NumNewDesignators);
3110 Designators = NewDesignators;
3111 NumDesignators = NumDesignators - 1 + NumNewDesignators;
3114 ParenListExpr::ParenListExpr(ASTContext& C, SourceLocation lparenloc,
3115 Expr **exprs, unsigned nexprs,
3116 SourceLocation rparenloc, QualType T)
3117 : Expr(ParenListExprClass, T, VK_RValue, OK_Ordinary,
3118 false, false, false, false),
3119 NumExprs(nexprs), LParenLoc(lparenloc), RParenLoc(rparenloc) {
3120 assert(!T.isNull() && "ParenListExpr must have a valid type");
3121 Exprs = new (C) Stmt*[nexprs];
3122 for (unsigned i = 0; i != nexprs; ++i) {
3123 if (exprs[i]->isTypeDependent())
3124 ExprBits.TypeDependent = true;
3125 if (exprs[i]->isValueDependent())
3126 ExprBits.ValueDependent = true;
3127 if (exprs[i]->isInstantiationDependent())
3128 ExprBits.InstantiationDependent = true;
3129 if (exprs[i]->containsUnexpandedParameterPack())
3130 ExprBits.ContainsUnexpandedParameterPack = true;
3132 Exprs[i] = exprs[i];
3136 const OpaqueValueExpr *OpaqueValueExpr::findInCopyConstruct(const Expr *e) {
3137 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(e))
3138 e = ewc->getSubExpr();
3139 if (const MaterializeTemporaryExpr *m = dyn_cast<MaterializeTemporaryExpr>(e))
3140 e = m->GetTemporaryExpr();
3141 e = cast<CXXConstructExpr>(e)->getArg(0);
3142 while (const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
3143 e = ice->getSubExpr();
3144 return cast<OpaqueValueExpr>(e);
3147 //===----------------------------------------------------------------------===//
3149 //===----------------------------------------------------------------------===//
3151 Expr* ExprIterator::operator[](size_t idx) { return cast<Expr>(I[idx]); }
3152 Expr* ExprIterator::operator*() const { return cast<Expr>(*I); }
3153 Expr* ExprIterator::operator->() const { return cast<Expr>(*I); }
3154 const Expr* ConstExprIterator::operator[](size_t idx) const {
3155 return cast<Expr>(I[idx]);
3157 const Expr* ConstExprIterator::operator*() const { return cast<Expr>(*I); }
3158 const Expr* ConstExprIterator::operator->() const { return cast<Expr>(*I); }
3160 //===----------------------------------------------------------------------===//
3161 // Child Iterators for iterating over subexpressions/substatements
3162 //===----------------------------------------------------------------------===//
3164 // UnaryExprOrTypeTraitExpr
3165 Stmt::child_range UnaryExprOrTypeTraitExpr::children() {
3166 // If this is of a type and the type is a VLA type (and not a typedef), the
3167 // size expression of the VLA needs to be treated as an executable expression.
3168 // Why isn't this weirdness documented better in StmtIterator?
3169 if (isArgumentType()) {
3170 if (const VariableArrayType* T = dyn_cast<VariableArrayType>(
3171 getArgumentType().getTypePtr()))
3172 return child_range(child_iterator(T), child_iterator());
3173 return child_range();
3175 return child_range(&Argument.Ex, &Argument.Ex + 1);
3179 Stmt::child_range ObjCMessageExpr::children() {
3181 if (getReceiverKind() == Instance)
3182 begin = reinterpret_cast<Stmt **>(this + 1);
3184 begin = reinterpret_cast<Stmt **>(getArgs());
3185 return child_range(begin,
3186 reinterpret_cast<Stmt **>(getArgs() + getNumArgs()));
3190 BlockDeclRefExpr::BlockDeclRefExpr(VarDecl *d, QualType t, ExprValueKind VK,
3191 SourceLocation l, bool ByRef,
3193 : Expr(BlockDeclRefExprClass, t, VK, OK_Ordinary, false, false, false,
3194 d->isParameterPack()),
3195 D(d), Loc(l), IsByRef(ByRef), ConstQualAdded(constAdded)
3197 bool TypeDependent = false;
3198 bool ValueDependent = false;
3199 bool InstantiationDependent = false;
3200 computeDeclRefDependence(D, getType(), TypeDependent, ValueDependent,
3201 InstantiationDependent);
3202 ExprBits.TypeDependent = TypeDependent;
3203 ExprBits.ValueDependent = ValueDependent;
3204 ExprBits.InstantiationDependent = InstantiationDependent;