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