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