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