Expr.cpp revision f111d935722ed488144600cea5ed03a6b5069e8f
1//===--- Expr.cpp - Expression AST Node Implementation --------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expr class and subclasses.
11//
12//===----------------------------------------------------------------------===//
13
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/Basic/Builtins.h"
26#include "clang/Basic/SourceManager.h"
27#include "clang/Basic/TargetInfo.h"
28#include "llvm/Support/ErrorHandling.h"
29#include "llvm/Support/raw_ostream.h"
30#include <algorithm>
31using namespace clang;
32
33/// isKnownToHaveBooleanValue - Return true if this is an integer expression
34/// that is known to return 0 or 1.  This happens for _Bool/bool expressions
35/// but also int expressions which are produced by things like comparisons in
36/// C.
37bool Expr::isKnownToHaveBooleanValue() const {
38  const Expr *E = IgnoreParens();
39
40  // If this value has _Bool type, it is obvious 0/1.
41  if (E->getType()->isBooleanType()) return true;
42  // If this is a non-scalar-integer type, we don't care enough to try.
43  if (!E->getType()->isIntegralOrEnumerationType()) return false;
44
45  if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
46    switch (UO->getOpcode()) {
47    case UO_Plus:
48      return UO->getSubExpr()->isKnownToHaveBooleanValue();
49    default:
50      return false;
51    }
52  }
53
54  // Only look through implicit casts.  If the user writes
55  // '(int) (a && b)' treat it as an arbitrary int.
56  if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
57    return CE->getSubExpr()->isKnownToHaveBooleanValue();
58
59  if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
60    switch (BO->getOpcode()) {
61    default: return false;
62    case BO_LT:   // Relational operators.
63    case BO_GT:
64    case BO_LE:
65    case BO_GE:
66    case BO_EQ:   // Equality operators.
67    case BO_NE:
68    case BO_LAnd: // AND operator.
69    case BO_LOr:  // Logical OR operator.
70      return true;
71
72    case BO_And:  // Bitwise AND operator.
73    case BO_Xor:  // Bitwise XOR operator.
74    case BO_Or:   // Bitwise OR operator.
75      // Handle things like (x==2)|(y==12).
76      return BO->getLHS()->isKnownToHaveBooleanValue() &&
77             BO->getRHS()->isKnownToHaveBooleanValue();
78
79    case BO_Comma:
80    case BO_Assign:
81      return BO->getRHS()->isKnownToHaveBooleanValue();
82    }
83  }
84
85  if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
86    return CO->getTrueExpr()->isKnownToHaveBooleanValue() &&
87           CO->getFalseExpr()->isKnownToHaveBooleanValue();
88
89  return false;
90}
91
92// Amusing macro metaprogramming hack: check whether a class provides
93// a more specific implementation of getExprLoc().
94namespace {
95  /// This implementation is used when a class provides a custom
96  /// implementation of getExprLoc.
97  template <class E, class T>
98  SourceLocation getExprLocImpl(const Expr *expr,
99                                SourceLocation (T::*v)() const) {
100    return static_cast<const E*>(expr)->getExprLoc();
101  }
102
103  /// This implementation is used when a class doesn't provide
104  /// a custom implementation of getExprLoc.  Overload resolution
105  /// should pick it over the implementation above because it's
106  /// more specialized according to function template partial ordering.
107  template <class E>
108  SourceLocation getExprLocImpl(const Expr *expr,
109                                SourceLocation (Expr::*v)() const) {
110    return static_cast<const E*>(expr)->getSourceRange().getBegin();
111  }
112}
113
114SourceLocation Expr::getExprLoc() const {
115  switch (getStmtClass()) {
116  case Stmt::NoStmtClass: llvm_unreachable("statement without class");
117#define ABSTRACT_STMT(type)
118#define STMT(type, base) \
119  case Stmt::type##Class: llvm_unreachable(#type " is not an Expr"); break;
120#define EXPR(type, base) \
121  case Stmt::type##Class: return getExprLocImpl<type>(this, &type::getExprLoc);
122#include "clang/AST/StmtNodes.inc"
123  }
124  llvm_unreachable("unknown statement kind");
125  return SourceLocation();
126}
127
128//===----------------------------------------------------------------------===//
129// Primary Expressions.
130//===----------------------------------------------------------------------===//
131
132void ExplicitTemplateArgumentList::initializeFrom(
133                                      const TemplateArgumentListInfo &Info) {
134  LAngleLoc = Info.getLAngleLoc();
135  RAngleLoc = Info.getRAngleLoc();
136  NumTemplateArgs = Info.size();
137
138  TemplateArgumentLoc *ArgBuffer = getTemplateArgs();
139  for (unsigned i = 0; i != NumTemplateArgs; ++i)
140    new (&ArgBuffer[i]) TemplateArgumentLoc(Info[i]);
141}
142
143void ExplicitTemplateArgumentList::initializeFrom(
144                                   const TemplateArgumentListInfo &Info,
145                                   bool &Dependent,
146                                   bool &ContainsUnexpandedParameterPack) {
147  LAngleLoc = Info.getLAngleLoc();
148  RAngleLoc = Info.getRAngleLoc();
149  NumTemplateArgs = Info.size();
150
151  TemplateArgumentLoc *ArgBuffer = getTemplateArgs();
152  for (unsigned i = 0; i != NumTemplateArgs; ++i) {
153    Dependent = Dependent || Info[i].getArgument().isDependent();
154    ContainsUnexpandedParameterPack
155      = ContainsUnexpandedParameterPack ||
156        Info[i].getArgument().containsUnexpandedParameterPack();
157
158    new (&ArgBuffer[i]) TemplateArgumentLoc(Info[i]);
159  }
160}
161
162void ExplicitTemplateArgumentList::copyInto(
163                                      TemplateArgumentListInfo &Info) const {
164  Info.setLAngleLoc(LAngleLoc);
165  Info.setRAngleLoc(RAngleLoc);
166  for (unsigned I = 0; I != NumTemplateArgs; ++I)
167    Info.addArgument(getTemplateArgs()[I]);
168}
169
170std::size_t ExplicitTemplateArgumentList::sizeFor(unsigned NumTemplateArgs) {
171  return sizeof(ExplicitTemplateArgumentList) +
172         sizeof(TemplateArgumentLoc) * NumTemplateArgs;
173}
174
175std::size_t ExplicitTemplateArgumentList::sizeFor(
176                                      const TemplateArgumentListInfo &Info) {
177  return sizeFor(Info.size());
178}
179
180/// \brief Compute the type- and value-dependence of a declaration reference
181/// based on the declaration being referenced.
182static void computeDeclRefDependence(NamedDecl *D, QualType T,
183                                     bool &TypeDependent,
184                                     bool &ValueDependent) {
185  TypeDependent = false;
186  ValueDependent = false;
187
188
189  // (TD) C++ [temp.dep.expr]p3:
190  //   An id-expression is type-dependent if it contains:
191  //
192  // and
193  //
194  // (VD) C++ [temp.dep.constexpr]p2:
195  //  An identifier is value-dependent if it is:
196
197  //  (TD)  - an identifier that was declared with dependent type
198  //  (VD)  - a name declared with a dependent type,
199  if (T->isDependentType()) {
200    TypeDependent = true;
201    ValueDependent = true;
202    return;
203  }
204
205  //  (TD)  - a conversion-function-id that specifies a dependent type
206  if (D->getDeclName().getNameKind()
207           == DeclarationName::CXXConversionFunctionName &&
208           D->getDeclName().getCXXNameType()->isDependentType()) {
209    TypeDependent = true;
210    ValueDependent = true;
211    return;
212  }
213  //  (VD)  - the name of a non-type template parameter,
214  if (isa<NonTypeTemplateParmDecl>(D)) {
215    ValueDependent = true;
216    return;
217  }
218
219  //  (VD) - a constant with integral or enumeration type and is
220  //         initialized with an expression that is value-dependent.
221  if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
222    if (Var->getType()->isIntegralOrEnumerationType() &&
223        Var->getType().getCVRQualifiers() == Qualifiers::Const) {
224      if (const Expr *Init = Var->getAnyInitializer())
225        if (Init->isValueDependent())
226          ValueDependent = true;
227    }
228
229    // (VD) - FIXME: Missing from the standard:
230    //      -  a member function or a static data member of the current
231    //         instantiation
232    else if (Var->isStaticDataMember() &&
233             Var->getDeclContext()->isDependentContext())
234      ValueDependent = true;
235
236    return;
237  }
238
239  // (VD) - FIXME: Missing from the standard:
240  //      -  a member function or a static data member of the current
241  //         instantiation
242  if (isa<CXXMethodDecl>(D) && D->getDeclContext()->isDependentContext()) {
243    ValueDependent = true;
244    return;
245  }
246}
247
248void DeclRefExpr::computeDependence() {
249  bool TypeDependent = false;
250  bool ValueDependent = false;
251  computeDeclRefDependence(getDecl(), getType(), TypeDependent, ValueDependent);
252
253  // (TD) C++ [temp.dep.expr]p3:
254  //   An id-expression is type-dependent if it contains:
255  //
256  // and
257  //
258  // (VD) C++ [temp.dep.constexpr]p2:
259  //  An identifier is value-dependent if it is:
260  if (!TypeDependent && !ValueDependent &&
261      hasExplicitTemplateArgs() &&
262      TemplateSpecializationType::anyDependentTemplateArguments(
263                                                            getTemplateArgs(),
264                                                       getNumTemplateArgs())) {
265    TypeDependent = true;
266    ValueDependent = true;
267  }
268
269  ExprBits.TypeDependent = TypeDependent;
270  ExprBits.ValueDependent = ValueDependent;
271
272  // Is the declaration a parameter pack?
273  if (getDecl()->isParameterPack())
274    ExprBits.ContainsUnexpandedParameterPack = true;
275}
276
277DeclRefExpr::DeclRefExpr(NestedNameSpecifierLoc QualifierLoc,
278                         ValueDecl *D, SourceLocation NameLoc,
279                         const TemplateArgumentListInfo *TemplateArgs,
280                         QualType T, ExprValueKind VK)
281  : Expr(DeclRefExprClass, T, VK, OK_Ordinary, false, false, false),
282    DecoratedD(D,
283               (QualifierLoc? HasQualifierFlag : 0) |
284               (TemplateArgs ? HasExplicitTemplateArgumentListFlag : 0)),
285    Loc(NameLoc) {
286  if (QualifierLoc) {
287    NameQualifier *NQ = getNameQualifier();
288    NQ->QualifierLoc = QualifierLoc;
289  }
290
291  if (TemplateArgs)
292    getExplicitTemplateArgs().initializeFrom(*TemplateArgs);
293
294  computeDependence();
295}
296
297DeclRefExpr::DeclRefExpr(NestedNameSpecifierLoc QualifierLoc,
298                         ValueDecl *D, const DeclarationNameInfo &NameInfo,
299                         const TemplateArgumentListInfo *TemplateArgs,
300                         QualType T, ExprValueKind VK)
301  : Expr(DeclRefExprClass, T, VK, OK_Ordinary, false, false, false),
302    DecoratedD(D,
303               (QualifierLoc? HasQualifierFlag : 0) |
304               (TemplateArgs ? HasExplicitTemplateArgumentListFlag : 0)),
305    Loc(NameInfo.getLoc()), DNLoc(NameInfo.getInfo()) {
306  if (QualifierLoc) {
307    NameQualifier *NQ = getNameQualifier();
308    NQ->QualifierLoc = QualifierLoc;
309  }
310
311  if (TemplateArgs)
312    getExplicitTemplateArgs().initializeFrom(*TemplateArgs);
313
314  computeDependence();
315}
316
317DeclRefExpr *DeclRefExpr::Create(ASTContext &Context,
318                                 NestedNameSpecifierLoc QualifierLoc,
319                                 ValueDecl *D,
320                                 SourceLocation NameLoc,
321                                 QualType T,
322                                 ExprValueKind VK,
323                                 const TemplateArgumentListInfo *TemplateArgs) {
324  return Create(Context, QualifierLoc, D,
325                DeclarationNameInfo(D->getDeclName(), NameLoc),
326                T, VK, TemplateArgs);
327}
328
329DeclRefExpr *DeclRefExpr::Create(ASTContext &Context,
330                                 NestedNameSpecifierLoc QualifierLoc,
331                                 ValueDecl *D,
332                                 const DeclarationNameInfo &NameInfo,
333                                 QualType T,
334                                 ExprValueKind VK,
335                                 const TemplateArgumentListInfo *TemplateArgs) {
336  std::size_t Size = sizeof(DeclRefExpr);
337  if (QualifierLoc != 0)
338    Size += sizeof(NameQualifier);
339
340  if (TemplateArgs)
341    Size += ExplicitTemplateArgumentList::sizeFor(*TemplateArgs);
342
343  void *Mem = Context.Allocate(Size, llvm::alignOf<DeclRefExpr>());
344  return new (Mem) DeclRefExpr(QualifierLoc, D, NameInfo, TemplateArgs, T, VK);
345}
346
347DeclRefExpr *DeclRefExpr::CreateEmpty(ASTContext &Context,
348                                      bool HasQualifier,
349                                      bool HasExplicitTemplateArgs,
350                                      unsigned NumTemplateArgs) {
351  std::size_t Size = sizeof(DeclRefExpr);
352  if (HasQualifier)
353    Size += sizeof(NameQualifier);
354
355  if (HasExplicitTemplateArgs)
356    Size += ExplicitTemplateArgumentList::sizeFor(NumTemplateArgs);
357
358  void *Mem = Context.Allocate(Size, llvm::alignOf<DeclRefExpr>());
359  return new (Mem) DeclRefExpr(EmptyShell());
360}
361
362SourceRange DeclRefExpr::getSourceRange() const {
363  SourceRange R = getNameInfo().getSourceRange();
364  if (hasQualifier())
365    R.setBegin(getQualifierLoc().getBeginLoc());
366  if (hasExplicitTemplateArgs())
367    R.setEnd(getRAngleLoc());
368  return R;
369}
370
371// FIXME: Maybe this should use DeclPrinter with a special "print predefined
372// expr" policy instead.
373std::string PredefinedExpr::ComputeName(IdentType IT, const Decl *CurrentDecl) {
374  ASTContext &Context = CurrentDecl->getASTContext();
375
376  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CurrentDecl)) {
377    if (IT != PrettyFunction && IT != PrettyFunctionNoVirtual)
378      return FD->getNameAsString();
379
380    llvm::SmallString<256> Name;
381    llvm::raw_svector_ostream Out(Name);
382
383    if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
384      if (MD->isVirtual() && IT != PrettyFunctionNoVirtual)
385        Out << "virtual ";
386      if (MD->isStatic())
387        Out << "static ";
388    }
389
390    PrintingPolicy Policy(Context.getLangOptions());
391
392    std::string Proto = FD->getQualifiedNameAsString(Policy);
393
394    const FunctionType *AFT = FD->getType()->getAs<FunctionType>();
395    const FunctionProtoType *FT = 0;
396    if (FD->hasWrittenPrototype())
397      FT = dyn_cast<FunctionProtoType>(AFT);
398
399    Proto += "(";
400    if (FT) {
401      llvm::raw_string_ostream POut(Proto);
402      for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) {
403        if (i) POut << ", ";
404        std::string Param;
405        FD->getParamDecl(i)->getType().getAsStringInternal(Param, Policy);
406        POut << Param;
407      }
408
409      if (FT->isVariadic()) {
410        if (FD->getNumParams()) POut << ", ";
411        POut << "...";
412      }
413    }
414    Proto += ")";
415
416    if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
417      Qualifiers ThisQuals = Qualifiers::fromCVRMask(MD->getTypeQualifiers());
418      if (ThisQuals.hasConst())
419        Proto += " const";
420      if (ThisQuals.hasVolatile())
421        Proto += " volatile";
422    }
423
424    if (!isa<CXXConstructorDecl>(FD) && !isa<CXXDestructorDecl>(FD))
425      AFT->getResultType().getAsStringInternal(Proto, Policy);
426
427    Out << Proto;
428
429    Out.flush();
430    return Name.str().str();
431  }
432  if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurrentDecl)) {
433    llvm::SmallString<256> Name;
434    llvm::raw_svector_ostream Out(Name);
435    Out << (MD->isInstanceMethod() ? '-' : '+');
436    Out << '[';
437
438    // For incorrect code, there might not be an ObjCInterfaceDecl.  Do
439    // a null check to avoid a crash.
440    if (const ObjCInterfaceDecl *ID = MD->getClassInterface())
441      Out << ID;
442
443    if (const ObjCCategoryImplDecl *CID =
444        dyn_cast<ObjCCategoryImplDecl>(MD->getDeclContext()))
445      Out << '(' << CID << ')';
446
447    Out <<  ' ';
448    Out << MD->getSelector().getAsString();
449    Out <<  ']';
450
451    Out.flush();
452    return Name.str().str();
453  }
454  if (isa<TranslationUnitDecl>(CurrentDecl) && IT == PrettyFunction) {
455    // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
456    return "top level";
457  }
458  return "";
459}
460
461void APNumericStorage::setIntValue(ASTContext &C, const llvm::APInt &Val) {
462  if (hasAllocation())
463    C.Deallocate(pVal);
464
465  BitWidth = Val.getBitWidth();
466  unsigned NumWords = Val.getNumWords();
467  const uint64_t* Words = Val.getRawData();
468  if (NumWords > 1) {
469    pVal = new (C) uint64_t[NumWords];
470    std::copy(Words, Words + NumWords, pVal);
471  } else if (NumWords == 1)
472    VAL = Words[0];
473  else
474    VAL = 0;
475}
476
477IntegerLiteral *
478IntegerLiteral::Create(ASTContext &C, const llvm::APInt &V,
479                       QualType type, SourceLocation l) {
480  return new (C) IntegerLiteral(C, V, type, l);
481}
482
483IntegerLiteral *
484IntegerLiteral::Create(ASTContext &C, EmptyShell Empty) {
485  return new (C) IntegerLiteral(Empty);
486}
487
488FloatingLiteral *
489FloatingLiteral::Create(ASTContext &C, const llvm::APFloat &V,
490                        bool isexact, QualType Type, SourceLocation L) {
491  return new (C) FloatingLiteral(C, V, isexact, Type, L);
492}
493
494FloatingLiteral *
495FloatingLiteral::Create(ASTContext &C, EmptyShell Empty) {
496  return new (C) FloatingLiteral(Empty);
497}
498
499/// getValueAsApproximateDouble - This returns the value as an inaccurate
500/// double.  Note that this may cause loss of precision, but is useful for
501/// debugging dumps, etc.
502double FloatingLiteral::getValueAsApproximateDouble() const {
503  llvm::APFloat V = getValue();
504  bool ignored;
505  V.convert(llvm::APFloat::IEEEdouble, llvm::APFloat::rmNearestTiesToEven,
506            &ignored);
507  return V.convertToDouble();
508}
509
510StringLiteral *StringLiteral::Create(ASTContext &C, const char *StrData,
511                                     unsigned ByteLength, bool Wide,
512                                     bool Pascal, QualType Ty,
513                                     const SourceLocation *Loc,
514                                     unsigned NumStrs) {
515  // Allocate enough space for the StringLiteral plus an array of locations for
516  // any concatenated string tokens.
517  void *Mem = C.Allocate(sizeof(StringLiteral)+
518                         sizeof(SourceLocation)*(NumStrs-1),
519                         llvm::alignOf<StringLiteral>());
520  StringLiteral *SL = new (Mem) StringLiteral(Ty);
521
522  // OPTIMIZE: could allocate this appended to the StringLiteral.
523  char *AStrData = new (C, 1) char[ByteLength];
524  memcpy(AStrData, StrData, ByteLength);
525  SL->StrData = AStrData;
526  SL->ByteLength = ByteLength;
527  SL->IsWide = Wide;
528  SL->IsPascal = Pascal;
529  SL->TokLocs[0] = Loc[0];
530  SL->NumConcatenated = NumStrs;
531
532  if (NumStrs != 1)
533    memcpy(&SL->TokLocs[1], Loc+1, sizeof(SourceLocation)*(NumStrs-1));
534  return SL;
535}
536
537StringLiteral *StringLiteral::CreateEmpty(ASTContext &C, unsigned NumStrs) {
538  void *Mem = C.Allocate(sizeof(StringLiteral)+
539                         sizeof(SourceLocation)*(NumStrs-1),
540                         llvm::alignOf<StringLiteral>());
541  StringLiteral *SL = new (Mem) StringLiteral(QualType());
542  SL->StrData = 0;
543  SL->ByteLength = 0;
544  SL->NumConcatenated = NumStrs;
545  return SL;
546}
547
548void StringLiteral::setString(ASTContext &C, llvm::StringRef Str) {
549  char *AStrData = new (C, 1) char[Str.size()];
550  memcpy(AStrData, Str.data(), Str.size());
551  StrData = AStrData;
552  ByteLength = Str.size();
553}
554
555/// getLocationOfByte - Return a source location that points to the specified
556/// byte of this string literal.
557///
558/// Strings are amazingly complex.  They can be formed from multiple tokens and
559/// can have escape sequences in them in addition to the usual trigraph and
560/// escaped newline business.  This routine handles this complexity.
561///
562SourceLocation StringLiteral::
563getLocationOfByte(unsigned ByteNo, const SourceManager &SM,
564                  const LangOptions &Features, const TargetInfo &Target) const {
565  assert(!isWide() && "This doesn't work for wide strings yet");
566
567  // Loop over all of the tokens in this string until we find the one that
568  // contains the byte we're looking for.
569  unsigned TokNo = 0;
570  while (1) {
571    assert(TokNo < getNumConcatenated() && "Invalid byte number!");
572    SourceLocation StrTokLoc = getStrTokenLoc(TokNo);
573
574    // Get the spelling of the string so that we can get the data that makes up
575    // the string literal, not the identifier for the macro it is potentially
576    // expanded through.
577    SourceLocation StrTokSpellingLoc = SM.getSpellingLoc(StrTokLoc);
578
579    // Re-lex the token to get its length and original spelling.
580    std::pair<FileID, unsigned> LocInfo =SM.getDecomposedLoc(StrTokSpellingLoc);
581    bool Invalid = false;
582    llvm::StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
583    if (Invalid)
584      return StrTokSpellingLoc;
585
586    const char *StrData = Buffer.data()+LocInfo.second;
587
588    // Create a langops struct and enable trigraphs.  This is sufficient for
589    // relexing tokens.
590    LangOptions LangOpts;
591    LangOpts.Trigraphs = true;
592
593    // Create a lexer starting at the beginning of this token.
594    Lexer TheLexer(StrTokSpellingLoc, Features, Buffer.begin(), StrData,
595                   Buffer.end());
596    Token TheTok;
597    TheLexer.LexFromRawLexer(TheTok);
598
599    // Use the StringLiteralParser to compute the length of the string in bytes.
600    StringLiteralParser SLP(&TheTok, 1, SM, Features, Target);
601    unsigned TokNumBytes = SLP.GetStringLength();
602
603    // If the byte is in this token, return the location of the byte.
604    if (ByteNo < TokNumBytes ||
605        (ByteNo == TokNumBytes && TokNo == getNumConcatenated())) {
606      unsigned Offset = SLP.getOffsetOfStringByte(TheTok, ByteNo);
607
608      // Now that we know the offset of the token in the spelling, use the
609      // preprocessor to get the offset in the original source.
610      return Lexer::AdvanceToTokenCharacter(StrTokLoc, Offset, SM, Features);
611    }
612
613    // Move to the next string token.
614    ++TokNo;
615    ByteNo -= TokNumBytes;
616  }
617}
618
619
620
621/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
622/// corresponds to, e.g. "sizeof" or "[pre]++".
623const char *UnaryOperator::getOpcodeStr(Opcode Op) {
624  switch (Op) {
625  default: assert(0 && "Unknown unary operator");
626  case UO_PostInc: return "++";
627  case UO_PostDec: return "--";
628  case UO_PreInc:  return "++";
629  case UO_PreDec:  return "--";
630  case UO_AddrOf:  return "&";
631  case UO_Deref:   return "*";
632  case UO_Plus:    return "+";
633  case UO_Minus:   return "-";
634  case UO_Not:     return "~";
635  case UO_LNot:    return "!";
636  case UO_Real:    return "__real";
637  case UO_Imag:    return "__imag";
638  case UO_Extension: return "__extension__";
639  }
640}
641
642UnaryOperatorKind
643UnaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix) {
644  switch (OO) {
645  default: assert(false && "No unary operator for overloaded function");
646  case OO_PlusPlus:   return Postfix ? UO_PostInc : UO_PreInc;
647  case OO_MinusMinus: return Postfix ? UO_PostDec : UO_PreDec;
648  case OO_Amp:        return UO_AddrOf;
649  case OO_Star:       return UO_Deref;
650  case OO_Plus:       return UO_Plus;
651  case OO_Minus:      return UO_Minus;
652  case OO_Tilde:      return UO_Not;
653  case OO_Exclaim:    return UO_LNot;
654  }
655}
656
657OverloadedOperatorKind UnaryOperator::getOverloadedOperator(Opcode Opc) {
658  switch (Opc) {
659  case UO_PostInc: case UO_PreInc: return OO_PlusPlus;
660  case UO_PostDec: case UO_PreDec: return OO_MinusMinus;
661  case UO_AddrOf: return OO_Amp;
662  case UO_Deref: return OO_Star;
663  case UO_Plus: return OO_Plus;
664  case UO_Minus: return OO_Minus;
665  case UO_Not: return OO_Tilde;
666  case UO_LNot: return OO_Exclaim;
667  default: return OO_None;
668  }
669}
670
671
672//===----------------------------------------------------------------------===//
673// Postfix Operators.
674//===----------------------------------------------------------------------===//
675
676CallExpr::CallExpr(ASTContext& C, StmtClass SC, Expr *fn, unsigned NumPreArgs,
677                   Expr **args, unsigned numargs, QualType t, ExprValueKind VK,
678                   SourceLocation rparenloc)
679  : Expr(SC, t, VK, OK_Ordinary,
680         fn->isTypeDependent(),
681         fn->isValueDependent(),
682         fn->containsUnexpandedParameterPack()),
683    NumArgs(numargs) {
684
685  SubExprs = new (C) Stmt*[numargs+PREARGS_START+NumPreArgs];
686  SubExprs[FN] = fn;
687  for (unsigned i = 0; i != numargs; ++i) {
688    if (args[i]->isTypeDependent())
689      ExprBits.TypeDependent = true;
690    if (args[i]->isValueDependent())
691      ExprBits.ValueDependent = true;
692    if (args[i]->containsUnexpandedParameterPack())
693      ExprBits.ContainsUnexpandedParameterPack = true;
694
695    SubExprs[i+PREARGS_START+NumPreArgs] = args[i];
696  }
697
698  CallExprBits.NumPreArgs = NumPreArgs;
699  RParenLoc = rparenloc;
700}
701
702CallExpr::CallExpr(ASTContext& C, Expr *fn, Expr **args, unsigned numargs,
703                   QualType t, ExprValueKind VK, SourceLocation rparenloc)
704  : Expr(CallExprClass, t, VK, OK_Ordinary,
705         fn->isTypeDependent(),
706         fn->isValueDependent(),
707         fn->containsUnexpandedParameterPack()),
708    NumArgs(numargs) {
709
710  SubExprs = new (C) Stmt*[numargs+PREARGS_START];
711  SubExprs[FN] = fn;
712  for (unsigned i = 0; i != numargs; ++i) {
713    if (args[i]->isTypeDependent())
714      ExprBits.TypeDependent = true;
715    if (args[i]->isValueDependent())
716      ExprBits.ValueDependent = true;
717    if (args[i]->containsUnexpandedParameterPack())
718      ExprBits.ContainsUnexpandedParameterPack = true;
719
720    SubExprs[i+PREARGS_START] = args[i];
721  }
722
723  CallExprBits.NumPreArgs = 0;
724  RParenLoc = rparenloc;
725}
726
727CallExpr::CallExpr(ASTContext &C, StmtClass SC, EmptyShell Empty)
728  : Expr(SC, Empty), SubExprs(0), NumArgs(0) {
729  // FIXME: Why do we allocate this?
730  SubExprs = new (C) Stmt*[PREARGS_START];
731  CallExprBits.NumPreArgs = 0;
732}
733
734CallExpr::CallExpr(ASTContext &C, StmtClass SC, unsigned NumPreArgs,
735                   EmptyShell Empty)
736  : Expr(SC, Empty), SubExprs(0), NumArgs(0) {
737  // FIXME: Why do we allocate this?
738  SubExprs = new (C) Stmt*[PREARGS_START+NumPreArgs];
739  CallExprBits.NumPreArgs = NumPreArgs;
740}
741
742Decl *CallExpr::getCalleeDecl() {
743  Expr *CEE = getCallee()->IgnoreParenCasts();
744  // If we're calling a dereference, look at the pointer instead.
745  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CEE)) {
746    if (BO->isPtrMemOp())
747      CEE = BO->getRHS()->IgnoreParenCasts();
748  } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(CEE)) {
749    if (UO->getOpcode() == UO_Deref)
750      CEE = UO->getSubExpr()->IgnoreParenCasts();
751  }
752  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CEE))
753    return DRE->getDecl();
754  if (MemberExpr *ME = dyn_cast<MemberExpr>(CEE))
755    return ME->getMemberDecl();
756
757  return 0;
758}
759
760FunctionDecl *CallExpr::getDirectCallee() {
761  return dyn_cast_or_null<FunctionDecl>(getCalleeDecl());
762}
763
764/// setNumArgs - This changes the number of arguments present in this call.
765/// Any orphaned expressions are deleted by this, and any new operands are set
766/// to null.
767void CallExpr::setNumArgs(ASTContext& C, unsigned NumArgs) {
768  // No change, just return.
769  if (NumArgs == getNumArgs()) return;
770
771  // If shrinking # arguments, just delete the extras and forgot them.
772  if (NumArgs < getNumArgs()) {
773    this->NumArgs = NumArgs;
774    return;
775  }
776
777  // Otherwise, we are growing the # arguments.  New an bigger argument array.
778  unsigned NumPreArgs = getNumPreArgs();
779  Stmt **NewSubExprs = new (C) Stmt*[NumArgs+PREARGS_START+NumPreArgs];
780  // Copy over args.
781  for (unsigned i = 0; i != getNumArgs()+PREARGS_START+NumPreArgs; ++i)
782    NewSubExprs[i] = SubExprs[i];
783  // Null out new args.
784  for (unsigned i = getNumArgs()+PREARGS_START+NumPreArgs;
785       i != NumArgs+PREARGS_START+NumPreArgs; ++i)
786    NewSubExprs[i] = 0;
787
788  if (SubExprs) C.Deallocate(SubExprs);
789  SubExprs = NewSubExprs;
790  this->NumArgs = NumArgs;
791}
792
793/// isBuiltinCall - If this is a call to a builtin, return the builtin ID.  If
794/// not, return 0.
795unsigned CallExpr::isBuiltinCall(const ASTContext &Context) const {
796  // All simple function calls (e.g. func()) are implicitly cast to pointer to
797  // function. As a result, we try and obtain the DeclRefExpr from the
798  // ImplicitCastExpr.
799  const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(getCallee());
800  if (!ICE) // FIXME: deal with more complex calls (e.g. (func)(), (*func)()).
801    return 0;
802
803  const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr());
804  if (!DRE)
805    return 0;
806
807  const FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
808  if (!FDecl)
809    return 0;
810
811  if (!FDecl->getIdentifier())
812    return 0;
813
814  return FDecl->getBuiltinID();
815}
816
817QualType CallExpr::getCallReturnType() const {
818  QualType CalleeType = getCallee()->getType();
819  if (const PointerType *FnTypePtr = CalleeType->getAs<PointerType>())
820    CalleeType = FnTypePtr->getPointeeType();
821  else if (const BlockPointerType *BPT = CalleeType->getAs<BlockPointerType>())
822    CalleeType = BPT->getPointeeType();
823  else if (const MemberPointerType *MPT
824                                      = CalleeType->getAs<MemberPointerType>())
825    CalleeType = MPT->getPointeeType();
826
827  const FunctionType *FnType = CalleeType->getAs<FunctionType>();
828  return FnType->getResultType();
829}
830
831SourceRange CallExpr::getSourceRange() const {
832  if (isa<CXXOperatorCallExpr>(this))
833    return cast<CXXOperatorCallExpr>(this)->getSourceRange();
834
835  SourceLocation begin = getCallee()->getLocStart();
836  if (begin.isInvalid() && getNumArgs() > 0)
837    begin = getArg(0)->getLocStart();
838  SourceLocation end = getRParenLoc();
839  if (end.isInvalid() && getNumArgs() > 0)
840    end = getArg(getNumArgs() - 1)->getLocEnd();
841  return SourceRange(begin, end);
842}
843
844OffsetOfExpr *OffsetOfExpr::Create(ASTContext &C, QualType type,
845                                   SourceLocation OperatorLoc,
846                                   TypeSourceInfo *tsi,
847                                   OffsetOfNode* compsPtr, unsigned numComps,
848                                   Expr** exprsPtr, unsigned numExprs,
849                                   SourceLocation RParenLoc) {
850  void *Mem = C.Allocate(sizeof(OffsetOfExpr) +
851                         sizeof(OffsetOfNode) * numComps +
852                         sizeof(Expr*) * numExprs);
853
854  return new (Mem) OffsetOfExpr(C, type, OperatorLoc, tsi, compsPtr, numComps,
855                                exprsPtr, numExprs, RParenLoc);
856}
857
858OffsetOfExpr *OffsetOfExpr::CreateEmpty(ASTContext &C,
859                                        unsigned numComps, unsigned numExprs) {
860  void *Mem = C.Allocate(sizeof(OffsetOfExpr) +
861                         sizeof(OffsetOfNode) * numComps +
862                         sizeof(Expr*) * numExprs);
863  return new (Mem) OffsetOfExpr(numComps, numExprs);
864}
865
866OffsetOfExpr::OffsetOfExpr(ASTContext &C, QualType type,
867                           SourceLocation OperatorLoc, TypeSourceInfo *tsi,
868                           OffsetOfNode* compsPtr, unsigned numComps,
869                           Expr** exprsPtr, unsigned numExprs,
870                           SourceLocation RParenLoc)
871  : Expr(OffsetOfExprClass, type, VK_RValue, OK_Ordinary,
872         /*TypeDependent=*/false,
873         /*ValueDependent=*/tsi->getType()->isDependentType(),
874         tsi->getType()->containsUnexpandedParameterPack()),
875    OperatorLoc(OperatorLoc), RParenLoc(RParenLoc), TSInfo(tsi),
876    NumComps(numComps), NumExprs(numExprs)
877{
878  for(unsigned i = 0; i < numComps; ++i) {
879    setComponent(i, compsPtr[i]);
880  }
881
882  for(unsigned i = 0; i < numExprs; ++i) {
883    if (exprsPtr[i]->isTypeDependent() || exprsPtr[i]->isValueDependent())
884      ExprBits.ValueDependent = true;
885    if (exprsPtr[i]->containsUnexpandedParameterPack())
886      ExprBits.ContainsUnexpandedParameterPack = true;
887
888    setIndexExpr(i, exprsPtr[i]);
889  }
890}
891
892IdentifierInfo *OffsetOfExpr::OffsetOfNode::getFieldName() const {
893  assert(getKind() == Field || getKind() == Identifier);
894  if (getKind() == Field)
895    return getField()->getIdentifier();
896
897  return reinterpret_cast<IdentifierInfo *> (Data & ~(uintptr_t)Mask);
898}
899
900MemberExpr *MemberExpr::Create(ASTContext &C, Expr *base, bool isarrow,
901                               NestedNameSpecifierLoc QualifierLoc,
902                               ValueDecl *memberdecl,
903                               DeclAccessPair founddecl,
904                               DeclarationNameInfo nameinfo,
905                               const TemplateArgumentListInfo *targs,
906                               QualType ty,
907                               ExprValueKind vk,
908                               ExprObjectKind ok) {
909  std::size_t Size = sizeof(MemberExpr);
910
911  bool hasQualOrFound = (QualifierLoc ||
912                         founddecl.getDecl() != memberdecl ||
913                         founddecl.getAccess() != memberdecl->getAccess());
914  if (hasQualOrFound)
915    Size += sizeof(MemberNameQualifier);
916
917  if (targs)
918    Size += ExplicitTemplateArgumentList::sizeFor(*targs);
919
920  void *Mem = C.Allocate(Size, llvm::alignOf<MemberExpr>());
921  MemberExpr *E = new (Mem) MemberExpr(base, isarrow, memberdecl, nameinfo,
922                                       ty, vk, ok);
923
924  if (hasQualOrFound) {
925    // FIXME: Wrong. We should be looking at the member declaration we found.
926    if (QualifierLoc && QualifierLoc.getNestedNameSpecifier()->isDependent()) {
927      E->setValueDependent(true);
928      E->setTypeDependent(true);
929    }
930    E->HasQualifierOrFoundDecl = true;
931
932    MemberNameQualifier *NQ = E->getMemberQualifier();
933    NQ->QualifierLoc = QualifierLoc;
934    NQ->FoundDecl = founddecl;
935  }
936
937  if (targs) {
938    E->HasExplicitTemplateArgumentList = true;
939    E->getExplicitTemplateArgs().initializeFrom(*targs);
940  }
941
942  return E;
943}
944
945SourceRange MemberExpr::getSourceRange() const {
946  SourceLocation StartLoc;
947  if (isImplicitAccess()) {
948    if (hasQualifier())
949      StartLoc = getQualifierLoc().getBeginLoc();
950    else
951      StartLoc = MemberLoc;
952  } else {
953    // FIXME: We don't want this to happen. Rather, we should be able to
954    // detect all kinds of implicit accesses more cleanly.
955    StartLoc = getBase()->getLocStart();
956    if (StartLoc.isInvalid())
957      StartLoc = MemberLoc;
958  }
959
960  SourceLocation EndLoc =
961    HasExplicitTemplateArgumentList? getRAngleLoc()
962                                   : getMemberNameInfo().getEndLoc();
963
964  return SourceRange(StartLoc, EndLoc);
965}
966
967const char *CastExpr::getCastKindName() const {
968  switch (getCastKind()) {
969  case CK_Dependent:
970    return "Dependent";
971  case CK_BitCast:
972    return "BitCast";
973  case CK_LValueBitCast:
974    return "LValueBitCast";
975  case CK_LValueToRValue:
976    return "LValueToRValue";
977  case CK_GetObjCProperty:
978    return "GetObjCProperty";
979  case CK_NoOp:
980    return "NoOp";
981  case CK_BaseToDerived:
982    return "BaseToDerived";
983  case CK_DerivedToBase:
984    return "DerivedToBase";
985  case CK_UncheckedDerivedToBase:
986    return "UncheckedDerivedToBase";
987  case CK_Dynamic:
988    return "Dynamic";
989  case CK_ToUnion:
990    return "ToUnion";
991  case CK_ArrayToPointerDecay:
992    return "ArrayToPointerDecay";
993  case CK_FunctionToPointerDecay:
994    return "FunctionToPointerDecay";
995  case CK_NullToMemberPointer:
996    return "NullToMemberPointer";
997  case CK_NullToPointer:
998    return "NullToPointer";
999  case CK_BaseToDerivedMemberPointer:
1000    return "BaseToDerivedMemberPointer";
1001  case CK_DerivedToBaseMemberPointer:
1002    return "DerivedToBaseMemberPointer";
1003  case CK_UserDefinedConversion:
1004    return "UserDefinedConversion";
1005  case CK_ConstructorConversion:
1006    return "ConstructorConversion";
1007  case CK_IntegralToPointer:
1008    return "IntegralToPointer";
1009  case CK_PointerToIntegral:
1010    return "PointerToIntegral";
1011  case CK_PointerToBoolean:
1012    return "PointerToBoolean";
1013  case CK_ToVoid:
1014    return "ToVoid";
1015  case CK_VectorSplat:
1016    return "VectorSplat";
1017  case CK_IntegralCast:
1018    return "IntegralCast";
1019  case CK_IntegralToBoolean:
1020    return "IntegralToBoolean";
1021  case CK_IntegralToFloating:
1022    return "IntegralToFloating";
1023  case CK_FloatingToIntegral:
1024    return "FloatingToIntegral";
1025  case CK_FloatingCast:
1026    return "FloatingCast";
1027  case CK_FloatingToBoolean:
1028    return "FloatingToBoolean";
1029  case CK_MemberPointerToBoolean:
1030    return "MemberPointerToBoolean";
1031  case CK_AnyPointerToObjCPointerCast:
1032    return "AnyPointerToObjCPointerCast";
1033  case CK_AnyPointerToBlockPointerCast:
1034    return "AnyPointerToBlockPointerCast";
1035  case CK_ObjCObjectLValueCast:
1036    return "ObjCObjectLValueCast";
1037  case CK_FloatingRealToComplex:
1038    return "FloatingRealToComplex";
1039  case CK_FloatingComplexToReal:
1040    return "FloatingComplexToReal";
1041  case CK_FloatingComplexToBoolean:
1042    return "FloatingComplexToBoolean";
1043  case CK_FloatingComplexCast:
1044    return "FloatingComplexCast";
1045  case CK_FloatingComplexToIntegralComplex:
1046    return "FloatingComplexToIntegralComplex";
1047  case CK_IntegralRealToComplex:
1048    return "IntegralRealToComplex";
1049  case CK_IntegralComplexToReal:
1050    return "IntegralComplexToReal";
1051  case CK_IntegralComplexToBoolean:
1052    return "IntegralComplexToBoolean";
1053  case CK_IntegralComplexCast:
1054    return "IntegralComplexCast";
1055  case CK_IntegralComplexToFloatingComplex:
1056    return "IntegralComplexToFloatingComplex";
1057  }
1058
1059  llvm_unreachable("Unhandled cast kind!");
1060  return 0;
1061}
1062
1063Expr *CastExpr::getSubExprAsWritten() {
1064  Expr *SubExpr = 0;
1065  CastExpr *E = this;
1066  do {
1067    SubExpr = E->getSubExpr();
1068
1069    // Skip any temporary bindings; they're implicit.
1070    if (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(SubExpr))
1071      SubExpr = Binder->getSubExpr();
1072
1073    // Conversions by constructor and conversion functions have a
1074    // subexpression describing the call; strip it off.
1075    if (E->getCastKind() == CK_ConstructorConversion)
1076      SubExpr = cast<CXXConstructExpr>(SubExpr)->getArg(0);
1077    else if (E->getCastKind() == CK_UserDefinedConversion)
1078      SubExpr = cast<CXXMemberCallExpr>(SubExpr)->getImplicitObjectArgument();
1079
1080    // If the subexpression we're left with is an implicit cast, look
1081    // through that, too.
1082  } while ((E = dyn_cast<ImplicitCastExpr>(SubExpr)));
1083
1084  return SubExpr;
1085}
1086
1087CXXBaseSpecifier **CastExpr::path_buffer() {
1088  switch (getStmtClass()) {
1089#define ABSTRACT_STMT(x)
1090#define CASTEXPR(Type, Base) \
1091  case Stmt::Type##Class: \
1092    return reinterpret_cast<CXXBaseSpecifier**>(static_cast<Type*>(this)+1);
1093#define STMT(Type, Base)
1094#include "clang/AST/StmtNodes.inc"
1095  default:
1096    llvm_unreachable("non-cast expressions not possible here");
1097    return 0;
1098  }
1099}
1100
1101void CastExpr::setCastPath(const CXXCastPath &Path) {
1102  assert(Path.size() == path_size());
1103  memcpy(path_buffer(), Path.data(), Path.size() * sizeof(CXXBaseSpecifier*));
1104}
1105
1106ImplicitCastExpr *ImplicitCastExpr::Create(ASTContext &C, QualType T,
1107                                           CastKind Kind, Expr *Operand,
1108                                           const CXXCastPath *BasePath,
1109                                           ExprValueKind VK) {
1110  unsigned PathSize = (BasePath ? BasePath->size() : 0);
1111  void *Buffer =
1112    C.Allocate(sizeof(ImplicitCastExpr) + PathSize * sizeof(CXXBaseSpecifier*));
1113  ImplicitCastExpr *E =
1114    new (Buffer) ImplicitCastExpr(T, Kind, Operand, PathSize, VK);
1115  if (PathSize) E->setCastPath(*BasePath);
1116  return E;
1117}
1118
1119ImplicitCastExpr *ImplicitCastExpr::CreateEmpty(ASTContext &C,
1120                                                unsigned PathSize) {
1121  void *Buffer =
1122    C.Allocate(sizeof(ImplicitCastExpr) + PathSize * sizeof(CXXBaseSpecifier*));
1123  return new (Buffer) ImplicitCastExpr(EmptyShell(), PathSize);
1124}
1125
1126
1127CStyleCastExpr *CStyleCastExpr::Create(ASTContext &C, QualType T,
1128                                       ExprValueKind VK, CastKind K, Expr *Op,
1129                                       const CXXCastPath *BasePath,
1130                                       TypeSourceInfo *WrittenTy,
1131                                       SourceLocation L, SourceLocation R) {
1132  unsigned PathSize = (BasePath ? BasePath->size() : 0);
1133  void *Buffer =
1134    C.Allocate(sizeof(CStyleCastExpr) + PathSize * sizeof(CXXBaseSpecifier*));
1135  CStyleCastExpr *E =
1136    new (Buffer) CStyleCastExpr(T, VK, K, Op, PathSize, WrittenTy, L, R);
1137  if (PathSize) E->setCastPath(*BasePath);
1138  return E;
1139}
1140
1141CStyleCastExpr *CStyleCastExpr::CreateEmpty(ASTContext &C, unsigned PathSize) {
1142  void *Buffer =
1143    C.Allocate(sizeof(CStyleCastExpr) + PathSize * sizeof(CXXBaseSpecifier*));
1144  return new (Buffer) CStyleCastExpr(EmptyShell(), PathSize);
1145}
1146
1147/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1148/// corresponds to, e.g. "<<=".
1149const char *BinaryOperator::getOpcodeStr(Opcode Op) {
1150  switch (Op) {
1151  case BO_PtrMemD:   return ".*";
1152  case BO_PtrMemI:   return "->*";
1153  case BO_Mul:       return "*";
1154  case BO_Div:       return "/";
1155  case BO_Rem:       return "%";
1156  case BO_Add:       return "+";
1157  case BO_Sub:       return "-";
1158  case BO_Shl:       return "<<";
1159  case BO_Shr:       return ">>";
1160  case BO_LT:        return "<";
1161  case BO_GT:        return ">";
1162  case BO_LE:        return "<=";
1163  case BO_GE:        return ">=";
1164  case BO_EQ:        return "==";
1165  case BO_NE:        return "!=";
1166  case BO_And:       return "&";
1167  case BO_Xor:       return "^";
1168  case BO_Or:        return "|";
1169  case BO_LAnd:      return "&&";
1170  case BO_LOr:       return "||";
1171  case BO_Assign:    return "=";
1172  case BO_MulAssign: return "*=";
1173  case BO_DivAssign: return "/=";
1174  case BO_RemAssign: return "%=";
1175  case BO_AddAssign: return "+=";
1176  case BO_SubAssign: return "-=";
1177  case BO_ShlAssign: return "<<=";
1178  case BO_ShrAssign: return ">>=";
1179  case BO_AndAssign: return "&=";
1180  case BO_XorAssign: return "^=";
1181  case BO_OrAssign:  return "|=";
1182  case BO_Comma:     return ",";
1183  }
1184
1185  return "";
1186}
1187
1188BinaryOperatorKind
1189BinaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO) {
1190  switch (OO) {
1191  default: assert(false && "Not an overloadable binary operator");
1192  case OO_Plus: return BO_Add;
1193  case OO_Minus: return BO_Sub;
1194  case OO_Star: return BO_Mul;
1195  case OO_Slash: return BO_Div;
1196  case OO_Percent: return BO_Rem;
1197  case OO_Caret: return BO_Xor;
1198  case OO_Amp: return BO_And;
1199  case OO_Pipe: return BO_Or;
1200  case OO_Equal: return BO_Assign;
1201  case OO_Less: return BO_LT;
1202  case OO_Greater: return BO_GT;
1203  case OO_PlusEqual: return BO_AddAssign;
1204  case OO_MinusEqual: return BO_SubAssign;
1205  case OO_StarEqual: return BO_MulAssign;
1206  case OO_SlashEqual: return BO_DivAssign;
1207  case OO_PercentEqual: return BO_RemAssign;
1208  case OO_CaretEqual: return BO_XorAssign;
1209  case OO_AmpEqual: return BO_AndAssign;
1210  case OO_PipeEqual: return BO_OrAssign;
1211  case OO_LessLess: return BO_Shl;
1212  case OO_GreaterGreater: return BO_Shr;
1213  case OO_LessLessEqual: return BO_ShlAssign;
1214  case OO_GreaterGreaterEqual: return BO_ShrAssign;
1215  case OO_EqualEqual: return BO_EQ;
1216  case OO_ExclaimEqual: return BO_NE;
1217  case OO_LessEqual: return BO_LE;
1218  case OO_GreaterEqual: return BO_GE;
1219  case OO_AmpAmp: return BO_LAnd;
1220  case OO_PipePipe: return BO_LOr;
1221  case OO_Comma: return BO_Comma;
1222  case OO_ArrowStar: return BO_PtrMemI;
1223  }
1224}
1225
1226OverloadedOperatorKind BinaryOperator::getOverloadedOperator(Opcode Opc) {
1227  static const OverloadedOperatorKind OverOps[] = {
1228    /* .* Cannot be overloaded */OO_None, OO_ArrowStar,
1229    OO_Star, OO_Slash, OO_Percent,
1230    OO_Plus, OO_Minus,
1231    OO_LessLess, OO_GreaterGreater,
1232    OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
1233    OO_EqualEqual, OO_ExclaimEqual,
1234    OO_Amp,
1235    OO_Caret,
1236    OO_Pipe,
1237    OO_AmpAmp,
1238    OO_PipePipe,
1239    OO_Equal, OO_StarEqual,
1240    OO_SlashEqual, OO_PercentEqual,
1241    OO_PlusEqual, OO_MinusEqual,
1242    OO_LessLessEqual, OO_GreaterGreaterEqual,
1243    OO_AmpEqual, OO_CaretEqual,
1244    OO_PipeEqual,
1245    OO_Comma
1246  };
1247  return OverOps[Opc];
1248}
1249
1250InitListExpr::InitListExpr(ASTContext &C, SourceLocation lbraceloc,
1251                           Expr **initExprs, unsigned numInits,
1252                           SourceLocation rbraceloc)
1253  : Expr(InitListExprClass, QualType(), VK_RValue, OK_Ordinary, false, false,
1254         false),
1255    InitExprs(C, numInits),
1256    LBraceLoc(lbraceloc), RBraceLoc(rbraceloc), SyntacticForm(0),
1257    UnionFieldInit(0), HadArrayRangeDesignator(false)
1258{
1259  for (unsigned I = 0; I != numInits; ++I) {
1260    if (initExprs[I]->isTypeDependent())
1261      ExprBits.TypeDependent = true;
1262    if (initExprs[I]->isValueDependent())
1263      ExprBits.ValueDependent = true;
1264    if (initExprs[I]->containsUnexpandedParameterPack())
1265      ExprBits.ContainsUnexpandedParameterPack = true;
1266  }
1267
1268  InitExprs.insert(C, InitExprs.end(), initExprs, initExprs+numInits);
1269}
1270
1271void InitListExpr::reserveInits(ASTContext &C, unsigned NumInits) {
1272  if (NumInits > InitExprs.size())
1273    InitExprs.reserve(C, NumInits);
1274}
1275
1276void InitListExpr::resizeInits(ASTContext &C, unsigned NumInits) {
1277  InitExprs.resize(C, NumInits, 0);
1278}
1279
1280Expr *InitListExpr::updateInit(ASTContext &C, unsigned Init, Expr *expr) {
1281  if (Init >= InitExprs.size()) {
1282    InitExprs.insert(C, InitExprs.end(), Init - InitExprs.size() + 1, 0);
1283    InitExprs.back() = expr;
1284    return 0;
1285  }
1286
1287  Expr *Result = cast_or_null<Expr>(InitExprs[Init]);
1288  InitExprs[Init] = expr;
1289  return Result;
1290}
1291
1292SourceRange InitListExpr::getSourceRange() const {
1293  if (SyntacticForm)
1294    return SyntacticForm->getSourceRange();
1295  SourceLocation Beg = LBraceLoc, End = RBraceLoc;
1296  if (Beg.isInvalid()) {
1297    // Find the first non-null initializer.
1298    for (InitExprsTy::const_iterator I = InitExprs.begin(),
1299                                     E = InitExprs.end();
1300      I != E; ++I) {
1301      if (Stmt *S = *I) {
1302        Beg = S->getLocStart();
1303        break;
1304      }
1305    }
1306  }
1307  if (End.isInvalid()) {
1308    // Find the first non-null initializer from the end.
1309    for (InitExprsTy::const_reverse_iterator I = InitExprs.rbegin(),
1310                                             E = InitExprs.rend();
1311      I != E; ++I) {
1312      if (Stmt *S = *I) {
1313        End = S->getSourceRange().getEnd();
1314        break;
1315      }
1316    }
1317  }
1318  return SourceRange(Beg, End);
1319}
1320
1321/// getFunctionType - Return the underlying function type for this block.
1322///
1323const FunctionType *BlockExpr::getFunctionType() const {
1324  return getType()->getAs<BlockPointerType>()->
1325                    getPointeeType()->getAs<FunctionType>();
1326}
1327
1328SourceLocation BlockExpr::getCaretLocation() const {
1329  return TheBlock->getCaretLocation();
1330}
1331const Stmt *BlockExpr::getBody() const {
1332  return TheBlock->getBody();
1333}
1334Stmt *BlockExpr::getBody() {
1335  return TheBlock->getBody();
1336}
1337
1338
1339//===----------------------------------------------------------------------===//
1340// Generic Expression Routines
1341//===----------------------------------------------------------------------===//
1342
1343/// isUnusedResultAWarning - Return true if this immediate expression should
1344/// be warned about if the result is unused.  If so, fill in Loc and Ranges
1345/// with location to warn on and the source range[s] to report with the
1346/// warning.
1347bool Expr::isUnusedResultAWarning(SourceLocation &Loc, SourceRange &R1,
1348                                  SourceRange &R2, ASTContext &Ctx) const {
1349  // Don't warn if the expr is type dependent. The type could end up
1350  // instantiating to void.
1351  if (isTypeDependent())
1352    return false;
1353
1354  switch (getStmtClass()) {
1355  default:
1356    if (getType()->isVoidType())
1357      return false;
1358    Loc = getExprLoc();
1359    R1 = getSourceRange();
1360    return true;
1361  case ParenExprClass:
1362    return cast<ParenExpr>(this)->getSubExpr()->
1363      isUnusedResultAWarning(Loc, R1, R2, Ctx);
1364  case GenericSelectionExprClass:
1365    return cast<GenericSelectionExpr>(this)->getResultExpr()->
1366      isUnusedResultAWarning(Loc, R1, R2, Ctx);
1367  case UnaryOperatorClass: {
1368    const UnaryOperator *UO = cast<UnaryOperator>(this);
1369
1370    switch (UO->getOpcode()) {
1371    default: break;
1372    case UO_PostInc:
1373    case UO_PostDec:
1374    case UO_PreInc:
1375    case UO_PreDec:                 // ++/--
1376      return false;  // Not a warning.
1377    case UO_Deref:
1378      // Dereferencing a volatile pointer is a side-effect.
1379      if (Ctx.getCanonicalType(getType()).isVolatileQualified())
1380        return false;
1381      break;
1382    case UO_Real:
1383    case UO_Imag:
1384      // accessing a piece of a volatile complex is a side-effect.
1385      if (Ctx.getCanonicalType(UO->getSubExpr()->getType())
1386          .isVolatileQualified())
1387        return false;
1388      break;
1389    case UO_Extension:
1390      return UO->getSubExpr()->isUnusedResultAWarning(Loc, R1, R2, Ctx);
1391    }
1392    Loc = UO->getOperatorLoc();
1393    R1 = UO->getSubExpr()->getSourceRange();
1394    return true;
1395  }
1396  case BinaryOperatorClass: {
1397    const BinaryOperator *BO = cast<BinaryOperator>(this);
1398    switch (BO->getOpcode()) {
1399      default:
1400        break;
1401      // Consider the RHS of comma for side effects. LHS was checked by
1402      // Sema::CheckCommaOperands.
1403      case BO_Comma:
1404        // ((foo = <blah>), 0) is an idiom for hiding the result (and
1405        // lvalue-ness) of an assignment written in a macro.
1406        if (IntegerLiteral *IE =
1407              dyn_cast<IntegerLiteral>(BO->getRHS()->IgnoreParens()))
1408          if (IE->getValue() == 0)
1409            return false;
1410        return BO->getRHS()->isUnusedResultAWarning(Loc, R1, R2, Ctx);
1411      // Consider '||', '&&' to have side effects if the LHS or RHS does.
1412      case BO_LAnd:
1413      case BO_LOr:
1414        if (!BO->getLHS()->isUnusedResultAWarning(Loc, R1, R2, Ctx) ||
1415            !BO->getRHS()->isUnusedResultAWarning(Loc, R1, R2, Ctx))
1416          return false;
1417        break;
1418    }
1419    if (BO->isAssignmentOp())
1420      return false;
1421    Loc = BO->getOperatorLoc();
1422    R1 = BO->getLHS()->getSourceRange();
1423    R2 = BO->getRHS()->getSourceRange();
1424    return true;
1425  }
1426  case CompoundAssignOperatorClass:
1427  case VAArgExprClass:
1428    return false;
1429
1430  case ConditionalOperatorClass: {
1431    // If only one of the LHS or RHS is a warning, the operator might
1432    // be being used for control flow. Only warn if both the LHS and
1433    // RHS are warnings.
1434    const ConditionalOperator *Exp = cast<ConditionalOperator>(this);
1435    if (!Exp->getRHS()->isUnusedResultAWarning(Loc, R1, R2, Ctx))
1436      return false;
1437    if (!Exp->getLHS())
1438      return true;
1439    return Exp->getLHS()->isUnusedResultAWarning(Loc, R1, R2, Ctx);
1440  }
1441
1442  case MemberExprClass:
1443    // If the base pointer or element is to a volatile pointer/field, accessing
1444    // it is a side effect.
1445    if (Ctx.getCanonicalType(getType()).isVolatileQualified())
1446      return false;
1447    Loc = cast<MemberExpr>(this)->getMemberLoc();
1448    R1 = SourceRange(Loc, Loc);
1449    R2 = cast<MemberExpr>(this)->getBase()->getSourceRange();
1450    return true;
1451
1452  case ArraySubscriptExprClass:
1453    // If the base pointer or element is to a volatile pointer/field, accessing
1454    // it is a side effect.
1455    if (Ctx.getCanonicalType(getType()).isVolatileQualified())
1456      return false;
1457    Loc = cast<ArraySubscriptExpr>(this)->getRBracketLoc();
1458    R1 = cast<ArraySubscriptExpr>(this)->getLHS()->getSourceRange();
1459    R2 = cast<ArraySubscriptExpr>(this)->getRHS()->getSourceRange();
1460    return true;
1461
1462  case CallExprClass:
1463  case CXXOperatorCallExprClass:
1464  case CXXMemberCallExprClass: {
1465    // If this is a direct call, get the callee.
1466    const CallExpr *CE = cast<CallExpr>(this);
1467    if (const Decl *FD = CE->getCalleeDecl()) {
1468      // If the callee has attribute pure, const, or warn_unused_result, warn
1469      // about it. void foo() { strlen("bar"); } should warn.
1470      //
1471      // Note: If new cases are added here, DiagnoseUnusedExprResult should be
1472      // updated to match for QoI.
1473      if (FD->getAttr<WarnUnusedResultAttr>() ||
1474          FD->getAttr<PureAttr>() || FD->getAttr<ConstAttr>()) {
1475        Loc = CE->getCallee()->getLocStart();
1476        R1 = CE->getCallee()->getSourceRange();
1477
1478        if (unsigned NumArgs = CE->getNumArgs())
1479          R2 = SourceRange(CE->getArg(0)->getLocStart(),
1480                           CE->getArg(NumArgs-1)->getLocEnd());
1481        return true;
1482      }
1483    }
1484    return false;
1485  }
1486
1487  case CXXTemporaryObjectExprClass:
1488  case CXXConstructExprClass:
1489    return false;
1490
1491  case ObjCMessageExprClass: {
1492    const ObjCMessageExpr *ME = cast<ObjCMessageExpr>(this);
1493    const ObjCMethodDecl *MD = ME->getMethodDecl();
1494    if (MD && MD->getAttr<WarnUnusedResultAttr>()) {
1495      Loc = getExprLoc();
1496      return true;
1497    }
1498    return false;
1499  }
1500
1501  case ObjCPropertyRefExprClass:
1502    Loc = getExprLoc();
1503    R1 = getSourceRange();
1504    return true;
1505
1506  case StmtExprClass: {
1507    // Statement exprs don't logically have side effects themselves, but are
1508    // sometimes used in macros in ways that give them a type that is unused.
1509    // For example ({ blah; foo(); }) will end up with a type if foo has a type.
1510    // however, if the result of the stmt expr is dead, we don't want to emit a
1511    // warning.
1512    const CompoundStmt *CS = cast<StmtExpr>(this)->getSubStmt();
1513    if (!CS->body_empty()) {
1514      if (const Expr *E = dyn_cast<Expr>(CS->body_back()))
1515        return E->isUnusedResultAWarning(Loc, R1, R2, Ctx);
1516      if (const LabelStmt *Label = dyn_cast<LabelStmt>(CS->body_back()))
1517        if (const Expr *E = dyn_cast<Expr>(Label->getSubStmt()))
1518          return E->isUnusedResultAWarning(Loc, R1, R2, Ctx);
1519    }
1520
1521    if (getType()->isVoidType())
1522      return false;
1523    Loc = cast<StmtExpr>(this)->getLParenLoc();
1524    R1 = getSourceRange();
1525    return true;
1526  }
1527  case CStyleCastExprClass:
1528    // If this is an explicit cast to void, allow it.  People do this when they
1529    // think they know what they're doing :).
1530    if (getType()->isVoidType())
1531      return false;
1532    Loc = cast<CStyleCastExpr>(this)->getLParenLoc();
1533    R1 = cast<CStyleCastExpr>(this)->getSubExpr()->getSourceRange();
1534    return true;
1535  case CXXFunctionalCastExprClass: {
1536    if (getType()->isVoidType())
1537      return false;
1538    const CastExpr *CE = cast<CastExpr>(this);
1539
1540    // If this is a cast to void or a constructor conversion, check the operand.
1541    // Otherwise, the result of the cast is unused.
1542    if (CE->getCastKind() == CK_ToVoid ||
1543        CE->getCastKind() == CK_ConstructorConversion)
1544      return (cast<CastExpr>(this)->getSubExpr()
1545              ->isUnusedResultAWarning(Loc, R1, R2, Ctx));
1546    Loc = cast<CXXFunctionalCastExpr>(this)->getTypeBeginLoc();
1547    R1 = cast<CXXFunctionalCastExpr>(this)->getSubExpr()->getSourceRange();
1548    return true;
1549  }
1550
1551  case ImplicitCastExprClass:
1552    // Check the operand, since implicit casts are inserted by Sema
1553    return (cast<ImplicitCastExpr>(this)
1554            ->getSubExpr()->isUnusedResultAWarning(Loc, R1, R2, Ctx));
1555
1556  case CXXDefaultArgExprClass:
1557    return (cast<CXXDefaultArgExpr>(this)
1558            ->getExpr()->isUnusedResultAWarning(Loc, R1, R2, Ctx));
1559
1560  case CXXNewExprClass:
1561    // FIXME: In theory, there might be new expressions that don't have side
1562    // effects (e.g. a placement new with an uninitialized POD).
1563  case CXXDeleteExprClass:
1564    return false;
1565  case CXXBindTemporaryExprClass:
1566    return (cast<CXXBindTemporaryExpr>(this)
1567            ->getSubExpr()->isUnusedResultAWarning(Loc, R1, R2, Ctx));
1568  case ExprWithCleanupsClass:
1569    return (cast<ExprWithCleanups>(this)
1570            ->getSubExpr()->isUnusedResultAWarning(Loc, R1, R2, Ctx));
1571  }
1572}
1573
1574/// isOBJCGCCandidate - Check if an expression is objc gc'able.
1575/// returns true, if it is; false otherwise.
1576bool Expr::isOBJCGCCandidate(ASTContext &Ctx) const {
1577  const Expr *E = IgnoreParens();
1578  switch (E->getStmtClass()) {
1579  default:
1580    return false;
1581  case ObjCIvarRefExprClass:
1582    return true;
1583  case Expr::UnaryOperatorClass:
1584    return cast<UnaryOperator>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
1585  case ImplicitCastExprClass:
1586    return cast<ImplicitCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
1587  case CStyleCastExprClass:
1588    return cast<CStyleCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
1589  case DeclRefExprClass: {
1590    const Decl *D = cast<DeclRefExpr>(E)->getDecl();
1591    if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1592      if (VD->hasGlobalStorage())
1593        return true;
1594      QualType T = VD->getType();
1595      // dereferencing to a  pointer is always a gc'able candidate,
1596      // unless it is __weak.
1597      return T->isPointerType() &&
1598             (Ctx.getObjCGCAttrKind(T) != Qualifiers::Weak);
1599    }
1600    return false;
1601  }
1602  case MemberExprClass: {
1603    const MemberExpr *M = cast<MemberExpr>(E);
1604    return M->getBase()->isOBJCGCCandidate(Ctx);
1605  }
1606  case ArraySubscriptExprClass:
1607    return cast<ArraySubscriptExpr>(E)->getBase()->isOBJCGCCandidate(Ctx);
1608  }
1609}
1610
1611bool Expr::isBoundMemberFunction(ASTContext &Ctx) const {
1612  if (isTypeDependent())
1613    return false;
1614  return ClassifyLValue(Ctx) == Expr::LV_MemberFunction;
1615}
1616
1617static Expr::CanThrowResult MergeCanThrow(Expr::CanThrowResult CT1,
1618                                          Expr::CanThrowResult CT2) {
1619  // CanThrowResult constants are ordered so that the maximum is the correct
1620  // merge result.
1621  return CT1 > CT2 ? CT1 : CT2;
1622}
1623
1624static Expr::CanThrowResult CanSubExprsThrow(ASTContext &C, const Expr *CE) {
1625  Expr *E = const_cast<Expr*>(CE);
1626  Expr::CanThrowResult R = Expr::CT_Cannot;
1627  for (Expr::child_range I = E->children(); I && R != Expr::CT_Can; ++I) {
1628    R = MergeCanThrow(R, cast<Expr>(*I)->CanThrow(C));
1629  }
1630  return R;
1631}
1632
1633static Expr::CanThrowResult CanCalleeThrow(ASTContext &Ctx, const Decl *D,
1634                                           bool NullThrows = true) {
1635  if (!D)
1636    return NullThrows ? Expr::CT_Can : Expr::CT_Cannot;
1637
1638  // See if we can get a function type from the decl somehow.
1639  const ValueDecl *VD = dyn_cast<ValueDecl>(D);
1640  if (!VD) // If we have no clue what we're calling, assume the worst.
1641    return Expr::CT_Can;
1642
1643  // As an extension, we assume that __attribute__((nothrow)) functions don't
1644  // throw.
1645  if (isa<FunctionDecl>(D) && D->hasAttr<NoThrowAttr>())
1646    return Expr::CT_Cannot;
1647
1648  QualType T = VD->getType();
1649  const FunctionProtoType *FT;
1650  if ((FT = T->getAs<FunctionProtoType>())) {
1651  } else if (const PointerType *PT = T->getAs<PointerType>())
1652    FT = PT->getPointeeType()->getAs<FunctionProtoType>();
1653  else if (const ReferenceType *RT = T->getAs<ReferenceType>())
1654    FT = RT->getPointeeType()->getAs<FunctionProtoType>();
1655  else if (const MemberPointerType *MT = T->getAs<MemberPointerType>())
1656    FT = MT->getPointeeType()->getAs<FunctionProtoType>();
1657  else if (const BlockPointerType *BT = T->getAs<BlockPointerType>())
1658    FT = BT->getPointeeType()->getAs<FunctionProtoType>();
1659
1660  if (!FT)
1661    return Expr::CT_Can;
1662
1663  return FT->isNothrow(Ctx) ? Expr::CT_Cannot : Expr::CT_Can;
1664}
1665
1666static Expr::CanThrowResult CanDynamicCastThrow(const CXXDynamicCastExpr *DC) {
1667  if (DC->isTypeDependent())
1668    return Expr::CT_Dependent;
1669
1670  if (!DC->getTypeAsWritten()->isReferenceType())
1671    return Expr::CT_Cannot;
1672
1673  return DC->getCastKind() == clang::CK_Dynamic? Expr::CT_Can : Expr::CT_Cannot;
1674}
1675
1676static Expr::CanThrowResult CanTypeidThrow(ASTContext &C,
1677                                           const CXXTypeidExpr *DC) {
1678  if (DC->isTypeOperand())
1679    return Expr::CT_Cannot;
1680
1681  Expr *Op = DC->getExprOperand();
1682  if (Op->isTypeDependent())
1683    return Expr::CT_Dependent;
1684
1685  const RecordType *RT = Op->getType()->getAs<RecordType>();
1686  if (!RT)
1687    return Expr::CT_Cannot;
1688
1689  if (!cast<CXXRecordDecl>(RT->getDecl())->isPolymorphic())
1690    return Expr::CT_Cannot;
1691
1692  if (Op->Classify(C).isPRValue())
1693    return Expr::CT_Cannot;
1694
1695  return Expr::CT_Can;
1696}
1697
1698Expr::CanThrowResult Expr::CanThrow(ASTContext &C) const {
1699  // C++ [expr.unary.noexcept]p3:
1700  //   [Can throw] if in a potentially-evaluated context the expression would
1701  //   contain:
1702  switch (getStmtClass()) {
1703  case CXXThrowExprClass:
1704    //   - a potentially evaluated throw-expression
1705    return CT_Can;
1706
1707  case CXXDynamicCastExprClass: {
1708    //   - a potentially evaluated dynamic_cast expression dynamic_cast<T>(v),
1709    //     where T is a reference type, that requires a run-time check
1710    CanThrowResult CT = CanDynamicCastThrow(cast<CXXDynamicCastExpr>(this));
1711    if (CT == CT_Can)
1712      return CT;
1713    return MergeCanThrow(CT, CanSubExprsThrow(C, this));
1714  }
1715
1716  case CXXTypeidExprClass:
1717    //   - a potentially evaluated typeid expression applied to a glvalue
1718    //     expression whose type is a polymorphic class type
1719    return CanTypeidThrow(C, cast<CXXTypeidExpr>(this));
1720
1721    //   - a potentially evaluated call to a function, member function, function
1722    //     pointer, or member function pointer that does not have a non-throwing
1723    //     exception-specification
1724  case CallExprClass:
1725  case CXXOperatorCallExprClass:
1726  case CXXMemberCallExprClass: {
1727    CanThrowResult CT = CanCalleeThrow(C,cast<CallExpr>(this)->getCalleeDecl());
1728    if (CT == CT_Can)
1729      return CT;
1730    return MergeCanThrow(CT, CanSubExprsThrow(C, this));
1731  }
1732
1733  case CXXConstructExprClass:
1734  case CXXTemporaryObjectExprClass: {
1735    CanThrowResult CT = CanCalleeThrow(C,
1736        cast<CXXConstructExpr>(this)->getConstructor());
1737    if (CT == CT_Can)
1738      return CT;
1739    return MergeCanThrow(CT, CanSubExprsThrow(C, this));
1740  }
1741
1742  case CXXNewExprClass: {
1743    CanThrowResult CT = MergeCanThrow(
1744        CanCalleeThrow(C, cast<CXXNewExpr>(this)->getOperatorNew()),
1745        CanCalleeThrow(C, cast<CXXNewExpr>(this)->getConstructor(),
1746                       /*NullThrows*/false));
1747    if (CT == CT_Can)
1748      return CT;
1749    return MergeCanThrow(CT, CanSubExprsThrow(C, this));
1750  }
1751
1752  case CXXDeleteExprClass: {
1753    CanThrowResult CT = CanCalleeThrow(C,
1754        cast<CXXDeleteExpr>(this)->getOperatorDelete());
1755    if (CT == CT_Can)
1756      return CT;
1757    const Expr *Arg = cast<CXXDeleteExpr>(this)->getArgument();
1758    // Unwrap exactly one implicit cast, which converts all pointers to void*.
1759    if (const ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
1760      Arg = Cast->getSubExpr();
1761    if (const PointerType *PT = Arg->getType()->getAs<PointerType>()) {
1762      if (const RecordType *RT = PT->getPointeeType()->getAs<RecordType>()) {
1763        CanThrowResult CT2 = CanCalleeThrow(C,
1764            cast<CXXRecordDecl>(RT->getDecl())->getDestructor());
1765        if (CT2 == CT_Can)
1766          return CT2;
1767        CT = MergeCanThrow(CT, CT2);
1768      }
1769    }
1770    return MergeCanThrow(CT, CanSubExprsThrow(C, this));
1771  }
1772
1773  case CXXBindTemporaryExprClass: {
1774    // The bound temporary has to be destroyed again, which might throw.
1775    CanThrowResult CT = CanCalleeThrow(C,
1776      cast<CXXBindTemporaryExpr>(this)->getTemporary()->getDestructor());
1777    if (CT == CT_Can)
1778      return CT;
1779    return MergeCanThrow(CT, CanSubExprsThrow(C, this));
1780  }
1781
1782    // ObjC message sends are like function calls, but never have exception
1783    // specs.
1784  case ObjCMessageExprClass:
1785  case ObjCPropertyRefExprClass:
1786    return CT_Can;
1787
1788    // Many other things have subexpressions, so we have to test those.
1789    // Some are simple:
1790  case ParenExprClass:
1791  case MemberExprClass:
1792  case CXXReinterpretCastExprClass:
1793  case CXXConstCastExprClass:
1794  case ConditionalOperatorClass:
1795  case CompoundLiteralExprClass:
1796  case ExtVectorElementExprClass:
1797  case InitListExprClass:
1798  case DesignatedInitExprClass:
1799  case ParenListExprClass:
1800  case VAArgExprClass:
1801  case CXXDefaultArgExprClass:
1802  case ExprWithCleanupsClass:
1803  case ObjCIvarRefExprClass:
1804  case ObjCIsaExprClass:
1805  case ShuffleVectorExprClass:
1806    return CanSubExprsThrow(C, this);
1807
1808    // Some might be dependent for other reasons.
1809  case UnaryOperatorClass:
1810  case ArraySubscriptExprClass:
1811  case ImplicitCastExprClass:
1812  case CStyleCastExprClass:
1813  case CXXStaticCastExprClass:
1814  case CXXFunctionalCastExprClass:
1815  case BinaryOperatorClass:
1816  case CompoundAssignOperatorClass: {
1817    CanThrowResult CT = isTypeDependent() ? CT_Dependent : CT_Cannot;
1818    return MergeCanThrow(CT, CanSubExprsThrow(C, this));
1819  }
1820
1821    // FIXME: We should handle StmtExpr, but that opens a MASSIVE can of worms.
1822  case StmtExprClass:
1823    return CT_Can;
1824
1825  case ChooseExprClass:
1826    if (isTypeDependent() || isValueDependent())
1827      return CT_Dependent;
1828    return cast<ChooseExpr>(this)->getChosenSubExpr(C)->CanThrow(C);
1829
1830  case GenericSelectionExprClass:
1831    if (cast<GenericSelectionExpr>(this)->isResultDependent())
1832      return CT_Dependent;
1833    return cast<GenericSelectionExpr>(this)->getResultExpr()->CanThrow(C);
1834
1835    // Some expressions are always dependent.
1836  case DependentScopeDeclRefExprClass:
1837  case CXXUnresolvedConstructExprClass:
1838  case CXXDependentScopeMemberExprClass:
1839    return CT_Dependent;
1840
1841  default:
1842    // All other expressions don't have subexpressions, or else they are
1843    // unevaluated.
1844    return CT_Cannot;
1845  }
1846}
1847
1848Expr* Expr::IgnoreParens() {
1849  Expr* E = this;
1850  while (true) {
1851    if (ParenExpr* P = dyn_cast<ParenExpr>(E)) {
1852      E = P->getSubExpr();
1853      continue;
1854    }
1855    if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) {
1856      if (P->getOpcode() == UO_Extension) {
1857        E = P->getSubExpr();
1858        continue;
1859      }
1860    }
1861    if (GenericSelectionExpr* P = dyn_cast<GenericSelectionExpr>(E)) {
1862      if (!P->isResultDependent()) {
1863        E = P->getResultExpr();
1864        continue;
1865      }
1866    }
1867    return E;
1868  }
1869}
1870
1871/// IgnoreParenCasts - Ignore parentheses and casts.  Strip off any ParenExpr
1872/// or CastExprs or ImplicitCastExprs, returning their operand.
1873Expr *Expr::IgnoreParenCasts() {
1874  Expr *E = this;
1875  while (true) {
1876    if (ParenExpr* P = dyn_cast<ParenExpr>(E)) {
1877      E = P->getSubExpr();
1878      continue;
1879    }
1880    if (CastExpr *P = dyn_cast<CastExpr>(E)) {
1881      E = P->getSubExpr();
1882      continue;
1883    }
1884    if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) {
1885      if (P->getOpcode() == UO_Extension) {
1886        E = P->getSubExpr();
1887        continue;
1888      }
1889    }
1890    if (GenericSelectionExpr* P = dyn_cast<GenericSelectionExpr>(E)) {
1891      if (!P->isResultDependent()) {
1892        E = P->getResultExpr();
1893        continue;
1894      }
1895    }
1896    return E;
1897  }
1898}
1899
1900/// IgnoreParenLValueCasts - Ignore parentheses and lvalue-to-rvalue
1901/// casts.  This is intended purely as a temporary workaround for code
1902/// that hasn't yet been rewritten to do the right thing about those
1903/// casts, and may disappear along with the last internal use.
1904Expr *Expr::IgnoreParenLValueCasts() {
1905  Expr *E = this;
1906  while (true) {
1907    if (ParenExpr *P = dyn_cast<ParenExpr>(E)) {
1908      E = P->getSubExpr();
1909      continue;
1910    } else if (CastExpr *P = dyn_cast<CastExpr>(E)) {
1911      if (P->getCastKind() == CK_LValueToRValue) {
1912        E = P->getSubExpr();
1913        continue;
1914      }
1915    } else if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) {
1916      if (P->getOpcode() == UO_Extension) {
1917        E = P->getSubExpr();
1918        continue;
1919      }
1920    } else if (GenericSelectionExpr* P = dyn_cast<GenericSelectionExpr>(E)) {
1921      if (!P->isResultDependent()) {
1922        E = P->getResultExpr();
1923        continue;
1924      }
1925    }
1926    break;
1927  }
1928  return E;
1929}
1930
1931Expr *Expr::IgnoreParenImpCasts() {
1932  Expr *E = this;
1933  while (true) {
1934    if (ParenExpr *P = dyn_cast<ParenExpr>(E)) {
1935      E = P->getSubExpr();
1936      continue;
1937    }
1938    if (ImplicitCastExpr *P = dyn_cast<ImplicitCastExpr>(E)) {
1939      E = P->getSubExpr();
1940      continue;
1941    }
1942    if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) {
1943      if (P->getOpcode() == UO_Extension) {
1944        E = P->getSubExpr();
1945        continue;
1946      }
1947    }
1948    if (GenericSelectionExpr* P = dyn_cast<GenericSelectionExpr>(E)) {
1949      if (!P->isResultDependent()) {
1950        E = P->getResultExpr();
1951        continue;
1952      }
1953    }
1954    return E;
1955  }
1956}
1957
1958/// IgnoreParenNoopCasts - Ignore parentheses and casts that do not change the
1959/// value (including ptr->int casts of the same size).  Strip off any
1960/// ParenExpr or CastExprs, returning their operand.
1961Expr *Expr::IgnoreParenNoopCasts(ASTContext &Ctx) {
1962  Expr *E = this;
1963  while (true) {
1964    if (ParenExpr *P = dyn_cast<ParenExpr>(E)) {
1965      E = P->getSubExpr();
1966      continue;
1967    }
1968
1969    if (CastExpr *P = dyn_cast<CastExpr>(E)) {
1970      // We ignore integer <-> casts that are of the same width, ptr<->ptr and
1971      // ptr<->int casts of the same width.  We also ignore all identity casts.
1972      Expr *SE = P->getSubExpr();
1973
1974      if (Ctx.hasSameUnqualifiedType(E->getType(), SE->getType())) {
1975        E = SE;
1976        continue;
1977      }
1978
1979      if ((E->getType()->isPointerType() ||
1980           E->getType()->isIntegralType(Ctx)) &&
1981          (SE->getType()->isPointerType() ||
1982           SE->getType()->isIntegralType(Ctx)) &&
1983          Ctx.getTypeSize(E->getType()) == Ctx.getTypeSize(SE->getType())) {
1984        E = SE;
1985        continue;
1986      }
1987    }
1988
1989    if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) {
1990      if (P->getOpcode() == UO_Extension) {
1991        E = P->getSubExpr();
1992        continue;
1993      }
1994    }
1995
1996    if (GenericSelectionExpr* P = dyn_cast<GenericSelectionExpr>(E)) {
1997      if (!P->isResultDependent()) {
1998        E = P->getResultExpr();
1999        continue;
2000      }
2001    }
2002
2003    return E;
2004  }
2005}
2006
2007bool Expr::isDefaultArgument() const {
2008  const Expr *E = this;
2009  while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
2010    E = ICE->getSubExprAsWritten();
2011
2012  return isa<CXXDefaultArgExpr>(E);
2013}
2014
2015/// \brief Skip over any no-op casts and any temporary-binding
2016/// expressions.
2017static const Expr *skipTemporaryBindingsNoOpCastsAndParens(const Expr *E) {
2018  while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2019    if (ICE->getCastKind() == CK_NoOp)
2020      E = ICE->getSubExpr();
2021    else
2022      break;
2023  }
2024
2025  while (const CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
2026    E = BE->getSubExpr();
2027
2028  while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2029    if (ICE->getCastKind() == CK_NoOp)
2030      E = ICE->getSubExpr();
2031    else
2032      break;
2033  }
2034
2035  return E->IgnoreParens();
2036}
2037
2038/// isTemporaryObject - Determines if this expression produces a
2039/// temporary of the given class type.
2040bool Expr::isTemporaryObject(ASTContext &C, const CXXRecordDecl *TempTy) const {
2041  if (!C.hasSameUnqualifiedType(getType(), C.getTypeDeclType(TempTy)))
2042    return false;
2043
2044  const Expr *E = skipTemporaryBindingsNoOpCastsAndParens(this);
2045
2046  // Temporaries are by definition pr-values of class type.
2047  if (!E->Classify(C).isPRValue()) {
2048    // In this context, property reference is a message call and is pr-value.
2049    if (!isa<ObjCPropertyRefExpr>(E))
2050      return false;
2051  }
2052
2053  // Black-list a few cases which yield pr-values of class type that don't
2054  // refer to temporaries of that type:
2055
2056  // - implicit derived-to-base conversions
2057  if (isa<ImplicitCastExpr>(E)) {
2058    switch (cast<ImplicitCastExpr>(E)->getCastKind()) {
2059    case CK_DerivedToBase:
2060    case CK_UncheckedDerivedToBase:
2061      return false;
2062    default:
2063      break;
2064    }
2065  }
2066
2067  // - member expressions (all)
2068  if (isa<MemberExpr>(E))
2069    return false;
2070
2071  // - opaque values (all)
2072  if (isa<OpaqueValueExpr>(E))
2073    return false;
2074
2075  return true;
2076}
2077
2078bool Expr::isImplicitCXXThis() const {
2079  const Expr *E = this;
2080
2081  // Strip away parentheses and casts we don't care about.
2082  while (true) {
2083    if (const ParenExpr *Paren = dyn_cast<ParenExpr>(E)) {
2084      E = Paren->getSubExpr();
2085      continue;
2086    }
2087
2088    if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2089      if (ICE->getCastKind() == CK_NoOp ||
2090          ICE->getCastKind() == CK_LValueToRValue ||
2091          ICE->getCastKind() == CK_DerivedToBase ||
2092          ICE->getCastKind() == CK_UncheckedDerivedToBase) {
2093        E = ICE->getSubExpr();
2094        continue;
2095      }
2096    }
2097
2098    if (const UnaryOperator* UnOp = dyn_cast<UnaryOperator>(E)) {
2099      if (UnOp->getOpcode() == UO_Extension) {
2100        E = UnOp->getSubExpr();
2101        continue;
2102      }
2103    }
2104
2105    break;
2106  }
2107
2108  if (const CXXThisExpr *This = dyn_cast<CXXThisExpr>(E))
2109    return This->isImplicit();
2110
2111  return false;
2112}
2113
2114/// hasAnyTypeDependentArguments - Determines if any of the expressions
2115/// in Exprs is type-dependent.
2116bool Expr::hasAnyTypeDependentArguments(Expr** Exprs, unsigned NumExprs) {
2117  for (unsigned I = 0; I < NumExprs; ++I)
2118    if (Exprs[I]->isTypeDependent())
2119      return true;
2120
2121  return false;
2122}
2123
2124/// hasAnyValueDependentArguments - Determines if any of the expressions
2125/// in Exprs is value-dependent.
2126bool Expr::hasAnyValueDependentArguments(Expr** Exprs, unsigned NumExprs) {
2127  for (unsigned I = 0; I < NumExprs; ++I)
2128    if (Exprs[I]->isValueDependent())
2129      return true;
2130
2131  return false;
2132}
2133
2134bool Expr::isConstantInitializer(ASTContext &Ctx, bool IsForRef) const {
2135  // This function is attempting whether an expression is an initializer
2136  // which can be evaluated at compile-time.  isEvaluatable handles most
2137  // of the cases, but it can't deal with some initializer-specific
2138  // expressions, and it can't deal with aggregates; we deal with those here,
2139  // and fall back to isEvaluatable for the other cases.
2140
2141  // If we ever capture reference-binding directly in the AST, we can
2142  // kill the second parameter.
2143
2144  if (IsForRef) {
2145    EvalResult Result;
2146    return EvaluateAsLValue(Result, Ctx) && !Result.HasSideEffects;
2147  }
2148
2149  switch (getStmtClass()) {
2150  default: break;
2151  case StringLiteralClass:
2152  case ObjCStringLiteralClass:
2153  case ObjCEncodeExprClass:
2154    return true;
2155  case CXXTemporaryObjectExprClass:
2156  case CXXConstructExprClass: {
2157    const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
2158
2159    // Only if it's
2160    // 1) an application of the trivial default constructor or
2161    if (!CE->getConstructor()->isTrivial()) return false;
2162    if (!CE->getNumArgs()) return true;
2163
2164    // 2) an elidable trivial copy construction of an operand which is
2165    //    itself a constant initializer.  Note that we consider the
2166    //    operand on its own, *not* as a reference binding.
2167    return CE->isElidable() &&
2168           CE->getArg(0)->isConstantInitializer(Ctx, false);
2169  }
2170  case CompoundLiteralExprClass: {
2171    // This handles gcc's extension that allows global initializers like
2172    // "struct x {int x;} x = (struct x) {};".
2173    // FIXME: This accepts other cases it shouldn't!
2174    const Expr *Exp = cast<CompoundLiteralExpr>(this)->getInitializer();
2175    return Exp->isConstantInitializer(Ctx, false);
2176  }
2177  case InitListExprClass: {
2178    // FIXME: This doesn't deal with fields with reference types correctly.
2179    // FIXME: This incorrectly allows pointers cast to integers to be assigned
2180    // to bitfields.
2181    const InitListExpr *Exp = cast<InitListExpr>(this);
2182    unsigned numInits = Exp->getNumInits();
2183    for (unsigned i = 0; i < numInits; i++) {
2184      if (!Exp->getInit(i)->isConstantInitializer(Ctx, false))
2185        return false;
2186    }
2187    return true;
2188  }
2189  case ImplicitValueInitExprClass:
2190    return true;
2191  case ParenExprClass:
2192    return cast<ParenExpr>(this)->getSubExpr()
2193      ->isConstantInitializer(Ctx, IsForRef);
2194  case GenericSelectionExprClass:
2195    if (cast<GenericSelectionExpr>(this)->isResultDependent())
2196      return false;
2197    return cast<GenericSelectionExpr>(this)->getResultExpr()
2198      ->isConstantInitializer(Ctx, IsForRef);
2199  case ChooseExprClass:
2200    return cast<ChooseExpr>(this)->getChosenSubExpr(Ctx)
2201      ->isConstantInitializer(Ctx, IsForRef);
2202  case UnaryOperatorClass: {
2203    const UnaryOperator* Exp = cast<UnaryOperator>(this);
2204    if (Exp->getOpcode() == UO_Extension)
2205      return Exp->getSubExpr()->isConstantInitializer(Ctx, false);
2206    break;
2207  }
2208  case BinaryOperatorClass: {
2209    // Special case &&foo - &&bar.  It would be nice to generalize this somehow
2210    // but this handles the common case.
2211    const BinaryOperator *Exp = cast<BinaryOperator>(this);
2212    if (Exp->getOpcode() == BO_Sub &&
2213        isa<AddrLabelExpr>(Exp->getLHS()->IgnoreParenNoopCasts(Ctx)) &&
2214        isa<AddrLabelExpr>(Exp->getRHS()->IgnoreParenNoopCasts(Ctx)))
2215      return true;
2216    break;
2217  }
2218  case CXXFunctionalCastExprClass:
2219  case CXXStaticCastExprClass:
2220  case ImplicitCastExprClass:
2221  case CStyleCastExprClass:
2222    // Handle casts with a destination that's a struct or union; this
2223    // deals with both the gcc no-op struct cast extension and the
2224    // cast-to-union extension.
2225    if (getType()->isRecordType())
2226      return cast<CastExpr>(this)->getSubExpr()
2227        ->isConstantInitializer(Ctx, false);
2228
2229    // Integer->integer casts can be handled here, which is important for
2230    // things like (int)(&&x-&&y).  Scary but true.
2231    if (getType()->isIntegerType() &&
2232        cast<CastExpr>(this)->getSubExpr()->getType()->isIntegerType())
2233      return cast<CastExpr>(this)->getSubExpr()
2234        ->isConstantInitializer(Ctx, false);
2235
2236    break;
2237  }
2238  return isEvaluatable(Ctx);
2239}
2240
2241/// isNullPointerConstant - C99 6.3.2.3p3 - Return whether this is a null
2242/// pointer constant or not, as well as the specific kind of constant detected.
2243/// Null pointer constants can be integer constant expressions with the
2244/// value zero, casts of zero to void*, nullptr (C++0X), or __null
2245/// (a GNU extension).
2246Expr::NullPointerConstantKind
2247Expr::isNullPointerConstant(ASTContext &Ctx,
2248                            NullPointerConstantValueDependence NPC) const {
2249  if (isValueDependent()) {
2250    switch (NPC) {
2251    case NPC_NeverValueDependent:
2252      assert(false && "Unexpected value dependent expression!");
2253      // If the unthinkable happens, fall through to the safest alternative.
2254
2255    case NPC_ValueDependentIsNull:
2256      if (isTypeDependent() || getType()->isIntegralType(Ctx))
2257        return NPCK_ZeroInteger;
2258      else
2259        return NPCK_NotNull;
2260
2261    case NPC_ValueDependentIsNotNull:
2262      return NPCK_NotNull;
2263    }
2264  }
2265
2266  // Strip off a cast to void*, if it exists. Except in C++.
2267  if (const ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(this)) {
2268    if (!Ctx.getLangOptions().CPlusPlus) {
2269      // Check that it is a cast to void*.
2270      if (const PointerType *PT = CE->getType()->getAs<PointerType>()) {
2271        QualType Pointee = PT->getPointeeType();
2272        if (!Pointee.hasQualifiers() &&
2273            Pointee->isVoidType() &&                              // to void*
2274            CE->getSubExpr()->getType()->isIntegerType())         // from int.
2275          return CE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
2276      }
2277    }
2278  } else if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(this)) {
2279    // Ignore the ImplicitCastExpr type entirely.
2280    return ICE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
2281  } else if (const ParenExpr *PE = dyn_cast<ParenExpr>(this)) {
2282    // Accept ((void*)0) as a null pointer constant, as many other
2283    // implementations do.
2284    return PE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
2285  } else if (const GenericSelectionExpr *GE =
2286               dyn_cast<GenericSelectionExpr>(this)) {
2287    return GE->getResultExpr()->isNullPointerConstant(Ctx, NPC);
2288  } else if (const CXXDefaultArgExpr *DefaultArg
2289               = dyn_cast<CXXDefaultArgExpr>(this)) {
2290    // See through default argument expressions
2291    return DefaultArg->getExpr()->isNullPointerConstant(Ctx, NPC);
2292  } else if (isa<GNUNullExpr>(this)) {
2293    // The GNU __null extension is always a null pointer constant.
2294    return NPCK_GNUNull;
2295  }
2296
2297  // C++0x nullptr_t is always a null pointer constant.
2298  if (getType()->isNullPtrType())
2299    return NPCK_CXX0X_nullptr;
2300
2301  if (const RecordType *UT = getType()->getAsUnionType())
2302    if (UT && UT->getDecl()->hasAttr<TransparentUnionAttr>())
2303      if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(this)){
2304        const Expr *InitExpr = CLE->getInitializer();
2305        if (const InitListExpr *ILE = dyn_cast<InitListExpr>(InitExpr))
2306          return ILE->getInit(0)->isNullPointerConstant(Ctx, NPC);
2307      }
2308  // This expression must be an integer type.
2309  if (!getType()->isIntegerType() ||
2310      (Ctx.getLangOptions().CPlusPlus && getType()->isEnumeralType()))
2311    return NPCK_NotNull;
2312
2313  // If we have an integer constant expression, we need to *evaluate* it and
2314  // test for the value 0.
2315  llvm::APSInt Result;
2316  bool IsNull = isIntegerConstantExpr(Result, Ctx) && Result == 0;
2317
2318  return (IsNull ? NPCK_ZeroInteger : NPCK_NotNull);
2319}
2320
2321/// \brief If this expression is an l-value for an Objective C
2322/// property, find the underlying property reference expression.
2323const ObjCPropertyRefExpr *Expr::getObjCProperty() const {
2324  const Expr *E = this;
2325  while (true) {
2326    assert((E->getValueKind() == VK_LValue &&
2327            E->getObjectKind() == OK_ObjCProperty) &&
2328           "expression is not a property reference");
2329    E = E->IgnoreParenCasts();
2330    if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2331      if (BO->getOpcode() == BO_Comma) {
2332        E = BO->getRHS();
2333        continue;
2334      }
2335    }
2336
2337    break;
2338  }
2339
2340  return cast<ObjCPropertyRefExpr>(E);
2341}
2342
2343FieldDecl *Expr::getBitField() {
2344  Expr *E = this->IgnoreParens();
2345
2346  while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2347    if (ICE->getCastKind() == CK_LValueToRValue ||
2348        (ICE->getValueKind() != VK_RValue && ICE->getCastKind() == CK_NoOp))
2349      E = ICE->getSubExpr()->IgnoreParens();
2350    else
2351      break;
2352  }
2353
2354  if (MemberExpr *MemRef = dyn_cast<MemberExpr>(E))
2355    if (FieldDecl *Field = dyn_cast<FieldDecl>(MemRef->getMemberDecl()))
2356      if (Field->isBitField())
2357        return Field;
2358
2359  if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E))
2360    if (FieldDecl *Field = dyn_cast<FieldDecl>(DeclRef->getDecl()))
2361      if (Field->isBitField())
2362        return Field;
2363
2364  if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(E))
2365    if (BinOp->isAssignmentOp() && BinOp->getLHS())
2366      return BinOp->getLHS()->getBitField();
2367
2368  return 0;
2369}
2370
2371bool Expr::refersToVectorElement() const {
2372  const Expr *E = this->IgnoreParens();
2373
2374  while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2375    if (ICE->getValueKind() != VK_RValue &&
2376        ICE->getCastKind() == CK_NoOp)
2377      E = ICE->getSubExpr()->IgnoreParens();
2378    else
2379      break;
2380  }
2381
2382  if (const ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(E))
2383    return ASE->getBase()->getType()->isVectorType();
2384
2385  if (isa<ExtVectorElementExpr>(E))
2386    return true;
2387
2388  return false;
2389}
2390
2391/// isArrow - Return true if the base expression is a pointer to vector,
2392/// return false if the base expression is a vector.
2393bool ExtVectorElementExpr::isArrow() const {
2394  return getBase()->getType()->isPointerType();
2395}
2396
2397unsigned ExtVectorElementExpr::getNumElements() const {
2398  if (const VectorType *VT = getType()->getAs<VectorType>())
2399    return VT->getNumElements();
2400  return 1;
2401}
2402
2403/// containsDuplicateElements - Return true if any element access is repeated.
2404bool ExtVectorElementExpr::containsDuplicateElements() const {
2405  // FIXME: Refactor this code to an accessor on the AST node which returns the
2406  // "type" of component access, and share with code below and in Sema.
2407  llvm::StringRef Comp = Accessor->getName();
2408
2409  // Halving swizzles do not contain duplicate elements.
2410  if (Comp == "hi" || Comp == "lo" || Comp == "even" || Comp == "odd")
2411    return false;
2412
2413  // Advance past s-char prefix on hex swizzles.
2414  if (Comp[0] == 's' || Comp[0] == 'S')
2415    Comp = Comp.substr(1);
2416
2417  for (unsigned i = 0, e = Comp.size(); i != e; ++i)
2418    if (Comp.substr(i + 1).find(Comp[i]) != llvm::StringRef::npos)
2419        return true;
2420
2421  return false;
2422}
2423
2424/// getEncodedElementAccess - We encode the fields as a llvm ConstantArray.
2425void ExtVectorElementExpr::getEncodedElementAccess(
2426                                  llvm::SmallVectorImpl<unsigned> &Elts) const {
2427  llvm::StringRef Comp = Accessor->getName();
2428  if (Comp[0] == 's' || Comp[0] == 'S')
2429    Comp = Comp.substr(1);
2430
2431  bool isHi =   Comp == "hi";
2432  bool isLo =   Comp == "lo";
2433  bool isEven = Comp == "even";
2434  bool isOdd  = Comp == "odd";
2435
2436  for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
2437    uint64_t Index;
2438
2439    if (isHi)
2440      Index = e + i;
2441    else if (isLo)
2442      Index = i;
2443    else if (isEven)
2444      Index = 2 * i;
2445    else if (isOdd)
2446      Index = 2 * i + 1;
2447    else
2448      Index = ExtVectorType::getAccessorIdx(Comp[i]);
2449
2450    Elts.push_back(Index);
2451  }
2452}
2453
2454ObjCMessageExpr::ObjCMessageExpr(QualType T,
2455                                 ExprValueKind VK,
2456                                 SourceLocation LBracLoc,
2457                                 SourceLocation SuperLoc,
2458                                 bool IsInstanceSuper,
2459                                 QualType SuperType,
2460                                 Selector Sel,
2461                                 SourceLocation SelLoc,
2462                                 ObjCMethodDecl *Method,
2463                                 Expr **Args, unsigned NumArgs,
2464                                 SourceLocation RBracLoc)
2465  : Expr(ObjCMessageExprClass, T, VK, OK_Ordinary,
2466         /*TypeDependent=*/false, /*ValueDependent=*/false,
2467         /*ContainsUnexpandedParameterPack=*/false),
2468    NumArgs(NumArgs), Kind(IsInstanceSuper? SuperInstance : SuperClass),
2469    HasMethod(Method != 0), SuperLoc(SuperLoc),
2470    SelectorOrMethod(reinterpret_cast<uintptr_t>(Method? Method
2471                                                       : Sel.getAsOpaquePtr())),
2472    SelectorLoc(SelLoc), LBracLoc(LBracLoc), RBracLoc(RBracLoc)
2473{
2474  setReceiverPointer(SuperType.getAsOpaquePtr());
2475  if (NumArgs)
2476    memcpy(getArgs(), Args, NumArgs * sizeof(Expr *));
2477}
2478
2479ObjCMessageExpr::ObjCMessageExpr(QualType T,
2480                                 ExprValueKind VK,
2481                                 SourceLocation LBracLoc,
2482                                 TypeSourceInfo *Receiver,
2483                                 Selector Sel,
2484                                 SourceLocation SelLoc,
2485                                 ObjCMethodDecl *Method,
2486                                 Expr **Args, unsigned NumArgs,
2487                                 SourceLocation RBracLoc)
2488  : Expr(ObjCMessageExprClass, T, VK, OK_Ordinary, T->isDependentType(),
2489         T->isDependentType(), T->containsUnexpandedParameterPack()),
2490    NumArgs(NumArgs), Kind(Class), HasMethod(Method != 0),
2491    SelectorOrMethod(reinterpret_cast<uintptr_t>(Method? Method
2492                                                       : Sel.getAsOpaquePtr())),
2493    SelectorLoc(SelLoc), LBracLoc(LBracLoc), RBracLoc(RBracLoc)
2494{
2495  setReceiverPointer(Receiver);
2496  Expr **MyArgs = getArgs();
2497  for (unsigned I = 0; I != NumArgs; ++I) {
2498    if (Args[I]->isTypeDependent())
2499      ExprBits.TypeDependent = true;
2500    if (Args[I]->isValueDependent())
2501      ExprBits.ValueDependent = true;
2502    if (Args[I]->containsUnexpandedParameterPack())
2503      ExprBits.ContainsUnexpandedParameterPack = true;
2504
2505    MyArgs[I] = Args[I];
2506  }
2507}
2508
2509ObjCMessageExpr::ObjCMessageExpr(QualType T,
2510                                 ExprValueKind VK,
2511                                 SourceLocation LBracLoc,
2512                                 Expr *Receiver,
2513                                 Selector Sel,
2514                                 SourceLocation SelLoc,
2515                                 ObjCMethodDecl *Method,
2516                                 Expr **Args, unsigned NumArgs,
2517                                 SourceLocation RBracLoc)
2518  : Expr(ObjCMessageExprClass, T, VK, OK_Ordinary, Receiver->isTypeDependent(),
2519         Receiver->isTypeDependent(),
2520         Receiver->containsUnexpandedParameterPack()),
2521    NumArgs(NumArgs), Kind(Instance), HasMethod(Method != 0),
2522    SelectorOrMethod(reinterpret_cast<uintptr_t>(Method? Method
2523                                                       : Sel.getAsOpaquePtr())),
2524    SelectorLoc(SelLoc), LBracLoc(LBracLoc), RBracLoc(RBracLoc)
2525{
2526  setReceiverPointer(Receiver);
2527  Expr **MyArgs = getArgs();
2528  for (unsigned I = 0; I != NumArgs; ++I) {
2529    if (Args[I]->isTypeDependent())
2530      ExprBits.TypeDependent = true;
2531    if (Args[I]->isValueDependent())
2532      ExprBits.ValueDependent = true;
2533    if (Args[I]->containsUnexpandedParameterPack())
2534      ExprBits.ContainsUnexpandedParameterPack = true;
2535
2536    MyArgs[I] = Args[I];
2537  }
2538}
2539
2540ObjCMessageExpr *ObjCMessageExpr::Create(ASTContext &Context, QualType T,
2541                                         ExprValueKind VK,
2542                                         SourceLocation LBracLoc,
2543                                         SourceLocation SuperLoc,
2544                                         bool IsInstanceSuper,
2545                                         QualType SuperType,
2546                                         Selector Sel,
2547                                         SourceLocation SelLoc,
2548                                         ObjCMethodDecl *Method,
2549                                         Expr **Args, unsigned NumArgs,
2550                                         SourceLocation RBracLoc) {
2551  unsigned Size = sizeof(ObjCMessageExpr) + sizeof(void *) +
2552    NumArgs * sizeof(Expr *);
2553  void *Mem = Context.Allocate(Size, llvm::AlignOf<ObjCMessageExpr>::Alignment);
2554  return new (Mem) ObjCMessageExpr(T, VK, LBracLoc, SuperLoc, IsInstanceSuper,
2555                                   SuperType, Sel, SelLoc, Method, Args,NumArgs,
2556                                   RBracLoc);
2557}
2558
2559ObjCMessageExpr *ObjCMessageExpr::Create(ASTContext &Context, QualType T,
2560                                         ExprValueKind VK,
2561                                         SourceLocation LBracLoc,
2562                                         TypeSourceInfo *Receiver,
2563                                         Selector Sel,
2564                                         SourceLocation SelLoc,
2565                                         ObjCMethodDecl *Method,
2566                                         Expr **Args, unsigned NumArgs,
2567                                         SourceLocation RBracLoc) {
2568  unsigned Size = sizeof(ObjCMessageExpr) + sizeof(void *) +
2569    NumArgs * sizeof(Expr *);
2570  void *Mem = Context.Allocate(Size, llvm::AlignOf<ObjCMessageExpr>::Alignment);
2571  return new (Mem) ObjCMessageExpr(T, VK, LBracLoc, Receiver, Sel, SelLoc,
2572                                   Method, Args, NumArgs, RBracLoc);
2573}
2574
2575ObjCMessageExpr *ObjCMessageExpr::Create(ASTContext &Context, QualType T,
2576                                         ExprValueKind VK,
2577                                         SourceLocation LBracLoc,
2578                                         Expr *Receiver,
2579                                         Selector Sel,
2580                                         SourceLocation SelLoc,
2581                                         ObjCMethodDecl *Method,
2582                                         Expr **Args, unsigned NumArgs,
2583                                         SourceLocation RBracLoc) {
2584  unsigned Size = sizeof(ObjCMessageExpr) + sizeof(void *) +
2585    NumArgs * sizeof(Expr *);
2586  void *Mem = Context.Allocate(Size, llvm::AlignOf<ObjCMessageExpr>::Alignment);
2587  return new (Mem) ObjCMessageExpr(T, VK, LBracLoc, Receiver, Sel, SelLoc,
2588                                   Method, Args, NumArgs, RBracLoc);
2589}
2590
2591ObjCMessageExpr *ObjCMessageExpr::CreateEmpty(ASTContext &Context,
2592                                              unsigned NumArgs) {
2593  unsigned Size = sizeof(ObjCMessageExpr) + sizeof(void *) +
2594    NumArgs * sizeof(Expr *);
2595  void *Mem = Context.Allocate(Size, llvm::AlignOf<ObjCMessageExpr>::Alignment);
2596  return new (Mem) ObjCMessageExpr(EmptyShell(), NumArgs);
2597}
2598
2599SourceRange ObjCMessageExpr::getReceiverRange() const {
2600  switch (getReceiverKind()) {
2601  case Instance:
2602    return getInstanceReceiver()->getSourceRange();
2603
2604  case Class:
2605    return getClassReceiverTypeInfo()->getTypeLoc().getSourceRange();
2606
2607  case SuperInstance:
2608  case SuperClass:
2609    return getSuperLoc();
2610  }
2611
2612  return SourceLocation();
2613}
2614
2615Selector ObjCMessageExpr::getSelector() const {
2616  if (HasMethod)
2617    return reinterpret_cast<const ObjCMethodDecl *>(SelectorOrMethod)
2618                                                               ->getSelector();
2619  return Selector(SelectorOrMethod);
2620}
2621
2622ObjCInterfaceDecl *ObjCMessageExpr::getReceiverInterface() const {
2623  switch (getReceiverKind()) {
2624  case Instance:
2625    if (const ObjCObjectPointerType *Ptr
2626          = getInstanceReceiver()->getType()->getAs<ObjCObjectPointerType>())
2627      return Ptr->getInterfaceDecl();
2628    break;
2629
2630  case Class:
2631    if (const ObjCObjectType *Ty
2632          = getClassReceiver()->getAs<ObjCObjectType>())
2633      return Ty->getInterface();
2634    break;
2635
2636  case SuperInstance:
2637    if (const ObjCObjectPointerType *Ptr
2638          = getSuperType()->getAs<ObjCObjectPointerType>())
2639      return Ptr->getInterfaceDecl();
2640    break;
2641
2642  case SuperClass:
2643    if (const ObjCObjectType *Iface
2644          = getSuperType()->getAs<ObjCObjectType>())
2645      return Iface->getInterface();
2646    break;
2647  }
2648
2649  return 0;
2650}
2651
2652bool ChooseExpr::isConditionTrue(const ASTContext &C) const {
2653  return getCond()->EvaluateAsInt(C) != 0;
2654}
2655
2656ShuffleVectorExpr::ShuffleVectorExpr(ASTContext &C, Expr **args, unsigned nexpr,
2657                                     QualType Type, SourceLocation BLoc,
2658                                     SourceLocation RP)
2659   : Expr(ShuffleVectorExprClass, Type, VK_RValue, OK_Ordinary,
2660          Type->isDependentType(), Type->isDependentType(),
2661          Type->containsUnexpandedParameterPack()),
2662     BuiltinLoc(BLoc), RParenLoc(RP), NumExprs(nexpr)
2663{
2664  SubExprs = new (C) Stmt*[nexpr];
2665  for (unsigned i = 0; i < nexpr; i++) {
2666    if (args[i]->isTypeDependent())
2667      ExprBits.TypeDependent = true;
2668    if (args[i]->isValueDependent())
2669      ExprBits.ValueDependent = true;
2670    if (args[i]->containsUnexpandedParameterPack())
2671      ExprBits.ContainsUnexpandedParameterPack = true;
2672
2673    SubExprs[i] = args[i];
2674  }
2675}
2676
2677void ShuffleVectorExpr::setExprs(ASTContext &C, Expr ** Exprs,
2678                                 unsigned NumExprs) {
2679  if (SubExprs) C.Deallocate(SubExprs);
2680
2681  SubExprs = new (C) Stmt* [NumExprs];
2682  this->NumExprs = NumExprs;
2683  memcpy(SubExprs, Exprs, sizeof(Expr *) * NumExprs);
2684}
2685
2686GenericSelectionExpr::GenericSelectionExpr(ASTContext &Context,
2687                               SourceLocation GenericLoc, Expr *ControllingExpr,
2688                               TypeSourceInfo **AssocTypes, Expr **AssocExprs,
2689                               unsigned NumAssocs, SourceLocation DefaultLoc,
2690                               SourceLocation RParenLoc,
2691                               bool ContainsUnexpandedParameterPack,
2692                               unsigned ResultIndex)
2693  : Expr(GenericSelectionExprClass,
2694         AssocExprs[ResultIndex]->getType(),
2695         AssocExprs[ResultIndex]->getValueKind(),
2696         AssocExprs[ResultIndex]->getObjectKind(),
2697         AssocExprs[ResultIndex]->isTypeDependent(),
2698         AssocExprs[ResultIndex]->isValueDependent(),
2699         ContainsUnexpandedParameterPack),
2700    AssocTypes(new (Context) TypeSourceInfo*[NumAssocs]),
2701    SubExprs(new (Context) Stmt*[END_EXPR+NumAssocs]), NumAssocs(NumAssocs),
2702    ResultIndex(ResultIndex), GenericLoc(GenericLoc), DefaultLoc(DefaultLoc),
2703    RParenLoc(RParenLoc) {
2704  SubExprs[CONTROLLING] = ControllingExpr;
2705  std::copy(AssocTypes, AssocTypes+NumAssocs, this->AssocTypes);
2706  std::copy(AssocExprs, AssocExprs+NumAssocs, SubExprs+END_EXPR);
2707}
2708
2709GenericSelectionExpr::GenericSelectionExpr(ASTContext &Context,
2710                               SourceLocation GenericLoc, Expr *ControllingExpr,
2711                               TypeSourceInfo **AssocTypes, Expr **AssocExprs,
2712                               unsigned NumAssocs, SourceLocation DefaultLoc,
2713                               SourceLocation RParenLoc,
2714                               bool ContainsUnexpandedParameterPack)
2715  : Expr(GenericSelectionExprClass,
2716         Context.DependentTy,
2717         VK_RValue,
2718         OK_Ordinary,
2719         /*isTypeDependent=*/  true,
2720         /*isValueDependent=*/ true,
2721         ContainsUnexpandedParameterPack),
2722    AssocTypes(new (Context) TypeSourceInfo*[NumAssocs]),
2723    SubExprs(new (Context) Stmt*[END_EXPR+NumAssocs]), NumAssocs(NumAssocs),
2724    ResultIndex(-1U), GenericLoc(GenericLoc), DefaultLoc(DefaultLoc),
2725    RParenLoc(RParenLoc) {
2726  SubExprs[CONTROLLING] = ControllingExpr;
2727  std::copy(AssocTypes, AssocTypes+NumAssocs, this->AssocTypes);
2728  std::copy(AssocExprs, AssocExprs+NumAssocs, SubExprs+END_EXPR);
2729}
2730
2731//===----------------------------------------------------------------------===//
2732//  DesignatedInitExpr
2733//===----------------------------------------------------------------------===//
2734
2735IdentifierInfo *DesignatedInitExpr::Designator::getFieldName() {
2736  assert(Kind == FieldDesignator && "Only valid on a field designator");
2737  if (Field.NameOrField & 0x01)
2738    return reinterpret_cast<IdentifierInfo *>(Field.NameOrField&~0x01);
2739  else
2740    return getField()->getIdentifier();
2741}
2742
2743DesignatedInitExpr::DesignatedInitExpr(ASTContext &C, QualType Ty,
2744                                       unsigned NumDesignators,
2745                                       const Designator *Designators,
2746                                       SourceLocation EqualOrColonLoc,
2747                                       bool GNUSyntax,
2748                                       Expr **IndexExprs,
2749                                       unsigned NumIndexExprs,
2750                                       Expr *Init)
2751  : Expr(DesignatedInitExprClass, Ty,
2752         Init->getValueKind(), Init->getObjectKind(),
2753         Init->isTypeDependent(), Init->isValueDependent(),
2754         Init->containsUnexpandedParameterPack()),
2755    EqualOrColonLoc(EqualOrColonLoc), GNUSyntax(GNUSyntax),
2756    NumDesignators(NumDesignators), NumSubExprs(NumIndexExprs + 1) {
2757  this->Designators = new (C) Designator[NumDesignators];
2758
2759  // Record the initializer itself.
2760  child_range Child = children();
2761  *Child++ = Init;
2762
2763  // Copy the designators and their subexpressions, computing
2764  // value-dependence along the way.
2765  unsigned IndexIdx = 0;
2766  for (unsigned I = 0; I != NumDesignators; ++I) {
2767    this->Designators[I] = Designators[I];
2768
2769    if (this->Designators[I].isArrayDesignator()) {
2770      // Compute type- and value-dependence.
2771      Expr *Index = IndexExprs[IndexIdx];
2772      if (Index->isTypeDependent() || Index->isValueDependent())
2773        ExprBits.ValueDependent = true;
2774
2775      // Propagate unexpanded parameter packs.
2776      if (Index->containsUnexpandedParameterPack())
2777        ExprBits.ContainsUnexpandedParameterPack = true;
2778
2779      // Copy the index expressions into permanent storage.
2780      *Child++ = IndexExprs[IndexIdx++];
2781    } else if (this->Designators[I].isArrayRangeDesignator()) {
2782      // Compute type- and value-dependence.
2783      Expr *Start = IndexExprs[IndexIdx];
2784      Expr *End = IndexExprs[IndexIdx + 1];
2785      if (Start->isTypeDependent() || Start->isValueDependent() ||
2786          End->isTypeDependent() || End->isValueDependent())
2787        ExprBits.ValueDependent = true;
2788
2789      // Propagate unexpanded parameter packs.
2790      if (Start->containsUnexpandedParameterPack() ||
2791          End->containsUnexpandedParameterPack())
2792        ExprBits.ContainsUnexpandedParameterPack = true;
2793
2794      // Copy the start/end expressions into permanent storage.
2795      *Child++ = IndexExprs[IndexIdx++];
2796      *Child++ = IndexExprs[IndexIdx++];
2797    }
2798  }
2799
2800  assert(IndexIdx == NumIndexExprs && "Wrong number of index expressions");
2801}
2802
2803DesignatedInitExpr *
2804DesignatedInitExpr::Create(ASTContext &C, Designator *Designators,
2805                           unsigned NumDesignators,
2806                           Expr **IndexExprs, unsigned NumIndexExprs,
2807                           SourceLocation ColonOrEqualLoc,
2808                           bool UsesColonSyntax, Expr *Init) {
2809  void *Mem = C.Allocate(sizeof(DesignatedInitExpr) +
2810                         sizeof(Stmt *) * (NumIndexExprs + 1), 8);
2811  return new (Mem) DesignatedInitExpr(C, C.VoidTy, NumDesignators, Designators,
2812                                      ColonOrEqualLoc, UsesColonSyntax,
2813                                      IndexExprs, NumIndexExprs, Init);
2814}
2815
2816DesignatedInitExpr *DesignatedInitExpr::CreateEmpty(ASTContext &C,
2817                                                    unsigned NumIndexExprs) {
2818  void *Mem = C.Allocate(sizeof(DesignatedInitExpr) +
2819                         sizeof(Stmt *) * (NumIndexExprs + 1), 8);
2820  return new (Mem) DesignatedInitExpr(NumIndexExprs + 1);
2821}
2822
2823void DesignatedInitExpr::setDesignators(ASTContext &C,
2824                                        const Designator *Desigs,
2825                                        unsigned NumDesigs) {
2826  Designators = new (C) Designator[NumDesigs];
2827  NumDesignators = NumDesigs;
2828  for (unsigned I = 0; I != NumDesigs; ++I)
2829    Designators[I] = Desigs[I];
2830}
2831
2832SourceRange DesignatedInitExpr::getDesignatorsSourceRange() const {
2833  DesignatedInitExpr *DIE = const_cast<DesignatedInitExpr*>(this);
2834  if (size() == 1)
2835    return DIE->getDesignator(0)->getSourceRange();
2836  return SourceRange(DIE->getDesignator(0)->getStartLocation(),
2837                     DIE->getDesignator(size()-1)->getEndLocation());
2838}
2839
2840SourceRange DesignatedInitExpr::getSourceRange() const {
2841  SourceLocation StartLoc;
2842  Designator &First =
2843    *const_cast<DesignatedInitExpr*>(this)->designators_begin();
2844  if (First.isFieldDesignator()) {
2845    if (GNUSyntax)
2846      StartLoc = SourceLocation::getFromRawEncoding(First.Field.FieldLoc);
2847    else
2848      StartLoc = SourceLocation::getFromRawEncoding(First.Field.DotLoc);
2849  } else
2850    StartLoc =
2851      SourceLocation::getFromRawEncoding(First.ArrayOrRange.LBracketLoc);
2852  return SourceRange(StartLoc, getInit()->getSourceRange().getEnd());
2853}
2854
2855Expr *DesignatedInitExpr::getArrayIndex(const Designator& D) {
2856  assert(D.Kind == Designator::ArrayDesignator && "Requires array designator");
2857  char* Ptr = static_cast<char*>(static_cast<void *>(this));
2858  Ptr += sizeof(DesignatedInitExpr);
2859  Stmt **SubExprs = reinterpret_cast<Stmt**>(reinterpret_cast<void**>(Ptr));
2860  return cast<Expr>(*(SubExprs + D.ArrayOrRange.Index + 1));
2861}
2862
2863Expr *DesignatedInitExpr::getArrayRangeStart(const Designator& D) {
2864  assert(D.Kind == Designator::ArrayRangeDesignator &&
2865         "Requires array range designator");
2866  char* Ptr = static_cast<char*>(static_cast<void *>(this));
2867  Ptr += sizeof(DesignatedInitExpr);
2868  Stmt **SubExprs = reinterpret_cast<Stmt**>(reinterpret_cast<void**>(Ptr));
2869  return cast<Expr>(*(SubExprs + D.ArrayOrRange.Index + 1));
2870}
2871
2872Expr *DesignatedInitExpr::getArrayRangeEnd(const Designator& D) {
2873  assert(D.Kind == Designator::ArrayRangeDesignator &&
2874         "Requires array range designator");
2875  char* Ptr = static_cast<char*>(static_cast<void *>(this));
2876  Ptr += sizeof(DesignatedInitExpr);
2877  Stmt **SubExprs = reinterpret_cast<Stmt**>(reinterpret_cast<void**>(Ptr));
2878  return cast<Expr>(*(SubExprs + D.ArrayOrRange.Index + 2));
2879}
2880
2881/// \brief Replaces the designator at index @p Idx with the series
2882/// of designators in [First, Last).
2883void DesignatedInitExpr::ExpandDesignator(ASTContext &C, unsigned Idx,
2884                                          const Designator *First,
2885                                          const Designator *Last) {
2886  unsigned NumNewDesignators = Last - First;
2887  if (NumNewDesignators == 0) {
2888    std::copy_backward(Designators + Idx + 1,
2889                       Designators + NumDesignators,
2890                       Designators + Idx);
2891    --NumNewDesignators;
2892    return;
2893  } else if (NumNewDesignators == 1) {
2894    Designators[Idx] = *First;
2895    return;
2896  }
2897
2898  Designator *NewDesignators
2899    = new (C) Designator[NumDesignators - 1 + NumNewDesignators];
2900  std::copy(Designators, Designators + Idx, NewDesignators);
2901  std::copy(First, Last, NewDesignators + Idx);
2902  std::copy(Designators + Idx + 1, Designators + NumDesignators,
2903            NewDesignators + Idx + NumNewDesignators);
2904  Designators = NewDesignators;
2905  NumDesignators = NumDesignators - 1 + NumNewDesignators;
2906}
2907
2908ParenListExpr::ParenListExpr(ASTContext& C, SourceLocation lparenloc,
2909                             Expr **exprs, unsigned nexprs,
2910                             SourceLocation rparenloc)
2911  : Expr(ParenListExprClass, QualType(), VK_RValue, OK_Ordinary,
2912         false, false, false),
2913    NumExprs(nexprs), LParenLoc(lparenloc), RParenLoc(rparenloc) {
2914
2915  Exprs = new (C) Stmt*[nexprs];
2916  for (unsigned i = 0; i != nexprs; ++i) {
2917    if (exprs[i]->isTypeDependent())
2918      ExprBits.TypeDependent = true;
2919    if (exprs[i]->isValueDependent())
2920      ExprBits.ValueDependent = true;
2921    if (exprs[i]->containsUnexpandedParameterPack())
2922      ExprBits.ContainsUnexpandedParameterPack = true;
2923
2924    Exprs[i] = exprs[i];
2925  }
2926}
2927
2928const OpaqueValueExpr *OpaqueValueExpr::findInCopyConstruct(const Expr *e) {
2929  if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(e))
2930    e = ewc->getSubExpr();
2931  e = cast<CXXConstructExpr>(e)->getArg(0);
2932  while (const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
2933    e = ice->getSubExpr();
2934  return cast<OpaqueValueExpr>(e);
2935}
2936
2937//===----------------------------------------------------------------------===//
2938//  ExprIterator.
2939//===----------------------------------------------------------------------===//
2940
2941Expr* ExprIterator::operator[](size_t idx) { return cast<Expr>(I[idx]); }
2942Expr* ExprIterator::operator*() const { return cast<Expr>(*I); }
2943Expr* ExprIterator::operator->() const { return cast<Expr>(*I); }
2944const Expr* ConstExprIterator::operator[](size_t idx) const {
2945  return cast<Expr>(I[idx]);
2946}
2947const Expr* ConstExprIterator::operator*() const { return cast<Expr>(*I); }
2948const Expr* ConstExprIterator::operator->() const { return cast<Expr>(*I); }
2949
2950//===----------------------------------------------------------------------===//
2951//  Child Iterators for iterating over subexpressions/substatements
2952//===----------------------------------------------------------------------===//
2953
2954// UnaryExprOrTypeTraitExpr
2955Stmt::child_range UnaryExprOrTypeTraitExpr::children() {
2956  // If this is of a type and the type is a VLA type (and not a typedef), the
2957  // size expression of the VLA needs to be treated as an executable expression.
2958  // Why isn't this weirdness documented better in StmtIterator?
2959  if (isArgumentType()) {
2960    if (const VariableArrayType* T = dyn_cast<VariableArrayType>(
2961                                   getArgumentType().getTypePtr()))
2962      return child_range(child_iterator(T), child_iterator());
2963    return child_range();
2964  }
2965  return child_range(&Argument.Ex, &Argument.Ex + 1);
2966}
2967
2968// ObjCMessageExpr
2969Stmt::child_range ObjCMessageExpr::children() {
2970  Stmt **begin;
2971  if (getReceiverKind() == Instance)
2972    begin = reinterpret_cast<Stmt **>(this + 1);
2973  else
2974    begin = reinterpret_cast<Stmt **>(getArgs());
2975  return child_range(begin,
2976                     reinterpret_cast<Stmt **>(getArgs() + getNumArgs()));
2977}
2978
2979// Blocks
2980BlockDeclRefExpr::BlockDeclRefExpr(VarDecl *d, QualType t, ExprValueKind VK,
2981                                   SourceLocation l, bool ByRef,
2982                                   bool constAdded)
2983  : Expr(BlockDeclRefExprClass, t, VK, OK_Ordinary, false, false,
2984         d->isParameterPack()),
2985    D(d), Loc(l), IsByRef(ByRef), ConstQualAdded(constAdded)
2986{
2987  bool TypeDependent = false;
2988  bool ValueDependent = false;
2989  computeDeclRefDependence(D, getType(), TypeDependent, ValueDependent);
2990  ExprBits.TypeDependent = TypeDependent;
2991  ExprBits.ValueDependent = ValueDependent;
2992}
2993
2994