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