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