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