Expr.cpp revision e1b2abc2ed3f2c98985b06b4ad01c977bd584020
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/EvaluatedExprVisitor.h"
22#include "clang/AST/RecordLayout.h"
23#include "clang/AST/StmtVisitor.h"
24#include "clang/Lex/LiteralSupport.h"
25#include "clang/Lex/Lexer.h"
26#include "clang/Sema/SemaDiagnostic.h"
27#include "clang/Basic/Builtins.h"
28#include "clang/Basic/SourceManager.h"
29#include "clang/Basic/TargetInfo.h"
30#include "llvm/Support/ErrorHandling.h"
31#include "llvm/Support/raw_ostream.h"
32#include <algorithm>
33#include <cstring>
34using namespace clang;
35
36/// isKnownToHaveBooleanValue - Return true if this is an integer expression
37/// that is known to return 0 or 1.  This happens for _Bool/bool expressions
38/// but also int expressions which are produced by things like comparisons in
39/// C.
40bool Expr::isKnownToHaveBooleanValue() const {
41  const Expr *E = IgnoreParens();
42
43  // If this value has _Bool type, it is obvious 0/1.
44  if (E->getType()->isBooleanType()) return true;
45  // If this is a non-scalar-integer type, we don't care enough to try.
46  if (!E->getType()->isIntegralOrEnumerationType()) return false;
47
48  if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
49    switch (UO->getOpcode()) {
50    case UO_Plus:
51      return UO->getSubExpr()->isKnownToHaveBooleanValue();
52    default:
53      return false;
54    }
55  }
56
57  // Only look through implicit casts.  If the user writes
58  // '(int) (a && b)' treat it as an arbitrary int.
59  if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
60    return CE->getSubExpr()->isKnownToHaveBooleanValue();
61
62  if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
63    switch (BO->getOpcode()) {
64    default: return false;
65    case BO_LT:   // Relational operators.
66    case BO_GT:
67    case BO_LE:
68    case BO_GE:
69    case BO_EQ:   // Equality operators.
70    case BO_NE:
71    case BO_LAnd: // AND operator.
72    case BO_LOr:  // Logical OR operator.
73      return true;
74
75    case BO_And:  // Bitwise AND operator.
76    case BO_Xor:  // Bitwise XOR operator.
77    case BO_Or:   // Bitwise OR operator.
78      // Handle things like (x==2)|(y==12).
79      return BO->getLHS()->isKnownToHaveBooleanValue() &&
80             BO->getRHS()->isKnownToHaveBooleanValue();
81
82    case BO_Comma:
83    case BO_Assign:
84      return BO->getRHS()->isKnownToHaveBooleanValue();
85    }
86  }
87
88  if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
89    return CO->getTrueExpr()->isKnownToHaveBooleanValue() &&
90           CO->getFalseExpr()->isKnownToHaveBooleanValue();
91
92  return false;
93}
94
95// Amusing macro metaprogramming hack: check whether a class provides
96// a more specific implementation of getExprLoc().
97//
98// See also Stmt.cpp:{getLocStart(),getLocEnd()}.
99namespace {
100  /// This implementation is used when a class provides a custom
101  /// implementation of getExprLoc.
102  template <class E, class T>
103  SourceLocation getExprLocImpl(const Expr *expr,
104                                SourceLocation (T::*v)() const) {
105    return static_cast<const E*>(expr)->getExprLoc();
106  }
107
108  /// This implementation is used when a class doesn't provide
109  /// a custom implementation of getExprLoc.  Overload resolution
110  /// should pick it over the implementation above because it's
111  /// more specialized according to function template partial ordering.
112  template <class E>
113  SourceLocation getExprLocImpl(const Expr *expr,
114                                SourceLocation (Expr::*v)() const) {
115    return static_cast<const E*>(expr)->getLocStart();
116  }
117}
118
119SourceLocation Expr::getExprLoc() const {
120  switch (getStmtClass()) {
121  case Stmt::NoStmtClass: llvm_unreachable("statement without class");
122#define ABSTRACT_STMT(type)
123#define STMT(type, base) \
124  case Stmt::type##Class: llvm_unreachable(#type " is not an Expr"); break;
125#define EXPR(type, base) \
126  case Stmt::type##Class: return getExprLocImpl<type>(this, &type::getExprLoc);
127#include "clang/AST/StmtNodes.inc"
128  }
129  llvm_unreachable("unknown statement kind");
130}
131
132//===----------------------------------------------------------------------===//
133// Primary Expressions.
134//===----------------------------------------------------------------------===//
135
136/// \brief Compute the type-, value-, and instantiation-dependence of a
137/// declaration reference
138/// based on the declaration being referenced.
139static void computeDeclRefDependence(ASTContext &Ctx, NamedDecl *D, QualType T,
140                                     bool &TypeDependent,
141                                     bool &ValueDependent,
142                                     bool &InstantiationDependent) {
143  TypeDependent = false;
144  ValueDependent = false;
145  InstantiationDependent = false;
146
147  // (TD) C++ [temp.dep.expr]p3:
148  //   An id-expression is type-dependent if it contains:
149  //
150  // and
151  //
152  // (VD) C++ [temp.dep.constexpr]p2:
153  //  An identifier is value-dependent if it is:
154
155  //  (TD)  - an identifier that was declared with dependent type
156  //  (VD)  - a name declared with a dependent type,
157  if (T->isDependentType()) {
158    TypeDependent = true;
159    ValueDependent = true;
160    InstantiationDependent = true;
161    return;
162  } else if (T->isInstantiationDependentType()) {
163    InstantiationDependent = true;
164  }
165
166  //  (TD)  - a conversion-function-id that specifies a dependent type
167  if (D->getDeclName().getNameKind()
168                                == DeclarationName::CXXConversionFunctionName) {
169    QualType T = D->getDeclName().getCXXNameType();
170    if (T->isDependentType()) {
171      TypeDependent = true;
172      ValueDependent = true;
173      InstantiationDependent = true;
174      return;
175    }
176
177    if (T->isInstantiationDependentType())
178      InstantiationDependent = true;
179  }
180
181  //  (VD)  - the name of a non-type template parameter,
182  if (isa<NonTypeTemplateParmDecl>(D)) {
183    ValueDependent = true;
184    InstantiationDependent = true;
185    return;
186  }
187
188  //  (VD) - a constant with integral or enumeration type and is
189  //         initialized with an expression that is value-dependent.
190  //  (VD) - a constant with literal type and is initialized with an
191  //         expression that is value-dependent [C++11].
192  //  (VD) - FIXME: Missing from the standard:
193  //       -  an entity with reference type and is initialized with an
194  //          expression that is value-dependent [C++11]
195  if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
196    if ((Ctx.getLangOpts().CPlusPlus0x ?
197           Var->getType()->isLiteralType() :
198           Var->getType()->isIntegralOrEnumerationType()) &&
199        (Var->getType().getCVRQualifiers() == Qualifiers::Const ||
200         Var->getType()->isReferenceType())) {
201      if (const Expr *Init = Var->getAnyInitializer())
202        if (Init->isValueDependent()) {
203          ValueDependent = true;
204          InstantiationDependent = true;
205        }
206    }
207
208    // (VD) - FIXME: Missing from the standard:
209    //      -  a member function or a static data member of the current
210    //         instantiation
211    if (Var->isStaticDataMember() &&
212        Var->getDeclContext()->isDependentContext()) {
213      ValueDependent = true;
214      InstantiationDependent = true;
215    }
216
217    return;
218  }
219
220  // (VD) - FIXME: Missing from the standard:
221  //      -  a member function or a static data member of the current
222  //         instantiation
223  if (isa<CXXMethodDecl>(D) && D->getDeclContext()->isDependentContext()) {
224    ValueDependent = true;
225    InstantiationDependent = true;
226  }
227}
228
229void DeclRefExpr::computeDependence(ASTContext &Ctx) {
230  bool TypeDependent = false;
231  bool ValueDependent = false;
232  bool InstantiationDependent = false;
233  computeDeclRefDependence(Ctx, getDecl(), getType(), TypeDependent,
234                           ValueDependent, InstantiationDependent);
235
236  // (TD) C++ [temp.dep.expr]p3:
237  //   An id-expression is type-dependent if it contains:
238  //
239  // and
240  //
241  // (VD) C++ [temp.dep.constexpr]p2:
242  //  An identifier is value-dependent if it is:
243  if (!TypeDependent && !ValueDependent &&
244      hasExplicitTemplateArgs() &&
245      TemplateSpecializationType::anyDependentTemplateArguments(
246                                                            getTemplateArgs(),
247                                                       getNumTemplateArgs(),
248                                                      InstantiationDependent)) {
249    TypeDependent = true;
250    ValueDependent = true;
251    InstantiationDependent = true;
252  }
253
254  ExprBits.TypeDependent = TypeDependent;
255  ExprBits.ValueDependent = ValueDependent;
256  ExprBits.InstantiationDependent = InstantiationDependent;
257
258  // Is the declaration a parameter pack?
259  if (getDecl()->isParameterPack())
260    ExprBits.ContainsUnexpandedParameterPack = true;
261}
262
263DeclRefExpr::DeclRefExpr(ASTContext &Ctx,
264                         NestedNameSpecifierLoc QualifierLoc,
265                         SourceLocation TemplateKWLoc,
266                         ValueDecl *D, bool RefersToEnclosingLocal,
267                         const DeclarationNameInfo &NameInfo,
268                         NamedDecl *FoundD,
269                         const TemplateArgumentListInfo *TemplateArgs,
270                         QualType T, ExprValueKind VK)
271  : Expr(DeclRefExprClass, T, VK, OK_Ordinary, false, false, false, false),
272    D(D), Loc(NameInfo.getLoc()), DNLoc(NameInfo.getInfo()) {
273  DeclRefExprBits.HasQualifier = QualifierLoc ? 1 : 0;
274  if (QualifierLoc)
275    getInternalQualifierLoc() = QualifierLoc;
276  DeclRefExprBits.HasFoundDecl = FoundD ? 1 : 0;
277  if (FoundD)
278    getInternalFoundDecl() = FoundD;
279  DeclRefExprBits.HasTemplateKWAndArgsInfo
280    = (TemplateArgs || TemplateKWLoc.isValid()) ? 1 : 0;
281  DeclRefExprBits.RefersToEnclosingLocal = RefersToEnclosingLocal;
282  if (TemplateArgs) {
283    bool Dependent = false;
284    bool InstantiationDependent = false;
285    bool ContainsUnexpandedParameterPack = false;
286    getTemplateKWAndArgsInfo()->initializeFrom(TemplateKWLoc, *TemplateArgs,
287                                               Dependent,
288                                               InstantiationDependent,
289                                               ContainsUnexpandedParameterPack);
290    if (InstantiationDependent)
291      setInstantiationDependent(true);
292  } else if (TemplateKWLoc.isValid()) {
293    getTemplateKWAndArgsInfo()->initializeFrom(TemplateKWLoc);
294  }
295  DeclRefExprBits.HadMultipleCandidates = 0;
296
297  computeDependence(Ctx);
298}
299
300DeclRefExpr *DeclRefExpr::Create(ASTContext &Context,
301                                 NestedNameSpecifierLoc QualifierLoc,
302                                 SourceLocation TemplateKWLoc,
303                                 ValueDecl *D,
304                                 bool RefersToEnclosingLocal,
305                                 SourceLocation NameLoc,
306                                 QualType T,
307                                 ExprValueKind VK,
308                                 NamedDecl *FoundD,
309                                 const TemplateArgumentListInfo *TemplateArgs) {
310  return Create(Context, QualifierLoc, TemplateKWLoc, D,
311                RefersToEnclosingLocal,
312                DeclarationNameInfo(D->getDeclName(), NameLoc),
313                T, VK, FoundD, TemplateArgs);
314}
315
316DeclRefExpr *DeclRefExpr::Create(ASTContext &Context,
317                                 NestedNameSpecifierLoc QualifierLoc,
318                                 SourceLocation TemplateKWLoc,
319                                 ValueDecl *D,
320                                 bool RefersToEnclosingLocal,
321                                 const DeclarationNameInfo &NameInfo,
322                                 QualType T,
323                                 ExprValueKind VK,
324                                 NamedDecl *FoundD,
325                                 const TemplateArgumentListInfo *TemplateArgs) {
326  // Filter out cases where the found Decl is the same as the value refenenced.
327  if (D == FoundD)
328    FoundD = 0;
329
330  std::size_t Size = sizeof(DeclRefExpr);
331  if (QualifierLoc != 0)
332    Size += sizeof(NestedNameSpecifierLoc);
333  if (FoundD)
334    Size += sizeof(NamedDecl *);
335  if (TemplateArgs)
336    Size += ASTTemplateKWAndArgsInfo::sizeFor(TemplateArgs->size());
337  else if (TemplateKWLoc.isValid())
338    Size += ASTTemplateKWAndArgsInfo::sizeFor(0);
339
340  void *Mem = Context.Allocate(Size, llvm::alignOf<DeclRefExpr>());
341  return new (Mem) DeclRefExpr(Context, QualifierLoc, TemplateKWLoc, D,
342                               RefersToEnclosingLocal,
343                               NameInfo, FoundD, TemplateArgs, T, VK);
344}
345
346DeclRefExpr *DeclRefExpr::CreateEmpty(ASTContext &Context,
347                                      bool HasQualifier,
348                                      bool HasFoundDecl,
349                                      bool HasTemplateKWAndArgsInfo,
350                                      unsigned NumTemplateArgs) {
351  std::size_t Size = sizeof(DeclRefExpr);
352  if (HasQualifier)
353    Size += sizeof(NestedNameSpecifierLoc);
354  if (HasFoundDecl)
355    Size += sizeof(NamedDecl *);
356  if (HasTemplateKWAndArgsInfo)
357    Size += ASTTemplateKWAndArgsInfo::sizeFor(NumTemplateArgs);
358
359  void *Mem = Context.Allocate(Size, llvm::alignOf<DeclRefExpr>());
360  return new (Mem) DeclRefExpr(EmptyShell());
361}
362
363SourceRange DeclRefExpr::getSourceRange() const {
364  SourceRange R = getNameInfo().getSourceRange();
365  if (hasQualifier())
366    R.setBegin(getQualifierLoc().getBeginLoc());
367  if (hasExplicitTemplateArgs())
368    R.setEnd(getRAngleLoc());
369  return R;
370}
371SourceLocation DeclRefExpr::getLocStart() const {
372  if (hasQualifier())
373    return getQualifierLoc().getBeginLoc();
374  return getNameInfo().getLocStart();
375}
376SourceLocation DeclRefExpr::getLocEnd() const {
377  if (hasExplicitTemplateArgs())
378    return getRAngleLoc();
379  return getNameInfo().getLocEnd();
380}
381
382// FIXME: Maybe this should use DeclPrinter with a special "print predefined
383// expr" policy instead.
384std::string PredefinedExpr::ComputeName(IdentType IT, const Decl *CurrentDecl) {
385  ASTContext &Context = CurrentDecl->getASTContext();
386
387  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CurrentDecl)) {
388    if (IT != PrettyFunction && IT != PrettyFunctionNoVirtual)
389      return FD->getNameAsString();
390
391    SmallString<256> Name;
392    llvm::raw_svector_ostream Out(Name);
393
394    if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
395      if (MD->isVirtual() && IT != PrettyFunctionNoVirtual)
396        Out << "virtual ";
397      if (MD->isStatic())
398        Out << "static ";
399    }
400
401    PrintingPolicy Policy(Context.getLangOpts());
402    std::string Proto = FD->getQualifiedNameAsString(Policy);
403    llvm::raw_string_ostream POut(Proto);
404
405    const FunctionDecl *Decl = FD;
406    if (const FunctionDecl* Pattern = FD->getTemplateInstantiationPattern())
407      Decl = Pattern;
408    const FunctionType *AFT = Decl->getType()->getAs<FunctionType>();
409    const FunctionProtoType *FT = 0;
410    if (FD->hasWrittenPrototype())
411      FT = dyn_cast<FunctionProtoType>(AFT);
412
413    POut << "(";
414    if (FT) {
415      for (unsigned i = 0, e = Decl->getNumParams(); i != e; ++i) {
416        if (i) POut << ", ";
417        std::string Param;
418        Decl->getParamDecl(i)->getType().getAsStringInternal(Param, Policy);
419        POut << Param;
420      }
421
422      if (FT->isVariadic()) {
423        if (FD->getNumParams()) POut << ", ";
424        POut << "...";
425      }
426    }
427    POut << ")";
428
429    if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
430      Qualifiers ThisQuals = Qualifiers::fromCVRMask(MD->getTypeQualifiers());
431      if (ThisQuals.hasConst())
432        POut << " const";
433      if (ThisQuals.hasVolatile())
434        POut << " volatile";
435      RefQualifierKind Ref = MD->getRefQualifier();
436      if (Ref == RQ_LValue)
437        POut << " &";
438      else if (Ref == RQ_RValue)
439        POut << " &&";
440    }
441
442    typedef SmallVector<const ClassTemplateSpecializationDecl *, 8> SpecsTy;
443    SpecsTy Specs;
444    const DeclContext *Ctx = FD->getDeclContext();
445    while (Ctx && isa<NamedDecl>(Ctx)) {
446      const ClassTemplateSpecializationDecl *Spec
447                               = dyn_cast<ClassTemplateSpecializationDecl>(Ctx);
448      if (Spec && !Spec->isExplicitSpecialization())
449        Specs.push_back(Spec);
450      Ctx = Ctx->getParent();
451    }
452
453    std::string TemplateParams;
454    llvm::raw_string_ostream TOut(TemplateParams);
455    for (SpecsTy::reverse_iterator I = Specs.rbegin(), E = Specs.rend();
456         I != E; ++I) {
457      const TemplateParameterList *Params
458                  = (*I)->getSpecializedTemplate()->getTemplateParameters();
459      const TemplateArgumentList &Args = (*I)->getTemplateArgs();
460      assert(Params->size() == Args.size());
461      for (unsigned i = 0, numParams = Params->size(); i != numParams; ++i) {
462        StringRef Param = Params->getParam(i)->getName();
463        if (Param.empty()) continue;
464        TOut << Param << " = ";
465        Args.get(i).print(Policy, TOut);
466        TOut << ", ";
467      }
468    }
469
470    FunctionTemplateSpecializationInfo *FSI
471                                          = FD->getTemplateSpecializationInfo();
472    if (FSI && !FSI->isExplicitSpecialization()) {
473      const TemplateParameterList* Params
474                                  = FSI->getTemplate()->getTemplateParameters();
475      const TemplateArgumentList* Args = FSI->TemplateArguments;
476      assert(Params->size() == Args->size());
477      for (unsigned i = 0, e = Params->size(); i != e; ++i) {
478        StringRef Param = Params->getParam(i)->getName();
479        if (Param.empty()) continue;
480        TOut << Param << " = ";
481        Args->get(i).print(Policy, TOut);
482        TOut << ", ";
483      }
484    }
485
486    TOut.flush();
487    if (!TemplateParams.empty()) {
488      // remove the trailing comma and space
489      TemplateParams.resize(TemplateParams.size() - 2);
490      POut << " [" << TemplateParams << "]";
491    }
492
493    POut.flush();
494
495    if (!isa<CXXConstructorDecl>(FD) && !isa<CXXDestructorDecl>(FD))
496      AFT->getResultType().getAsStringInternal(Proto, Policy);
497
498    Out << Proto;
499
500    Out.flush();
501    return Name.str().str();
502  }
503  if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurrentDecl)) {
504    SmallString<256> Name;
505    llvm::raw_svector_ostream Out(Name);
506    Out << (MD->isInstanceMethod() ? '-' : '+');
507    Out << '[';
508
509    // For incorrect code, there might not be an ObjCInterfaceDecl.  Do
510    // a null check to avoid a crash.
511    if (const ObjCInterfaceDecl *ID = MD->getClassInterface())
512      Out << *ID;
513
514    if (const ObjCCategoryImplDecl *CID =
515        dyn_cast<ObjCCategoryImplDecl>(MD->getDeclContext()))
516      Out << '(' << *CID << ')';
517
518    Out <<  ' ';
519    Out << MD->getSelector().getAsString();
520    Out <<  ']';
521
522    Out.flush();
523    return Name.str().str();
524  }
525  if (isa<TranslationUnitDecl>(CurrentDecl) && IT == PrettyFunction) {
526    // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
527    return "top level";
528  }
529  return "";
530}
531
532void APNumericStorage::setIntValue(ASTContext &C, const llvm::APInt &Val) {
533  if (hasAllocation())
534    C.Deallocate(pVal);
535
536  BitWidth = Val.getBitWidth();
537  unsigned NumWords = Val.getNumWords();
538  const uint64_t* Words = Val.getRawData();
539  if (NumWords > 1) {
540    pVal = new (C) uint64_t[NumWords];
541    std::copy(Words, Words + NumWords, pVal);
542  } else if (NumWords == 1)
543    VAL = Words[0];
544  else
545    VAL = 0;
546}
547
548IntegerLiteral *
549IntegerLiteral::Create(ASTContext &C, const llvm::APInt &V,
550                       QualType type, SourceLocation l) {
551  return new (C) IntegerLiteral(C, V, type, l);
552}
553
554IntegerLiteral *
555IntegerLiteral::Create(ASTContext &C, EmptyShell Empty) {
556  return new (C) IntegerLiteral(Empty);
557}
558
559FloatingLiteral *
560FloatingLiteral::Create(ASTContext &C, const llvm::APFloat &V,
561                        bool isexact, QualType Type, SourceLocation L) {
562  return new (C) FloatingLiteral(C, V, isexact, Type, L);
563}
564
565FloatingLiteral *
566FloatingLiteral::Create(ASTContext &C, EmptyShell Empty) {
567  return new (C) FloatingLiteral(C, Empty);
568}
569
570/// getValueAsApproximateDouble - This returns the value as an inaccurate
571/// double.  Note that this may cause loss of precision, but is useful for
572/// debugging dumps, etc.
573double FloatingLiteral::getValueAsApproximateDouble() const {
574  llvm::APFloat V = getValue();
575  bool ignored;
576  V.convert(llvm::APFloat::IEEEdouble, llvm::APFloat::rmNearestTiesToEven,
577            &ignored);
578  return V.convertToDouble();
579}
580
581int StringLiteral::mapCharByteWidth(TargetInfo const &target,StringKind k) {
582  int CharByteWidth = 0;
583  switch(k) {
584    case Ascii:
585    case UTF8:
586      CharByteWidth = target.getCharWidth();
587      break;
588    case Wide:
589      CharByteWidth = target.getWCharWidth();
590      break;
591    case UTF16:
592      CharByteWidth = target.getChar16Width();
593      break;
594    case UTF32:
595      CharByteWidth = target.getChar32Width();
596      break;
597  }
598  assert((CharByteWidth & 7) == 0 && "Assumes character size is byte multiple");
599  CharByteWidth /= 8;
600  assert((CharByteWidth==1 || CharByteWidth==2 || CharByteWidth==4)
601         && "character byte widths supported are 1, 2, and 4 only");
602  return CharByteWidth;
603}
604
605StringLiteral *StringLiteral::Create(ASTContext &C, StringRef Str,
606                                     StringKind Kind, bool Pascal, QualType Ty,
607                                     const SourceLocation *Loc,
608                                     unsigned NumStrs) {
609  // Allocate enough space for the StringLiteral plus an array of locations for
610  // any concatenated string tokens.
611  void *Mem = C.Allocate(sizeof(StringLiteral)+
612                         sizeof(SourceLocation)*(NumStrs-1),
613                         llvm::alignOf<StringLiteral>());
614  StringLiteral *SL = new (Mem) StringLiteral(Ty);
615
616  // OPTIMIZE: could allocate this appended to the StringLiteral.
617  SL->setString(C,Str,Kind,Pascal);
618
619  SL->TokLocs[0] = Loc[0];
620  SL->NumConcatenated = NumStrs;
621
622  if (NumStrs != 1)
623    memcpy(&SL->TokLocs[1], Loc+1, sizeof(SourceLocation)*(NumStrs-1));
624  return SL;
625}
626
627StringLiteral *StringLiteral::CreateEmpty(ASTContext &C, unsigned NumStrs) {
628  void *Mem = C.Allocate(sizeof(StringLiteral)+
629                         sizeof(SourceLocation)*(NumStrs-1),
630                         llvm::alignOf<StringLiteral>());
631  StringLiteral *SL = new (Mem) StringLiteral(QualType());
632  SL->CharByteWidth = 0;
633  SL->Length = 0;
634  SL->NumConcatenated = NumStrs;
635  return SL;
636}
637
638void StringLiteral::setString(ASTContext &C, StringRef Str,
639                              StringKind Kind, bool IsPascal) {
640  //FIXME: we assume that the string data comes from a target that uses the same
641  // code unit size and endianess for the type of string.
642  this->Kind = Kind;
643  this->IsPascal = IsPascal;
644
645  CharByteWidth = mapCharByteWidth(C.getTargetInfo(),Kind);
646  assert((Str.size()%CharByteWidth == 0)
647         && "size of data must be multiple of CharByteWidth");
648  Length = Str.size()/CharByteWidth;
649
650  switch(CharByteWidth) {
651    case 1: {
652      char *AStrData = new (C) char[Length];
653      std::memcpy(AStrData,Str.data(),Str.size());
654      StrData.asChar = AStrData;
655      break;
656    }
657    case 2: {
658      uint16_t *AStrData = new (C) uint16_t[Length];
659      std::memcpy(AStrData,Str.data(),Str.size());
660      StrData.asUInt16 = AStrData;
661      break;
662    }
663    case 4: {
664      uint32_t *AStrData = new (C) uint32_t[Length];
665      std::memcpy(AStrData,Str.data(),Str.size());
666      StrData.asUInt32 = AStrData;
667      break;
668    }
669    default:
670      assert(false && "unsupported CharByteWidth");
671  }
672}
673
674/// getLocationOfByte - Return a source location that points to the specified
675/// byte of this string literal.
676///
677/// Strings are amazingly complex.  They can be formed from multiple tokens and
678/// can have escape sequences in them in addition to the usual trigraph and
679/// escaped newline business.  This routine handles this complexity.
680///
681SourceLocation StringLiteral::
682getLocationOfByte(unsigned ByteNo, const SourceManager &SM,
683                  const LangOptions &Features, const TargetInfo &Target) const {
684  assert(Kind == StringLiteral::Ascii && "This only works for ASCII strings");
685
686  // Loop over all of the tokens in this string until we find the one that
687  // contains the byte we're looking for.
688  unsigned TokNo = 0;
689  while (1) {
690    assert(TokNo < getNumConcatenated() && "Invalid byte number!");
691    SourceLocation StrTokLoc = getStrTokenLoc(TokNo);
692
693    // Get the spelling of the string so that we can get the data that makes up
694    // the string literal, not the identifier for the macro it is potentially
695    // expanded through.
696    SourceLocation StrTokSpellingLoc = SM.getSpellingLoc(StrTokLoc);
697
698    // Re-lex the token to get its length and original spelling.
699    std::pair<FileID, unsigned> LocInfo =SM.getDecomposedLoc(StrTokSpellingLoc);
700    bool Invalid = false;
701    StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
702    if (Invalid)
703      return StrTokSpellingLoc;
704
705    const char *StrData = Buffer.data()+LocInfo.second;
706
707    // Create a langops struct and enable trigraphs.  This is sufficient for
708    // relexing tokens.
709    LangOptions LangOpts;
710    LangOpts.Trigraphs = true;
711
712    // Create a lexer starting at the beginning of this token.
713    Lexer TheLexer(StrTokSpellingLoc, Features, Buffer.begin(), StrData,
714                   Buffer.end());
715    Token TheTok;
716    TheLexer.LexFromRawLexer(TheTok);
717
718    // Use the StringLiteralParser to compute the length of the string in bytes.
719    StringLiteralParser SLP(&TheTok, 1, SM, Features, Target);
720    unsigned TokNumBytes = SLP.GetStringLength();
721
722    // If the byte is in this token, return the location of the byte.
723    if (ByteNo < TokNumBytes ||
724        (ByteNo == TokNumBytes && TokNo == getNumConcatenated() - 1)) {
725      unsigned Offset = SLP.getOffsetOfStringByte(TheTok, ByteNo);
726
727      // Now that we know the offset of the token in the spelling, use the
728      // preprocessor to get the offset in the original source.
729      return Lexer::AdvanceToTokenCharacter(StrTokLoc, Offset, SM, Features);
730    }
731
732    // Move to the next string token.
733    ++TokNo;
734    ByteNo -= TokNumBytes;
735  }
736}
737
738
739
740/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
741/// corresponds to, e.g. "sizeof" or "[pre]++".
742const char *UnaryOperator::getOpcodeStr(Opcode Op) {
743  switch (Op) {
744  case UO_PostInc: return "++";
745  case UO_PostDec: return "--";
746  case UO_PreInc:  return "++";
747  case UO_PreDec:  return "--";
748  case UO_AddrOf:  return "&";
749  case UO_Deref:   return "*";
750  case UO_Plus:    return "+";
751  case UO_Minus:   return "-";
752  case UO_Not:     return "~";
753  case UO_LNot:    return "!";
754  case UO_Real:    return "__real";
755  case UO_Imag:    return "__imag";
756  case UO_Extension: return "__extension__";
757  }
758  llvm_unreachable("Unknown unary operator");
759}
760
761UnaryOperatorKind
762UnaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix) {
763  switch (OO) {
764  default: llvm_unreachable("No unary operator for overloaded function");
765  case OO_PlusPlus:   return Postfix ? UO_PostInc : UO_PreInc;
766  case OO_MinusMinus: return Postfix ? UO_PostDec : UO_PreDec;
767  case OO_Amp:        return UO_AddrOf;
768  case OO_Star:       return UO_Deref;
769  case OO_Plus:       return UO_Plus;
770  case OO_Minus:      return UO_Minus;
771  case OO_Tilde:      return UO_Not;
772  case OO_Exclaim:    return UO_LNot;
773  }
774}
775
776OverloadedOperatorKind UnaryOperator::getOverloadedOperator(Opcode Opc) {
777  switch (Opc) {
778  case UO_PostInc: case UO_PreInc: return OO_PlusPlus;
779  case UO_PostDec: case UO_PreDec: return OO_MinusMinus;
780  case UO_AddrOf: return OO_Amp;
781  case UO_Deref: return OO_Star;
782  case UO_Plus: return OO_Plus;
783  case UO_Minus: return OO_Minus;
784  case UO_Not: return OO_Tilde;
785  case UO_LNot: return OO_Exclaim;
786  default: return OO_None;
787  }
788}
789
790
791//===----------------------------------------------------------------------===//
792// Postfix Operators.
793//===----------------------------------------------------------------------===//
794
795CallExpr::CallExpr(ASTContext& C, StmtClass SC, Expr *fn, unsigned NumPreArgs,
796                   Expr **args, unsigned numargs, QualType t, ExprValueKind VK,
797                   SourceLocation rparenloc)
798  : Expr(SC, t, VK, OK_Ordinary,
799         fn->isTypeDependent(),
800         fn->isValueDependent(),
801         fn->isInstantiationDependent(),
802         fn->containsUnexpandedParameterPack()),
803    NumArgs(numargs) {
804
805  SubExprs = new (C) Stmt*[numargs+PREARGS_START+NumPreArgs];
806  SubExprs[FN] = fn;
807  for (unsigned i = 0; i != numargs; ++i) {
808    if (args[i]->isTypeDependent())
809      ExprBits.TypeDependent = true;
810    if (args[i]->isValueDependent())
811      ExprBits.ValueDependent = true;
812    if (args[i]->isInstantiationDependent())
813      ExprBits.InstantiationDependent = true;
814    if (args[i]->containsUnexpandedParameterPack())
815      ExprBits.ContainsUnexpandedParameterPack = true;
816
817    SubExprs[i+PREARGS_START+NumPreArgs] = args[i];
818  }
819
820  CallExprBits.NumPreArgs = NumPreArgs;
821  RParenLoc = rparenloc;
822}
823
824CallExpr::CallExpr(ASTContext& C, Expr *fn, Expr **args, unsigned numargs,
825                   QualType t, ExprValueKind VK, SourceLocation rparenloc)
826  : Expr(CallExprClass, t, VK, OK_Ordinary,
827         fn->isTypeDependent(),
828         fn->isValueDependent(),
829         fn->isInstantiationDependent(),
830         fn->containsUnexpandedParameterPack()),
831    NumArgs(numargs) {
832
833  SubExprs = new (C) Stmt*[numargs+PREARGS_START];
834  SubExprs[FN] = fn;
835  for (unsigned i = 0; i != numargs; ++i) {
836    if (args[i]->isTypeDependent())
837      ExprBits.TypeDependent = true;
838    if (args[i]->isValueDependent())
839      ExprBits.ValueDependent = true;
840    if (args[i]->isInstantiationDependent())
841      ExprBits.InstantiationDependent = true;
842    if (args[i]->containsUnexpandedParameterPack())
843      ExprBits.ContainsUnexpandedParameterPack = true;
844
845    SubExprs[i+PREARGS_START] = args[i];
846  }
847
848  CallExprBits.NumPreArgs = 0;
849  RParenLoc = rparenloc;
850}
851
852CallExpr::CallExpr(ASTContext &C, StmtClass SC, EmptyShell Empty)
853  : Expr(SC, Empty), SubExprs(0), NumArgs(0) {
854  // FIXME: Why do we allocate this?
855  SubExprs = new (C) Stmt*[PREARGS_START];
856  CallExprBits.NumPreArgs = 0;
857}
858
859CallExpr::CallExpr(ASTContext &C, StmtClass SC, unsigned NumPreArgs,
860                   EmptyShell Empty)
861  : Expr(SC, Empty), SubExprs(0), NumArgs(0) {
862  // FIXME: Why do we allocate this?
863  SubExprs = new (C) Stmt*[PREARGS_START+NumPreArgs];
864  CallExprBits.NumPreArgs = NumPreArgs;
865}
866
867Decl *CallExpr::getCalleeDecl() {
868  Expr *CEE = getCallee()->IgnoreParenImpCasts();
869
870  while (SubstNonTypeTemplateParmExpr *NTTP
871                                = dyn_cast<SubstNonTypeTemplateParmExpr>(CEE)) {
872    CEE = NTTP->getReplacement()->IgnoreParenCasts();
873  }
874
875  // If we're calling a dereference, look at the pointer instead.
876  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CEE)) {
877    if (BO->isPtrMemOp())
878      CEE = BO->getRHS()->IgnoreParenCasts();
879  } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(CEE)) {
880    if (UO->getOpcode() == UO_Deref)
881      CEE = UO->getSubExpr()->IgnoreParenCasts();
882  }
883  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CEE))
884    return DRE->getDecl();
885  if (MemberExpr *ME = dyn_cast<MemberExpr>(CEE))
886    return ME->getMemberDecl();
887
888  return 0;
889}
890
891FunctionDecl *CallExpr::getDirectCallee() {
892  return dyn_cast_or_null<FunctionDecl>(getCalleeDecl());
893}
894
895/// setNumArgs - This changes the number of arguments present in this call.
896/// Any orphaned expressions are deleted by this, and any new operands are set
897/// to null.
898void CallExpr::setNumArgs(ASTContext& C, unsigned NumArgs) {
899  // No change, just return.
900  if (NumArgs == getNumArgs()) return;
901
902  // If shrinking # arguments, just delete the extras and forgot them.
903  if (NumArgs < getNumArgs()) {
904    this->NumArgs = NumArgs;
905    return;
906  }
907
908  // Otherwise, we are growing the # arguments.  New an bigger argument array.
909  unsigned NumPreArgs = getNumPreArgs();
910  Stmt **NewSubExprs = new (C) Stmt*[NumArgs+PREARGS_START+NumPreArgs];
911  // Copy over args.
912  for (unsigned i = 0; i != getNumArgs()+PREARGS_START+NumPreArgs; ++i)
913    NewSubExprs[i] = SubExprs[i];
914  // Null out new args.
915  for (unsigned i = getNumArgs()+PREARGS_START+NumPreArgs;
916       i != NumArgs+PREARGS_START+NumPreArgs; ++i)
917    NewSubExprs[i] = 0;
918
919  if (SubExprs) C.Deallocate(SubExprs);
920  SubExprs = NewSubExprs;
921  this->NumArgs = NumArgs;
922}
923
924/// isBuiltinCall - If this is a call to a builtin, return the builtin ID.  If
925/// not, return 0.
926unsigned CallExpr::isBuiltinCall() const {
927  // All simple function calls (e.g. func()) are implicitly cast to pointer to
928  // function. As a result, we try and obtain the DeclRefExpr from the
929  // ImplicitCastExpr.
930  const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(getCallee());
931  if (!ICE) // FIXME: deal with more complex calls (e.g. (func)(), (*func)()).
932    return 0;
933
934  const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr());
935  if (!DRE)
936    return 0;
937
938  const FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
939  if (!FDecl)
940    return 0;
941
942  if (!FDecl->getIdentifier())
943    return 0;
944
945  return FDecl->getBuiltinID();
946}
947
948QualType CallExpr::getCallReturnType() const {
949  QualType CalleeType = getCallee()->getType();
950  if (const PointerType *FnTypePtr = CalleeType->getAs<PointerType>())
951    CalleeType = FnTypePtr->getPointeeType();
952  else if (const BlockPointerType *BPT = CalleeType->getAs<BlockPointerType>())
953    CalleeType = BPT->getPointeeType();
954  else if (CalleeType->isSpecificPlaceholderType(BuiltinType::BoundMember))
955    // This should never be overloaded and so should never return null.
956    CalleeType = Expr::findBoundMemberType(getCallee());
957
958  const FunctionType *FnType = CalleeType->castAs<FunctionType>();
959  return FnType->getResultType();
960}
961
962SourceRange CallExpr::getSourceRange() const {
963  if (isa<CXXOperatorCallExpr>(this))
964    return cast<CXXOperatorCallExpr>(this)->getSourceRange();
965
966  SourceLocation begin = getCallee()->getLocStart();
967  if (begin.isInvalid() && getNumArgs() > 0)
968    begin = getArg(0)->getLocStart();
969  SourceLocation end = getRParenLoc();
970  if (end.isInvalid() && getNumArgs() > 0)
971    end = getArg(getNumArgs() - 1)->getLocEnd();
972  return SourceRange(begin, end);
973}
974SourceLocation CallExpr::getLocStart() const {
975  if (isa<CXXOperatorCallExpr>(this))
976    return cast<CXXOperatorCallExpr>(this)->getSourceRange().getBegin();
977
978  SourceLocation begin = getCallee()->getLocStart();
979  if (begin.isInvalid() && getNumArgs() > 0)
980    begin = getArg(0)->getLocStart();
981  return begin;
982}
983SourceLocation CallExpr::getLocEnd() const {
984  if (isa<CXXOperatorCallExpr>(this))
985    return cast<CXXOperatorCallExpr>(this)->getSourceRange().getEnd();
986
987  SourceLocation end = getRParenLoc();
988  if (end.isInvalid() && getNumArgs() > 0)
989    end = getArg(getNumArgs() - 1)->getLocEnd();
990  return end;
991}
992
993OffsetOfExpr *OffsetOfExpr::Create(ASTContext &C, QualType type,
994                                   SourceLocation OperatorLoc,
995                                   TypeSourceInfo *tsi,
996                                   OffsetOfNode* compsPtr, unsigned numComps,
997                                   Expr** exprsPtr, unsigned numExprs,
998                                   SourceLocation RParenLoc) {
999  void *Mem = C.Allocate(sizeof(OffsetOfExpr) +
1000                         sizeof(OffsetOfNode) * numComps +
1001                         sizeof(Expr*) * numExprs);
1002
1003  return new (Mem) OffsetOfExpr(C, type, OperatorLoc, tsi, compsPtr, numComps,
1004                                exprsPtr, numExprs, RParenLoc);
1005}
1006
1007OffsetOfExpr *OffsetOfExpr::CreateEmpty(ASTContext &C,
1008                                        unsigned numComps, unsigned numExprs) {
1009  void *Mem = C.Allocate(sizeof(OffsetOfExpr) +
1010                         sizeof(OffsetOfNode) * numComps +
1011                         sizeof(Expr*) * numExprs);
1012  return new (Mem) OffsetOfExpr(numComps, numExprs);
1013}
1014
1015OffsetOfExpr::OffsetOfExpr(ASTContext &C, QualType type,
1016                           SourceLocation OperatorLoc, TypeSourceInfo *tsi,
1017                           OffsetOfNode* compsPtr, unsigned numComps,
1018                           Expr** exprsPtr, unsigned numExprs,
1019                           SourceLocation RParenLoc)
1020  : Expr(OffsetOfExprClass, type, VK_RValue, OK_Ordinary,
1021         /*TypeDependent=*/false,
1022         /*ValueDependent=*/tsi->getType()->isDependentType(),
1023         tsi->getType()->isInstantiationDependentType(),
1024         tsi->getType()->containsUnexpandedParameterPack()),
1025    OperatorLoc(OperatorLoc), RParenLoc(RParenLoc), TSInfo(tsi),
1026    NumComps(numComps), NumExprs(numExprs)
1027{
1028  for(unsigned i = 0; i < numComps; ++i) {
1029    setComponent(i, compsPtr[i]);
1030  }
1031
1032  for(unsigned i = 0; i < numExprs; ++i) {
1033    if (exprsPtr[i]->isTypeDependent() || exprsPtr[i]->isValueDependent())
1034      ExprBits.ValueDependent = true;
1035    if (exprsPtr[i]->containsUnexpandedParameterPack())
1036      ExprBits.ContainsUnexpandedParameterPack = true;
1037
1038    setIndexExpr(i, exprsPtr[i]);
1039  }
1040}
1041
1042IdentifierInfo *OffsetOfExpr::OffsetOfNode::getFieldName() const {
1043  assert(getKind() == Field || getKind() == Identifier);
1044  if (getKind() == Field)
1045    return getField()->getIdentifier();
1046
1047  return reinterpret_cast<IdentifierInfo *> (Data & ~(uintptr_t)Mask);
1048}
1049
1050MemberExpr *MemberExpr::Create(ASTContext &C, Expr *base, bool isarrow,
1051                               NestedNameSpecifierLoc QualifierLoc,
1052                               SourceLocation TemplateKWLoc,
1053                               ValueDecl *memberdecl,
1054                               DeclAccessPair founddecl,
1055                               DeclarationNameInfo nameinfo,
1056                               const TemplateArgumentListInfo *targs,
1057                               QualType ty,
1058                               ExprValueKind vk,
1059                               ExprObjectKind ok) {
1060  std::size_t Size = sizeof(MemberExpr);
1061
1062  bool hasQualOrFound = (QualifierLoc ||
1063                         founddecl.getDecl() != memberdecl ||
1064                         founddecl.getAccess() != memberdecl->getAccess());
1065  if (hasQualOrFound)
1066    Size += sizeof(MemberNameQualifier);
1067
1068  if (targs)
1069    Size += ASTTemplateKWAndArgsInfo::sizeFor(targs->size());
1070  else if (TemplateKWLoc.isValid())
1071    Size += ASTTemplateKWAndArgsInfo::sizeFor(0);
1072
1073  void *Mem = C.Allocate(Size, llvm::alignOf<MemberExpr>());
1074  MemberExpr *E = new (Mem) MemberExpr(base, isarrow, memberdecl, nameinfo,
1075                                       ty, vk, ok);
1076
1077  if (hasQualOrFound) {
1078    // FIXME: Wrong. We should be looking at the member declaration we found.
1079    if (QualifierLoc && QualifierLoc.getNestedNameSpecifier()->isDependent()) {
1080      E->setValueDependent(true);
1081      E->setTypeDependent(true);
1082      E->setInstantiationDependent(true);
1083    }
1084    else if (QualifierLoc &&
1085             QualifierLoc.getNestedNameSpecifier()->isInstantiationDependent())
1086      E->setInstantiationDependent(true);
1087
1088    E->HasQualifierOrFoundDecl = true;
1089
1090    MemberNameQualifier *NQ = E->getMemberQualifier();
1091    NQ->QualifierLoc = QualifierLoc;
1092    NQ->FoundDecl = founddecl;
1093  }
1094
1095  E->HasTemplateKWAndArgsInfo = (targs || TemplateKWLoc.isValid());
1096
1097  if (targs) {
1098    bool Dependent = false;
1099    bool InstantiationDependent = false;
1100    bool ContainsUnexpandedParameterPack = false;
1101    E->getTemplateKWAndArgsInfo()->initializeFrom(TemplateKWLoc, *targs,
1102                                                  Dependent,
1103                                                  InstantiationDependent,
1104                                             ContainsUnexpandedParameterPack);
1105    if (InstantiationDependent)
1106      E->setInstantiationDependent(true);
1107  } else if (TemplateKWLoc.isValid()) {
1108    E->getTemplateKWAndArgsInfo()->initializeFrom(TemplateKWLoc);
1109  }
1110
1111  return E;
1112}
1113
1114SourceRange MemberExpr::getSourceRange() const {
1115  return SourceRange(getLocStart(), getLocEnd());
1116}
1117SourceLocation MemberExpr::getLocStart() const {
1118  if (isImplicitAccess()) {
1119    if (hasQualifier())
1120      return getQualifierLoc().getBeginLoc();
1121    return MemberLoc;
1122  }
1123
1124  // FIXME: We don't want this to happen. Rather, we should be able to
1125  // detect all kinds of implicit accesses more cleanly.
1126  SourceLocation BaseStartLoc = getBase()->getLocStart();
1127  if (BaseStartLoc.isValid())
1128    return BaseStartLoc;
1129  return MemberLoc;
1130}
1131SourceLocation MemberExpr::getLocEnd() const {
1132  if (hasExplicitTemplateArgs())
1133    return getRAngleLoc();
1134  return getMemberNameInfo().getEndLoc();
1135}
1136
1137void CastExpr::CheckCastConsistency() const {
1138  switch (getCastKind()) {
1139  case CK_DerivedToBase:
1140  case CK_UncheckedDerivedToBase:
1141  case CK_DerivedToBaseMemberPointer:
1142  case CK_BaseToDerived:
1143  case CK_BaseToDerivedMemberPointer:
1144    assert(!path_empty() && "Cast kind should have a base path!");
1145    break;
1146
1147  case CK_CPointerToObjCPointerCast:
1148    assert(getType()->isObjCObjectPointerType());
1149    assert(getSubExpr()->getType()->isPointerType());
1150    goto CheckNoBasePath;
1151
1152  case CK_BlockPointerToObjCPointerCast:
1153    assert(getType()->isObjCObjectPointerType());
1154    assert(getSubExpr()->getType()->isBlockPointerType());
1155    goto CheckNoBasePath;
1156
1157  case CK_ReinterpretMemberPointer:
1158    assert(getType()->isMemberPointerType());
1159    assert(getSubExpr()->getType()->isMemberPointerType());
1160    goto CheckNoBasePath;
1161
1162  case CK_BitCast:
1163    // Arbitrary casts to C pointer types count as bitcasts.
1164    // Otherwise, we should only have block and ObjC pointer casts
1165    // here if they stay within the type kind.
1166    if (!getType()->isPointerType()) {
1167      assert(getType()->isObjCObjectPointerType() ==
1168             getSubExpr()->getType()->isObjCObjectPointerType());
1169      assert(getType()->isBlockPointerType() ==
1170             getSubExpr()->getType()->isBlockPointerType());
1171    }
1172    goto CheckNoBasePath;
1173
1174  case CK_AnyPointerToBlockPointerCast:
1175    assert(getType()->isBlockPointerType());
1176    assert(getSubExpr()->getType()->isAnyPointerType() &&
1177           !getSubExpr()->getType()->isBlockPointerType());
1178    goto CheckNoBasePath;
1179
1180  case CK_CopyAndAutoreleaseBlockObject:
1181    assert(getType()->isBlockPointerType());
1182    assert(getSubExpr()->getType()->isBlockPointerType());
1183    goto CheckNoBasePath;
1184
1185  // These should not have an inheritance path.
1186  case CK_Dynamic:
1187  case CK_ToUnion:
1188  case CK_ArrayToPointerDecay:
1189  case CK_FunctionToPointerDecay:
1190  case CK_NullToMemberPointer:
1191  case CK_NullToPointer:
1192  case CK_ConstructorConversion:
1193  case CK_IntegralToPointer:
1194  case CK_PointerToIntegral:
1195  case CK_ToVoid:
1196  case CK_VectorSplat:
1197  case CK_IntegralCast:
1198  case CK_IntegralToFloating:
1199  case CK_FloatingToIntegral:
1200  case CK_FloatingCast:
1201  case CK_ObjCObjectLValueCast:
1202  case CK_FloatingRealToComplex:
1203  case CK_FloatingComplexToReal:
1204  case CK_FloatingComplexCast:
1205  case CK_FloatingComplexToIntegralComplex:
1206  case CK_IntegralRealToComplex:
1207  case CK_IntegralComplexToReal:
1208  case CK_IntegralComplexCast:
1209  case CK_IntegralComplexToFloatingComplex:
1210  case CK_ARCProduceObject:
1211  case CK_ARCConsumeObject:
1212  case CK_ARCReclaimReturnedObject:
1213  case CK_ARCExtendBlockObject:
1214    assert(!getType()->isBooleanType() && "unheralded conversion to bool");
1215    goto CheckNoBasePath;
1216
1217  case CK_Dependent:
1218  case CK_LValueToRValue:
1219  case CK_NoOp:
1220  case CK_AtomicToNonAtomic:
1221  case CK_NonAtomicToAtomic:
1222  case CK_PointerToBoolean:
1223  case CK_IntegralToBoolean:
1224  case CK_FloatingToBoolean:
1225  case CK_MemberPointerToBoolean:
1226  case CK_FloatingComplexToBoolean:
1227  case CK_IntegralComplexToBoolean:
1228  case CK_LValueBitCast:            // -> bool&
1229  case CK_UserDefinedConversion:    // operator bool()
1230  CheckNoBasePath:
1231    assert(path_empty() && "Cast kind should not have a base path!");
1232    break;
1233  }
1234}
1235
1236const char *CastExpr::getCastKindName() const {
1237  switch (getCastKind()) {
1238  case CK_Dependent:
1239    return "Dependent";
1240  case CK_BitCast:
1241    return "BitCast";
1242  case CK_LValueBitCast:
1243    return "LValueBitCast";
1244  case CK_LValueToRValue:
1245    return "LValueToRValue";
1246  case CK_NoOp:
1247    return "NoOp";
1248  case CK_BaseToDerived:
1249    return "BaseToDerived";
1250  case CK_DerivedToBase:
1251    return "DerivedToBase";
1252  case CK_UncheckedDerivedToBase:
1253    return "UncheckedDerivedToBase";
1254  case CK_Dynamic:
1255    return "Dynamic";
1256  case CK_ToUnion:
1257    return "ToUnion";
1258  case CK_ArrayToPointerDecay:
1259    return "ArrayToPointerDecay";
1260  case CK_FunctionToPointerDecay:
1261    return "FunctionToPointerDecay";
1262  case CK_NullToMemberPointer:
1263    return "NullToMemberPointer";
1264  case CK_NullToPointer:
1265    return "NullToPointer";
1266  case CK_BaseToDerivedMemberPointer:
1267    return "BaseToDerivedMemberPointer";
1268  case CK_DerivedToBaseMemberPointer:
1269    return "DerivedToBaseMemberPointer";
1270  case CK_ReinterpretMemberPointer:
1271    return "ReinterpretMemberPointer";
1272  case CK_UserDefinedConversion:
1273    return "UserDefinedConversion";
1274  case CK_ConstructorConversion:
1275    return "ConstructorConversion";
1276  case CK_IntegralToPointer:
1277    return "IntegralToPointer";
1278  case CK_PointerToIntegral:
1279    return "PointerToIntegral";
1280  case CK_PointerToBoolean:
1281    return "PointerToBoolean";
1282  case CK_ToVoid:
1283    return "ToVoid";
1284  case CK_VectorSplat:
1285    return "VectorSplat";
1286  case CK_IntegralCast:
1287    return "IntegralCast";
1288  case CK_IntegralToBoolean:
1289    return "IntegralToBoolean";
1290  case CK_IntegralToFloating:
1291    return "IntegralToFloating";
1292  case CK_FloatingToIntegral:
1293    return "FloatingToIntegral";
1294  case CK_FloatingCast:
1295    return "FloatingCast";
1296  case CK_FloatingToBoolean:
1297    return "FloatingToBoolean";
1298  case CK_MemberPointerToBoolean:
1299    return "MemberPointerToBoolean";
1300  case CK_CPointerToObjCPointerCast:
1301    return "CPointerToObjCPointerCast";
1302  case CK_BlockPointerToObjCPointerCast:
1303    return "BlockPointerToObjCPointerCast";
1304  case CK_AnyPointerToBlockPointerCast:
1305    return "AnyPointerToBlockPointerCast";
1306  case CK_ObjCObjectLValueCast:
1307    return "ObjCObjectLValueCast";
1308  case CK_FloatingRealToComplex:
1309    return "FloatingRealToComplex";
1310  case CK_FloatingComplexToReal:
1311    return "FloatingComplexToReal";
1312  case CK_FloatingComplexToBoolean:
1313    return "FloatingComplexToBoolean";
1314  case CK_FloatingComplexCast:
1315    return "FloatingComplexCast";
1316  case CK_FloatingComplexToIntegralComplex:
1317    return "FloatingComplexToIntegralComplex";
1318  case CK_IntegralRealToComplex:
1319    return "IntegralRealToComplex";
1320  case CK_IntegralComplexToReal:
1321    return "IntegralComplexToReal";
1322  case CK_IntegralComplexToBoolean:
1323    return "IntegralComplexToBoolean";
1324  case CK_IntegralComplexCast:
1325    return "IntegralComplexCast";
1326  case CK_IntegralComplexToFloatingComplex:
1327    return "IntegralComplexToFloatingComplex";
1328  case CK_ARCConsumeObject:
1329    return "ARCConsumeObject";
1330  case CK_ARCProduceObject:
1331    return "ARCProduceObject";
1332  case CK_ARCReclaimReturnedObject:
1333    return "ARCReclaimReturnedObject";
1334  case CK_ARCExtendBlockObject:
1335    return "ARCCExtendBlockObject";
1336  case CK_AtomicToNonAtomic:
1337    return "AtomicToNonAtomic";
1338  case CK_NonAtomicToAtomic:
1339    return "NonAtomicToAtomic";
1340  case CK_CopyAndAutoreleaseBlockObject:
1341    return "CopyAndAutoreleaseBlockObject";
1342  }
1343
1344  llvm_unreachable("Unhandled cast kind!");
1345}
1346
1347Expr *CastExpr::getSubExprAsWritten() {
1348  Expr *SubExpr = 0;
1349  CastExpr *E = this;
1350  do {
1351    SubExpr = E->getSubExpr();
1352
1353    // Skip through reference binding to temporary.
1354    if (MaterializeTemporaryExpr *Materialize
1355                                  = dyn_cast<MaterializeTemporaryExpr>(SubExpr))
1356      SubExpr = Materialize->GetTemporaryExpr();
1357
1358    // Skip any temporary bindings; they're implicit.
1359    if (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(SubExpr))
1360      SubExpr = Binder->getSubExpr();
1361
1362    // Conversions by constructor and conversion functions have a
1363    // subexpression describing the call; strip it off.
1364    if (E->getCastKind() == CK_ConstructorConversion)
1365      SubExpr = cast<CXXConstructExpr>(SubExpr)->getArg(0);
1366    else if (E->getCastKind() == CK_UserDefinedConversion)
1367      SubExpr = cast<CXXMemberCallExpr>(SubExpr)->getImplicitObjectArgument();
1368
1369    // If the subexpression we're left with is an implicit cast, look
1370    // through that, too.
1371  } while ((E = dyn_cast<ImplicitCastExpr>(SubExpr)));
1372
1373  return SubExpr;
1374}
1375
1376CXXBaseSpecifier **CastExpr::path_buffer() {
1377  switch (getStmtClass()) {
1378#define ABSTRACT_STMT(x)
1379#define CASTEXPR(Type, Base) \
1380  case Stmt::Type##Class: \
1381    return reinterpret_cast<CXXBaseSpecifier**>(static_cast<Type*>(this)+1);
1382#define STMT(Type, Base)
1383#include "clang/AST/StmtNodes.inc"
1384  default:
1385    llvm_unreachable("non-cast expressions not possible here");
1386  }
1387}
1388
1389void CastExpr::setCastPath(const CXXCastPath &Path) {
1390  assert(Path.size() == path_size());
1391  memcpy(path_buffer(), Path.data(), Path.size() * sizeof(CXXBaseSpecifier*));
1392}
1393
1394ImplicitCastExpr *ImplicitCastExpr::Create(ASTContext &C, QualType T,
1395                                           CastKind Kind, Expr *Operand,
1396                                           const CXXCastPath *BasePath,
1397                                           ExprValueKind VK) {
1398  unsigned PathSize = (BasePath ? BasePath->size() : 0);
1399  void *Buffer =
1400    C.Allocate(sizeof(ImplicitCastExpr) + PathSize * sizeof(CXXBaseSpecifier*));
1401  ImplicitCastExpr *E =
1402    new (Buffer) ImplicitCastExpr(T, Kind, Operand, PathSize, VK);
1403  if (PathSize) E->setCastPath(*BasePath);
1404  return E;
1405}
1406
1407ImplicitCastExpr *ImplicitCastExpr::CreateEmpty(ASTContext &C,
1408                                                unsigned PathSize) {
1409  void *Buffer =
1410    C.Allocate(sizeof(ImplicitCastExpr) + PathSize * sizeof(CXXBaseSpecifier*));
1411  return new (Buffer) ImplicitCastExpr(EmptyShell(), PathSize);
1412}
1413
1414
1415CStyleCastExpr *CStyleCastExpr::Create(ASTContext &C, QualType T,
1416                                       ExprValueKind VK, CastKind K, Expr *Op,
1417                                       const CXXCastPath *BasePath,
1418                                       TypeSourceInfo *WrittenTy,
1419                                       SourceLocation L, SourceLocation R) {
1420  unsigned PathSize = (BasePath ? BasePath->size() : 0);
1421  void *Buffer =
1422    C.Allocate(sizeof(CStyleCastExpr) + PathSize * sizeof(CXXBaseSpecifier*));
1423  CStyleCastExpr *E =
1424    new (Buffer) CStyleCastExpr(T, VK, K, Op, PathSize, WrittenTy, L, R);
1425  if (PathSize) E->setCastPath(*BasePath);
1426  return E;
1427}
1428
1429CStyleCastExpr *CStyleCastExpr::CreateEmpty(ASTContext &C, unsigned PathSize) {
1430  void *Buffer =
1431    C.Allocate(sizeof(CStyleCastExpr) + PathSize * sizeof(CXXBaseSpecifier*));
1432  return new (Buffer) CStyleCastExpr(EmptyShell(), PathSize);
1433}
1434
1435/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1436/// corresponds to, e.g. "<<=".
1437const char *BinaryOperator::getOpcodeStr(Opcode Op) {
1438  switch (Op) {
1439  case BO_PtrMemD:   return ".*";
1440  case BO_PtrMemI:   return "->*";
1441  case BO_Mul:       return "*";
1442  case BO_Div:       return "/";
1443  case BO_Rem:       return "%";
1444  case BO_Add:       return "+";
1445  case BO_Sub:       return "-";
1446  case BO_Shl:       return "<<";
1447  case BO_Shr:       return ">>";
1448  case BO_LT:        return "<";
1449  case BO_GT:        return ">";
1450  case BO_LE:        return "<=";
1451  case BO_GE:        return ">=";
1452  case BO_EQ:        return "==";
1453  case BO_NE:        return "!=";
1454  case BO_And:       return "&";
1455  case BO_Xor:       return "^";
1456  case BO_Or:        return "|";
1457  case BO_LAnd:      return "&&";
1458  case BO_LOr:       return "||";
1459  case BO_Assign:    return "=";
1460  case BO_MulAssign: return "*=";
1461  case BO_DivAssign: return "/=";
1462  case BO_RemAssign: return "%=";
1463  case BO_AddAssign: return "+=";
1464  case BO_SubAssign: return "-=";
1465  case BO_ShlAssign: return "<<=";
1466  case BO_ShrAssign: return ">>=";
1467  case BO_AndAssign: return "&=";
1468  case BO_XorAssign: return "^=";
1469  case BO_OrAssign:  return "|=";
1470  case BO_Comma:     return ",";
1471  }
1472
1473  llvm_unreachable("Invalid OpCode!");
1474}
1475
1476BinaryOperatorKind
1477BinaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO) {
1478  switch (OO) {
1479  default: llvm_unreachable("Not an overloadable binary operator");
1480  case OO_Plus: return BO_Add;
1481  case OO_Minus: return BO_Sub;
1482  case OO_Star: return BO_Mul;
1483  case OO_Slash: return BO_Div;
1484  case OO_Percent: return BO_Rem;
1485  case OO_Caret: return BO_Xor;
1486  case OO_Amp: return BO_And;
1487  case OO_Pipe: return BO_Or;
1488  case OO_Equal: return BO_Assign;
1489  case OO_Less: return BO_LT;
1490  case OO_Greater: return BO_GT;
1491  case OO_PlusEqual: return BO_AddAssign;
1492  case OO_MinusEqual: return BO_SubAssign;
1493  case OO_StarEqual: return BO_MulAssign;
1494  case OO_SlashEqual: return BO_DivAssign;
1495  case OO_PercentEqual: return BO_RemAssign;
1496  case OO_CaretEqual: return BO_XorAssign;
1497  case OO_AmpEqual: return BO_AndAssign;
1498  case OO_PipeEqual: return BO_OrAssign;
1499  case OO_LessLess: return BO_Shl;
1500  case OO_GreaterGreater: return BO_Shr;
1501  case OO_LessLessEqual: return BO_ShlAssign;
1502  case OO_GreaterGreaterEqual: return BO_ShrAssign;
1503  case OO_EqualEqual: return BO_EQ;
1504  case OO_ExclaimEqual: return BO_NE;
1505  case OO_LessEqual: return BO_LE;
1506  case OO_GreaterEqual: return BO_GE;
1507  case OO_AmpAmp: return BO_LAnd;
1508  case OO_PipePipe: return BO_LOr;
1509  case OO_Comma: return BO_Comma;
1510  case OO_ArrowStar: return BO_PtrMemI;
1511  }
1512}
1513
1514OverloadedOperatorKind BinaryOperator::getOverloadedOperator(Opcode Opc) {
1515  static const OverloadedOperatorKind OverOps[] = {
1516    /* .* Cannot be overloaded */OO_None, OO_ArrowStar,
1517    OO_Star, OO_Slash, OO_Percent,
1518    OO_Plus, OO_Minus,
1519    OO_LessLess, OO_GreaterGreater,
1520    OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
1521    OO_EqualEqual, OO_ExclaimEqual,
1522    OO_Amp,
1523    OO_Caret,
1524    OO_Pipe,
1525    OO_AmpAmp,
1526    OO_PipePipe,
1527    OO_Equal, OO_StarEqual,
1528    OO_SlashEqual, OO_PercentEqual,
1529    OO_PlusEqual, OO_MinusEqual,
1530    OO_LessLessEqual, OO_GreaterGreaterEqual,
1531    OO_AmpEqual, OO_CaretEqual,
1532    OO_PipeEqual,
1533    OO_Comma
1534  };
1535  return OverOps[Opc];
1536}
1537
1538InitListExpr::InitListExpr(ASTContext &C, SourceLocation lbraceloc,
1539                           Expr **initExprs, unsigned numInits,
1540                           SourceLocation rbraceloc)
1541  : Expr(InitListExprClass, QualType(), VK_RValue, OK_Ordinary, false, false,
1542         false, false),
1543    InitExprs(C, numInits),
1544    LBraceLoc(lbraceloc), RBraceLoc(rbraceloc), SyntacticForm(0)
1545{
1546  sawArrayRangeDesignator(false);
1547  setInitializesStdInitializerList(false);
1548  for (unsigned I = 0; I != numInits; ++I) {
1549    if (initExprs[I]->isTypeDependent())
1550      ExprBits.TypeDependent = true;
1551    if (initExprs[I]->isValueDependent())
1552      ExprBits.ValueDependent = true;
1553    if (initExprs[I]->isInstantiationDependent())
1554      ExprBits.InstantiationDependent = true;
1555    if (initExprs[I]->containsUnexpandedParameterPack())
1556      ExprBits.ContainsUnexpandedParameterPack = true;
1557  }
1558
1559  InitExprs.insert(C, InitExprs.end(), initExprs, initExprs+numInits);
1560}
1561
1562void InitListExpr::reserveInits(ASTContext &C, unsigned NumInits) {
1563  if (NumInits > InitExprs.size())
1564    InitExprs.reserve(C, NumInits);
1565}
1566
1567void InitListExpr::resizeInits(ASTContext &C, unsigned NumInits) {
1568  InitExprs.resize(C, NumInits, 0);
1569}
1570
1571Expr *InitListExpr::updateInit(ASTContext &C, unsigned Init, Expr *expr) {
1572  if (Init >= InitExprs.size()) {
1573    InitExprs.insert(C, InitExprs.end(), Init - InitExprs.size() + 1, 0);
1574    InitExprs.back() = expr;
1575    return 0;
1576  }
1577
1578  Expr *Result = cast_or_null<Expr>(InitExprs[Init]);
1579  InitExprs[Init] = expr;
1580  return Result;
1581}
1582
1583void InitListExpr::setArrayFiller(Expr *filler) {
1584  assert(!hasArrayFiller() && "Filler already set!");
1585  ArrayFillerOrUnionFieldInit = filler;
1586  // Fill out any "holes" in the array due to designated initializers.
1587  Expr **inits = getInits();
1588  for (unsigned i = 0, e = getNumInits(); i != e; ++i)
1589    if (inits[i] == 0)
1590      inits[i] = filler;
1591}
1592
1593SourceRange InitListExpr::getSourceRange() const {
1594  if (SyntacticForm)
1595    return SyntacticForm->getSourceRange();
1596  SourceLocation Beg = LBraceLoc, End = RBraceLoc;
1597  if (Beg.isInvalid()) {
1598    // Find the first non-null initializer.
1599    for (InitExprsTy::const_iterator I = InitExprs.begin(),
1600                                     E = InitExprs.end();
1601      I != E; ++I) {
1602      if (Stmt *S = *I) {
1603        Beg = S->getLocStart();
1604        break;
1605      }
1606    }
1607  }
1608  if (End.isInvalid()) {
1609    // Find the first non-null initializer from the end.
1610    for (InitExprsTy::const_reverse_iterator I = InitExprs.rbegin(),
1611                                             E = InitExprs.rend();
1612      I != E; ++I) {
1613      if (Stmt *S = *I) {
1614        End = S->getSourceRange().getEnd();
1615        break;
1616      }
1617    }
1618  }
1619  return SourceRange(Beg, End);
1620}
1621
1622/// getFunctionType - Return the underlying function type for this block.
1623///
1624const FunctionProtoType *BlockExpr::getFunctionType() const {
1625  // The block pointer is never sugared, but the function type might be.
1626  return cast<BlockPointerType>(getType())
1627           ->getPointeeType()->castAs<FunctionProtoType>();
1628}
1629
1630SourceLocation BlockExpr::getCaretLocation() const {
1631  return TheBlock->getCaretLocation();
1632}
1633const Stmt *BlockExpr::getBody() const {
1634  return TheBlock->getBody();
1635}
1636Stmt *BlockExpr::getBody() {
1637  return TheBlock->getBody();
1638}
1639
1640
1641//===----------------------------------------------------------------------===//
1642// Generic Expression Routines
1643//===----------------------------------------------------------------------===//
1644
1645/// isUnusedResultAWarning - Return true if this immediate expression should
1646/// be warned about if the result is unused.  If so, fill in Loc and Ranges
1647/// with location to warn on and the source range[s] to report with the
1648/// warning.
1649bool Expr::isUnusedResultAWarning(SourceLocation &Loc, SourceRange &R1,
1650                                  SourceRange &R2, ASTContext &Ctx) const {
1651  // Don't warn if the expr is type dependent. The type could end up
1652  // instantiating to void.
1653  if (isTypeDependent())
1654    return false;
1655
1656  switch (getStmtClass()) {
1657  default:
1658    if (getType()->isVoidType())
1659      return false;
1660    Loc = getExprLoc();
1661    R1 = getSourceRange();
1662    return true;
1663  case ParenExprClass:
1664    return cast<ParenExpr>(this)->getSubExpr()->
1665      isUnusedResultAWarning(Loc, R1, R2, Ctx);
1666  case GenericSelectionExprClass:
1667    return cast<GenericSelectionExpr>(this)->getResultExpr()->
1668      isUnusedResultAWarning(Loc, R1, R2, Ctx);
1669  case UnaryOperatorClass: {
1670    const UnaryOperator *UO = cast<UnaryOperator>(this);
1671
1672    switch (UO->getOpcode()) {
1673    default: break;
1674    case UO_PostInc:
1675    case UO_PostDec:
1676    case UO_PreInc:
1677    case UO_PreDec:                 // ++/--
1678      return false;  // Not a warning.
1679    case UO_Deref:
1680      // Dereferencing a volatile pointer is a side-effect.
1681      if (Ctx.getCanonicalType(getType()).isVolatileQualified())
1682        return false;
1683      break;
1684    case UO_Real:
1685    case UO_Imag:
1686      // accessing a piece of a volatile complex is a side-effect.
1687      if (Ctx.getCanonicalType(UO->getSubExpr()->getType())
1688          .isVolatileQualified())
1689        return false;
1690      break;
1691    case UO_Extension:
1692      return UO->getSubExpr()->isUnusedResultAWarning(Loc, R1, R2, Ctx);
1693    }
1694    Loc = UO->getOperatorLoc();
1695    R1 = UO->getSubExpr()->getSourceRange();
1696    return true;
1697  }
1698  case BinaryOperatorClass: {
1699    const BinaryOperator *BO = cast<BinaryOperator>(this);
1700    switch (BO->getOpcode()) {
1701      default:
1702        break;
1703      // Consider the RHS of comma for side effects. LHS was checked by
1704      // Sema::CheckCommaOperands.
1705      case BO_Comma:
1706        // ((foo = <blah>), 0) is an idiom for hiding the result (and
1707        // lvalue-ness) of an assignment written in a macro.
1708        if (IntegerLiteral *IE =
1709              dyn_cast<IntegerLiteral>(BO->getRHS()->IgnoreParens()))
1710          if (IE->getValue() == 0)
1711            return false;
1712        return BO->getRHS()->isUnusedResultAWarning(Loc, R1, R2, Ctx);
1713      // Consider '||', '&&' to have side effects if the LHS or RHS does.
1714      case BO_LAnd:
1715      case BO_LOr:
1716        if (!BO->getLHS()->isUnusedResultAWarning(Loc, R1, R2, Ctx) ||
1717            !BO->getRHS()->isUnusedResultAWarning(Loc, R1, R2, Ctx))
1718          return false;
1719        break;
1720    }
1721    if (BO->isAssignmentOp())
1722      return false;
1723    Loc = BO->getOperatorLoc();
1724    R1 = BO->getLHS()->getSourceRange();
1725    R2 = BO->getRHS()->getSourceRange();
1726    return true;
1727  }
1728  case CompoundAssignOperatorClass:
1729  case VAArgExprClass:
1730  case AtomicExprClass:
1731    return false;
1732
1733  case ConditionalOperatorClass: {
1734    // If only one of the LHS or RHS is a warning, the operator might
1735    // be being used for control flow. Only warn if both the LHS and
1736    // RHS are warnings.
1737    const ConditionalOperator *Exp = cast<ConditionalOperator>(this);
1738    if (!Exp->getRHS()->isUnusedResultAWarning(Loc, R1, R2, Ctx))
1739      return false;
1740    if (!Exp->getLHS())
1741      return true;
1742    return Exp->getLHS()->isUnusedResultAWarning(Loc, R1, R2, Ctx);
1743  }
1744
1745  case MemberExprClass:
1746    // If the base pointer or element is to a volatile pointer/field, accessing
1747    // it is a side effect.
1748    if (Ctx.getCanonicalType(getType()).isVolatileQualified())
1749      return false;
1750    Loc = cast<MemberExpr>(this)->getMemberLoc();
1751    R1 = SourceRange(Loc, Loc);
1752    R2 = cast<MemberExpr>(this)->getBase()->getSourceRange();
1753    return true;
1754
1755  case ArraySubscriptExprClass:
1756    // If the base pointer or element is to a volatile pointer/field, accessing
1757    // it is a side effect.
1758    if (Ctx.getCanonicalType(getType()).isVolatileQualified())
1759      return false;
1760    Loc = cast<ArraySubscriptExpr>(this)->getRBracketLoc();
1761    R1 = cast<ArraySubscriptExpr>(this)->getLHS()->getSourceRange();
1762    R2 = cast<ArraySubscriptExpr>(this)->getRHS()->getSourceRange();
1763    return true;
1764
1765  case CXXOperatorCallExprClass: {
1766    // We warn about operator== and operator!= even when user-defined operator
1767    // overloads as there is no reasonable way to define these such that they
1768    // have non-trivial, desirable side-effects. See the -Wunused-comparison
1769    // warning: these operators are commonly typo'ed, and so warning on them
1770    // provides additional value as well. If this list is updated,
1771    // DiagnoseUnusedComparison should be as well.
1772    const CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(this);
1773    if (Op->getOperator() == OO_EqualEqual ||
1774        Op->getOperator() == OO_ExclaimEqual) {
1775      Loc = Op->getOperatorLoc();
1776      R1 = Op->getSourceRange();
1777      return true;
1778    }
1779
1780    // Fallthrough for generic call handling.
1781  }
1782  case CallExprClass:
1783  case CXXMemberCallExprClass:
1784  case UserDefinedLiteralClass: {
1785    // If this is a direct call, get the callee.
1786    const CallExpr *CE = cast<CallExpr>(this);
1787    if (const Decl *FD = CE->getCalleeDecl()) {
1788      // If the callee has attribute pure, const, or warn_unused_result, warn
1789      // about it. void foo() { strlen("bar"); } should warn.
1790      //
1791      // Note: If new cases are added here, DiagnoseUnusedExprResult should be
1792      // updated to match for QoI.
1793      if (FD->getAttr<WarnUnusedResultAttr>() ||
1794          FD->getAttr<PureAttr>() || FD->getAttr<ConstAttr>()) {
1795        Loc = CE->getCallee()->getLocStart();
1796        R1 = CE->getCallee()->getSourceRange();
1797
1798        if (unsigned NumArgs = CE->getNumArgs())
1799          R2 = SourceRange(CE->getArg(0)->getLocStart(),
1800                           CE->getArg(NumArgs-1)->getLocEnd());
1801        return true;
1802      }
1803    }
1804    return false;
1805  }
1806
1807  case CXXTemporaryObjectExprClass:
1808  case CXXConstructExprClass:
1809    return false;
1810
1811  case ObjCMessageExprClass: {
1812    const ObjCMessageExpr *ME = cast<ObjCMessageExpr>(this);
1813    if (Ctx.getLangOpts().ObjCAutoRefCount &&
1814        ME->isInstanceMessage() &&
1815        !ME->getType()->isVoidType() &&
1816        ME->getSelector().getIdentifierInfoForSlot(0) &&
1817        ME->getSelector().getIdentifierInfoForSlot(0)
1818                                               ->getName().startswith("init")) {
1819      Loc = getExprLoc();
1820      R1 = ME->getSourceRange();
1821      return true;
1822    }
1823
1824    const ObjCMethodDecl *MD = ME->getMethodDecl();
1825    if (MD && MD->getAttr<WarnUnusedResultAttr>()) {
1826      Loc = getExprLoc();
1827      return true;
1828    }
1829    return false;
1830  }
1831
1832  case ObjCPropertyRefExprClass:
1833    Loc = getExprLoc();
1834    R1 = getSourceRange();
1835    return true;
1836
1837  case PseudoObjectExprClass: {
1838    const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this);
1839
1840    // Only complain about things that have the form of a getter.
1841    if (isa<UnaryOperator>(PO->getSyntacticForm()) ||
1842        isa<BinaryOperator>(PO->getSyntacticForm()))
1843      return false;
1844
1845    Loc = getExprLoc();
1846    R1 = getSourceRange();
1847    return true;
1848  }
1849
1850  case StmtExprClass: {
1851    // Statement exprs don't logically have side effects themselves, but are
1852    // sometimes used in macros in ways that give them a type that is unused.
1853    // For example ({ blah; foo(); }) will end up with a type if foo has a type.
1854    // however, if the result of the stmt expr is dead, we don't want to emit a
1855    // warning.
1856    const CompoundStmt *CS = cast<StmtExpr>(this)->getSubStmt();
1857    if (!CS->body_empty()) {
1858      if (const Expr *E = dyn_cast<Expr>(CS->body_back()))
1859        return E->isUnusedResultAWarning(Loc, R1, R2, Ctx);
1860      if (const LabelStmt *Label = dyn_cast<LabelStmt>(CS->body_back()))
1861        if (const Expr *E = dyn_cast<Expr>(Label->getSubStmt()))
1862          return E->isUnusedResultAWarning(Loc, R1, R2, Ctx);
1863    }
1864
1865    if (getType()->isVoidType())
1866      return false;
1867    Loc = cast<StmtExpr>(this)->getLParenLoc();
1868    R1 = getSourceRange();
1869    return true;
1870  }
1871  case CStyleCastExprClass:
1872    // If this is an explicit cast to void, allow it.  People do this when they
1873    // think they know what they're doing :).
1874    if (getType()->isVoidType())
1875      return false;
1876    Loc = cast<CStyleCastExpr>(this)->getLParenLoc();
1877    R1 = cast<CStyleCastExpr>(this)->getSubExpr()->getSourceRange();
1878    return true;
1879  case CXXFunctionalCastExprClass: {
1880    if (getType()->isVoidType())
1881      return false;
1882    const CastExpr *CE = cast<CastExpr>(this);
1883
1884    // If this is a cast to void or a constructor conversion, check the operand.
1885    // Otherwise, the result of the cast is unused.
1886    if (CE->getCastKind() == CK_ToVoid ||
1887        CE->getCastKind() == CK_ConstructorConversion)
1888      return (cast<CastExpr>(this)->getSubExpr()
1889              ->isUnusedResultAWarning(Loc, R1, R2, Ctx));
1890    Loc = cast<CXXFunctionalCastExpr>(this)->getTypeBeginLoc();
1891    R1 = cast<CXXFunctionalCastExpr>(this)->getSubExpr()->getSourceRange();
1892    return true;
1893  }
1894
1895  case ImplicitCastExprClass:
1896    // Check the operand, since implicit casts are inserted by Sema
1897    return (cast<ImplicitCastExpr>(this)
1898            ->getSubExpr()->isUnusedResultAWarning(Loc, R1, R2, Ctx));
1899
1900  case CXXDefaultArgExprClass:
1901    return (cast<CXXDefaultArgExpr>(this)
1902            ->getExpr()->isUnusedResultAWarning(Loc, R1, R2, Ctx));
1903
1904  case CXXNewExprClass:
1905    // FIXME: In theory, there might be new expressions that don't have side
1906    // effects (e.g. a placement new with an uninitialized POD).
1907  case CXXDeleteExprClass:
1908    return false;
1909  case CXXBindTemporaryExprClass:
1910    return (cast<CXXBindTemporaryExpr>(this)
1911            ->getSubExpr()->isUnusedResultAWarning(Loc, R1, R2, Ctx));
1912  case ExprWithCleanupsClass:
1913    return (cast<ExprWithCleanups>(this)
1914            ->getSubExpr()->isUnusedResultAWarning(Loc, R1, R2, Ctx));
1915  }
1916}
1917
1918/// isOBJCGCCandidate - Check if an expression is objc gc'able.
1919/// returns true, if it is; false otherwise.
1920bool Expr::isOBJCGCCandidate(ASTContext &Ctx) const {
1921  const Expr *E = IgnoreParens();
1922  switch (E->getStmtClass()) {
1923  default:
1924    return false;
1925  case ObjCIvarRefExprClass:
1926    return true;
1927  case Expr::UnaryOperatorClass:
1928    return cast<UnaryOperator>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
1929  case ImplicitCastExprClass:
1930    return cast<ImplicitCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
1931  case MaterializeTemporaryExprClass:
1932    return cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr()
1933                                                      ->isOBJCGCCandidate(Ctx);
1934  case CStyleCastExprClass:
1935    return cast<CStyleCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
1936  case DeclRefExprClass: {
1937    const Decl *D = cast<DeclRefExpr>(E)->getDecl();
1938
1939    if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1940      if (VD->hasGlobalStorage())
1941        return true;
1942      QualType T = VD->getType();
1943      // dereferencing to a  pointer is always a gc'able candidate,
1944      // unless it is __weak.
1945      return T->isPointerType() &&
1946             (Ctx.getObjCGCAttrKind(T) != Qualifiers::Weak);
1947    }
1948    return false;
1949  }
1950  case MemberExprClass: {
1951    const MemberExpr *M = cast<MemberExpr>(E);
1952    return M->getBase()->isOBJCGCCandidate(Ctx);
1953  }
1954  case ArraySubscriptExprClass:
1955    return cast<ArraySubscriptExpr>(E)->getBase()->isOBJCGCCandidate(Ctx);
1956  }
1957}
1958
1959bool Expr::isBoundMemberFunction(ASTContext &Ctx) const {
1960  if (isTypeDependent())
1961    return false;
1962  return ClassifyLValue(Ctx) == Expr::LV_MemberFunction;
1963}
1964
1965QualType Expr::findBoundMemberType(const Expr *expr) {
1966  assert(expr->hasPlaceholderType(BuiltinType::BoundMember));
1967
1968  // Bound member expressions are always one of these possibilities:
1969  //   x->m      x.m      x->*y      x.*y
1970  // (possibly parenthesized)
1971
1972  expr = expr->IgnoreParens();
1973  if (const MemberExpr *mem = dyn_cast<MemberExpr>(expr)) {
1974    assert(isa<CXXMethodDecl>(mem->getMemberDecl()));
1975    return mem->getMemberDecl()->getType();
1976  }
1977
1978  if (const BinaryOperator *op = dyn_cast<BinaryOperator>(expr)) {
1979    QualType type = op->getRHS()->getType()->castAs<MemberPointerType>()
1980                      ->getPointeeType();
1981    assert(type->isFunctionType());
1982    return type;
1983  }
1984
1985  assert(isa<UnresolvedMemberExpr>(expr));
1986  return QualType();
1987}
1988
1989static Expr::CanThrowResult MergeCanThrow(Expr::CanThrowResult CT1,
1990                                          Expr::CanThrowResult CT2) {
1991  // CanThrowResult constants are ordered so that the maximum is the correct
1992  // merge result.
1993  return CT1 > CT2 ? CT1 : CT2;
1994}
1995
1996static Expr::CanThrowResult CanSubExprsThrow(ASTContext &C, const Expr *CE) {
1997  Expr *E = const_cast<Expr*>(CE);
1998  Expr::CanThrowResult R = Expr::CT_Cannot;
1999  for (Expr::child_range I = E->children(); I && R != Expr::CT_Can; ++I) {
2000    R = MergeCanThrow(R, cast<Expr>(*I)->CanThrow(C));
2001  }
2002  return R;
2003}
2004
2005static Expr::CanThrowResult CanCalleeThrow(ASTContext &Ctx, const Expr *E,
2006                                           const Decl *D,
2007                                           bool NullThrows = true) {
2008  if (!D)
2009    return NullThrows ? Expr::CT_Can : Expr::CT_Cannot;
2010
2011  // See if we can get a function type from the decl somehow.
2012  const ValueDecl *VD = dyn_cast<ValueDecl>(D);
2013  if (!VD) // If we have no clue what we're calling, assume the worst.
2014    return Expr::CT_Can;
2015
2016  // As an extension, we assume that __attribute__((nothrow)) functions don't
2017  // throw.
2018  if (isa<FunctionDecl>(D) && D->hasAttr<NoThrowAttr>())
2019    return Expr::CT_Cannot;
2020
2021  QualType T = VD->getType();
2022  const FunctionProtoType *FT;
2023  if ((FT = T->getAs<FunctionProtoType>())) {
2024  } else if (const PointerType *PT = T->getAs<PointerType>())
2025    FT = PT->getPointeeType()->getAs<FunctionProtoType>();
2026  else if (const ReferenceType *RT = T->getAs<ReferenceType>())
2027    FT = RT->getPointeeType()->getAs<FunctionProtoType>();
2028  else if (const MemberPointerType *MT = T->getAs<MemberPointerType>())
2029    FT = MT->getPointeeType()->getAs<FunctionProtoType>();
2030  else if (const BlockPointerType *BT = T->getAs<BlockPointerType>())
2031    FT = BT->getPointeeType()->getAs<FunctionProtoType>();
2032
2033  if (!FT)
2034    return Expr::CT_Can;
2035
2036  if (FT->getExceptionSpecType() == EST_Delayed) {
2037    assert(isa<CXXConstructorDecl>(D) &&
2038           "only constructor exception specs can be unknown");
2039    Ctx.getDiagnostics().Report(E->getLocStart(),
2040                                diag::err_exception_spec_unknown)
2041      << E->getSourceRange();
2042    return Expr::CT_Can;
2043  }
2044
2045  return FT->isNothrow(Ctx) ? Expr::CT_Cannot : Expr::CT_Can;
2046}
2047
2048static Expr::CanThrowResult CanDynamicCastThrow(const CXXDynamicCastExpr *DC) {
2049  if (DC->isTypeDependent())
2050    return Expr::CT_Dependent;
2051
2052  if (!DC->getTypeAsWritten()->isReferenceType())
2053    return Expr::CT_Cannot;
2054
2055  if (DC->getSubExpr()->isTypeDependent())
2056    return Expr::CT_Dependent;
2057
2058  return DC->getCastKind() == clang::CK_Dynamic? Expr::CT_Can : Expr::CT_Cannot;
2059}
2060
2061static Expr::CanThrowResult CanTypeidThrow(ASTContext &C,
2062                                           const CXXTypeidExpr *DC) {
2063  if (DC->isTypeOperand())
2064    return Expr::CT_Cannot;
2065
2066  Expr *Op = DC->getExprOperand();
2067  if (Op->isTypeDependent())
2068    return Expr::CT_Dependent;
2069
2070  const RecordType *RT = Op->getType()->getAs<RecordType>();
2071  if (!RT)
2072    return Expr::CT_Cannot;
2073
2074  if (!cast<CXXRecordDecl>(RT->getDecl())->isPolymorphic())
2075    return Expr::CT_Cannot;
2076
2077  if (Op->Classify(C).isPRValue())
2078    return Expr::CT_Cannot;
2079
2080  return Expr::CT_Can;
2081}
2082
2083Expr::CanThrowResult Expr::CanThrow(ASTContext &C) const {
2084  // C++ [expr.unary.noexcept]p3:
2085  //   [Can throw] if in a potentially-evaluated context the expression would
2086  //   contain:
2087  switch (getStmtClass()) {
2088  case CXXThrowExprClass:
2089    //   - a potentially evaluated throw-expression
2090    return CT_Can;
2091
2092  case CXXDynamicCastExprClass: {
2093    //   - a potentially evaluated dynamic_cast expression dynamic_cast<T>(v),
2094    //     where T is a reference type, that requires a run-time check
2095    CanThrowResult CT = CanDynamicCastThrow(cast<CXXDynamicCastExpr>(this));
2096    if (CT == CT_Can)
2097      return CT;
2098    return MergeCanThrow(CT, CanSubExprsThrow(C, this));
2099  }
2100
2101  case CXXTypeidExprClass:
2102    //   - a potentially evaluated typeid expression applied to a glvalue
2103    //     expression whose type is a polymorphic class type
2104    return CanTypeidThrow(C, cast<CXXTypeidExpr>(this));
2105
2106    //   - a potentially evaluated call to a function, member function, function
2107    //     pointer, or member function pointer that does not have a non-throwing
2108    //     exception-specification
2109  case CallExprClass:
2110  case CXXMemberCallExprClass:
2111  case CXXOperatorCallExprClass:
2112  case UserDefinedLiteralClass: {
2113    const CallExpr *CE = cast<CallExpr>(this);
2114    CanThrowResult CT;
2115    if (isTypeDependent())
2116      CT = CT_Dependent;
2117    else if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens()))
2118      CT = CT_Cannot;
2119    else
2120      CT = CanCalleeThrow(C, this, CE->getCalleeDecl());
2121    if (CT == CT_Can)
2122      return CT;
2123    return MergeCanThrow(CT, CanSubExprsThrow(C, this));
2124  }
2125
2126  case CXXConstructExprClass:
2127  case CXXTemporaryObjectExprClass: {
2128    CanThrowResult CT = CanCalleeThrow(C, this,
2129        cast<CXXConstructExpr>(this)->getConstructor());
2130    if (CT == CT_Can)
2131      return CT;
2132    return MergeCanThrow(CT, CanSubExprsThrow(C, this));
2133  }
2134
2135  case LambdaExprClass: {
2136    const LambdaExpr *Lambda = cast<LambdaExpr>(this);
2137    CanThrowResult CT = Expr::CT_Cannot;
2138    for (LambdaExpr::capture_init_iterator Cap = Lambda->capture_init_begin(),
2139                                        CapEnd = Lambda->capture_init_end();
2140         Cap != CapEnd; ++Cap)
2141      CT = MergeCanThrow(CT, (*Cap)->CanThrow(C));
2142    return CT;
2143  }
2144
2145  case CXXNewExprClass: {
2146    CanThrowResult CT;
2147    if (isTypeDependent())
2148      CT = CT_Dependent;
2149    else
2150      CT = CanCalleeThrow(C, this, cast<CXXNewExpr>(this)->getOperatorNew());
2151    if (CT == CT_Can)
2152      return CT;
2153    return MergeCanThrow(CT, CanSubExprsThrow(C, this));
2154  }
2155
2156  case CXXDeleteExprClass: {
2157    CanThrowResult CT;
2158    QualType DTy = cast<CXXDeleteExpr>(this)->getDestroyedType();
2159    if (DTy.isNull() || DTy->isDependentType()) {
2160      CT = CT_Dependent;
2161    } else {
2162      CT = CanCalleeThrow(C, this,
2163                          cast<CXXDeleteExpr>(this)->getOperatorDelete());
2164      if (const RecordType *RT = DTy->getAs<RecordType>()) {
2165        const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2166        CT = MergeCanThrow(CT, CanCalleeThrow(C, this, RD->getDestructor()));
2167      }
2168      if (CT == CT_Can)
2169        return CT;
2170    }
2171    return MergeCanThrow(CT, CanSubExprsThrow(C, this));
2172  }
2173
2174  case CXXBindTemporaryExprClass: {
2175    // The bound temporary has to be destroyed again, which might throw.
2176    CanThrowResult CT = CanCalleeThrow(C, this,
2177      cast<CXXBindTemporaryExpr>(this)->getTemporary()->getDestructor());
2178    if (CT == CT_Can)
2179      return CT;
2180    return MergeCanThrow(CT, CanSubExprsThrow(C, this));
2181  }
2182
2183    // ObjC message sends are like function calls, but never have exception
2184    // specs.
2185  case ObjCMessageExprClass:
2186  case ObjCPropertyRefExprClass:
2187  case ObjCSubscriptRefExprClass:
2188    return CT_Can;
2189
2190    // All the ObjC literals that are implemented as calls are
2191    // potentially throwing unless we decide to close off that
2192    // possibility.
2193  case ObjCArrayLiteralClass:
2194  case ObjCDictionaryLiteralClass:
2195  case ObjCNumericLiteralClass:
2196    return CT_Can;
2197
2198    // Many other things have subexpressions, so we have to test those.
2199    // Some are simple:
2200  case ConditionalOperatorClass:
2201  case CompoundLiteralExprClass:
2202  case CXXConstCastExprClass:
2203  case CXXDefaultArgExprClass:
2204  case CXXReinterpretCastExprClass:
2205  case DesignatedInitExprClass:
2206  case ExprWithCleanupsClass:
2207  case ExtVectorElementExprClass:
2208  case InitListExprClass:
2209  case MemberExprClass:
2210  case ObjCIsaExprClass:
2211  case ObjCIvarRefExprClass:
2212  case ParenExprClass:
2213  case ParenListExprClass:
2214  case ShuffleVectorExprClass:
2215  case VAArgExprClass:
2216    return CanSubExprsThrow(C, this);
2217
2218    // Some might be dependent for other reasons.
2219  case ArraySubscriptExprClass:
2220  case BinaryOperatorClass:
2221  case CompoundAssignOperatorClass:
2222  case CStyleCastExprClass:
2223  case CXXStaticCastExprClass:
2224  case CXXFunctionalCastExprClass:
2225  case ImplicitCastExprClass:
2226  case MaterializeTemporaryExprClass:
2227  case UnaryOperatorClass: {
2228    CanThrowResult CT = isTypeDependent() ? CT_Dependent : CT_Cannot;
2229    return MergeCanThrow(CT, CanSubExprsThrow(C, this));
2230  }
2231
2232    // FIXME: We should handle StmtExpr, but that opens a MASSIVE can of worms.
2233  case StmtExprClass:
2234    return CT_Can;
2235
2236  case ChooseExprClass:
2237    if (isTypeDependent() || isValueDependent())
2238      return CT_Dependent;
2239    return cast<ChooseExpr>(this)->getChosenSubExpr(C)->CanThrow(C);
2240
2241  case GenericSelectionExprClass:
2242    if (cast<GenericSelectionExpr>(this)->isResultDependent())
2243      return CT_Dependent;
2244    return cast<GenericSelectionExpr>(this)->getResultExpr()->CanThrow(C);
2245
2246    // Some expressions are always dependent.
2247  case CXXDependentScopeMemberExprClass:
2248  case CXXUnresolvedConstructExprClass:
2249  case DependentScopeDeclRefExprClass:
2250    return CT_Dependent;
2251
2252  case AtomicExprClass:
2253  case AsTypeExprClass:
2254  case BinaryConditionalOperatorClass:
2255  case BlockExprClass:
2256  case CUDAKernelCallExprClass:
2257  case DeclRefExprClass:
2258  case ObjCBridgedCastExprClass:
2259  case ObjCIndirectCopyRestoreExprClass:
2260  case ObjCProtocolExprClass:
2261  case ObjCSelectorExprClass:
2262  case OffsetOfExprClass:
2263  case PackExpansionExprClass:
2264  case PseudoObjectExprClass:
2265  case SubstNonTypeTemplateParmExprClass:
2266  case SubstNonTypeTemplateParmPackExprClass:
2267  case UnaryExprOrTypeTraitExprClass:
2268  case UnresolvedLookupExprClass:
2269  case UnresolvedMemberExprClass:
2270    // FIXME: Can any of the above throw?  If so, when?
2271    return CT_Cannot;
2272
2273  case AddrLabelExprClass:
2274  case ArrayTypeTraitExprClass:
2275  case BinaryTypeTraitExprClass:
2276  case TypeTraitExprClass:
2277  case CXXBoolLiteralExprClass:
2278  case CXXNoexceptExprClass:
2279  case CXXNullPtrLiteralExprClass:
2280  case CXXPseudoDestructorExprClass:
2281  case CXXScalarValueInitExprClass:
2282  case CXXThisExprClass:
2283  case CXXUuidofExprClass:
2284  case CharacterLiteralClass:
2285  case ExpressionTraitExprClass:
2286  case FloatingLiteralClass:
2287  case GNUNullExprClass:
2288  case ImaginaryLiteralClass:
2289  case ImplicitValueInitExprClass:
2290  case IntegerLiteralClass:
2291  case ObjCEncodeExprClass:
2292  case ObjCStringLiteralClass:
2293  case ObjCBoolLiteralExprClass:
2294  case OpaqueValueExprClass:
2295  case PredefinedExprClass:
2296  case SizeOfPackExprClass:
2297  case StringLiteralClass:
2298  case UnaryTypeTraitExprClass:
2299    // These expressions can never throw.
2300    return CT_Cannot;
2301
2302#define STMT(CLASS, PARENT) case CLASS##Class:
2303#define STMT_RANGE(Base, First, Last)
2304#define LAST_STMT_RANGE(BASE, FIRST, LAST)
2305#define EXPR(CLASS, PARENT)
2306#define ABSTRACT_STMT(STMT)
2307#include "clang/AST/StmtNodes.inc"
2308  case NoStmtClass:
2309    llvm_unreachable("Invalid class for expression");
2310  }
2311  llvm_unreachable("Bogus StmtClass");
2312}
2313
2314Expr* Expr::IgnoreParens() {
2315  Expr* E = this;
2316  while (true) {
2317    if (ParenExpr* P = dyn_cast<ParenExpr>(E)) {
2318      E = P->getSubExpr();
2319      continue;
2320    }
2321    if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) {
2322      if (P->getOpcode() == UO_Extension) {
2323        E = P->getSubExpr();
2324        continue;
2325      }
2326    }
2327    if (GenericSelectionExpr* P = dyn_cast<GenericSelectionExpr>(E)) {
2328      if (!P->isResultDependent()) {
2329        E = P->getResultExpr();
2330        continue;
2331      }
2332    }
2333    return E;
2334  }
2335}
2336
2337/// IgnoreParenCasts - Ignore parentheses and casts.  Strip off any ParenExpr
2338/// or CastExprs or ImplicitCastExprs, returning their operand.
2339Expr *Expr::IgnoreParenCasts() {
2340  Expr *E = this;
2341  while (true) {
2342    if (ParenExpr* P = dyn_cast<ParenExpr>(E)) {
2343      E = P->getSubExpr();
2344      continue;
2345    }
2346    if (CastExpr *P = dyn_cast<CastExpr>(E)) {
2347      E = P->getSubExpr();
2348      continue;
2349    }
2350    if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) {
2351      if (P->getOpcode() == UO_Extension) {
2352        E = P->getSubExpr();
2353        continue;
2354      }
2355    }
2356    if (GenericSelectionExpr* P = dyn_cast<GenericSelectionExpr>(E)) {
2357      if (!P->isResultDependent()) {
2358        E = P->getResultExpr();
2359        continue;
2360      }
2361    }
2362    if (MaterializeTemporaryExpr *Materialize
2363                                      = dyn_cast<MaterializeTemporaryExpr>(E)) {
2364      E = Materialize->GetTemporaryExpr();
2365      continue;
2366    }
2367    if (SubstNonTypeTemplateParmExpr *NTTP
2368                                  = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2369      E = NTTP->getReplacement();
2370      continue;
2371    }
2372    return E;
2373  }
2374}
2375
2376/// IgnoreParenLValueCasts - Ignore parentheses and lvalue-to-rvalue
2377/// casts.  This is intended purely as a temporary workaround for code
2378/// that hasn't yet been rewritten to do the right thing about those
2379/// casts, and may disappear along with the last internal use.
2380Expr *Expr::IgnoreParenLValueCasts() {
2381  Expr *E = this;
2382  while (true) {
2383    if (ParenExpr *P = dyn_cast<ParenExpr>(E)) {
2384      E = P->getSubExpr();
2385      continue;
2386    } else if (CastExpr *P = dyn_cast<CastExpr>(E)) {
2387      if (P->getCastKind() == CK_LValueToRValue) {
2388        E = P->getSubExpr();
2389        continue;
2390      }
2391    } else if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) {
2392      if (P->getOpcode() == UO_Extension) {
2393        E = P->getSubExpr();
2394        continue;
2395      }
2396    } else if (GenericSelectionExpr* P = dyn_cast<GenericSelectionExpr>(E)) {
2397      if (!P->isResultDependent()) {
2398        E = P->getResultExpr();
2399        continue;
2400      }
2401    } else if (MaterializeTemporaryExpr *Materialize
2402                                      = dyn_cast<MaterializeTemporaryExpr>(E)) {
2403      E = Materialize->GetTemporaryExpr();
2404      continue;
2405    } else if (SubstNonTypeTemplateParmExpr *NTTP
2406                                  = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2407      E = NTTP->getReplacement();
2408      continue;
2409    }
2410    break;
2411  }
2412  return E;
2413}
2414
2415Expr *Expr::IgnoreParenImpCasts() {
2416  Expr *E = this;
2417  while (true) {
2418    if (ParenExpr *P = dyn_cast<ParenExpr>(E)) {
2419      E = P->getSubExpr();
2420      continue;
2421    }
2422    if (ImplicitCastExpr *P = dyn_cast<ImplicitCastExpr>(E)) {
2423      E = P->getSubExpr();
2424      continue;
2425    }
2426    if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) {
2427      if (P->getOpcode() == UO_Extension) {
2428        E = P->getSubExpr();
2429        continue;
2430      }
2431    }
2432    if (GenericSelectionExpr* P = dyn_cast<GenericSelectionExpr>(E)) {
2433      if (!P->isResultDependent()) {
2434        E = P->getResultExpr();
2435        continue;
2436      }
2437    }
2438    if (MaterializeTemporaryExpr *Materialize
2439                                      = dyn_cast<MaterializeTemporaryExpr>(E)) {
2440      E = Materialize->GetTemporaryExpr();
2441      continue;
2442    }
2443    if (SubstNonTypeTemplateParmExpr *NTTP
2444                                  = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2445      E = NTTP->getReplacement();
2446      continue;
2447    }
2448    return E;
2449  }
2450}
2451
2452Expr *Expr::IgnoreConversionOperator() {
2453  if (CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(this)) {
2454    if (MCE->getMethodDecl() && isa<CXXConversionDecl>(MCE->getMethodDecl()))
2455      return MCE->getImplicitObjectArgument();
2456  }
2457  return this;
2458}
2459
2460/// IgnoreParenNoopCasts - Ignore parentheses and casts that do not change the
2461/// value (including ptr->int casts of the same size).  Strip off any
2462/// ParenExpr or CastExprs, returning their operand.
2463Expr *Expr::IgnoreParenNoopCasts(ASTContext &Ctx) {
2464  Expr *E = this;
2465  while (true) {
2466    if (ParenExpr *P = dyn_cast<ParenExpr>(E)) {
2467      E = P->getSubExpr();
2468      continue;
2469    }
2470
2471    if (CastExpr *P = dyn_cast<CastExpr>(E)) {
2472      // We ignore integer <-> casts that are of the same width, ptr<->ptr and
2473      // ptr<->int casts of the same width.  We also ignore all identity casts.
2474      Expr *SE = P->getSubExpr();
2475
2476      if (Ctx.hasSameUnqualifiedType(E->getType(), SE->getType())) {
2477        E = SE;
2478        continue;
2479      }
2480
2481      if ((E->getType()->isPointerType() ||
2482           E->getType()->isIntegralType(Ctx)) &&
2483          (SE->getType()->isPointerType() ||
2484           SE->getType()->isIntegralType(Ctx)) &&
2485          Ctx.getTypeSize(E->getType()) == Ctx.getTypeSize(SE->getType())) {
2486        E = SE;
2487        continue;
2488      }
2489    }
2490
2491    if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) {
2492      if (P->getOpcode() == UO_Extension) {
2493        E = P->getSubExpr();
2494        continue;
2495      }
2496    }
2497
2498    if (GenericSelectionExpr* P = dyn_cast<GenericSelectionExpr>(E)) {
2499      if (!P->isResultDependent()) {
2500        E = P->getResultExpr();
2501        continue;
2502      }
2503    }
2504
2505    if (SubstNonTypeTemplateParmExpr *NTTP
2506                                  = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2507      E = NTTP->getReplacement();
2508      continue;
2509    }
2510
2511    return E;
2512  }
2513}
2514
2515bool Expr::isDefaultArgument() const {
2516  const Expr *E = this;
2517  if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
2518    E = M->GetTemporaryExpr();
2519
2520  while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
2521    E = ICE->getSubExprAsWritten();
2522
2523  return isa<CXXDefaultArgExpr>(E);
2524}
2525
2526/// \brief Skip over any no-op casts and any temporary-binding
2527/// expressions.
2528static const Expr *skipTemporaryBindingsNoOpCastsAndParens(const Expr *E) {
2529  if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
2530    E = M->GetTemporaryExpr();
2531
2532  while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2533    if (ICE->getCastKind() == CK_NoOp)
2534      E = ICE->getSubExpr();
2535    else
2536      break;
2537  }
2538
2539  while (const CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
2540    E = BE->getSubExpr();
2541
2542  while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2543    if (ICE->getCastKind() == CK_NoOp)
2544      E = ICE->getSubExpr();
2545    else
2546      break;
2547  }
2548
2549  return E->IgnoreParens();
2550}
2551
2552/// isTemporaryObject - Determines if this expression produces a
2553/// temporary of the given class type.
2554bool Expr::isTemporaryObject(ASTContext &C, const CXXRecordDecl *TempTy) const {
2555  if (!C.hasSameUnqualifiedType(getType(), C.getTypeDeclType(TempTy)))
2556    return false;
2557
2558  const Expr *E = skipTemporaryBindingsNoOpCastsAndParens(this);
2559
2560  // Temporaries are by definition pr-values of class type.
2561  if (!E->Classify(C).isPRValue()) {
2562    // In this context, property reference is a message call and is pr-value.
2563    if (!isa<ObjCPropertyRefExpr>(E))
2564      return false;
2565  }
2566
2567  // Black-list a few cases which yield pr-values of class type that don't
2568  // refer to temporaries of that type:
2569
2570  // - implicit derived-to-base conversions
2571  if (isa<ImplicitCastExpr>(E)) {
2572    switch (cast<ImplicitCastExpr>(E)->getCastKind()) {
2573    case CK_DerivedToBase:
2574    case CK_UncheckedDerivedToBase:
2575      return false;
2576    default:
2577      break;
2578    }
2579  }
2580
2581  // - member expressions (all)
2582  if (isa<MemberExpr>(E))
2583    return false;
2584
2585  // - opaque values (all)
2586  if (isa<OpaqueValueExpr>(E))
2587    return false;
2588
2589  return true;
2590}
2591
2592bool Expr::isImplicitCXXThis() const {
2593  const Expr *E = this;
2594
2595  // Strip away parentheses and casts we don't care about.
2596  while (true) {
2597    if (const ParenExpr *Paren = dyn_cast<ParenExpr>(E)) {
2598      E = Paren->getSubExpr();
2599      continue;
2600    }
2601
2602    if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2603      if (ICE->getCastKind() == CK_NoOp ||
2604          ICE->getCastKind() == CK_LValueToRValue ||
2605          ICE->getCastKind() == CK_DerivedToBase ||
2606          ICE->getCastKind() == CK_UncheckedDerivedToBase) {
2607        E = ICE->getSubExpr();
2608        continue;
2609      }
2610    }
2611
2612    if (const UnaryOperator* UnOp = dyn_cast<UnaryOperator>(E)) {
2613      if (UnOp->getOpcode() == UO_Extension) {
2614        E = UnOp->getSubExpr();
2615        continue;
2616      }
2617    }
2618
2619    if (const MaterializeTemporaryExpr *M
2620                                      = dyn_cast<MaterializeTemporaryExpr>(E)) {
2621      E = M->GetTemporaryExpr();
2622      continue;
2623    }
2624
2625    break;
2626  }
2627
2628  if (const CXXThisExpr *This = dyn_cast<CXXThisExpr>(E))
2629    return This->isImplicit();
2630
2631  return false;
2632}
2633
2634/// hasAnyTypeDependentArguments - Determines if any of the expressions
2635/// in Exprs is type-dependent.
2636bool Expr::hasAnyTypeDependentArguments(llvm::ArrayRef<Expr *> Exprs) {
2637  for (unsigned I = 0; I < Exprs.size(); ++I)
2638    if (Exprs[I]->isTypeDependent())
2639      return true;
2640
2641  return false;
2642}
2643
2644bool Expr::isConstantInitializer(ASTContext &Ctx, bool IsForRef) const {
2645  // This function is attempting whether an expression is an initializer
2646  // which can be evaluated at compile-time.  isEvaluatable handles most
2647  // of the cases, but it can't deal with some initializer-specific
2648  // expressions, and it can't deal with aggregates; we deal with those here,
2649  // and fall back to isEvaluatable for the other cases.
2650
2651  // If we ever capture reference-binding directly in the AST, we can
2652  // kill the second parameter.
2653
2654  if (IsForRef) {
2655    EvalResult Result;
2656    return EvaluateAsLValue(Result, Ctx) && !Result.HasSideEffects;
2657  }
2658
2659  switch (getStmtClass()) {
2660  default: break;
2661  case IntegerLiteralClass:
2662  case FloatingLiteralClass:
2663  case StringLiteralClass:
2664  case ObjCStringLiteralClass:
2665  case ObjCEncodeExprClass:
2666    return true;
2667  case CXXTemporaryObjectExprClass:
2668  case CXXConstructExprClass: {
2669    const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
2670
2671    // Only if it's
2672    if (CE->getConstructor()->isTrivial()) {
2673      // 1) an application of the trivial default constructor or
2674      if (!CE->getNumArgs()) return true;
2675
2676      // 2) an elidable trivial copy construction of an operand which is
2677      //    itself a constant initializer.  Note that we consider the
2678      //    operand on its own, *not* as a reference binding.
2679      if (CE->isElidable() &&
2680          CE->getArg(0)->isConstantInitializer(Ctx, false))
2681        return true;
2682    }
2683
2684    // 3) a foldable constexpr constructor.
2685    break;
2686  }
2687  case CompoundLiteralExprClass: {
2688    // This handles gcc's extension that allows global initializers like
2689    // "struct x {int x;} x = (struct x) {};".
2690    // FIXME: This accepts other cases it shouldn't!
2691    const Expr *Exp = cast<CompoundLiteralExpr>(this)->getInitializer();
2692    return Exp->isConstantInitializer(Ctx, false);
2693  }
2694  case InitListExprClass: {
2695    // FIXME: This doesn't deal with fields with reference types correctly.
2696    // FIXME: This incorrectly allows pointers cast to integers to be assigned
2697    // to bitfields.
2698    const InitListExpr *Exp = cast<InitListExpr>(this);
2699    unsigned numInits = Exp->getNumInits();
2700    for (unsigned i = 0; i < numInits; i++) {
2701      if (!Exp->getInit(i)->isConstantInitializer(Ctx, false))
2702        return false;
2703    }
2704    return true;
2705  }
2706  case ImplicitValueInitExprClass:
2707    return true;
2708  case ParenExprClass:
2709    return cast<ParenExpr>(this)->getSubExpr()
2710      ->isConstantInitializer(Ctx, IsForRef);
2711  case GenericSelectionExprClass:
2712    if (cast<GenericSelectionExpr>(this)->isResultDependent())
2713      return false;
2714    return cast<GenericSelectionExpr>(this)->getResultExpr()
2715      ->isConstantInitializer(Ctx, IsForRef);
2716  case ChooseExprClass:
2717    return cast<ChooseExpr>(this)->getChosenSubExpr(Ctx)
2718      ->isConstantInitializer(Ctx, IsForRef);
2719  case UnaryOperatorClass: {
2720    const UnaryOperator* Exp = cast<UnaryOperator>(this);
2721    if (Exp->getOpcode() == UO_Extension)
2722      return Exp->getSubExpr()->isConstantInitializer(Ctx, false);
2723    break;
2724  }
2725  case CXXFunctionalCastExprClass:
2726  case CXXStaticCastExprClass:
2727  case ImplicitCastExprClass:
2728  case CStyleCastExprClass: {
2729    const CastExpr *CE = cast<CastExpr>(this);
2730
2731    // If we're promoting an integer to an _Atomic type then this is constant
2732    // if the integer is constant.  We also need to check the converse in case
2733    // someone does something like:
2734    //
2735    // int a = (_Atomic(int))42;
2736    //
2737    // I doubt anyone would write code like this directly, but it's quite
2738    // possible as the result of macro expansions.
2739    if (CE->getCastKind() == CK_NonAtomicToAtomic ||
2740        CE->getCastKind() == CK_AtomicToNonAtomic)
2741      return CE->getSubExpr()->isConstantInitializer(Ctx, false);
2742
2743    // Handle bitcasts of vector constants.
2744    if (getType()->isVectorType() && CE->getCastKind() == CK_BitCast)
2745      return CE->getSubExpr()->isConstantInitializer(Ctx, false);
2746
2747    // Handle misc casts we want to ignore.
2748    // FIXME: Is it really safe to ignore all these?
2749    if (CE->getCastKind() == CK_NoOp ||
2750        CE->getCastKind() == CK_LValueToRValue ||
2751        CE->getCastKind() == CK_ToUnion ||
2752        CE->getCastKind() == CK_ConstructorConversion)
2753      return CE->getSubExpr()->isConstantInitializer(Ctx, false);
2754
2755    break;
2756  }
2757  case MaterializeTemporaryExprClass:
2758    return cast<MaterializeTemporaryExpr>(this)->GetTemporaryExpr()
2759                                            ->isConstantInitializer(Ctx, false);
2760  }
2761  return isEvaluatable(Ctx);
2762}
2763
2764namespace {
2765  /// \brief Look for a call to a non-trivial function within an expression.
2766  class NonTrivialCallFinder : public EvaluatedExprVisitor<NonTrivialCallFinder>
2767  {
2768    typedef EvaluatedExprVisitor<NonTrivialCallFinder> Inherited;
2769
2770    bool NonTrivial;
2771
2772  public:
2773    explicit NonTrivialCallFinder(ASTContext &Context)
2774      : Inherited(Context), NonTrivial(false) { }
2775
2776    bool hasNonTrivialCall() const { return NonTrivial; }
2777
2778    void VisitCallExpr(CallExpr *E) {
2779      if (CXXMethodDecl *Method
2780          = dyn_cast_or_null<CXXMethodDecl>(E->getCalleeDecl())) {
2781        if (Method->isTrivial()) {
2782          // Recurse to children of the call.
2783          Inherited::VisitStmt(E);
2784          return;
2785        }
2786      }
2787
2788      NonTrivial = true;
2789    }
2790
2791    void VisitCXXConstructExpr(CXXConstructExpr *E) {
2792      if (E->getConstructor()->isTrivial()) {
2793        // Recurse to children of the call.
2794        Inherited::VisitStmt(E);
2795        return;
2796      }
2797
2798      NonTrivial = true;
2799    }
2800
2801    void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
2802      if (E->getTemporary()->getDestructor()->isTrivial()) {
2803        Inherited::VisitStmt(E);
2804        return;
2805      }
2806
2807      NonTrivial = true;
2808    }
2809  };
2810}
2811
2812bool Expr::hasNonTrivialCall(ASTContext &Ctx) {
2813  NonTrivialCallFinder Finder(Ctx);
2814  Finder.Visit(this);
2815  return Finder.hasNonTrivialCall();
2816}
2817
2818/// isNullPointerConstant - C99 6.3.2.3p3 - Return whether this is a null
2819/// pointer constant or not, as well as the specific kind of constant detected.
2820/// Null pointer constants can be integer constant expressions with the
2821/// value zero, casts of zero to void*, nullptr (C++0X), or __null
2822/// (a GNU extension).
2823Expr::NullPointerConstantKind
2824Expr::isNullPointerConstant(ASTContext &Ctx,
2825                            NullPointerConstantValueDependence NPC) const {
2826  if (isValueDependent()) {
2827    switch (NPC) {
2828    case NPC_NeverValueDependent:
2829      llvm_unreachable("Unexpected value dependent expression!");
2830    case NPC_ValueDependentIsNull:
2831      if (isTypeDependent() || getType()->isIntegralType(Ctx))
2832        return NPCK_ZeroInteger;
2833      else
2834        return NPCK_NotNull;
2835
2836    case NPC_ValueDependentIsNotNull:
2837      return NPCK_NotNull;
2838    }
2839  }
2840
2841  // Strip off a cast to void*, if it exists. Except in C++.
2842  if (const ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(this)) {
2843    if (!Ctx.getLangOpts().CPlusPlus) {
2844      // Check that it is a cast to void*.
2845      if (const PointerType *PT = CE->getType()->getAs<PointerType>()) {
2846        QualType Pointee = PT->getPointeeType();
2847        if (!Pointee.hasQualifiers() &&
2848            Pointee->isVoidType() &&                              // to void*
2849            CE->getSubExpr()->getType()->isIntegerType())         // from int.
2850          return CE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
2851      }
2852    }
2853  } else if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(this)) {
2854    // Ignore the ImplicitCastExpr type entirely.
2855    return ICE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
2856  } else if (const ParenExpr *PE = dyn_cast<ParenExpr>(this)) {
2857    // Accept ((void*)0) as a null pointer constant, as many other
2858    // implementations do.
2859    return PE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
2860  } else if (const GenericSelectionExpr *GE =
2861               dyn_cast<GenericSelectionExpr>(this)) {
2862    return GE->getResultExpr()->isNullPointerConstant(Ctx, NPC);
2863  } else if (const CXXDefaultArgExpr *DefaultArg
2864               = dyn_cast<CXXDefaultArgExpr>(this)) {
2865    // See through default argument expressions
2866    return DefaultArg->getExpr()->isNullPointerConstant(Ctx, NPC);
2867  } else if (isa<GNUNullExpr>(this)) {
2868    // The GNU __null extension is always a null pointer constant.
2869    return NPCK_GNUNull;
2870  } else if (const MaterializeTemporaryExpr *M
2871                                   = dyn_cast<MaterializeTemporaryExpr>(this)) {
2872    return M->GetTemporaryExpr()->isNullPointerConstant(Ctx, NPC);
2873  } else if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(this)) {
2874    if (const Expr *Source = OVE->getSourceExpr())
2875      return Source->isNullPointerConstant(Ctx, NPC);
2876  }
2877
2878  // C++0x nullptr_t is always a null pointer constant.
2879  if (getType()->isNullPtrType())
2880    return NPCK_CXX0X_nullptr;
2881
2882  if (const RecordType *UT = getType()->getAsUnionType())
2883    if (UT && UT->getDecl()->hasAttr<TransparentUnionAttr>())
2884      if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(this)){
2885        const Expr *InitExpr = CLE->getInitializer();
2886        if (const InitListExpr *ILE = dyn_cast<InitListExpr>(InitExpr))
2887          return ILE->getInit(0)->isNullPointerConstant(Ctx, NPC);
2888      }
2889  // This expression must be an integer type.
2890  if (!getType()->isIntegerType() ||
2891      (Ctx.getLangOpts().CPlusPlus && getType()->isEnumeralType()))
2892    return NPCK_NotNull;
2893
2894  // If we have an integer constant expression, we need to *evaluate* it and
2895  // test for the value 0. Don't use the C++11 constant expression semantics
2896  // for this, for now; once the dust settles on core issue 903, we might only
2897  // allow a literal 0 here in C++11 mode.
2898  if (Ctx.getLangOpts().CPlusPlus0x) {
2899    if (!isCXX98IntegralConstantExpr(Ctx))
2900      return NPCK_NotNull;
2901  } else {
2902    if (!isIntegerConstantExpr(Ctx))
2903      return NPCK_NotNull;
2904  }
2905
2906  return (EvaluateKnownConstInt(Ctx) == 0) ? NPCK_ZeroInteger : NPCK_NotNull;
2907}
2908
2909/// \brief If this expression is an l-value for an Objective C
2910/// property, find the underlying property reference expression.
2911const ObjCPropertyRefExpr *Expr::getObjCProperty() const {
2912  const Expr *E = this;
2913  while (true) {
2914    assert((E->getValueKind() == VK_LValue &&
2915            E->getObjectKind() == OK_ObjCProperty) &&
2916           "expression is not a property reference");
2917    E = E->IgnoreParenCasts();
2918    if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2919      if (BO->getOpcode() == BO_Comma) {
2920        E = BO->getRHS();
2921        continue;
2922      }
2923    }
2924
2925    break;
2926  }
2927
2928  return cast<ObjCPropertyRefExpr>(E);
2929}
2930
2931FieldDecl *Expr::getBitField() {
2932  Expr *E = this->IgnoreParens();
2933
2934  while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2935    if (ICE->getCastKind() == CK_LValueToRValue ||
2936        (ICE->getValueKind() != VK_RValue && ICE->getCastKind() == CK_NoOp))
2937      E = ICE->getSubExpr()->IgnoreParens();
2938    else
2939      break;
2940  }
2941
2942  if (MemberExpr *MemRef = dyn_cast<MemberExpr>(E))
2943    if (FieldDecl *Field = dyn_cast<FieldDecl>(MemRef->getMemberDecl()))
2944      if (Field->isBitField())
2945        return Field;
2946
2947  if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E))
2948    if (FieldDecl *Field = dyn_cast<FieldDecl>(DeclRef->getDecl()))
2949      if (Field->isBitField())
2950        return Field;
2951
2952  if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(E)) {
2953    if (BinOp->isAssignmentOp() && BinOp->getLHS())
2954      return BinOp->getLHS()->getBitField();
2955
2956    if (BinOp->getOpcode() == BO_Comma && BinOp->getRHS())
2957      return BinOp->getRHS()->getBitField();
2958  }
2959
2960  return 0;
2961}
2962
2963bool Expr::refersToVectorElement() const {
2964  const Expr *E = this->IgnoreParens();
2965
2966  while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2967    if (ICE->getValueKind() != VK_RValue &&
2968        ICE->getCastKind() == CK_NoOp)
2969      E = ICE->getSubExpr()->IgnoreParens();
2970    else
2971      break;
2972  }
2973
2974  if (const ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(E))
2975    return ASE->getBase()->getType()->isVectorType();
2976
2977  if (isa<ExtVectorElementExpr>(E))
2978    return true;
2979
2980  return false;
2981}
2982
2983/// isArrow - Return true if the base expression is a pointer to vector,
2984/// return false if the base expression is a vector.
2985bool ExtVectorElementExpr::isArrow() const {
2986  return getBase()->getType()->isPointerType();
2987}
2988
2989unsigned ExtVectorElementExpr::getNumElements() const {
2990  if (const VectorType *VT = getType()->getAs<VectorType>())
2991    return VT->getNumElements();
2992  return 1;
2993}
2994
2995/// containsDuplicateElements - Return true if any element access is repeated.
2996bool ExtVectorElementExpr::containsDuplicateElements() const {
2997  // FIXME: Refactor this code to an accessor on the AST node which returns the
2998  // "type" of component access, and share with code below and in Sema.
2999  StringRef Comp = Accessor->getName();
3000
3001  // Halving swizzles do not contain duplicate elements.
3002  if (Comp == "hi" || Comp == "lo" || Comp == "even" || Comp == "odd")
3003    return false;
3004
3005  // Advance past s-char prefix on hex swizzles.
3006  if (Comp[0] == 's' || Comp[0] == 'S')
3007    Comp = Comp.substr(1);
3008
3009  for (unsigned i = 0, e = Comp.size(); i != e; ++i)
3010    if (Comp.substr(i + 1).find(Comp[i]) != StringRef::npos)
3011        return true;
3012
3013  return false;
3014}
3015
3016/// getEncodedElementAccess - We encode the fields as a llvm ConstantArray.
3017void ExtVectorElementExpr::getEncodedElementAccess(
3018                                  SmallVectorImpl<unsigned> &Elts) const {
3019  StringRef Comp = Accessor->getName();
3020  if (Comp[0] == 's' || Comp[0] == 'S')
3021    Comp = Comp.substr(1);
3022
3023  bool isHi =   Comp == "hi";
3024  bool isLo =   Comp == "lo";
3025  bool isEven = Comp == "even";
3026  bool isOdd  = Comp == "odd";
3027
3028  for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
3029    uint64_t Index;
3030
3031    if (isHi)
3032      Index = e + i;
3033    else if (isLo)
3034      Index = i;
3035    else if (isEven)
3036      Index = 2 * i;
3037    else if (isOdd)
3038      Index = 2 * i + 1;
3039    else
3040      Index = ExtVectorType::getAccessorIdx(Comp[i]);
3041
3042    Elts.push_back(Index);
3043  }
3044}
3045
3046ObjCMessageExpr::ObjCMessageExpr(QualType T,
3047                                 ExprValueKind VK,
3048                                 SourceLocation LBracLoc,
3049                                 SourceLocation SuperLoc,
3050                                 bool IsInstanceSuper,
3051                                 QualType SuperType,
3052                                 Selector Sel,
3053                                 ArrayRef<SourceLocation> SelLocs,
3054                                 SelectorLocationsKind SelLocsK,
3055                                 ObjCMethodDecl *Method,
3056                                 ArrayRef<Expr *> Args,
3057                                 SourceLocation RBracLoc,
3058                                 bool isImplicit)
3059  : Expr(ObjCMessageExprClass, T, VK, OK_Ordinary,
3060         /*TypeDependent=*/false, /*ValueDependent=*/false,
3061         /*InstantiationDependent=*/false,
3062         /*ContainsUnexpandedParameterPack=*/false),
3063    SelectorOrMethod(reinterpret_cast<uintptr_t>(Method? Method
3064                                                       : Sel.getAsOpaquePtr())),
3065    Kind(IsInstanceSuper? SuperInstance : SuperClass),
3066    HasMethod(Method != 0), IsDelegateInitCall(false), IsImplicit(isImplicit),
3067    SuperLoc(SuperLoc), LBracLoc(LBracLoc), RBracLoc(RBracLoc)
3068{
3069  initArgsAndSelLocs(Args, SelLocs, SelLocsK);
3070  setReceiverPointer(SuperType.getAsOpaquePtr());
3071}
3072
3073ObjCMessageExpr::ObjCMessageExpr(QualType T,
3074                                 ExprValueKind VK,
3075                                 SourceLocation LBracLoc,
3076                                 TypeSourceInfo *Receiver,
3077                                 Selector Sel,
3078                                 ArrayRef<SourceLocation> SelLocs,
3079                                 SelectorLocationsKind SelLocsK,
3080                                 ObjCMethodDecl *Method,
3081                                 ArrayRef<Expr *> Args,
3082                                 SourceLocation RBracLoc,
3083                                 bool isImplicit)
3084  : Expr(ObjCMessageExprClass, T, VK, OK_Ordinary, T->isDependentType(),
3085         T->isDependentType(), T->isInstantiationDependentType(),
3086         T->containsUnexpandedParameterPack()),
3087    SelectorOrMethod(reinterpret_cast<uintptr_t>(Method? Method
3088                                                       : Sel.getAsOpaquePtr())),
3089    Kind(Class),
3090    HasMethod(Method != 0), IsDelegateInitCall(false), IsImplicit(isImplicit),
3091    LBracLoc(LBracLoc), RBracLoc(RBracLoc)
3092{
3093  initArgsAndSelLocs(Args, SelLocs, SelLocsK);
3094  setReceiverPointer(Receiver);
3095}
3096
3097ObjCMessageExpr::ObjCMessageExpr(QualType T,
3098                                 ExprValueKind VK,
3099                                 SourceLocation LBracLoc,
3100                                 Expr *Receiver,
3101                                 Selector Sel,
3102                                 ArrayRef<SourceLocation> SelLocs,
3103                                 SelectorLocationsKind SelLocsK,
3104                                 ObjCMethodDecl *Method,
3105                                 ArrayRef<Expr *> Args,
3106                                 SourceLocation RBracLoc,
3107                                 bool isImplicit)
3108  : Expr(ObjCMessageExprClass, T, VK, OK_Ordinary, Receiver->isTypeDependent(),
3109         Receiver->isTypeDependent(),
3110         Receiver->isInstantiationDependent(),
3111         Receiver->containsUnexpandedParameterPack()),
3112    SelectorOrMethod(reinterpret_cast<uintptr_t>(Method? Method
3113                                                       : Sel.getAsOpaquePtr())),
3114    Kind(Instance),
3115    HasMethod(Method != 0), IsDelegateInitCall(false), IsImplicit(isImplicit),
3116    LBracLoc(LBracLoc), RBracLoc(RBracLoc)
3117{
3118  initArgsAndSelLocs(Args, SelLocs, SelLocsK);
3119  setReceiverPointer(Receiver);
3120}
3121
3122void ObjCMessageExpr::initArgsAndSelLocs(ArrayRef<Expr *> Args,
3123                                         ArrayRef<SourceLocation> SelLocs,
3124                                         SelectorLocationsKind SelLocsK) {
3125  setNumArgs(Args.size());
3126  Expr **MyArgs = getArgs();
3127  for (unsigned I = 0; I != Args.size(); ++I) {
3128    if (Args[I]->isTypeDependent())
3129      ExprBits.TypeDependent = true;
3130    if (Args[I]->isValueDependent())
3131      ExprBits.ValueDependent = true;
3132    if (Args[I]->isInstantiationDependent())
3133      ExprBits.InstantiationDependent = true;
3134    if (Args[I]->containsUnexpandedParameterPack())
3135      ExprBits.ContainsUnexpandedParameterPack = true;
3136
3137    MyArgs[I] = Args[I];
3138  }
3139
3140  SelLocsKind = SelLocsK;
3141  if (!isImplicit()) {
3142    if (SelLocsK == SelLoc_NonStandard)
3143      std::copy(SelLocs.begin(), SelLocs.end(), getStoredSelLocs());
3144  }
3145}
3146
3147ObjCMessageExpr *ObjCMessageExpr::Create(ASTContext &Context, QualType T,
3148                                         ExprValueKind VK,
3149                                         SourceLocation LBracLoc,
3150                                         SourceLocation SuperLoc,
3151                                         bool IsInstanceSuper,
3152                                         QualType SuperType,
3153                                         Selector Sel,
3154                                         ArrayRef<SourceLocation> SelLocs,
3155                                         ObjCMethodDecl *Method,
3156                                         ArrayRef<Expr *> Args,
3157                                         SourceLocation RBracLoc,
3158                                         bool isImplicit) {
3159  assert((!SelLocs.empty() || isImplicit) &&
3160         "No selector locs for non-implicit message");
3161  ObjCMessageExpr *Mem;
3162  SelectorLocationsKind SelLocsK = SelectorLocationsKind();
3163  if (isImplicit)
3164    Mem = alloc(Context, Args.size(), 0);
3165  else
3166    Mem = alloc(Context, Args, RBracLoc, SelLocs, Sel, SelLocsK);
3167  return new (Mem) ObjCMessageExpr(T, VK, LBracLoc, SuperLoc, IsInstanceSuper,
3168                                   SuperType, Sel, SelLocs, SelLocsK,
3169                                   Method, Args, RBracLoc, isImplicit);
3170}
3171
3172ObjCMessageExpr *ObjCMessageExpr::Create(ASTContext &Context, QualType T,
3173                                         ExprValueKind VK,
3174                                         SourceLocation LBracLoc,
3175                                         TypeSourceInfo *Receiver,
3176                                         Selector Sel,
3177                                         ArrayRef<SourceLocation> SelLocs,
3178                                         ObjCMethodDecl *Method,
3179                                         ArrayRef<Expr *> Args,
3180                                         SourceLocation RBracLoc,
3181                                         bool isImplicit) {
3182  assert((!SelLocs.empty() || isImplicit) &&
3183         "No selector locs for non-implicit message");
3184  ObjCMessageExpr *Mem;
3185  SelectorLocationsKind SelLocsK = SelectorLocationsKind();
3186  if (isImplicit)
3187    Mem = alloc(Context, Args.size(), 0);
3188  else
3189    Mem = alloc(Context, Args, RBracLoc, SelLocs, Sel, SelLocsK);
3190  return new (Mem) ObjCMessageExpr(T, VK, LBracLoc, Receiver, Sel,
3191                                   SelLocs, SelLocsK, Method, Args, RBracLoc,
3192                                   isImplicit);
3193}
3194
3195ObjCMessageExpr *ObjCMessageExpr::Create(ASTContext &Context, QualType T,
3196                                         ExprValueKind VK,
3197                                         SourceLocation LBracLoc,
3198                                         Expr *Receiver,
3199                                         Selector Sel,
3200                                         ArrayRef<SourceLocation> SelLocs,
3201                                         ObjCMethodDecl *Method,
3202                                         ArrayRef<Expr *> Args,
3203                                         SourceLocation RBracLoc,
3204                                         bool isImplicit) {
3205  assert((!SelLocs.empty() || isImplicit) &&
3206         "No selector locs for non-implicit message");
3207  ObjCMessageExpr *Mem;
3208  SelectorLocationsKind SelLocsK = SelectorLocationsKind();
3209  if (isImplicit)
3210    Mem = alloc(Context, Args.size(), 0);
3211  else
3212    Mem = alloc(Context, Args, RBracLoc, SelLocs, Sel, SelLocsK);
3213  return new (Mem) ObjCMessageExpr(T, VK, LBracLoc, Receiver, Sel,
3214                                   SelLocs, SelLocsK, Method, Args, RBracLoc,
3215                                   isImplicit);
3216}
3217
3218ObjCMessageExpr *ObjCMessageExpr::CreateEmpty(ASTContext &Context,
3219                                              unsigned NumArgs,
3220                                              unsigned NumStoredSelLocs) {
3221  ObjCMessageExpr *Mem = alloc(Context, NumArgs, NumStoredSelLocs);
3222  return new (Mem) ObjCMessageExpr(EmptyShell(), NumArgs);
3223}
3224
3225ObjCMessageExpr *ObjCMessageExpr::alloc(ASTContext &C,
3226                                        ArrayRef<Expr *> Args,
3227                                        SourceLocation RBraceLoc,
3228                                        ArrayRef<SourceLocation> SelLocs,
3229                                        Selector Sel,
3230                                        SelectorLocationsKind &SelLocsK) {
3231  SelLocsK = hasStandardSelectorLocs(Sel, SelLocs, Args, RBraceLoc);
3232  unsigned NumStoredSelLocs = (SelLocsK == SelLoc_NonStandard) ? SelLocs.size()
3233                                                               : 0;
3234  return alloc(C, Args.size(), NumStoredSelLocs);
3235}
3236
3237ObjCMessageExpr *ObjCMessageExpr::alloc(ASTContext &C,
3238                                        unsigned NumArgs,
3239                                        unsigned NumStoredSelLocs) {
3240  unsigned Size = sizeof(ObjCMessageExpr) + sizeof(void *) +
3241    NumArgs * sizeof(Expr *) + NumStoredSelLocs * sizeof(SourceLocation);
3242  return (ObjCMessageExpr *)C.Allocate(Size,
3243                                     llvm::AlignOf<ObjCMessageExpr>::Alignment);
3244}
3245
3246void ObjCMessageExpr::getSelectorLocs(
3247                               SmallVectorImpl<SourceLocation> &SelLocs) const {
3248  for (unsigned i = 0, e = getNumSelectorLocs(); i != e; ++i)
3249    SelLocs.push_back(getSelectorLoc(i));
3250}
3251
3252SourceRange ObjCMessageExpr::getReceiverRange() const {
3253  switch (getReceiverKind()) {
3254  case Instance:
3255    return getInstanceReceiver()->getSourceRange();
3256
3257  case Class:
3258    return getClassReceiverTypeInfo()->getTypeLoc().getSourceRange();
3259
3260  case SuperInstance:
3261  case SuperClass:
3262    return getSuperLoc();
3263  }
3264
3265  llvm_unreachable("Invalid ReceiverKind!");
3266}
3267
3268Selector ObjCMessageExpr::getSelector() const {
3269  if (HasMethod)
3270    return reinterpret_cast<const ObjCMethodDecl *>(SelectorOrMethod)
3271                                                               ->getSelector();
3272  return Selector(SelectorOrMethod);
3273}
3274
3275ObjCInterfaceDecl *ObjCMessageExpr::getReceiverInterface() const {
3276  switch (getReceiverKind()) {
3277  case Instance:
3278    if (const ObjCObjectPointerType *Ptr
3279          = getInstanceReceiver()->getType()->getAs<ObjCObjectPointerType>())
3280      return Ptr->getInterfaceDecl();
3281    break;
3282
3283  case Class:
3284    if (const ObjCObjectType *Ty
3285          = getClassReceiver()->getAs<ObjCObjectType>())
3286      return Ty->getInterface();
3287    break;
3288
3289  case SuperInstance:
3290    if (const ObjCObjectPointerType *Ptr
3291          = getSuperType()->getAs<ObjCObjectPointerType>())
3292      return Ptr->getInterfaceDecl();
3293    break;
3294
3295  case SuperClass:
3296    if (const ObjCObjectType *Iface
3297          = getSuperType()->getAs<ObjCObjectType>())
3298      return Iface->getInterface();
3299    break;
3300  }
3301
3302  return 0;
3303}
3304
3305StringRef ObjCBridgedCastExpr::getBridgeKindName() const {
3306  switch (getBridgeKind()) {
3307  case OBC_Bridge:
3308    return "__bridge";
3309  case OBC_BridgeTransfer:
3310    return "__bridge_transfer";
3311  case OBC_BridgeRetained:
3312    return "__bridge_retained";
3313  }
3314
3315  llvm_unreachable("Invalid BridgeKind!");
3316}
3317
3318bool ChooseExpr::isConditionTrue(const ASTContext &C) const {
3319  return getCond()->EvaluateKnownConstInt(C) != 0;
3320}
3321
3322ShuffleVectorExpr::ShuffleVectorExpr(ASTContext &C, Expr **args, unsigned nexpr,
3323                                     QualType Type, SourceLocation BLoc,
3324                                     SourceLocation RP)
3325   : Expr(ShuffleVectorExprClass, Type, VK_RValue, OK_Ordinary,
3326          Type->isDependentType(), Type->isDependentType(),
3327          Type->isInstantiationDependentType(),
3328          Type->containsUnexpandedParameterPack()),
3329     BuiltinLoc(BLoc), RParenLoc(RP), NumExprs(nexpr)
3330{
3331  SubExprs = new (C) Stmt*[nexpr];
3332  for (unsigned i = 0; i < nexpr; i++) {
3333    if (args[i]->isTypeDependent())
3334      ExprBits.TypeDependent = true;
3335    if (args[i]->isValueDependent())
3336      ExprBits.ValueDependent = true;
3337    if (args[i]->isInstantiationDependent())
3338      ExprBits.InstantiationDependent = true;
3339    if (args[i]->containsUnexpandedParameterPack())
3340      ExprBits.ContainsUnexpandedParameterPack = true;
3341
3342    SubExprs[i] = args[i];
3343  }
3344}
3345
3346void ShuffleVectorExpr::setExprs(ASTContext &C, Expr ** Exprs,
3347                                 unsigned NumExprs) {
3348  if (SubExprs) C.Deallocate(SubExprs);
3349
3350  SubExprs = new (C) Stmt* [NumExprs];
3351  this->NumExprs = NumExprs;
3352  memcpy(SubExprs, Exprs, sizeof(Expr *) * NumExprs);
3353}
3354
3355GenericSelectionExpr::GenericSelectionExpr(ASTContext &Context,
3356                               SourceLocation GenericLoc, Expr *ControllingExpr,
3357                               TypeSourceInfo **AssocTypes, Expr **AssocExprs,
3358                               unsigned NumAssocs, SourceLocation DefaultLoc,
3359                               SourceLocation RParenLoc,
3360                               bool ContainsUnexpandedParameterPack,
3361                               unsigned ResultIndex)
3362  : Expr(GenericSelectionExprClass,
3363         AssocExprs[ResultIndex]->getType(),
3364         AssocExprs[ResultIndex]->getValueKind(),
3365         AssocExprs[ResultIndex]->getObjectKind(),
3366         AssocExprs[ResultIndex]->isTypeDependent(),
3367         AssocExprs[ResultIndex]->isValueDependent(),
3368         AssocExprs[ResultIndex]->isInstantiationDependent(),
3369         ContainsUnexpandedParameterPack),
3370    AssocTypes(new (Context) TypeSourceInfo*[NumAssocs]),
3371    SubExprs(new (Context) Stmt*[END_EXPR+NumAssocs]), NumAssocs(NumAssocs),
3372    ResultIndex(ResultIndex), GenericLoc(GenericLoc), DefaultLoc(DefaultLoc),
3373    RParenLoc(RParenLoc) {
3374  SubExprs[CONTROLLING] = ControllingExpr;
3375  std::copy(AssocTypes, AssocTypes+NumAssocs, this->AssocTypes);
3376  std::copy(AssocExprs, AssocExprs+NumAssocs, SubExprs+END_EXPR);
3377}
3378
3379GenericSelectionExpr::GenericSelectionExpr(ASTContext &Context,
3380                               SourceLocation GenericLoc, Expr *ControllingExpr,
3381                               TypeSourceInfo **AssocTypes, Expr **AssocExprs,
3382                               unsigned NumAssocs, SourceLocation DefaultLoc,
3383                               SourceLocation RParenLoc,
3384                               bool ContainsUnexpandedParameterPack)
3385  : Expr(GenericSelectionExprClass,
3386         Context.DependentTy,
3387         VK_RValue,
3388         OK_Ordinary,
3389         /*isTypeDependent=*/true,
3390         /*isValueDependent=*/true,
3391         /*isInstantiationDependent=*/true,
3392         ContainsUnexpandedParameterPack),
3393    AssocTypes(new (Context) TypeSourceInfo*[NumAssocs]),
3394    SubExprs(new (Context) Stmt*[END_EXPR+NumAssocs]), NumAssocs(NumAssocs),
3395    ResultIndex(-1U), GenericLoc(GenericLoc), DefaultLoc(DefaultLoc),
3396    RParenLoc(RParenLoc) {
3397  SubExprs[CONTROLLING] = ControllingExpr;
3398  std::copy(AssocTypes, AssocTypes+NumAssocs, this->AssocTypes);
3399  std::copy(AssocExprs, AssocExprs+NumAssocs, SubExprs+END_EXPR);
3400}
3401
3402//===----------------------------------------------------------------------===//
3403//  DesignatedInitExpr
3404//===----------------------------------------------------------------------===//
3405
3406IdentifierInfo *DesignatedInitExpr::Designator::getFieldName() const {
3407  assert(Kind == FieldDesignator && "Only valid on a field designator");
3408  if (Field.NameOrField & 0x01)
3409    return reinterpret_cast<IdentifierInfo *>(Field.NameOrField&~0x01);
3410  else
3411    return getField()->getIdentifier();
3412}
3413
3414DesignatedInitExpr::DesignatedInitExpr(ASTContext &C, QualType Ty,
3415                                       unsigned NumDesignators,
3416                                       const Designator *Designators,
3417                                       SourceLocation EqualOrColonLoc,
3418                                       bool GNUSyntax,
3419                                       Expr **IndexExprs,
3420                                       unsigned NumIndexExprs,
3421                                       Expr *Init)
3422  : Expr(DesignatedInitExprClass, Ty,
3423         Init->getValueKind(), Init->getObjectKind(),
3424         Init->isTypeDependent(), Init->isValueDependent(),
3425         Init->isInstantiationDependent(),
3426         Init->containsUnexpandedParameterPack()),
3427    EqualOrColonLoc(EqualOrColonLoc), GNUSyntax(GNUSyntax),
3428    NumDesignators(NumDesignators), NumSubExprs(NumIndexExprs + 1) {
3429  this->Designators = new (C) Designator[NumDesignators];
3430
3431  // Record the initializer itself.
3432  child_range Child = children();
3433  *Child++ = Init;
3434
3435  // Copy the designators and their subexpressions, computing
3436  // value-dependence along the way.
3437  unsigned IndexIdx = 0;
3438  for (unsigned I = 0; I != NumDesignators; ++I) {
3439    this->Designators[I] = Designators[I];
3440
3441    if (this->Designators[I].isArrayDesignator()) {
3442      // Compute type- and value-dependence.
3443      Expr *Index = IndexExprs[IndexIdx];
3444      if (Index->isTypeDependent() || Index->isValueDependent())
3445        ExprBits.ValueDependent = true;
3446      if (Index->isInstantiationDependent())
3447        ExprBits.InstantiationDependent = true;
3448      // Propagate unexpanded parameter packs.
3449      if (Index->containsUnexpandedParameterPack())
3450        ExprBits.ContainsUnexpandedParameterPack = true;
3451
3452      // Copy the index expressions into permanent storage.
3453      *Child++ = IndexExprs[IndexIdx++];
3454    } else if (this->Designators[I].isArrayRangeDesignator()) {
3455      // Compute type- and value-dependence.
3456      Expr *Start = IndexExprs[IndexIdx];
3457      Expr *End = IndexExprs[IndexIdx + 1];
3458      if (Start->isTypeDependent() || Start->isValueDependent() ||
3459          End->isTypeDependent() || End->isValueDependent()) {
3460        ExprBits.ValueDependent = true;
3461        ExprBits.InstantiationDependent = true;
3462      } else if (Start->isInstantiationDependent() ||
3463                 End->isInstantiationDependent()) {
3464        ExprBits.InstantiationDependent = true;
3465      }
3466
3467      // Propagate unexpanded parameter packs.
3468      if (Start->containsUnexpandedParameterPack() ||
3469          End->containsUnexpandedParameterPack())
3470        ExprBits.ContainsUnexpandedParameterPack = true;
3471
3472      // Copy the start/end expressions into permanent storage.
3473      *Child++ = IndexExprs[IndexIdx++];
3474      *Child++ = IndexExprs[IndexIdx++];
3475    }
3476  }
3477
3478  assert(IndexIdx == NumIndexExprs && "Wrong number of index expressions");
3479}
3480
3481DesignatedInitExpr *
3482DesignatedInitExpr::Create(ASTContext &C, Designator *Designators,
3483                           unsigned NumDesignators,
3484                           Expr **IndexExprs, unsigned NumIndexExprs,
3485                           SourceLocation ColonOrEqualLoc,
3486                           bool UsesColonSyntax, Expr *Init) {
3487  void *Mem = C.Allocate(sizeof(DesignatedInitExpr) +
3488                         sizeof(Stmt *) * (NumIndexExprs + 1), 8);
3489  return new (Mem) DesignatedInitExpr(C, C.VoidTy, NumDesignators, Designators,
3490                                      ColonOrEqualLoc, UsesColonSyntax,
3491                                      IndexExprs, NumIndexExprs, Init);
3492}
3493
3494DesignatedInitExpr *DesignatedInitExpr::CreateEmpty(ASTContext &C,
3495                                                    unsigned NumIndexExprs) {
3496  void *Mem = C.Allocate(sizeof(DesignatedInitExpr) +
3497                         sizeof(Stmt *) * (NumIndexExprs + 1), 8);
3498  return new (Mem) DesignatedInitExpr(NumIndexExprs + 1);
3499}
3500
3501void DesignatedInitExpr::setDesignators(ASTContext &C,
3502                                        const Designator *Desigs,
3503                                        unsigned NumDesigs) {
3504  Designators = new (C) Designator[NumDesigs];
3505  NumDesignators = NumDesigs;
3506  for (unsigned I = 0; I != NumDesigs; ++I)
3507    Designators[I] = Desigs[I];
3508}
3509
3510SourceRange DesignatedInitExpr::getDesignatorsSourceRange() const {
3511  DesignatedInitExpr *DIE = const_cast<DesignatedInitExpr*>(this);
3512  if (size() == 1)
3513    return DIE->getDesignator(0)->getSourceRange();
3514  return SourceRange(DIE->getDesignator(0)->getStartLocation(),
3515                     DIE->getDesignator(size()-1)->getEndLocation());
3516}
3517
3518SourceRange DesignatedInitExpr::getSourceRange() const {
3519  SourceLocation StartLoc;
3520  Designator &First =
3521    *const_cast<DesignatedInitExpr*>(this)->designators_begin();
3522  if (First.isFieldDesignator()) {
3523    if (GNUSyntax)
3524      StartLoc = SourceLocation::getFromRawEncoding(First.Field.FieldLoc);
3525    else
3526      StartLoc = SourceLocation::getFromRawEncoding(First.Field.DotLoc);
3527  } else
3528    StartLoc =
3529      SourceLocation::getFromRawEncoding(First.ArrayOrRange.LBracketLoc);
3530  return SourceRange(StartLoc, getInit()->getSourceRange().getEnd());
3531}
3532
3533Expr *DesignatedInitExpr::getArrayIndex(const Designator& D) {
3534  assert(D.Kind == Designator::ArrayDesignator && "Requires array designator");
3535  char* Ptr = static_cast<char*>(static_cast<void *>(this));
3536  Ptr += sizeof(DesignatedInitExpr);
3537  Stmt **SubExprs = reinterpret_cast<Stmt**>(reinterpret_cast<void**>(Ptr));
3538  return cast<Expr>(*(SubExprs + D.ArrayOrRange.Index + 1));
3539}
3540
3541Expr *DesignatedInitExpr::getArrayRangeStart(const Designator& D) {
3542  assert(D.Kind == Designator::ArrayRangeDesignator &&
3543         "Requires array range designator");
3544  char* Ptr = static_cast<char*>(static_cast<void *>(this));
3545  Ptr += sizeof(DesignatedInitExpr);
3546  Stmt **SubExprs = reinterpret_cast<Stmt**>(reinterpret_cast<void**>(Ptr));
3547  return cast<Expr>(*(SubExprs + D.ArrayOrRange.Index + 1));
3548}
3549
3550Expr *DesignatedInitExpr::getArrayRangeEnd(const Designator& D) {
3551  assert(D.Kind == Designator::ArrayRangeDesignator &&
3552         "Requires array range designator");
3553  char* Ptr = static_cast<char*>(static_cast<void *>(this));
3554  Ptr += sizeof(DesignatedInitExpr);
3555  Stmt **SubExprs = reinterpret_cast<Stmt**>(reinterpret_cast<void**>(Ptr));
3556  return cast<Expr>(*(SubExprs + D.ArrayOrRange.Index + 2));
3557}
3558
3559/// \brief Replaces the designator at index @p Idx with the series
3560/// of designators in [First, Last).
3561void DesignatedInitExpr::ExpandDesignator(ASTContext &C, unsigned Idx,
3562                                          const Designator *First,
3563                                          const Designator *Last) {
3564  unsigned NumNewDesignators = Last - First;
3565  if (NumNewDesignators == 0) {
3566    std::copy_backward(Designators + Idx + 1,
3567                       Designators + NumDesignators,
3568                       Designators + Idx);
3569    --NumNewDesignators;
3570    return;
3571  } else if (NumNewDesignators == 1) {
3572    Designators[Idx] = *First;
3573    return;
3574  }
3575
3576  Designator *NewDesignators
3577    = new (C) Designator[NumDesignators - 1 + NumNewDesignators];
3578  std::copy(Designators, Designators + Idx, NewDesignators);
3579  std::copy(First, Last, NewDesignators + Idx);
3580  std::copy(Designators + Idx + 1, Designators + NumDesignators,
3581            NewDesignators + Idx + NumNewDesignators);
3582  Designators = NewDesignators;
3583  NumDesignators = NumDesignators - 1 + NumNewDesignators;
3584}
3585
3586ParenListExpr::ParenListExpr(ASTContext& C, SourceLocation lparenloc,
3587                             Expr **exprs, unsigned nexprs,
3588                             SourceLocation rparenloc)
3589  : Expr(ParenListExprClass, QualType(), VK_RValue, OK_Ordinary,
3590         false, false, false, false),
3591    NumExprs(nexprs), LParenLoc(lparenloc), RParenLoc(rparenloc) {
3592  Exprs = new (C) Stmt*[nexprs];
3593  for (unsigned i = 0; i != nexprs; ++i) {
3594    if (exprs[i]->isTypeDependent())
3595      ExprBits.TypeDependent = true;
3596    if (exprs[i]->isValueDependent())
3597      ExprBits.ValueDependent = true;
3598    if (exprs[i]->isInstantiationDependent())
3599      ExprBits.InstantiationDependent = true;
3600    if (exprs[i]->containsUnexpandedParameterPack())
3601      ExprBits.ContainsUnexpandedParameterPack = true;
3602
3603    Exprs[i] = exprs[i];
3604  }
3605}
3606
3607const OpaqueValueExpr *OpaqueValueExpr::findInCopyConstruct(const Expr *e) {
3608  if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(e))
3609    e = ewc->getSubExpr();
3610  if (const MaterializeTemporaryExpr *m = dyn_cast<MaterializeTemporaryExpr>(e))
3611    e = m->GetTemporaryExpr();
3612  e = cast<CXXConstructExpr>(e)->getArg(0);
3613  while (const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
3614    e = ice->getSubExpr();
3615  return cast<OpaqueValueExpr>(e);
3616}
3617
3618PseudoObjectExpr *PseudoObjectExpr::Create(ASTContext &Context, EmptyShell sh,
3619                                           unsigned numSemanticExprs) {
3620  void *buffer = Context.Allocate(sizeof(PseudoObjectExpr) +
3621                                    (1 + numSemanticExprs) * sizeof(Expr*),
3622                                  llvm::alignOf<PseudoObjectExpr>());
3623  return new(buffer) PseudoObjectExpr(sh, numSemanticExprs);
3624}
3625
3626PseudoObjectExpr::PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs)
3627  : Expr(PseudoObjectExprClass, shell) {
3628  PseudoObjectExprBits.NumSubExprs = numSemanticExprs + 1;
3629}
3630
3631PseudoObjectExpr *PseudoObjectExpr::Create(ASTContext &C, Expr *syntax,
3632                                           ArrayRef<Expr*> semantics,
3633                                           unsigned resultIndex) {
3634  assert(syntax && "no syntactic expression!");
3635  assert(semantics.size() && "no semantic expressions!");
3636
3637  QualType type;
3638  ExprValueKind VK;
3639  if (resultIndex == NoResult) {
3640    type = C.VoidTy;
3641    VK = VK_RValue;
3642  } else {
3643    assert(resultIndex < semantics.size());
3644    type = semantics[resultIndex]->getType();
3645    VK = semantics[resultIndex]->getValueKind();
3646    assert(semantics[resultIndex]->getObjectKind() == OK_Ordinary);
3647  }
3648
3649  void *buffer = C.Allocate(sizeof(PseudoObjectExpr) +
3650                              (1 + semantics.size()) * sizeof(Expr*),
3651                            llvm::alignOf<PseudoObjectExpr>());
3652  return new(buffer) PseudoObjectExpr(type, VK, syntax, semantics,
3653                                      resultIndex);
3654}
3655
3656PseudoObjectExpr::PseudoObjectExpr(QualType type, ExprValueKind VK,
3657                                   Expr *syntax, ArrayRef<Expr*> semantics,
3658                                   unsigned resultIndex)
3659  : Expr(PseudoObjectExprClass, type, VK, OK_Ordinary,
3660         /*filled in at end of ctor*/ false, false, false, false) {
3661  PseudoObjectExprBits.NumSubExprs = semantics.size() + 1;
3662  PseudoObjectExprBits.ResultIndex = resultIndex + 1;
3663
3664  for (unsigned i = 0, e = semantics.size() + 1; i != e; ++i) {
3665    Expr *E = (i == 0 ? syntax : semantics[i-1]);
3666    getSubExprsBuffer()[i] = E;
3667
3668    if (E->isTypeDependent())
3669      ExprBits.TypeDependent = true;
3670    if (E->isValueDependent())
3671      ExprBits.ValueDependent = true;
3672    if (E->isInstantiationDependent())
3673      ExprBits.InstantiationDependent = true;
3674    if (E->containsUnexpandedParameterPack())
3675      ExprBits.ContainsUnexpandedParameterPack = true;
3676
3677    if (isa<OpaqueValueExpr>(E))
3678      assert(cast<OpaqueValueExpr>(E)->getSourceExpr() != 0 &&
3679             "opaque-value semantic expressions for pseudo-object "
3680             "operations must have sources");
3681  }
3682}
3683
3684//===----------------------------------------------------------------------===//
3685//  ExprIterator.
3686//===----------------------------------------------------------------------===//
3687
3688Expr* ExprIterator::operator[](size_t idx) { return cast<Expr>(I[idx]); }
3689Expr* ExprIterator::operator*() const { return cast<Expr>(*I); }
3690Expr* ExprIterator::operator->() const { return cast<Expr>(*I); }
3691const Expr* ConstExprIterator::operator[](size_t idx) const {
3692  return cast<Expr>(I[idx]);
3693}
3694const Expr* ConstExprIterator::operator*() const { return cast<Expr>(*I); }
3695const Expr* ConstExprIterator::operator->() const { return cast<Expr>(*I); }
3696
3697//===----------------------------------------------------------------------===//
3698//  Child Iterators for iterating over subexpressions/substatements
3699//===----------------------------------------------------------------------===//
3700
3701// UnaryExprOrTypeTraitExpr
3702Stmt::child_range UnaryExprOrTypeTraitExpr::children() {
3703  // If this is of a type and the type is a VLA type (and not a typedef), the
3704  // size expression of the VLA needs to be treated as an executable expression.
3705  // Why isn't this weirdness documented better in StmtIterator?
3706  if (isArgumentType()) {
3707    if (const VariableArrayType* T = dyn_cast<VariableArrayType>(
3708                                   getArgumentType().getTypePtr()))
3709      return child_range(child_iterator(T), child_iterator());
3710    return child_range();
3711  }
3712  return child_range(&Argument.Ex, &Argument.Ex + 1);
3713}
3714
3715// ObjCMessageExpr
3716Stmt::child_range ObjCMessageExpr::children() {
3717  Stmt **begin;
3718  if (getReceiverKind() == Instance)
3719    begin = reinterpret_cast<Stmt **>(this + 1);
3720  else
3721    begin = reinterpret_cast<Stmt **>(getArgs());
3722  return child_range(begin,
3723                     reinterpret_cast<Stmt **>(getArgs() + getNumArgs()));
3724}
3725
3726ObjCArrayLiteral::ObjCArrayLiteral(llvm::ArrayRef<Expr *> Elements,
3727                                   QualType T, ObjCMethodDecl *Method,
3728                                   SourceRange SR)
3729  : Expr(ObjCArrayLiteralClass, T, VK_RValue, OK_Ordinary,
3730         false, false, false, false),
3731    NumElements(Elements.size()), Range(SR), ArrayWithObjectsMethod(Method)
3732{
3733  Expr **SaveElements = getElements();
3734  for (unsigned I = 0, N = Elements.size(); I != N; ++I) {
3735    if (Elements[I]->isTypeDependent() || Elements[I]->isValueDependent())
3736      ExprBits.ValueDependent = true;
3737    if (Elements[I]->isInstantiationDependent())
3738      ExprBits.InstantiationDependent = true;
3739    if (Elements[I]->containsUnexpandedParameterPack())
3740      ExprBits.ContainsUnexpandedParameterPack = true;
3741
3742    SaveElements[I] = Elements[I];
3743  }
3744}
3745
3746ObjCArrayLiteral *ObjCArrayLiteral::Create(ASTContext &C,
3747                                           llvm::ArrayRef<Expr *> Elements,
3748                                           QualType T, ObjCMethodDecl * Method,
3749                                           SourceRange SR) {
3750  void *Mem = C.Allocate(sizeof(ObjCArrayLiteral)
3751                         + Elements.size() * sizeof(Expr *));
3752  return new (Mem) ObjCArrayLiteral(Elements, T, Method, SR);
3753}
3754
3755ObjCArrayLiteral *ObjCArrayLiteral::CreateEmpty(ASTContext &C,
3756                                                unsigned NumElements) {
3757
3758  void *Mem = C.Allocate(sizeof(ObjCArrayLiteral)
3759                         + NumElements * sizeof(Expr *));
3760  return new (Mem) ObjCArrayLiteral(EmptyShell(), NumElements);
3761}
3762
3763ObjCDictionaryLiteral::ObjCDictionaryLiteral(
3764                                             ArrayRef<ObjCDictionaryElement> VK,
3765                                             bool HasPackExpansions,
3766                                             QualType T, ObjCMethodDecl *method,
3767                                             SourceRange SR)
3768  : Expr(ObjCDictionaryLiteralClass, T, VK_RValue, OK_Ordinary, false, false,
3769         false, false),
3770    NumElements(VK.size()), HasPackExpansions(HasPackExpansions), Range(SR),
3771    DictWithObjectsMethod(method)
3772{
3773  KeyValuePair *KeyValues = getKeyValues();
3774  ExpansionData *Expansions = getExpansionData();
3775  for (unsigned I = 0; I < NumElements; I++) {
3776    if (VK[I].Key->isTypeDependent() || VK[I].Key->isValueDependent() ||
3777        VK[I].Value->isTypeDependent() || VK[I].Value->isValueDependent())
3778      ExprBits.ValueDependent = true;
3779    if (VK[I].Key->isInstantiationDependent() ||
3780        VK[I].Value->isInstantiationDependent())
3781      ExprBits.InstantiationDependent = true;
3782    if (VK[I].EllipsisLoc.isInvalid() &&
3783        (VK[I].Key->containsUnexpandedParameterPack() ||
3784         VK[I].Value->containsUnexpandedParameterPack()))
3785      ExprBits.ContainsUnexpandedParameterPack = true;
3786
3787    KeyValues[I].Key = VK[I].Key;
3788    KeyValues[I].Value = VK[I].Value;
3789    if (Expansions) {
3790      Expansions[I].EllipsisLoc = VK[I].EllipsisLoc;
3791      if (VK[I].NumExpansions)
3792        Expansions[I].NumExpansionsPlusOne = *VK[I].NumExpansions + 1;
3793      else
3794        Expansions[I].NumExpansionsPlusOne = 0;
3795    }
3796  }
3797}
3798
3799ObjCDictionaryLiteral *
3800ObjCDictionaryLiteral::Create(ASTContext &C,
3801                              ArrayRef<ObjCDictionaryElement> VK,
3802                              bool HasPackExpansions,
3803                              QualType T, ObjCMethodDecl *method,
3804                              SourceRange SR) {
3805  unsigned ExpansionsSize = 0;
3806  if (HasPackExpansions)
3807    ExpansionsSize = sizeof(ExpansionData) * VK.size();
3808
3809  void *Mem = C.Allocate(sizeof(ObjCDictionaryLiteral) +
3810                         sizeof(KeyValuePair) * VK.size() + ExpansionsSize);
3811  return new (Mem) ObjCDictionaryLiteral(VK, HasPackExpansions, T, method, SR);
3812}
3813
3814ObjCDictionaryLiteral *
3815ObjCDictionaryLiteral::CreateEmpty(ASTContext &C, unsigned NumElements,
3816                                   bool HasPackExpansions) {
3817  unsigned ExpansionsSize = 0;
3818  if (HasPackExpansions)
3819    ExpansionsSize = sizeof(ExpansionData) * NumElements;
3820  void *Mem = C.Allocate(sizeof(ObjCDictionaryLiteral) +
3821                         sizeof(KeyValuePair) * NumElements + ExpansionsSize);
3822  return new (Mem) ObjCDictionaryLiteral(EmptyShell(), NumElements,
3823                                         HasPackExpansions);
3824}
3825
3826ObjCSubscriptRefExpr *ObjCSubscriptRefExpr::Create(ASTContext &C,
3827                                                   Expr *base,
3828                                                   Expr *key, QualType T,
3829                                                   ObjCMethodDecl *getMethod,
3830                                                   ObjCMethodDecl *setMethod,
3831                                                   SourceLocation RB) {
3832  void *Mem = C.Allocate(sizeof(ObjCSubscriptRefExpr));
3833  return new (Mem) ObjCSubscriptRefExpr(base, key, T, VK_LValue,
3834                                        OK_ObjCSubscript,
3835                                        getMethod, setMethod, RB);
3836}
3837
3838AtomicExpr::AtomicExpr(SourceLocation BLoc, Expr **args, unsigned nexpr,
3839                       QualType t, AtomicOp op, SourceLocation RP)
3840  : Expr(AtomicExprClass, t, VK_RValue, OK_Ordinary,
3841         false, false, false, false),
3842    NumSubExprs(nexpr), BuiltinLoc(BLoc), RParenLoc(RP), Op(op)
3843{
3844  assert(nexpr == getNumSubExprs(op) && "wrong number of subexpressions");
3845  for (unsigned i = 0; i < nexpr; i++) {
3846    if (args[i]->isTypeDependent())
3847      ExprBits.TypeDependent = true;
3848    if (args[i]->isValueDependent())
3849      ExprBits.ValueDependent = true;
3850    if (args[i]->isInstantiationDependent())
3851      ExprBits.InstantiationDependent = true;
3852    if (args[i]->containsUnexpandedParameterPack())
3853      ExprBits.ContainsUnexpandedParameterPack = true;
3854
3855    SubExprs[i] = args[i];
3856  }
3857}
3858
3859unsigned AtomicExpr::getNumSubExprs(AtomicOp Op) {
3860  switch (Op) {
3861  case Init:
3862  case Load:
3863    return 2;
3864  case Store:
3865  case Xchg:
3866  case Add:
3867  case Sub:
3868  case And:
3869  case Or:
3870  case Xor:
3871    return 3;
3872  case CmpXchgStrong:
3873  case CmpXchgWeak:
3874    return 5;
3875  }
3876  llvm_unreachable("unknown atomic op");
3877}
3878