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