SemaExpr.cpp revision 62e8676ce94d29cbb14b5f14321d4c75fe620caa
1//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
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 semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/DeclObjC.h"
17#include "clang/AST/DeclTemplate.h"
18#include "clang/AST/ExprCXX.h"
19#include "clang/AST/ExprObjC.h"
20#include "clang/Basic/PartialDiagnostic.h"
21#include "clang/Basic/SourceManager.h"
22#include "clang/Basic/TargetInfo.h"
23#include "clang/Lex/LiteralSupport.h"
24#include "clang/Lex/Preprocessor.h"
25#include "clang/Parse/DeclSpec.h"
26#include "clang/Parse/Designator.h"
27#include "clang/Parse/Scope.h"
28using namespace clang;
29
30
31/// \brief Determine whether the use of this declaration is valid, and
32/// emit any corresponding diagnostics.
33///
34/// This routine diagnoses various problems with referencing
35/// declarations that can occur when using a declaration. For example,
36/// it might warn if a deprecated or unavailable declaration is being
37/// used, or produce an error (and return true) if a C++0x deleted
38/// function is being used.
39///
40/// \returns true if there was an error (this declaration cannot be
41/// referenced), false otherwise.
42bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc) {
43  // See if the decl is deprecated.
44  if (D->getAttr<DeprecatedAttr>()) {
45    // Implementing deprecated stuff requires referencing deprecated
46    // stuff. Don't warn if we are implementing a deprecated
47    // construct.
48    bool isSilenced = false;
49
50    if (NamedDecl *ND = getCurFunctionOrMethodDecl()) {
51      // If this reference happens *in* a deprecated function or method, don't
52      // warn.
53      isSilenced = ND->getAttr<DeprecatedAttr>();
54
55      // If this is an Objective-C method implementation, check to see if the
56      // method was deprecated on the declaration, not the definition.
57      if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(ND)) {
58        // The semantic decl context of a ObjCMethodDecl is the
59        // ObjCImplementationDecl.
60        if (ObjCImplementationDecl *Impl
61              = dyn_cast<ObjCImplementationDecl>(MD->getParent())) {
62
63          MD = Impl->getClassInterface()->getMethod(MD->getSelector(),
64                                                    MD->isInstanceMethod());
65          isSilenced |= MD && MD->getAttr<DeprecatedAttr>();
66        }
67      }
68    }
69
70    if (!isSilenced)
71      Diag(Loc, diag::warn_deprecated) << D->getDeclName();
72  }
73
74  // See if this is a deleted function.
75  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
76    if (FD->isDeleted()) {
77      Diag(Loc, diag::err_deleted_function_use);
78      Diag(D->getLocation(), diag::note_unavailable_here) << true;
79      return true;
80    }
81  }
82
83  // See if the decl is unavailable
84  if (D->getAttr<UnavailableAttr>()) {
85    Diag(Loc, diag::warn_unavailable) << D->getDeclName();
86    Diag(D->getLocation(), diag::note_unavailable_here) << 0;
87  }
88
89  return false;
90}
91
92/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
93/// (and other functions in future), which have been declared with sentinel
94/// attribute. It warns if call does not have the sentinel argument.
95///
96void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
97                                 Expr **Args, unsigned NumArgs) {
98  const SentinelAttr *attr = D->getAttr<SentinelAttr>();
99  if (!attr)
100    return;
101  int sentinelPos = attr->getSentinel();
102  int nullPos = attr->getNullPos();
103
104  // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
105  // base class. Then we won't be needing two versions of the same code.
106  unsigned int i = 0;
107  bool warnNotEnoughArgs = false;
108  int isMethod = 0;
109  if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
110    // skip over named parameters.
111    ObjCMethodDecl::param_iterator P, E = MD->param_end();
112    for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
113      if (nullPos)
114        --nullPos;
115      else
116        ++i;
117    }
118    warnNotEnoughArgs = (P != E || i >= NumArgs);
119    isMethod = 1;
120  } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
121    // skip over named parameters.
122    ObjCMethodDecl::param_iterator P, E = FD->param_end();
123    for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
124      if (nullPos)
125        --nullPos;
126      else
127        ++i;
128    }
129    warnNotEnoughArgs = (P != E || i >= NumArgs);
130  } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
131    // block or function pointer call.
132    QualType Ty = V->getType();
133    if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
134      const FunctionType *FT = Ty->isFunctionPointerType()
135      ? Ty->getAs<PointerType>()->getPointeeType()->getAsFunctionType()
136      : Ty->getAs<BlockPointerType>()->getPointeeType()->getAsFunctionType();
137      if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
138        unsigned NumArgsInProto = Proto->getNumArgs();
139        unsigned k;
140        for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
141          if (nullPos)
142            --nullPos;
143          else
144            ++i;
145        }
146        warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
147      }
148      if (Ty->isBlockPointerType())
149        isMethod = 2;
150    } else
151      return;
152  } else
153    return;
154
155  if (warnNotEnoughArgs) {
156    Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
157    Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
158    return;
159  }
160  int sentinel = i;
161  while (sentinelPos > 0 && i < NumArgs-1) {
162    --sentinelPos;
163    ++i;
164  }
165  if (sentinelPos > 0) {
166    Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
167    Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
168    return;
169  }
170  while (i < NumArgs-1) {
171    ++i;
172    ++sentinel;
173  }
174  Expr *sentinelExpr = Args[sentinel];
175  if (sentinelExpr && (!sentinelExpr->getType()->isPointerType() ||
176                       !sentinelExpr->isNullPointerConstant(Context))) {
177    Diag(Loc, diag::warn_missing_sentinel) << isMethod;
178    Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
179  }
180  return;
181}
182
183SourceRange Sema::getExprRange(ExprTy *E) const {
184  Expr *Ex = (Expr *)E;
185  return Ex? Ex->getSourceRange() : SourceRange();
186}
187
188//===----------------------------------------------------------------------===//
189//  Standard Promotions and Conversions
190//===----------------------------------------------------------------------===//
191
192/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
193void Sema::DefaultFunctionArrayConversion(Expr *&E) {
194  QualType Ty = E->getType();
195  assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
196
197  if (Ty->isFunctionType())
198    ImpCastExprToType(E, Context.getPointerType(Ty),
199                      CastExpr::CK_FunctionToPointerDecay);
200  else if (Ty->isArrayType()) {
201    // In C90 mode, arrays only promote to pointers if the array expression is
202    // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
203    // type 'array of type' is converted to an expression that has type 'pointer
204    // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
205    // that has type 'array of type' ...".  The relevant change is "an lvalue"
206    // (C90) to "an expression" (C99).
207    //
208    // C++ 4.2p1:
209    // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
210    // T" can be converted to an rvalue of type "pointer to T".
211    //
212    if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
213        E->isLvalue(Context) == Expr::LV_Valid)
214      ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
215                        CastExpr::CK_ArrayToPointerDecay);
216  }
217}
218
219/// UsualUnaryConversions - Performs various conversions that are common to most
220/// operators (C99 6.3). The conversions of array and function types are
221/// sometimes surpressed. For example, the array->pointer conversion doesn't
222/// apply if the array is an argument to the sizeof or address (&) operators.
223/// In these instances, this routine should *not* be called.
224Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
225  QualType Ty = Expr->getType();
226  assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
227
228  // C99 6.3.1.1p2:
229  //
230  //   The following may be used in an expression wherever an int or
231  //   unsigned int may be used:
232  //     - an object or expression with an integer type whose integer
233  //       conversion rank is less than or equal to the rank of int
234  //       and unsigned int.
235  //     - A bit-field of type _Bool, int, signed int, or unsigned int.
236  //
237  //   If an int can represent all values of the original type, the
238  //   value is converted to an int; otherwise, it is converted to an
239  //   unsigned int. These are called the integer promotions. All
240  //   other types are unchanged by the integer promotions.
241  QualType PTy = Context.isPromotableBitField(Expr);
242  if (!PTy.isNull()) {
243    ImpCastExprToType(Expr, PTy);
244    return Expr;
245  }
246  if (Ty->isPromotableIntegerType()) {
247    QualType PT = Context.getPromotedIntegerType(Ty);
248    ImpCastExprToType(Expr, PT);
249    return Expr;
250  }
251
252  DefaultFunctionArrayConversion(Expr);
253  return Expr;
254}
255
256/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
257/// do not have a prototype. Arguments that have type float are promoted to
258/// double. All other argument types are converted by UsualUnaryConversions().
259void Sema::DefaultArgumentPromotion(Expr *&Expr) {
260  QualType Ty = Expr->getType();
261  assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
262
263  // If this is a 'float' (CVR qualified or typedef) promote to double.
264  if (const BuiltinType *BT = Ty->getAsBuiltinType())
265    if (BT->getKind() == BuiltinType::Float)
266      return ImpCastExprToType(Expr, Context.DoubleTy);
267
268  UsualUnaryConversions(Expr);
269}
270
271/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
272/// will warn if the resulting type is not a POD type, and rejects ObjC
273/// interfaces passed by value.  This returns true if the argument type is
274/// completely illegal.
275bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT) {
276  DefaultArgumentPromotion(Expr);
277
278  if (Expr->getType()->isObjCInterfaceType()) {
279    Diag(Expr->getLocStart(),
280         diag::err_cannot_pass_objc_interface_to_vararg)
281      << Expr->getType() << CT;
282    return true;
283  }
284
285  if (!Expr->getType()->isPODType())
286    Diag(Expr->getLocStart(), diag::warn_cannot_pass_non_pod_arg_to_vararg)
287      << Expr->getType() << CT;
288
289  return false;
290}
291
292
293/// UsualArithmeticConversions - Performs various conversions that are common to
294/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
295/// routine returns the first non-arithmetic type found. The client is
296/// responsible for emitting appropriate error diagnostics.
297/// FIXME: verify the conversion rules for "complex int" are consistent with
298/// GCC.
299QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
300                                          bool isCompAssign) {
301  if (!isCompAssign)
302    UsualUnaryConversions(lhsExpr);
303
304  UsualUnaryConversions(rhsExpr);
305
306  // For conversion purposes, we ignore any qualifiers.
307  // For example, "const float" and "float" are equivalent.
308  QualType lhs =
309    Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
310  QualType rhs =
311    Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
312
313  // If both types are identical, no conversion is needed.
314  if (lhs == rhs)
315    return lhs;
316
317  // If either side is a non-arithmetic type (e.g. a pointer), we are done.
318  // The caller can deal with this (e.g. pointer + int).
319  if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
320    return lhs;
321
322  // Perform bitfield promotions.
323  QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr);
324  if (!LHSBitfieldPromoteTy.isNull())
325    lhs = LHSBitfieldPromoteTy;
326  QualType RHSBitfieldPromoteTy = Context.isPromotableBitField(rhsExpr);
327  if (!RHSBitfieldPromoteTy.isNull())
328    rhs = RHSBitfieldPromoteTy;
329
330  QualType destType = Context.UsualArithmeticConversionsType(lhs, rhs);
331  if (!isCompAssign)
332    ImpCastExprToType(lhsExpr, destType);
333  ImpCastExprToType(rhsExpr, destType);
334  return destType;
335}
336
337//===----------------------------------------------------------------------===//
338//  Semantic Analysis for various Expression Types
339//===----------------------------------------------------------------------===//
340
341
342/// ActOnStringLiteral - The specified tokens were lexed as pasted string
343/// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
344/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
345/// multiple tokens.  However, the common case is that StringToks points to one
346/// string.
347///
348Action::OwningExprResult
349Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
350  assert(NumStringToks && "Must have at least one string!");
351
352  StringLiteralParser Literal(StringToks, NumStringToks, PP);
353  if (Literal.hadError)
354    return ExprError();
355
356  llvm::SmallVector<SourceLocation, 4> StringTokLocs;
357  for (unsigned i = 0; i != NumStringToks; ++i)
358    StringTokLocs.push_back(StringToks[i].getLocation());
359
360  QualType StrTy = Context.CharTy;
361  if (Literal.AnyWide) StrTy = Context.getWCharType();
362  if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
363
364  // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
365  if (getLangOptions().CPlusPlus)
366    StrTy.addConst();
367
368  // Get an array type for the string, according to C99 6.4.5.  This includes
369  // the nul terminator character as well as the string length for pascal
370  // strings.
371  StrTy = Context.getConstantArrayType(StrTy,
372                                 llvm::APInt(32, Literal.GetNumStringChars()+1),
373                                       ArrayType::Normal, 0);
374
375  // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
376  return Owned(StringLiteral::Create(Context, Literal.GetString(),
377                                     Literal.GetStringLength(),
378                                     Literal.AnyWide, StrTy,
379                                     &StringTokLocs[0],
380                                     StringTokLocs.size()));
381}
382
383/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
384/// CurBlock to VD should cause it to be snapshotted (as we do for auto
385/// variables defined outside the block) or false if this is not needed (e.g.
386/// for values inside the block or for globals).
387///
388/// This also keeps the 'hasBlockDeclRefExprs' in the BlockSemaInfo records
389/// up-to-date.
390///
391static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
392                                              ValueDecl *VD) {
393  // If the value is defined inside the block, we couldn't snapshot it even if
394  // we wanted to.
395  if (CurBlock->TheDecl == VD->getDeclContext())
396    return false;
397
398  // If this is an enum constant or function, it is constant, don't snapshot.
399  if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
400    return false;
401
402  // If this is a reference to an extern, static, or global variable, no need to
403  // snapshot it.
404  // FIXME: What about 'const' variables in C++?
405  if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
406    if (!Var->hasLocalStorage())
407      return false;
408
409  // Blocks that have these can't be constant.
410  CurBlock->hasBlockDeclRefExprs = true;
411
412  // If we have nested blocks, the decl may be declared in an outer block (in
413  // which case that outer block doesn't get "hasBlockDeclRefExprs") or it may
414  // be defined outside all of the current blocks (in which case the blocks do
415  // all get the bit).  Walk the nesting chain.
416  for (BlockSemaInfo *NextBlock = CurBlock->PrevBlockInfo; NextBlock;
417       NextBlock = NextBlock->PrevBlockInfo) {
418    // If we found the defining block for the variable, don't mark the block as
419    // having a reference outside it.
420    if (NextBlock->TheDecl == VD->getDeclContext())
421      break;
422
423    // Otherwise, the DeclRef from the inner block causes the outer one to need
424    // a snapshot as well.
425    NextBlock->hasBlockDeclRefExprs = true;
426  }
427
428  return true;
429}
430
431
432
433/// ActOnIdentifierExpr - The parser read an identifier in expression context,
434/// validate it per-C99 6.5.1.  HasTrailingLParen indicates whether this
435/// identifier is used in a function call context.
436/// SS is only used for a C++ qualified-id (foo::bar) to indicate the
437/// class or namespace that the identifier must be a member of.
438Sema::OwningExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
439                                                 IdentifierInfo &II,
440                                                 bool HasTrailingLParen,
441                                                 const CXXScopeSpec *SS,
442                                                 bool isAddressOfOperand) {
443  return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS,
444                                  isAddressOfOperand);
445}
446
447/// BuildDeclRefExpr - Build either a DeclRefExpr or a
448/// QualifiedDeclRefExpr based on whether or not SS is a
449/// nested-name-specifier.
450Sema::OwningExprResult
451Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc,
452                       bool TypeDependent, bool ValueDependent,
453                       const CXXScopeSpec *SS) {
454  if (Context.getCanonicalType(Ty) == Context.UndeducedAutoTy) {
455    Diag(Loc,
456         diag::err_auto_variable_cannot_appear_in_own_initializer)
457      << D->getDeclName();
458    return ExprError();
459  }
460
461  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
462    if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
463      if (const FunctionDecl *FD = MD->getParent()->isLocalClass()) {
464        if (VD->hasLocalStorage() && VD->getDeclContext() != CurContext) {
465          Diag(Loc, diag::err_reference_to_local_var_in_enclosing_function)
466            << D->getIdentifier() << FD->getDeclName();
467          Diag(D->getLocation(), diag::note_local_variable_declared_here)
468            << D->getIdentifier();
469          return ExprError();
470        }
471      }
472    }
473  }
474
475  MarkDeclarationReferenced(Loc, D);
476
477  Expr *E;
478  if (SS && !SS->isEmpty()) {
479    E = new (Context) QualifiedDeclRefExpr(D, Ty, Loc, TypeDependent,
480                                          ValueDependent, SS->getRange(),
481                  static_cast<NestedNameSpecifier *>(SS->getScopeRep()));
482  } else
483    E = new (Context) DeclRefExpr(D, Ty, Loc, TypeDependent, ValueDependent);
484
485  return Owned(E);
486}
487
488/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
489/// variable corresponding to the anonymous union or struct whose type
490/// is Record.
491static Decl *getObjectForAnonymousRecordDecl(ASTContext &Context,
492                                             RecordDecl *Record) {
493  assert(Record->isAnonymousStructOrUnion() &&
494         "Record must be an anonymous struct or union!");
495
496  // FIXME: Once Decls are directly linked together, this will be an O(1)
497  // operation rather than a slow walk through DeclContext's vector (which
498  // itself will be eliminated). DeclGroups might make this even better.
499  DeclContext *Ctx = Record->getDeclContext();
500  for (DeclContext::decl_iterator D = Ctx->decls_begin(),
501                               DEnd = Ctx->decls_end();
502       D != DEnd; ++D) {
503    if (*D == Record) {
504      // The object for the anonymous struct/union directly
505      // follows its type in the list of declarations.
506      ++D;
507      assert(D != DEnd && "Missing object for anonymous record");
508      assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
509      return *D;
510    }
511  }
512
513  assert(false && "Missing object for anonymous record");
514  return 0;
515}
516
517/// \brief Given a field that represents a member of an anonymous
518/// struct/union, build the path from that field's context to the
519/// actual member.
520///
521/// Construct the sequence of field member references we'll have to
522/// perform to get to the field in the anonymous union/struct. The
523/// list of members is built from the field outward, so traverse it
524/// backwards to go from an object in the current context to the field
525/// we found.
526///
527/// \returns The variable from which the field access should begin,
528/// for an anonymous struct/union that is not a member of another
529/// class. Otherwise, returns NULL.
530VarDecl *Sema::BuildAnonymousStructUnionMemberPath(FieldDecl *Field,
531                                   llvm::SmallVectorImpl<FieldDecl *> &Path) {
532  assert(Field->getDeclContext()->isRecord() &&
533         cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
534         && "Field must be stored inside an anonymous struct or union");
535
536  Path.push_back(Field);
537  VarDecl *BaseObject = 0;
538  DeclContext *Ctx = Field->getDeclContext();
539  do {
540    RecordDecl *Record = cast<RecordDecl>(Ctx);
541    Decl *AnonObject = getObjectForAnonymousRecordDecl(Context, Record);
542    if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
543      Path.push_back(AnonField);
544    else {
545      BaseObject = cast<VarDecl>(AnonObject);
546      break;
547    }
548    Ctx = Ctx->getParent();
549  } while (Ctx->isRecord() &&
550           cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
551
552  return BaseObject;
553}
554
555Sema::OwningExprResult
556Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
557                                               FieldDecl *Field,
558                                               Expr *BaseObjectExpr,
559                                               SourceLocation OpLoc) {
560  llvm::SmallVector<FieldDecl *, 4> AnonFields;
561  VarDecl *BaseObject = BuildAnonymousStructUnionMemberPath(Field,
562                                                            AnonFields);
563
564  // Build the expression that refers to the base object, from
565  // which we will build a sequence of member references to each
566  // of the anonymous union objects and, eventually, the field we
567  // found via name lookup.
568  bool BaseObjectIsPointer = false;
569  unsigned ExtraQuals = 0;
570  if (BaseObject) {
571    // BaseObject is an anonymous struct/union variable (and is,
572    // therefore, not part of another non-anonymous record).
573    if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
574    MarkDeclarationReferenced(Loc, BaseObject);
575    BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
576                                               SourceLocation());
577    ExtraQuals
578      = Context.getCanonicalType(BaseObject->getType()).getCVRQualifiers();
579  } else if (BaseObjectExpr) {
580    // The caller provided the base object expression. Determine
581    // whether its a pointer and whether it adds any qualifiers to the
582    // anonymous struct/union fields we're looking into.
583    QualType ObjectType = BaseObjectExpr->getType();
584    if (const PointerType *ObjectPtr = ObjectType->getAs<PointerType>()) {
585      BaseObjectIsPointer = true;
586      ObjectType = ObjectPtr->getPointeeType();
587    }
588    ExtraQuals = Context.getCanonicalType(ObjectType).getCVRQualifiers();
589  } else {
590    // We've found a member of an anonymous struct/union that is
591    // inside a non-anonymous struct/union, so in a well-formed
592    // program our base object expression is "this".
593    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
594      if (!MD->isStatic()) {
595        QualType AnonFieldType
596          = Context.getTagDeclType(
597                     cast<RecordDecl>(AnonFields.back()->getDeclContext()));
598        QualType ThisType = Context.getTagDeclType(MD->getParent());
599        if ((Context.getCanonicalType(AnonFieldType)
600               == Context.getCanonicalType(ThisType)) ||
601            IsDerivedFrom(ThisType, AnonFieldType)) {
602          // Our base object expression is "this".
603          BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(),
604                                                     MD->getThisType(Context));
605          BaseObjectIsPointer = true;
606        }
607      } else {
608        return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
609          << Field->getDeclName());
610      }
611      ExtraQuals = MD->getTypeQualifiers();
612    }
613
614    if (!BaseObjectExpr)
615      return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
616        << Field->getDeclName());
617  }
618
619  // Build the implicit member references to the field of the
620  // anonymous struct/union.
621  Expr *Result = BaseObjectExpr;
622  unsigned BaseAddrSpace = BaseObjectExpr->getType().getAddressSpace();
623  for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
624         FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
625       FI != FIEnd; ++FI) {
626    QualType MemberType = (*FI)->getType();
627    if (!(*FI)->isMutable()) {
628      unsigned combinedQualifiers
629        = MemberType.getCVRQualifiers() | ExtraQuals;
630      MemberType = MemberType.getQualifiedType(combinedQualifiers);
631    }
632    if (BaseAddrSpace != MemberType.getAddressSpace())
633      MemberType = Context.getAddrSpaceQualType(MemberType, BaseAddrSpace);
634    MarkDeclarationReferenced(Loc, *FI);
635    // FIXME: Might this end up being a qualified name?
636    Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
637                                      OpLoc, MemberType);
638    BaseObjectIsPointer = false;
639    ExtraQuals = Context.getCanonicalType(MemberType).getCVRQualifiers();
640  }
641
642  return Owned(Result);
643}
644
645/// ActOnDeclarationNameExpr - The parser has read some kind of name
646/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
647/// performs lookup on that name and returns an expression that refers
648/// to that name. This routine isn't directly called from the parser,
649/// because the parser doesn't know about DeclarationName. Rather,
650/// this routine is called by ActOnIdentifierExpr,
651/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr,
652/// which form the DeclarationName from the corresponding syntactic
653/// forms.
654///
655/// HasTrailingLParen indicates whether this identifier is used in a
656/// function call context.  LookupCtx is only used for a C++
657/// qualified-id (foo::bar) to indicate the class or namespace that
658/// the identifier must be a member of.
659///
660/// isAddressOfOperand means that this expression is the direct operand
661/// of an address-of operator. This matters because this is the only
662/// situation where a qualified name referencing a non-static member may
663/// appear outside a member function of this class.
664Sema::OwningExprResult
665Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
666                               DeclarationName Name, bool HasTrailingLParen,
667                               const CXXScopeSpec *SS,
668                               bool isAddressOfOperand) {
669  // Could be enum-constant, value decl, instance variable, etc.
670  if (SS && SS->isInvalid())
671    return ExprError();
672
673  // C++ [temp.dep.expr]p3:
674  //   An id-expression is type-dependent if it contains:
675  //     -- a nested-name-specifier that contains a class-name that
676  //        names a dependent type.
677  // FIXME: Member of the current instantiation.
678  if (SS && isDependentScopeSpecifier(*SS)) {
679    return Owned(new (Context) UnresolvedDeclRefExpr(Name, Context.DependentTy,
680                                                     Loc, SS->getRange(),
681                static_cast<NestedNameSpecifier *>(SS->getScopeRep()),
682                                                     isAddressOfOperand));
683  }
684
685  LookupResult Lookup = LookupParsedName(S, SS, Name, LookupOrdinaryName,
686                                         false, true, Loc);
687
688  if (Lookup.isAmbiguous()) {
689    DiagnoseAmbiguousLookup(Lookup, Name, Loc,
690                            SS && SS->isSet() ? SS->getRange()
691                                              : SourceRange());
692    return ExprError();
693  }
694
695  NamedDecl *D = Lookup.getAsDecl();
696
697  // If this reference is in an Objective-C method, then ivar lookup happens as
698  // well.
699  IdentifierInfo *II = Name.getAsIdentifierInfo();
700  if (II && getCurMethodDecl()) {
701    // There are two cases to handle here.  1) scoped lookup could have failed,
702    // in which case we should look for an ivar.  2) scoped lookup could have
703    // found a decl, but that decl is outside the current instance method (i.e.
704    // a global variable).  In these two cases, we do a lookup for an ivar with
705    // this name, if the lookup sucedes, we replace it our current decl.
706    if (D == 0 || D->isDefinedOutsideFunctionOrMethod()) {
707      ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
708      ObjCInterfaceDecl *ClassDeclared;
709      if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
710        // Check if referencing a field with __attribute__((deprecated)).
711        if (DiagnoseUseOfDecl(IV, Loc))
712          return ExprError();
713
714        // If we're referencing an invalid decl, just return this as a silent
715        // error node.  The error diagnostic was already emitted on the decl.
716        if (IV->isInvalidDecl())
717          return ExprError();
718
719        bool IsClsMethod = getCurMethodDecl()->isClassMethod();
720        // If a class method attemps to use a free standing ivar, this is
721        // an error.
722        if (IsClsMethod && D && !D->isDefinedOutsideFunctionOrMethod())
723           return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
724                           << IV->getDeclName());
725        // If a class method uses a global variable, even if an ivar with
726        // same name exists, use the global.
727        if (!IsClsMethod) {
728          if (IV->getAccessControl() == ObjCIvarDecl::Private &&
729              ClassDeclared != IFace)
730           Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
731          // FIXME: This should use a new expr for a direct reference, don't
732          // turn this into Self->ivar, just return a BareIVarExpr or something.
733          IdentifierInfo &II = Context.Idents.get("self");
734          OwningExprResult SelfExpr = ActOnIdentifierExpr(S, SourceLocation(),
735                                                          II, false);
736          MarkDeclarationReferenced(Loc, IV);
737          return Owned(new (Context)
738                       ObjCIvarRefExpr(IV, IV->getType(), Loc,
739                                       SelfExpr.takeAs<Expr>(), true, true));
740        }
741      }
742    } else if (getCurMethodDecl()->isInstanceMethod()) {
743      // We should warn if a local variable hides an ivar.
744      ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
745      ObjCInterfaceDecl *ClassDeclared;
746      if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
747        if (IV->getAccessControl() != ObjCIvarDecl::Private ||
748            IFace == ClassDeclared)
749          Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
750      }
751    }
752    // Needed to implement property "super.method" notation.
753    if (D == 0 && II->isStr("super")) {
754      QualType T;
755
756      if (getCurMethodDecl()->isInstanceMethod())
757        T = Context.getObjCObjectPointerType(Context.getObjCInterfaceType(
758                                      getCurMethodDecl()->getClassInterface()));
759      else
760        T = Context.getObjCClassType();
761      return Owned(new (Context) ObjCSuperExpr(Loc, T));
762    }
763  }
764
765  // Determine whether this name might be a candidate for
766  // argument-dependent lookup.
767  bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
768             HasTrailingLParen;
769
770  if (ADL && D == 0) {
771    // We've seen something of the form
772    //
773    //   identifier(
774    //
775    // and we did not find any entity by the name
776    // "identifier". However, this identifier is still subject to
777    // argument-dependent lookup, so keep track of the name.
778    return Owned(new (Context) UnresolvedFunctionNameExpr(Name,
779                                                          Context.OverloadTy,
780                                                          Loc));
781  }
782
783  if (D == 0) {
784    // Otherwise, this could be an implicitly declared function reference (legal
785    // in C90, extension in C99).
786    if (HasTrailingLParen && II &&
787        !getLangOptions().CPlusPlus) // Not in C++.
788      D = ImplicitlyDefineFunction(Loc, *II, S);
789    else {
790      // If this name wasn't predeclared and if this is not a function call,
791      // diagnose the problem.
792      if (SS && !SS->isEmpty()) {
793        DiagnoseMissingMember(Loc, Name,
794                              (NestedNameSpecifier *)SS->getScopeRep(),
795                              SS->getRange());
796        return ExprError();
797      } else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
798               Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
799        return ExprError(Diag(Loc, diag::err_undeclared_use)
800          << Name.getAsString());
801      else
802        return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name);
803    }
804  }
805
806  if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
807    // Warn about constructs like:
808    //   if (void *X = foo()) { ... } else { X }.
809    // In the else block, the pointer is always false.
810
811    // FIXME: In a template instantiation, we don't have scope
812    // information to check this property.
813    if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
814      Scope *CheckS = S;
815      while (CheckS) {
816        if (CheckS->isWithinElse() &&
817            CheckS->getControlParent()->isDeclScope(DeclPtrTy::make(Var))) {
818          if (Var->getType()->isBooleanType())
819            ExprError(Diag(Loc, diag::warn_value_always_false)
820                      << Var->getDeclName());
821          else
822            ExprError(Diag(Loc, diag::warn_value_always_zero)
823                      << Var->getDeclName());
824          break;
825        }
826
827        // Move up one more control parent to check again.
828        CheckS = CheckS->getControlParent();
829        if (CheckS)
830          CheckS = CheckS->getParent();
831      }
832    }
833  } else if (FunctionDecl *Func = dyn_cast<FunctionDecl>(D)) {
834    if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
835      // C99 DR 316 says that, if a function type comes from a
836      // function definition (without a prototype), that type is only
837      // used for checking compatibility. Therefore, when referencing
838      // the function, we pretend that we don't have the full function
839      // type.
840      if (DiagnoseUseOfDecl(Func, Loc))
841        return ExprError();
842
843      QualType T = Func->getType();
844      QualType NoProtoType = T;
845      if (const FunctionProtoType *Proto = T->getAsFunctionProtoType())
846        NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType());
847      return BuildDeclRefExpr(Func, NoProtoType, Loc, false, false, SS);
848    }
849  }
850
851  return BuildDeclarationNameExpr(Loc, D, HasTrailingLParen, SS, isAddressOfOperand);
852}
853/// \brief Cast member's object to its own class if necessary.
854bool
855Sema::PerformObjectMemberConversion(Expr *&From, NamedDecl *Member) {
856  if (FieldDecl *FD = dyn_cast<FieldDecl>(Member))
857    if (CXXRecordDecl *RD =
858        dyn_cast<CXXRecordDecl>(FD->getDeclContext())) {
859      QualType DestType =
860        Context.getCanonicalType(Context.getTypeDeclType(RD));
861      if (DestType->isDependentType() || From->getType()->isDependentType())
862        return false;
863      QualType FromRecordType = From->getType();
864      QualType DestRecordType = DestType;
865      if (FromRecordType->getAs<PointerType>()) {
866        DestType = Context.getPointerType(DestType);
867        FromRecordType = FromRecordType->getPointeeType();
868      }
869      if (!Context.hasSameUnqualifiedType(FromRecordType, DestRecordType) &&
870          CheckDerivedToBaseConversion(FromRecordType,
871                                       DestRecordType,
872                                       From->getSourceRange().getBegin(),
873                                       From->getSourceRange()))
874        return true;
875      ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
876                        /*isLvalue=*/true);
877    }
878  return false;
879}
880
881/// \brief Build a MemberExpr AST node.
882static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
883                                   const CXXScopeSpec *SS, NamedDecl *Member,
884                                   SourceLocation Loc, QualType Ty) {
885  if (SS && SS->isSet())
886    return MemberExpr::Create(C, Base, isArrow,
887                              (NestedNameSpecifier *)SS->getScopeRep(),
888                              SS->getRange(), Member, Loc,
889                              // FIXME: Explicit template argument lists
890                              false, SourceLocation(), 0, 0, SourceLocation(),
891                              Ty);
892
893  return new (C) MemberExpr(Base, isArrow, Member, Loc, Ty);
894}
895
896/// \brief Complete semantic analysis for a reference to the given declaration.
897Sema::OwningExprResult
898Sema::BuildDeclarationNameExpr(SourceLocation Loc, NamedDecl *D,
899                               bool HasTrailingLParen,
900                               const CXXScopeSpec *SS,
901                               bool isAddressOfOperand) {
902  assert(D && "Cannot refer to a NULL declaration");
903  DeclarationName Name = D->getDeclName();
904
905  // If this is an expression of the form &Class::member, don't build an
906  // implicit member ref, because we want a pointer to the member in general,
907  // not any specific instance's member.
908  if (isAddressOfOperand && SS && !SS->isEmpty() && !HasTrailingLParen) {
909    DeclContext *DC = computeDeclContext(*SS);
910    if (D && isa<CXXRecordDecl>(DC)) {
911      QualType DType;
912      if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
913        DType = FD->getType().getNonReferenceType();
914      } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
915        DType = Method->getType();
916      } else if (isa<OverloadedFunctionDecl>(D)) {
917        DType = Context.OverloadTy;
918      }
919      // Could be an inner type. That's diagnosed below, so ignore it here.
920      if (!DType.isNull()) {
921        // The pointer is type- and value-dependent if it points into something
922        // dependent.
923        bool Dependent = DC->isDependentContext();
924        return BuildDeclRefExpr(D, DType, Loc, Dependent, Dependent, SS);
925      }
926    }
927  }
928
929  // We may have found a field within an anonymous union or struct
930  // (C++ [class.union]).
931  if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
932    if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
933      return BuildAnonymousStructUnionMemberReference(Loc, FD);
934
935  if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
936    if (!MD->isStatic()) {
937      // C++ [class.mfct.nonstatic]p2:
938      //   [...] if name lookup (3.4.1) resolves the name in the
939      //   id-expression to a nonstatic nontype member of class X or of
940      //   a base class of X, the id-expression is transformed into a
941      //   class member access expression (5.2.5) using (*this) (9.3.2)
942      //   as the postfix-expression to the left of the '.' operator.
943      DeclContext *Ctx = 0;
944      QualType MemberType;
945      if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
946        Ctx = FD->getDeclContext();
947        MemberType = FD->getType();
948
949        if (const ReferenceType *RefType = MemberType->getAs<ReferenceType>())
950          MemberType = RefType->getPointeeType();
951        else if (!FD->isMutable()) {
952          unsigned combinedQualifiers
953            = MemberType.getCVRQualifiers() | MD->getTypeQualifiers();
954          MemberType = MemberType.getQualifiedType(combinedQualifiers);
955        }
956      } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
957        if (!Method->isStatic()) {
958          Ctx = Method->getParent();
959          MemberType = Method->getType();
960        }
961      } else if (FunctionTemplateDecl *FunTmpl
962                   = dyn_cast<FunctionTemplateDecl>(D)) {
963        if (CXXMethodDecl *Method
964              = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())) {
965          if (!Method->isStatic()) {
966            Ctx = Method->getParent();
967            MemberType = Context.OverloadTy;
968          }
969        }
970      } else if (OverloadedFunctionDecl *Ovl
971                   = dyn_cast<OverloadedFunctionDecl>(D)) {
972        // FIXME: We need an abstraction for iterating over one or more function
973        // templates or functions. This code is far too repetitive!
974        for (OverloadedFunctionDecl::function_iterator
975               Func = Ovl->function_begin(),
976               FuncEnd = Ovl->function_end();
977             Func != FuncEnd; ++Func) {
978          CXXMethodDecl *DMethod = 0;
979          if (FunctionTemplateDecl *FunTmpl
980                = dyn_cast<FunctionTemplateDecl>(*Func))
981            DMethod = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
982          else
983            DMethod = dyn_cast<CXXMethodDecl>(*Func);
984
985          if (DMethod && !DMethod->isStatic()) {
986            Ctx = DMethod->getDeclContext();
987            MemberType = Context.OverloadTy;
988            break;
989          }
990        }
991      }
992
993      if (Ctx && Ctx->isRecord()) {
994        QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx));
995        QualType ThisType = Context.getTagDeclType(MD->getParent());
996        if ((Context.getCanonicalType(CtxType)
997               == Context.getCanonicalType(ThisType)) ||
998            IsDerivedFrom(ThisType, CtxType)) {
999          // Build the implicit member access expression.
1000          Expr *This = new (Context) CXXThisExpr(SourceLocation(),
1001                                                 MD->getThisType(Context));
1002          MarkDeclarationReferenced(Loc, D);
1003          if (PerformObjectMemberConversion(This, D))
1004            return ExprError();
1005
1006          bool ShouldCheckUse = true;
1007          if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
1008            // Don't diagnose the use of a virtual member function unless it's
1009            // explicitly qualified.
1010            if (MD->isVirtual() && (!SS || !SS->isSet()))
1011              ShouldCheckUse = false;
1012          }
1013
1014          if (ShouldCheckUse && DiagnoseUseOfDecl(D, Loc))
1015            return ExprError();
1016          return Owned(BuildMemberExpr(Context, This, true, SS, D,
1017                                       Loc, MemberType));
1018        }
1019      }
1020    }
1021  }
1022
1023  if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
1024    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
1025      if (MD->isStatic())
1026        // "invalid use of member 'x' in static member function"
1027        return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
1028          << FD->getDeclName());
1029    }
1030
1031    // Any other ways we could have found the field in a well-formed
1032    // program would have been turned into implicit member expressions
1033    // above.
1034    return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
1035      << FD->getDeclName());
1036  }
1037
1038  if (isa<TypedefDecl>(D))
1039    return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name);
1040  if (isa<ObjCInterfaceDecl>(D))
1041    return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name);
1042  if (isa<NamespaceDecl>(D))
1043    return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name);
1044
1045  // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
1046  if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
1047    return BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc,
1048                           false, false, SS);
1049  else if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
1050    return BuildDeclRefExpr(Template, Context.OverloadTy, Loc,
1051                            false, false, SS);
1052  else if (UnresolvedUsingDecl *UD = dyn_cast<UnresolvedUsingDecl>(D))
1053    return BuildDeclRefExpr(UD, Context.DependentTy, Loc,
1054                            /*TypeDependent=*/true,
1055                            /*ValueDependent=*/true, SS);
1056
1057  ValueDecl *VD = cast<ValueDecl>(D);
1058
1059  // Check whether this declaration can be used. Note that we suppress
1060  // this check when we're going to perform argument-dependent lookup
1061  // on this function name, because this might not be the function
1062  // that overload resolution actually selects.
1063  bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
1064             HasTrailingLParen;
1065  if (!(ADL && isa<FunctionDecl>(VD)) && DiagnoseUseOfDecl(VD, Loc))
1066    return ExprError();
1067
1068  // Only create DeclRefExpr's for valid Decl's.
1069  if (VD->isInvalidDecl())
1070    return ExprError();
1071
1072  // If the identifier reference is inside a block, and it refers to a value
1073  // that is outside the block, create a BlockDeclRefExpr instead of a
1074  // DeclRefExpr.  This ensures the value is treated as a copy-in snapshot when
1075  // the block is formed.
1076  //
1077  // We do not do this for things like enum constants, global variables, etc,
1078  // as they do not get snapshotted.
1079  //
1080  if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
1081    MarkDeclarationReferenced(Loc, VD);
1082    QualType ExprTy = VD->getType().getNonReferenceType();
1083    // The BlocksAttr indicates the variable is bound by-reference.
1084    if (VD->getAttr<BlocksAttr>())
1085      return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true));
1086    // This is to record that a 'const' was actually synthesize and added.
1087    bool constAdded = !ExprTy.isConstQualified();
1088    // Variable will be bound by-copy, make it const within the closure.
1089
1090    ExprTy.addConst();
1091    return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, false,
1092                                                constAdded));
1093  }
1094  // If this reference is not in a block or if the referenced variable is
1095  // within the block, create a normal DeclRefExpr.
1096
1097  bool TypeDependent = false;
1098  bool ValueDependent = false;
1099  if (getLangOptions().CPlusPlus) {
1100    // C++ [temp.dep.expr]p3:
1101    //   An id-expression is type-dependent if it contains:
1102    //     - an identifier that was declared with a dependent type,
1103    if (VD->getType()->isDependentType())
1104      TypeDependent = true;
1105    //     - FIXME: a template-id that is dependent,
1106    //     - a conversion-function-id that specifies a dependent type,
1107    else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1108             Name.getCXXNameType()->isDependentType())
1109      TypeDependent = true;
1110    //     - a nested-name-specifier that contains a class-name that
1111    //       names a dependent type.
1112    else if (SS && !SS->isEmpty()) {
1113      for (DeclContext *DC = computeDeclContext(*SS);
1114           DC; DC = DC->getParent()) {
1115        // FIXME: could stop early at namespace scope.
1116        if (DC->isRecord()) {
1117          CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
1118          if (Context.getTypeDeclType(Record)->isDependentType()) {
1119            TypeDependent = true;
1120            break;
1121          }
1122        }
1123      }
1124    }
1125
1126    // C++ [temp.dep.constexpr]p2:
1127    //
1128    //   An identifier is value-dependent if it is:
1129    //     - a name declared with a dependent type,
1130    if (TypeDependent)
1131      ValueDependent = true;
1132    //     - the name of a non-type template parameter,
1133    else if (isa<NonTypeTemplateParmDecl>(VD))
1134      ValueDependent = true;
1135    //    - a constant with integral or enumeration type and is
1136    //      initialized with an expression that is value-dependent
1137    else if (const VarDecl *Dcl = dyn_cast<VarDecl>(VD)) {
1138      if (Dcl->getType().getCVRQualifiers() == QualType::Const &&
1139          Dcl->getInit()) {
1140        ValueDependent = Dcl->getInit()->isValueDependent();
1141      }
1142    }
1143  }
1144
1145  return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
1146                          TypeDependent, ValueDependent, SS);
1147}
1148
1149Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
1150                                                 tok::TokenKind Kind) {
1151  PredefinedExpr::IdentType IT;
1152
1153  switch (Kind) {
1154  default: assert(0 && "Unknown simple primary expr!");
1155  case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
1156  case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
1157  case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
1158  }
1159
1160  // Pre-defined identifiers are of type char[x], where x is the length of the
1161  // string.
1162
1163  Decl *currentDecl = getCurFunctionOrMethodDecl();
1164  if (!currentDecl) {
1165    Diag(Loc, diag::ext_predef_outside_function);
1166    currentDecl = Context.getTranslationUnitDecl();
1167  }
1168
1169  QualType ResTy;
1170  if (cast<DeclContext>(currentDecl)->isDependentContext()) {
1171    ResTy = Context.DependentTy;
1172  } else {
1173    unsigned Length =
1174      PredefinedExpr::ComputeName(Context, IT, currentDecl).length();
1175
1176    llvm::APInt LengthI(32, Length + 1);
1177    ResTy = Context.CharTy.getQualifiedType(QualType::Const);
1178    ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
1179  }
1180  return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
1181}
1182
1183Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
1184  llvm::SmallString<16> CharBuffer;
1185  CharBuffer.resize(Tok.getLength());
1186  const char *ThisTokBegin = &CharBuffer[0];
1187  unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
1188
1189  CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1190                            Tok.getLocation(), PP);
1191  if (Literal.hadError())
1192    return ExprError();
1193
1194  QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
1195
1196  return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1197                                              Literal.isWide(),
1198                                              type, Tok.getLocation()));
1199}
1200
1201Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1202  // Fast path for a single digit (which is quite common).  A single digit
1203  // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1204  if (Tok.getLength() == 1) {
1205    const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
1206    unsigned IntSize = Context.Target.getIntWidth();
1207    return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
1208                    Context.IntTy, Tok.getLocation()));
1209  }
1210
1211  llvm::SmallString<512> IntegerBuffer;
1212  // Add padding so that NumericLiteralParser can overread by one character.
1213  IntegerBuffer.resize(Tok.getLength()+1);
1214  const char *ThisTokBegin = &IntegerBuffer[0];
1215
1216  // Get the spelling of the token, which eliminates trigraphs, etc.
1217  unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
1218
1219  NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1220                               Tok.getLocation(), PP);
1221  if (Literal.hadError)
1222    return ExprError();
1223
1224  Expr *Res;
1225
1226  if (Literal.isFloatingLiteral()) {
1227    QualType Ty;
1228    if (Literal.isFloat)
1229      Ty = Context.FloatTy;
1230    else if (!Literal.isLong)
1231      Ty = Context.DoubleTy;
1232    else
1233      Ty = Context.LongDoubleTy;
1234
1235    const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1236
1237    // isExact will be set by GetFloatValue().
1238    bool isExact = false;
1239    llvm::APFloat Val = Literal.GetFloatValue(Format, &isExact);
1240    Res = new (Context) FloatingLiteral(Val, isExact, Ty, Tok.getLocation());
1241
1242  } else if (!Literal.isIntegerLiteral()) {
1243    return ExprError();
1244  } else {
1245    QualType Ty;
1246
1247    // long long is a C99 feature.
1248    if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
1249        Literal.isLongLong)
1250      Diag(Tok.getLocation(), diag::ext_longlong);
1251
1252    // Get the value in the widest-possible width.
1253    llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
1254
1255    if (Literal.GetIntegerValue(ResultVal)) {
1256      // If this value didn't fit into uintmax_t, warn and force to ull.
1257      Diag(Tok.getLocation(), diag::warn_integer_too_large);
1258      Ty = Context.UnsignedLongLongTy;
1259      assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
1260             "long long is not intmax_t?");
1261    } else {
1262      // If this value fits into a ULL, try to figure out what else it fits into
1263      // according to the rules of C99 6.4.4.1p5.
1264
1265      // Octal, Hexadecimal, and integers with a U suffix are allowed to
1266      // be an unsigned int.
1267      bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1268
1269      // Check from smallest to largest, picking the smallest type we can.
1270      unsigned Width = 0;
1271      if (!Literal.isLong && !Literal.isLongLong) {
1272        // Are int/unsigned possibilities?
1273        unsigned IntSize = Context.Target.getIntWidth();
1274
1275        // Does it fit in a unsigned int?
1276        if (ResultVal.isIntN(IntSize)) {
1277          // Does it fit in a signed int?
1278          if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
1279            Ty = Context.IntTy;
1280          else if (AllowUnsigned)
1281            Ty = Context.UnsignedIntTy;
1282          Width = IntSize;
1283        }
1284      }
1285
1286      // Are long/unsigned long possibilities?
1287      if (Ty.isNull() && !Literal.isLongLong) {
1288        unsigned LongSize = Context.Target.getLongWidth();
1289
1290        // Does it fit in a unsigned long?
1291        if (ResultVal.isIntN(LongSize)) {
1292          // Does it fit in a signed long?
1293          if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
1294            Ty = Context.LongTy;
1295          else if (AllowUnsigned)
1296            Ty = Context.UnsignedLongTy;
1297          Width = LongSize;
1298        }
1299      }
1300
1301      // Finally, check long long if needed.
1302      if (Ty.isNull()) {
1303        unsigned LongLongSize = Context.Target.getLongLongWidth();
1304
1305        // Does it fit in a unsigned long long?
1306        if (ResultVal.isIntN(LongLongSize)) {
1307          // Does it fit in a signed long long?
1308          if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
1309            Ty = Context.LongLongTy;
1310          else if (AllowUnsigned)
1311            Ty = Context.UnsignedLongLongTy;
1312          Width = LongLongSize;
1313        }
1314      }
1315
1316      // If we still couldn't decide a type, we probably have something that
1317      // does not fit in a signed long long, but has no U suffix.
1318      if (Ty.isNull()) {
1319        Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
1320        Ty = Context.UnsignedLongLongTy;
1321        Width = Context.Target.getLongLongWidth();
1322      }
1323
1324      if (ResultVal.getBitWidth() != Width)
1325        ResultVal.trunc(Width);
1326    }
1327    Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
1328  }
1329
1330  // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1331  if (Literal.isImaginary)
1332    Res = new (Context) ImaginaryLiteral(Res,
1333                                        Context.getComplexType(Res->getType()));
1334
1335  return Owned(Res);
1336}
1337
1338Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1339                                              SourceLocation R, ExprArg Val) {
1340  Expr *E = Val.takeAs<Expr>();
1341  assert((E != 0) && "ActOnParenExpr() missing expr");
1342  return Owned(new (Context) ParenExpr(L, R, E));
1343}
1344
1345/// The UsualUnaryConversions() function is *not* called by this routine.
1346/// See C99 6.3.2.1p[2-4] for more details.
1347bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
1348                                     SourceLocation OpLoc,
1349                                     const SourceRange &ExprRange,
1350                                     bool isSizeof) {
1351  if (exprType->isDependentType())
1352    return false;
1353
1354  // C99 6.5.3.4p1:
1355  if (isa<FunctionType>(exprType)) {
1356    // alignof(function) is allowed as an extension.
1357    if (isSizeof)
1358      Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1359    return false;
1360  }
1361
1362  // Allow sizeof(void)/alignof(void) as an extension.
1363  if (exprType->isVoidType()) {
1364    Diag(OpLoc, diag::ext_sizeof_void_type)
1365      << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
1366    return false;
1367  }
1368
1369  if (RequireCompleteType(OpLoc, exprType,
1370                          isSizeof ? diag::err_sizeof_incomplete_type :
1371                          PDiag(diag::err_alignof_incomplete_type)
1372                            << ExprRange))
1373    return true;
1374
1375  // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
1376  if (LangOpts.ObjCNonFragileABI && exprType->isObjCInterfaceType()) {
1377    Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
1378      << exprType << isSizeof << ExprRange;
1379    return true;
1380  }
1381
1382  return false;
1383}
1384
1385bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1386                            const SourceRange &ExprRange) {
1387  E = E->IgnoreParens();
1388
1389  // alignof decl is always ok.
1390  if (isa<DeclRefExpr>(E))
1391    return false;
1392
1393  // Cannot know anything else if the expression is dependent.
1394  if (E->isTypeDependent())
1395    return false;
1396
1397  if (E->getBitField()) {
1398    Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
1399    return true;
1400  }
1401
1402  // Alignment of a field access is always okay, so long as it isn't a
1403  // bit-field.
1404  if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
1405    if (isa<FieldDecl>(ME->getMemberDecl()))
1406      return false;
1407
1408  return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1409}
1410
1411/// \brief Build a sizeof or alignof expression given a type operand.
1412Action::OwningExprResult
1413Sema::CreateSizeOfAlignOfExpr(QualType T, SourceLocation OpLoc,
1414                              bool isSizeOf, SourceRange R) {
1415  if (T.isNull())
1416    return ExprError();
1417
1418  if (!T->isDependentType() &&
1419      CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
1420    return ExprError();
1421
1422  // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1423  return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, T,
1424                                               Context.getSizeType(), OpLoc,
1425                                               R.getEnd()));
1426}
1427
1428/// \brief Build a sizeof or alignof expression given an expression
1429/// operand.
1430Action::OwningExprResult
1431Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
1432                              bool isSizeOf, SourceRange R) {
1433  // Verify that the operand is valid.
1434  bool isInvalid = false;
1435  if (E->isTypeDependent()) {
1436    // Delay type-checking for type-dependent expressions.
1437  } else if (!isSizeOf) {
1438    isInvalid = CheckAlignOfExpr(E, OpLoc, R);
1439  } else if (E->getBitField()) {  // C99 6.5.3.4p1.
1440    Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1441    isInvalid = true;
1442  } else {
1443    isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
1444  }
1445
1446  if (isInvalid)
1447    return ExprError();
1448
1449  // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1450  return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
1451                                               Context.getSizeType(), OpLoc,
1452                                               R.getEnd()));
1453}
1454
1455/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1456/// the same for @c alignof and @c __alignof
1457/// Note that the ArgRange is invalid if isType is false.
1458Action::OwningExprResult
1459Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1460                             void *TyOrEx, const SourceRange &ArgRange) {
1461  // If error parsing type, ignore.
1462  if (TyOrEx == 0) return ExprError();
1463
1464  if (isType) {
1465    // FIXME: Preserve type source info.
1466    QualType ArgTy = GetTypeFromParser(TyOrEx);
1467    return CreateSizeOfAlignOfExpr(ArgTy, OpLoc, isSizeof, ArgRange);
1468  }
1469
1470  // Get the end location.
1471  Expr *ArgEx = (Expr *)TyOrEx;
1472  Action::OwningExprResult Result
1473    = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
1474
1475  if (Result.isInvalid())
1476    DeleteExpr(ArgEx);
1477
1478  return move(Result);
1479}
1480
1481QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
1482  if (V->isTypeDependent())
1483    return Context.DependentTy;
1484
1485  // These operators return the element type of a complex type.
1486  if (const ComplexType *CT = V->getType()->getAsComplexType())
1487    return CT->getElementType();
1488
1489  // Otherwise they pass through real integer and floating point types here.
1490  if (V->getType()->isArithmeticType())
1491    return V->getType();
1492
1493  // Reject anything else.
1494  Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1495    << (isReal ? "__real" : "__imag");
1496  return QualType();
1497}
1498
1499
1500
1501Action::OwningExprResult
1502Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1503                          tok::TokenKind Kind, ExprArg Input) {
1504  // Since this might be a postfix expression, get rid of ParenListExprs.
1505  Input = MaybeConvertParenListExprToParenExpr(S, move(Input));
1506  Expr *Arg = (Expr *)Input.get();
1507
1508  UnaryOperator::Opcode Opc;
1509  switch (Kind) {
1510  default: assert(0 && "Unknown unary op!");
1511  case tok::plusplus:   Opc = UnaryOperator::PostInc; break;
1512  case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1513  }
1514
1515  if (getLangOptions().CPlusPlus &&
1516      (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1517    // Which overloaded operator?
1518    OverloadedOperatorKind OverOp =
1519      (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1520
1521    // C++ [over.inc]p1:
1522    //
1523    //     [...] If the function is a member function with one
1524    //     parameter (which shall be of type int) or a non-member
1525    //     function with two parameters (the second of which shall be
1526    //     of type int), it defines the postfix increment operator ++
1527    //     for objects of that type. When the postfix increment is
1528    //     called as a result of using the ++ operator, the int
1529    //     argument will have value zero.
1530    Expr *Args[2] = {
1531      Arg,
1532      new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1533                          /*isSigned=*/true), Context.IntTy, SourceLocation())
1534    };
1535
1536    // Build the candidate set for overloading
1537    OverloadCandidateSet CandidateSet;
1538    AddOperatorCandidates(OverOp, S, OpLoc, Args, 2, CandidateSet);
1539
1540    // Perform overload resolution.
1541    OverloadCandidateSet::iterator Best;
1542    switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
1543    case OR_Success: {
1544      // We found a built-in operator or an overloaded operator.
1545      FunctionDecl *FnDecl = Best->Function;
1546
1547      if (FnDecl) {
1548        // We matched an overloaded operator. Build a call to that
1549        // operator.
1550
1551        // Convert the arguments.
1552        if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1553          if (PerformObjectArgumentInitialization(Arg, Method))
1554            return ExprError();
1555        } else {
1556          // Convert the arguments.
1557          if (PerformCopyInitialization(Arg,
1558                                        FnDecl->getParamDecl(0)->getType(),
1559                                        "passing"))
1560            return ExprError();
1561        }
1562
1563        // Determine the result type
1564        QualType ResultTy
1565          = FnDecl->getType()->getAsFunctionType()->getResultType();
1566        ResultTy = ResultTy.getNonReferenceType();
1567
1568        // Build the actual expression node.
1569        Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
1570                                                 SourceLocation());
1571        UsualUnaryConversions(FnExpr);
1572
1573        Input.release();
1574        Args[0] = Arg;
1575        return Owned(new (Context) CXXOperatorCallExpr(Context, OverOp, FnExpr,
1576                                                       Args, 2, ResultTy,
1577                                                       OpLoc));
1578      } else {
1579        // We matched a built-in operator. Convert the arguments, then
1580        // break out so that we will build the appropriate built-in
1581        // operator node.
1582        if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1583                                      "passing"))
1584          return ExprError();
1585
1586        break;
1587      }
1588    }
1589
1590    case OR_No_Viable_Function:
1591      // No viable function; fall through to handling this as a
1592      // built-in operator, which will produce an error message for us.
1593      break;
1594
1595    case OR_Ambiguous:
1596      Diag(OpLoc,  diag::err_ovl_ambiguous_oper)
1597          << UnaryOperator::getOpcodeStr(Opc)
1598          << Arg->getSourceRange();
1599      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1600      return ExprError();
1601
1602    case OR_Deleted:
1603      Diag(OpLoc, diag::err_ovl_deleted_oper)
1604        << Best->Function->isDeleted()
1605        << UnaryOperator::getOpcodeStr(Opc)
1606        << Arg->getSourceRange();
1607      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1608      return ExprError();
1609    }
1610
1611    // Either we found no viable overloaded operator or we matched a
1612    // built-in operator. In either case, fall through to trying to
1613    // build a built-in operation.
1614  }
1615
1616  Input.release();
1617  Input = Arg;
1618  return CreateBuiltinUnaryOp(OpLoc, Opc, move(Input));
1619}
1620
1621Action::OwningExprResult
1622Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1623                              ExprArg Idx, SourceLocation RLoc) {
1624  // Since this might be a postfix expression, get rid of ParenListExprs.
1625  Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
1626
1627  Expr *LHSExp = static_cast<Expr*>(Base.get()),
1628       *RHSExp = static_cast<Expr*>(Idx.get());
1629
1630  if (getLangOptions().CPlusPlus &&
1631      (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
1632    Base.release();
1633    Idx.release();
1634    return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1635                                                  Context.DependentTy, RLoc));
1636  }
1637
1638  if (getLangOptions().CPlusPlus &&
1639      (LHSExp->getType()->isRecordType() ||
1640       LHSExp->getType()->isEnumeralType() ||
1641       RHSExp->getType()->isRecordType() ||
1642       RHSExp->getType()->isEnumeralType())) {
1643    // Add the appropriate overloaded operators (C++ [over.match.oper])
1644    // to the candidate set.
1645    OverloadCandidateSet CandidateSet;
1646    Expr *Args[2] = { LHSExp, RHSExp };
1647    AddOperatorCandidates(OO_Subscript, S, LLoc, Args, 2, CandidateSet,
1648                          SourceRange(LLoc, RLoc));
1649
1650    // Perform overload resolution.
1651    OverloadCandidateSet::iterator Best;
1652    switch (BestViableFunction(CandidateSet, LLoc, Best)) {
1653    case OR_Success: {
1654      // We found a built-in operator or an overloaded operator.
1655      FunctionDecl *FnDecl = Best->Function;
1656
1657      if (FnDecl) {
1658        // We matched an overloaded operator. Build a call to that
1659        // operator.
1660
1661        // Convert the arguments.
1662        if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1663          if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1664              PerformCopyInitialization(RHSExp,
1665                                        FnDecl->getParamDecl(0)->getType(),
1666                                        "passing"))
1667            return ExprError();
1668        } else {
1669          // Convert the arguments.
1670          if (PerformCopyInitialization(LHSExp,
1671                                        FnDecl->getParamDecl(0)->getType(),
1672                                        "passing") ||
1673              PerformCopyInitialization(RHSExp,
1674                                        FnDecl->getParamDecl(1)->getType(),
1675                                        "passing"))
1676            return ExprError();
1677        }
1678
1679        // Determine the result type
1680        QualType ResultTy
1681          = FnDecl->getType()->getAsFunctionType()->getResultType();
1682        ResultTy = ResultTy.getNonReferenceType();
1683
1684        // Build the actual expression node.
1685        Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
1686                                                 SourceLocation());
1687        UsualUnaryConversions(FnExpr);
1688
1689        Base.release();
1690        Idx.release();
1691        Args[0] = LHSExp;
1692        Args[1] = RHSExp;
1693        return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
1694                                                       FnExpr, Args, 2,
1695                                                       ResultTy, LLoc));
1696      } else {
1697        // We matched a built-in operator. Convert the arguments, then
1698        // break out so that we will build the appropriate built-in
1699        // operator node.
1700        if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1701                                      "passing") ||
1702            PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1703                                      "passing"))
1704          return ExprError();
1705
1706        break;
1707      }
1708    }
1709
1710    case OR_No_Viable_Function:
1711      // No viable function; fall through to handling this as a
1712      // built-in operator, which will produce an error message for us.
1713      break;
1714
1715    case OR_Ambiguous:
1716      Diag(LLoc,  diag::err_ovl_ambiguous_oper)
1717          << "[]"
1718          << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1719      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1720      return ExprError();
1721
1722    case OR_Deleted:
1723      Diag(LLoc, diag::err_ovl_deleted_oper)
1724        << Best->Function->isDeleted()
1725        << "[]"
1726        << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1727      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1728      return ExprError();
1729    }
1730
1731    // Either we found no viable overloaded operator or we matched a
1732    // built-in operator. In either case, fall through to trying to
1733    // build a built-in operation.
1734  }
1735
1736  // Perform default conversions.
1737  DefaultFunctionArrayConversion(LHSExp);
1738  DefaultFunctionArrayConversion(RHSExp);
1739
1740  QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
1741
1742  // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
1743  // to the expression *((e1)+(e2)). This means the array "Base" may actually be
1744  // in the subscript position. As a result, we need to derive the array base
1745  // and index from the expression types.
1746  Expr *BaseExpr, *IndexExpr;
1747  QualType ResultType;
1748  if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
1749    BaseExpr = LHSExp;
1750    IndexExpr = RHSExp;
1751    ResultType = Context.DependentTy;
1752  } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
1753    BaseExpr = LHSExp;
1754    IndexExpr = RHSExp;
1755    ResultType = PTy->getPointeeType();
1756  } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
1757     // Handle the uncommon case of "123[Ptr]".
1758    BaseExpr = RHSExp;
1759    IndexExpr = LHSExp;
1760    ResultType = PTy->getPointeeType();
1761  } else if (const ObjCObjectPointerType *PTy =
1762               LHSTy->getAsObjCObjectPointerType()) {
1763    BaseExpr = LHSExp;
1764    IndexExpr = RHSExp;
1765    ResultType = PTy->getPointeeType();
1766  } else if (const ObjCObjectPointerType *PTy =
1767               RHSTy->getAsObjCObjectPointerType()) {
1768     // Handle the uncommon case of "123[Ptr]".
1769    BaseExpr = RHSExp;
1770    IndexExpr = LHSExp;
1771    ResultType = PTy->getPointeeType();
1772  } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1773    BaseExpr = LHSExp;    // vectors: V[123]
1774    IndexExpr = RHSExp;
1775
1776    // FIXME: need to deal with const...
1777    ResultType = VTy->getElementType();
1778  } else if (LHSTy->isArrayType()) {
1779    // If we see an array that wasn't promoted by
1780    // DefaultFunctionArrayConversion, it must be an array that
1781    // wasn't promoted because of the C90 rule that doesn't
1782    // allow promoting non-lvalue arrays.  Warn, then
1783    // force the promotion here.
1784    Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1785        LHSExp->getSourceRange();
1786    ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy));
1787    LHSTy = LHSExp->getType();
1788
1789    BaseExpr = LHSExp;
1790    IndexExpr = RHSExp;
1791    ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
1792  } else if (RHSTy->isArrayType()) {
1793    // Same as previous, except for 123[f().a] case
1794    Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1795        RHSExp->getSourceRange();
1796    ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy));
1797    RHSTy = RHSExp->getType();
1798
1799    BaseExpr = RHSExp;
1800    IndexExpr = LHSExp;
1801    ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
1802  } else {
1803    return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
1804       << LHSExp->getSourceRange() << RHSExp->getSourceRange());
1805  }
1806  // C99 6.5.2.1p1
1807  if (!(IndexExpr->getType()->isIntegerType() &&
1808        IndexExpr->getType()->isScalarType()) && !IndexExpr->isTypeDependent())
1809    return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
1810                     << IndexExpr->getSourceRange());
1811
1812  QualType IndexTy = Context.getCanonicalType(IndexExpr->getType());
1813  if ((IndexTy == Context.CharTy || IndexTy == Context.SignedCharTy)
1814      && !IndexExpr->isTypeDependent())
1815    Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
1816
1817  // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
1818  // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
1819  // type. Note that Functions are not objects, and that (in C99 parlance)
1820  // incomplete types are not object types.
1821  if (ResultType->isFunctionType()) {
1822    Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
1823      << ResultType << BaseExpr->getSourceRange();
1824    return ExprError();
1825  }
1826
1827  if (!ResultType->isDependentType() &&
1828      RequireCompleteType(LLoc, ResultType,
1829                          PDiag(diag::err_subscript_incomplete_type)
1830                            << BaseExpr->getSourceRange()))
1831    return ExprError();
1832
1833  // Diagnose bad cases where we step over interface counts.
1834  if (ResultType->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
1835    Diag(LLoc, diag::err_subscript_nonfragile_interface)
1836      << ResultType << BaseExpr->getSourceRange();
1837    return ExprError();
1838  }
1839
1840  Base.release();
1841  Idx.release();
1842  return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1843                                                ResultType, RLoc));
1844}
1845
1846QualType Sema::
1847CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
1848                        const IdentifierInfo *CompName,
1849                        SourceLocation CompLoc) {
1850  const ExtVectorType *vecType = baseType->getAsExtVectorType();
1851
1852  // The vector accessor can't exceed the number of elements.
1853  const char *compStr = CompName->getName();
1854
1855  // This flag determines whether or not the component is one of the four
1856  // special names that indicate a subset of exactly half the elements are
1857  // to be selected.
1858  bool HalvingSwizzle = false;
1859
1860  // This flag determines whether or not CompName has an 's' char prefix,
1861  // indicating that it is a string of hex values to be used as vector indices.
1862  bool HexSwizzle = *compStr == 's' || *compStr == 'S';
1863
1864  // Check that we've found one of the special components, or that the component
1865  // names must come from the same set.
1866  if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
1867      !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1868    HalvingSwizzle = true;
1869  } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
1870    do
1871      compStr++;
1872    while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
1873  } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
1874    do
1875      compStr++;
1876    while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
1877  }
1878
1879  if (!HalvingSwizzle && *compStr) {
1880    // We didn't get to the end of the string. This means the component names
1881    // didn't come from the same set *or* we encountered an illegal name.
1882    Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1883      << std::string(compStr,compStr+1) << SourceRange(CompLoc);
1884    return QualType();
1885  }
1886
1887  // Ensure no component accessor exceeds the width of the vector type it
1888  // operates on.
1889  if (!HalvingSwizzle) {
1890    compStr = CompName->getName();
1891
1892    if (HexSwizzle)
1893      compStr++;
1894
1895    while (*compStr) {
1896      if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1897        Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1898          << baseType << SourceRange(CompLoc);
1899        return QualType();
1900      }
1901    }
1902  }
1903
1904  // If this is a halving swizzle, verify that the base type has an even
1905  // number of elements.
1906  if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
1907    Diag(OpLoc, diag::err_ext_vector_component_requires_even)
1908      << baseType << SourceRange(CompLoc);
1909    return QualType();
1910  }
1911
1912  // The component accessor looks fine - now we need to compute the actual type.
1913  // The vector type is implied by the component accessor. For example,
1914  // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
1915  // vec4.s0 is a float, vec4.s23 is a vec3, etc.
1916  // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
1917  unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
1918                                     : CompName->getLength();
1919  if (HexSwizzle)
1920    CompSize--;
1921
1922  if (CompSize == 1)
1923    return vecType->getElementType();
1924
1925  QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
1926  // Now look up the TypeDefDecl from the vector type. Without this,
1927  // diagostics look bad. We want extended vector types to appear built-in.
1928  for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1929    if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1930      return Context.getTypedefType(ExtVectorDecls[i]);
1931  }
1932  return VT; // should never get here (a typedef type should always be found).
1933}
1934
1935static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
1936                                                IdentifierInfo *Member,
1937                                                const Selector &Sel,
1938                                                ASTContext &Context) {
1939
1940  if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
1941    return PD;
1942  if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
1943    return OMD;
1944
1945  for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
1946       E = PDecl->protocol_end(); I != E; ++I) {
1947    if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel,
1948                                                     Context))
1949      return D;
1950  }
1951  return 0;
1952}
1953
1954static Decl *FindGetterNameDecl(const ObjCObjectPointerType *QIdTy,
1955                                IdentifierInfo *Member,
1956                                const Selector &Sel,
1957                                ASTContext &Context) {
1958  // Check protocols on qualified interfaces.
1959  Decl *GDecl = 0;
1960  for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
1961       E = QIdTy->qual_end(); I != E; ++I) {
1962    if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
1963      GDecl = PD;
1964      break;
1965    }
1966    // Also must look for a getter name which uses property syntax.
1967    if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
1968      GDecl = OMD;
1969      break;
1970    }
1971  }
1972  if (!GDecl) {
1973    for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
1974         E = QIdTy->qual_end(); I != E; ++I) {
1975      // Search in the protocol-qualifier list of current protocol.
1976      GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context);
1977      if (GDecl)
1978        return GDecl;
1979    }
1980  }
1981  return GDecl;
1982}
1983
1984/// FindMethodInNestedImplementations - Look up a method in current and
1985/// all base class implementations.
1986///
1987ObjCMethodDecl *Sema::FindMethodInNestedImplementations(
1988                                              const ObjCInterfaceDecl *IFace,
1989                                              const Selector &Sel) {
1990  ObjCMethodDecl *Method = 0;
1991  if (ObjCImplementationDecl *ImpDecl = IFace->getImplementation())
1992    Method = ImpDecl->getInstanceMethod(Sel);
1993
1994  if (!Method && IFace->getSuperClass())
1995    return FindMethodInNestedImplementations(IFace->getSuperClass(), Sel);
1996  return Method;
1997}
1998
1999Action::OwningExprResult
2000Sema::BuildMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
2001                               tok::TokenKind OpKind, SourceLocation MemberLoc,
2002                               DeclarationName MemberName,
2003                               bool HasExplicitTemplateArgs,
2004                               SourceLocation LAngleLoc,
2005                               const TemplateArgument *ExplicitTemplateArgs,
2006                               unsigned NumExplicitTemplateArgs,
2007                               SourceLocation RAngleLoc,
2008                               DeclPtrTy ObjCImpDecl, const CXXScopeSpec *SS,
2009                               NamedDecl *FirstQualifierInScope) {
2010  if (SS && SS->isInvalid())
2011    return ExprError();
2012
2013  // Since this might be a postfix expression, get rid of ParenListExprs.
2014  Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
2015
2016  Expr *BaseExpr = Base.takeAs<Expr>();
2017  assert(BaseExpr && "no base expression");
2018
2019  // Perform default conversions.
2020  DefaultFunctionArrayConversion(BaseExpr);
2021
2022  QualType BaseType = BaseExpr->getType();
2023  // If this is an Objective-C pseudo-builtin and a definition is provided then
2024  // use that.
2025  if (BaseType->isObjCIdType()) {
2026    // We have an 'id' type. Rather than fall through, we check if this
2027    // is a reference to 'isa'.
2028    if (BaseType != Context.ObjCIdRedefinitionType) {
2029      BaseType = Context.ObjCIdRedefinitionType;
2030      ImpCastExprToType(BaseExpr, BaseType);
2031    }
2032  } else if (BaseType->isObjCClassType() &&
2033             BaseType != Context.ObjCClassRedefinitionType) {
2034    BaseType = Context.ObjCClassRedefinitionType;
2035    ImpCastExprToType(BaseExpr, BaseType);
2036  }
2037  assert(!BaseType.isNull() && "no type for member expression");
2038
2039  // Get the type being accessed in BaseType.  If this is an arrow, the BaseExpr
2040  // must have pointer type, and the accessed type is the pointee.
2041  if (OpKind == tok::arrow) {
2042    if (BaseType->isDependentType()) {
2043      NestedNameSpecifier *Qualifier = 0;
2044      if (SS) {
2045        Qualifier = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
2046        if (!FirstQualifierInScope)
2047          FirstQualifierInScope = FindFirstQualifierInScope(S, Qualifier);
2048      }
2049
2050      return Owned(CXXUnresolvedMemberExpr::Create(Context, BaseExpr, true,
2051                                                   OpLoc, Qualifier,
2052                                            SS? SS->getRange() : SourceRange(),
2053                                                   FirstQualifierInScope,
2054                                                   MemberName,
2055                                                   MemberLoc,
2056                                                   HasExplicitTemplateArgs,
2057                                                   LAngleLoc,
2058                                                   ExplicitTemplateArgs,
2059                                                   NumExplicitTemplateArgs,
2060                                                   RAngleLoc));
2061    }
2062    else if (const PointerType *PT = BaseType->getAs<PointerType>())
2063      BaseType = PT->getPointeeType();
2064    else if (BaseType->isObjCObjectPointerType())
2065      ;
2066    else
2067      return ExprError(Diag(MemberLoc,
2068                            diag::err_typecheck_member_reference_arrow)
2069        << BaseType << BaseExpr->getSourceRange());
2070  } else {
2071    if (BaseType->isDependentType()) {
2072      // Require that the base type isn't a pointer type
2073      // (so we'll report an error for)
2074      // T* t;
2075      // t.f;
2076      //
2077      // In Obj-C++, however, the above expression is valid, since it could be
2078      // accessing the 'f' property if T is an Obj-C interface. The extra check
2079      // allows this, while still reporting an error if T is a struct pointer.
2080      const PointerType *PT = BaseType->getAs<PointerType>();
2081
2082      if (!PT || (getLangOptions().ObjC1 &&
2083                  !PT->getPointeeType()->isRecordType())) {
2084        NestedNameSpecifier *Qualifier = 0;
2085        if (SS) {
2086          Qualifier = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
2087          if (!FirstQualifierInScope)
2088            FirstQualifierInScope = FindFirstQualifierInScope(S, Qualifier);
2089        }
2090
2091        return Owned(CXXUnresolvedMemberExpr::Create(Context,
2092                                                     BaseExpr, false,
2093                                                     OpLoc,
2094                                                     Qualifier,
2095                                            SS? SS->getRange() : SourceRange(),
2096                                                     FirstQualifierInScope,
2097                                                     MemberName,
2098                                                     MemberLoc,
2099                                                     HasExplicitTemplateArgs,
2100                                                     LAngleLoc,
2101                                                     ExplicitTemplateArgs,
2102                                                     NumExplicitTemplateArgs,
2103                                                     RAngleLoc));
2104      }
2105    }
2106  }
2107
2108  // Handle field access to simple records.  This also handles access to fields
2109  // of the ObjC 'id' struct.
2110  if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
2111    RecordDecl *RDecl = RTy->getDecl();
2112    if (RequireCompleteType(OpLoc, BaseType,
2113                            PDiag(diag::err_typecheck_incomplete_tag)
2114                              << BaseExpr->getSourceRange()))
2115      return ExprError();
2116
2117    DeclContext *DC = RDecl;
2118    if (SS && SS->isSet()) {
2119      // If the member name was a qualified-id, look into the
2120      // nested-name-specifier.
2121      DC = computeDeclContext(*SS, false);
2122
2123      // FIXME: If DC is not computable, we should build a
2124      // CXXUnresolvedMemberExpr.
2125      assert(DC && "Cannot handle non-computable dependent contexts in lookup");
2126    }
2127
2128    // The record definition is complete, now make sure the member is valid.
2129    LookupResult Result
2130      = LookupQualifiedName(DC, MemberName, LookupMemberName, false);
2131
2132    if (!Result)
2133      return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member_deprecated)
2134               << MemberName << BaseExpr->getSourceRange());
2135    if (Result.isAmbiguous()) {
2136      DiagnoseAmbiguousLookup(Result, MemberName, MemberLoc,
2137                              BaseExpr->getSourceRange());
2138      return ExprError();
2139    }
2140
2141    if (SS && SS->isSet()) {
2142      QualType BaseTypeCanon
2143        = Context.getCanonicalType(BaseType).getUnqualifiedType();
2144      QualType MemberTypeCanon
2145        = Context.getCanonicalType(
2146                  Context.getTypeDeclType(
2147                    dyn_cast<TypeDecl>(Result.getAsDecl()->getDeclContext())));
2148
2149      if (BaseTypeCanon != MemberTypeCanon &&
2150          !IsDerivedFrom(BaseTypeCanon, MemberTypeCanon))
2151        return ExprError(Diag(SS->getBeginLoc(),
2152                              diag::err_not_direct_base_or_virtual)
2153                         << MemberTypeCanon << BaseTypeCanon);
2154    }
2155
2156    NamedDecl *MemberDecl = Result;
2157
2158    // If the decl being referenced had an error, return an error for this
2159    // sub-expr without emitting another error, in order to avoid cascading
2160    // error cases.
2161    if (MemberDecl->isInvalidDecl())
2162      return ExprError();
2163
2164    bool ShouldCheckUse = true;
2165    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
2166      // Don't diagnose the use of a virtual member function unless it's
2167      // explicitly qualified.
2168      if (MD->isVirtual() && (!SS || !SS->isSet()))
2169        ShouldCheckUse = false;
2170    }
2171
2172    // Check the use of this field
2173    if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc))
2174      return ExprError();
2175
2176    if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
2177      // We may have found a field within an anonymous union or struct
2178      // (C++ [class.union]).
2179      if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
2180        return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
2181                                                        BaseExpr, OpLoc);
2182
2183      // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
2184      QualType MemberType = FD->getType();
2185      if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>())
2186        MemberType = Ref->getPointeeType();
2187      else {
2188        unsigned BaseAddrSpace = BaseType.getAddressSpace();
2189        unsigned combinedQualifiers =
2190          MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
2191        if (FD->isMutable())
2192          combinedQualifiers &= ~QualType::Const;
2193        MemberType = MemberType.getQualifiedType(combinedQualifiers);
2194        if (BaseAddrSpace != MemberType.getAddressSpace())
2195           MemberType = Context.getAddrSpaceQualType(MemberType, BaseAddrSpace);
2196      }
2197
2198      MarkDeclarationReferenced(MemberLoc, FD);
2199      if (PerformObjectMemberConversion(BaseExpr, FD))
2200        return ExprError();
2201      return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2202                                   FD, MemberLoc, MemberType));
2203    }
2204
2205    if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
2206      MarkDeclarationReferenced(MemberLoc, MemberDecl);
2207      return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2208                                   Var, MemberLoc,
2209                                   Var->getType().getNonReferenceType()));
2210    }
2211    if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl)) {
2212      MarkDeclarationReferenced(MemberLoc, MemberDecl);
2213      return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2214                                   MemberFn, MemberLoc,
2215                                   MemberFn->getType()));
2216    }
2217    if (FunctionTemplateDecl *FunTmpl
2218          = dyn_cast<FunctionTemplateDecl>(MemberDecl)) {
2219      MarkDeclarationReferenced(MemberLoc, MemberDecl);
2220
2221      if (HasExplicitTemplateArgs)
2222        return Owned(MemberExpr::Create(Context, BaseExpr, OpKind == tok::arrow,
2223                             (NestedNameSpecifier *)(SS? SS->getScopeRep() : 0),
2224                                       SS? SS->getRange() : SourceRange(),
2225                                        FunTmpl, MemberLoc, true,
2226                                        LAngleLoc, ExplicitTemplateArgs,
2227                                        NumExplicitTemplateArgs, RAngleLoc,
2228                                        Context.OverloadTy));
2229
2230      return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2231                                   FunTmpl, MemberLoc,
2232                                   Context.OverloadTy));
2233    }
2234    if (OverloadedFunctionDecl *Ovl
2235          = dyn_cast<OverloadedFunctionDecl>(MemberDecl)) {
2236      if (HasExplicitTemplateArgs)
2237        return Owned(MemberExpr::Create(Context, BaseExpr, OpKind == tok::arrow,
2238                             (NestedNameSpecifier *)(SS? SS->getScopeRep() : 0),
2239                                        SS? SS->getRange() : SourceRange(),
2240                                        Ovl, MemberLoc, true,
2241                                        LAngleLoc, ExplicitTemplateArgs,
2242                                        NumExplicitTemplateArgs, RAngleLoc,
2243                                        Context.OverloadTy));
2244
2245      return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2246                                   Ovl, MemberLoc, Context.OverloadTy));
2247    }
2248    if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
2249      MarkDeclarationReferenced(MemberLoc, MemberDecl);
2250      return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2251                                   Enum, MemberLoc, Enum->getType()));
2252    }
2253    if (isa<TypeDecl>(MemberDecl))
2254      return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
2255        << MemberName << int(OpKind == tok::arrow));
2256
2257    // We found a declaration kind that we didn't expect. This is a
2258    // generic error message that tells the user that she can't refer
2259    // to this member with '.' or '->'.
2260    return ExprError(Diag(MemberLoc,
2261                          diag::err_typecheck_member_reference_unknown)
2262      << MemberName << int(OpKind == tok::arrow));
2263  }
2264
2265  // Handle pseudo-destructors (C++ [expr.pseudo]). Since anything referring
2266  // into a record type was handled above, any destructor we see here is a
2267  // pseudo-destructor.
2268  if (MemberName.getNameKind() == DeclarationName::CXXDestructorName) {
2269    // C++ [expr.pseudo]p2:
2270    //   The left hand side of the dot operator shall be of scalar type. The
2271    //   left hand side of the arrow operator shall be of pointer to scalar
2272    //   type.
2273    if (!BaseType->isScalarType())
2274      return Owned(Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
2275                     << BaseType << BaseExpr->getSourceRange());
2276
2277    //   [...] The type designated by the pseudo-destructor-name shall be the
2278    //   same as the object type.
2279    if (!MemberName.getCXXNameType()->isDependentType() &&
2280        !Context.hasSameUnqualifiedType(BaseType, MemberName.getCXXNameType()))
2281      return Owned(Diag(OpLoc, diag::err_pseudo_dtor_type_mismatch)
2282                     << BaseType << MemberName.getCXXNameType()
2283                     << BaseExpr->getSourceRange() << SourceRange(MemberLoc));
2284
2285    //   [...] Furthermore, the two type-names in a pseudo-destructor-name of
2286    //   the form
2287    //
2288    //       ::[opt] nested-name-specifier[opt] type-name ::  ̃ type-name
2289    //
2290    //   shall designate the same scalar type.
2291    //
2292    // FIXME: DPG can't see any way to trigger this particular clause, so it
2293    // isn't checked here.
2294
2295    // FIXME: We've lost the precise spelling of the type by going through
2296    // DeclarationName. Can we do better?
2297    return Owned(new (Context) CXXPseudoDestructorExpr(Context, BaseExpr,
2298                                                       OpKind == tok::arrow,
2299                                                       OpLoc,
2300                            (NestedNameSpecifier *)(SS? SS->getScopeRep() : 0),
2301                                            SS? SS->getRange() : SourceRange(),
2302                                                   MemberName.getCXXNameType(),
2303                                                       MemberLoc));
2304  }
2305
2306  // Handle properties on ObjC 'Class' types.
2307  if (OpKind == tok::period && BaseType->isObjCClassType()) {
2308    // Also must look for a getter name which uses property syntax.
2309    IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2310    Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
2311    if (ObjCMethodDecl *MD = getCurMethodDecl()) {
2312      ObjCInterfaceDecl *IFace = MD->getClassInterface();
2313      ObjCMethodDecl *Getter;
2314      // FIXME: need to also look locally in the implementation.
2315      if ((Getter = IFace->lookupClassMethod(Sel))) {
2316        // Check the use of this method.
2317        if (DiagnoseUseOfDecl(Getter, MemberLoc))
2318          return ExprError();
2319      }
2320      // If we found a getter then this may be a valid dot-reference, we
2321      // will look for the matching setter, in case it is needed.
2322      Selector SetterSel =
2323        SelectorTable::constructSetterName(PP.getIdentifierTable(),
2324                                           PP.getSelectorTable(), Member);
2325      ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
2326      if (!Setter) {
2327        // If this reference is in an @implementation, also check for 'private'
2328        // methods.
2329        Setter = FindMethodInNestedImplementations(IFace, SetterSel);
2330      }
2331      // Look through local category implementations associated with the class.
2332      if (!Setter)
2333        Setter = IFace->getCategoryClassMethod(SetterSel);
2334
2335      if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2336        return ExprError();
2337
2338      if (Getter || Setter) {
2339        QualType PType;
2340
2341        if (Getter)
2342          PType = Getter->getResultType();
2343        else
2344          // Get the expression type from Setter's incoming parameter.
2345          PType = (*(Setter->param_end() -1))->getType();
2346        // FIXME: we must check that the setter has property type.
2347        return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
2348                                        Setter, MemberLoc, BaseExpr));
2349      }
2350      return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2351        << MemberName << BaseType);
2352    }
2353  }
2354  // Handle access to Objective-C instance variables, such as "Obj->ivar" and
2355  // (*Obj).ivar.
2356  if ((OpKind == tok::arrow && BaseType->isObjCObjectPointerType()) ||
2357      (OpKind == tok::period && BaseType->isObjCInterfaceType())) {
2358    const ObjCObjectPointerType *OPT = BaseType->getAsObjCObjectPointerType();
2359    const ObjCInterfaceType *IFaceT =
2360      OPT ? OPT->getInterfaceType() : BaseType->getAsObjCInterfaceType();
2361    if (IFaceT) {
2362      IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2363
2364      ObjCInterfaceDecl *IDecl = IFaceT->getDecl();
2365      ObjCInterfaceDecl *ClassDeclared;
2366      ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
2367
2368      if (IV) {
2369        // If the decl being referenced had an error, return an error for this
2370        // sub-expr without emitting another error, in order to avoid cascading
2371        // error cases.
2372        if (IV->isInvalidDecl())
2373          return ExprError();
2374
2375        // Check whether we can reference this field.
2376        if (DiagnoseUseOfDecl(IV, MemberLoc))
2377          return ExprError();
2378        if (IV->getAccessControl() != ObjCIvarDecl::Public &&
2379            IV->getAccessControl() != ObjCIvarDecl::Package) {
2380          ObjCInterfaceDecl *ClassOfMethodDecl = 0;
2381          if (ObjCMethodDecl *MD = getCurMethodDecl())
2382            ClassOfMethodDecl =  MD->getClassInterface();
2383          else if (ObjCImpDecl && getCurFunctionDecl()) {
2384            // Case of a c-function declared inside an objc implementation.
2385            // FIXME: For a c-style function nested inside an objc implementation
2386            // class, there is no implementation context available, so we pass
2387            // down the context as argument to this routine. Ideally, this context
2388            // need be passed down in the AST node and somehow calculated from the
2389            // AST for a function decl.
2390            Decl *ImplDecl = ObjCImpDecl.getAs<Decl>();
2391            if (ObjCImplementationDecl *IMPD =
2392                dyn_cast<ObjCImplementationDecl>(ImplDecl))
2393              ClassOfMethodDecl = IMPD->getClassInterface();
2394            else if (ObjCCategoryImplDecl* CatImplClass =
2395                        dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
2396              ClassOfMethodDecl = CatImplClass->getClassInterface();
2397          }
2398
2399          if (IV->getAccessControl() == ObjCIvarDecl::Private) {
2400            if (ClassDeclared != IDecl ||
2401                ClassOfMethodDecl != ClassDeclared)
2402              Diag(MemberLoc, diag::error_private_ivar_access)
2403                << IV->getDeclName();
2404          } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
2405            // @protected
2406            Diag(MemberLoc, diag::error_protected_ivar_access)
2407              << IV->getDeclName();
2408        }
2409
2410        return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2411                                                   MemberLoc, BaseExpr,
2412                                                   OpKind == tok::arrow));
2413      }
2414      return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
2415                         << IDecl->getDeclName() << MemberName
2416                         << BaseExpr->getSourceRange());
2417    }
2418  }
2419  // Handle properties on 'id' and qualified "id".
2420  if (OpKind == tok::period && (BaseType->isObjCIdType() ||
2421                                BaseType->isObjCQualifiedIdType())) {
2422    const ObjCObjectPointerType *QIdTy = BaseType->getAsObjCObjectPointerType();
2423    IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2424
2425    // Check protocols on qualified interfaces.
2426    Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
2427    if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) {
2428      if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
2429        // Check the use of this declaration
2430        if (DiagnoseUseOfDecl(PD, MemberLoc))
2431          return ExprError();
2432
2433        return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2434                                                       MemberLoc, BaseExpr));
2435      }
2436      if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
2437        // Check the use of this method.
2438        if (DiagnoseUseOfDecl(OMD, MemberLoc))
2439          return ExprError();
2440
2441        return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
2442                                                   OMD->getResultType(),
2443                                                   OMD, OpLoc, MemberLoc,
2444                                                   NULL, 0));
2445      }
2446    }
2447
2448    return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2449                       << MemberName << BaseType);
2450  }
2451  // Handle Objective-C property access, which is "Obj.property" where Obj is a
2452  // pointer to a (potentially qualified) interface type.
2453  const ObjCObjectPointerType *OPT;
2454  if (OpKind == tok::period &&
2455      (OPT = BaseType->getAsObjCInterfacePointerType())) {
2456    const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
2457    ObjCInterfaceDecl *IFace = IFaceT->getDecl();
2458    IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2459
2460    // Search for a declared property first.
2461    if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
2462      // Check whether we can reference this property.
2463      if (DiagnoseUseOfDecl(PD, MemberLoc))
2464        return ExprError();
2465      QualType ResTy = PD->getType();
2466      Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
2467      ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
2468      if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc))
2469        ResTy = Getter->getResultType();
2470      return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
2471                                                     MemberLoc, BaseExpr));
2472    }
2473    // Check protocols on qualified interfaces.
2474    for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2475         E = OPT->qual_end(); I != E; ++I)
2476      if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
2477        // Check whether we can reference this property.
2478        if (DiagnoseUseOfDecl(PD, MemberLoc))
2479          return ExprError();
2480
2481        return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2482                                                       MemberLoc, BaseExpr));
2483      }
2484    for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2485         E = OPT->qual_end(); I != E; ++I)
2486      if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
2487        // Check whether we can reference this property.
2488        if (DiagnoseUseOfDecl(PD, MemberLoc))
2489          return ExprError();
2490
2491        return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2492                                                       MemberLoc, BaseExpr));
2493      }
2494    // If that failed, look for an "implicit" property by seeing if the nullary
2495    // selector is implemented.
2496
2497    // FIXME: The logic for looking up nullary and unary selectors should be
2498    // shared with the code in ActOnInstanceMessage.
2499
2500    Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
2501    ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
2502
2503    // If this reference is in an @implementation, check for 'private' methods.
2504    if (!Getter)
2505      Getter = FindMethodInNestedImplementations(IFace, Sel);
2506
2507    // Look through local category implementations associated with the class.
2508    if (!Getter)
2509      Getter = IFace->getCategoryInstanceMethod(Sel);
2510    if (Getter) {
2511      // Check if we can reference this property.
2512      if (DiagnoseUseOfDecl(Getter, MemberLoc))
2513        return ExprError();
2514    }
2515    // If we found a getter then this may be a valid dot-reference, we
2516    // will look for the matching setter, in case it is needed.
2517    Selector SetterSel =
2518      SelectorTable::constructSetterName(PP.getIdentifierTable(),
2519                                         PP.getSelectorTable(), Member);
2520    ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
2521    if (!Setter) {
2522      // If this reference is in an @implementation, also check for 'private'
2523      // methods.
2524      Setter = FindMethodInNestedImplementations(IFace, SetterSel);
2525    }
2526    // Look through local category implementations associated with the class.
2527    if (!Setter)
2528      Setter = IFace->getCategoryInstanceMethod(SetterSel);
2529
2530    if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2531      return ExprError();
2532
2533    if (Getter || Setter) {
2534      QualType PType;
2535
2536      if (Getter)
2537        PType = Getter->getResultType();
2538      else
2539        // Get the expression type from Setter's incoming parameter.
2540        PType = (*(Setter->param_end() -1))->getType();
2541      // FIXME: we must check that the setter has property type.
2542      return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
2543                                      Setter, MemberLoc, BaseExpr));
2544    }
2545    return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2546      << MemberName << BaseType);
2547  }
2548
2549  // Handle the following exceptional case (*Obj).isa.
2550  if (OpKind == tok::period &&
2551      BaseType->isSpecificBuiltinType(BuiltinType::ObjCId) &&
2552      MemberName.getAsIdentifierInfo()->isStr("isa"))
2553    return Owned(new (Context) ObjCIsaExpr(BaseExpr, false, MemberLoc,
2554                                           Context.getObjCIdType()));
2555
2556  // Handle 'field access' to vectors, such as 'V.xx'.
2557  if (BaseType->isExtVectorType()) {
2558    IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2559    QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
2560    if (ret.isNull())
2561      return ExprError();
2562    return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, *Member,
2563                                                    MemberLoc));
2564  }
2565
2566  Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
2567    << BaseType << BaseExpr->getSourceRange();
2568
2569  // If the user is trying to apply -> or . to a function or function
2570  // pointer, it's probably because they forgot parentheses to call
2571  // the function. Suggest the addition of those parentheses.
2572  if (BaseType == Context.OverloadTy ||
2573      BaseType->isFunctionType() ||
2574      (BaseType->isPointerType() &&
2575       BaseType->getAs<PointerType>()->isFunctionType())) {
2576    SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
2577    Diag(Loc, diag::note_member_reference_needs_call)
2578      << CodeModificationHint::CreateInsertion(Loc, "()");
2579  }
2580
2581  return ExprError();
2582}
2583
2584Action::OwningExprResult
2585Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
2586                               tok::TokenKind OpKind, SourceLocation MemberLoc,
2587                               IdentifierInfo &Member,
2588                               DeclPtrTy ObjCImpDecl, const CXXScopeSpec *SS) {
2589  return BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, MemberLoc,
2590                                  DeclarationName(&Member), ObjCImpDecl, SS);
2591}
2592
2593Sema::OwningExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
2594                                                    FunctionDecl *FD,
2595                                                    ParmVarDecl *Param) {
2596  if (Param->hasUnparsedDefaultArg()) {
2597    Diag (CallLoc,
2598          diag::err_use_of_default_argument_to_function_declared_later) <<
2599      FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
2600    Diag(UnparsedDefaultArgLocs[Param],
2601          diag::note_default_argument_declared_here);
2602  } else {
2603    if (Param->hasUninstantiatedDefaultArg()) {
2604      Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
2605
2606      // Instantiate the expression.
2607      MultiLevelTemplateArgumentList ArgList = getTemplateInstantiationArgs(FD);
2608
2609      InstantiatingTemplate Inst(*this, CallLoc, Param,
2610                                 ArgList.getInnermost().getFlatArgumentList(),
2611                                 ArgList.getInnermost().flat_size());
2612
2613      OwningExprResult Result = SubstExpr(UninstExpr, ArgList);
2614      if (Result.isInvalid())
2615        return ExprError();
2616
2617      if (SetParamDefaultArgument(Param, move(Result),
2618                                  /*FIXME:EqualLoc*/
2619                                  UninstExpr->getSourceRange().getBegin()))
2620        return ExprError();
2621    }
2622
2623    Expr *DefaultExpr = Param->getDefaultArg();
2624
2625    // If the default expression creates temporaries, we need to
2626    // push them to the current stack of expression temporaries so they'll
2627    // be properly destroyed.
2628    if (CXXExprWithTemporaries *E
2629          = dyn_cast_or_null<CXXExprWithTemporaries>(DefaultExpr)) {
2630      assert(!E->shouldDestroyTemporaries() &&
2631             "Can't destroy temporaries in a default argument expr!");
2632      for (unsigned I = 0, N = E->getNumTemporaries(); I != N; ++I)
2633        ExprTemporaries.push_back(E->getTemporary(I));
2634    }
2635  }
2636
2637  // We already type-checked the argument, so we know it works.
2638  return Owned(CXXDefaultArgExpr::Create(Context, Param));
2639}
2640
2641/// ConvertArgumentsForCall - Converts the arguments specified in
2642/// Args/NumArgs to the parameter types of the function FDecl with
2643/// function prototype Proto. Call is the call expression itself, and
2644/// Fn is the function expression. For a C++ member function, this
2645/// routine does not attempt to convert the object argument. Returns
2646/// true if the call is ill-formed.
2647bool
2648Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
2649                              FunctionDecl *FDecl,
2650                              const FunctionProtoType *Proto,
2651                              Expr **Args, unsigned NumArgs,
2652                              SourceLocation RParenLoc) {
2653  // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
2654  // assignment, to the types of the corresponding parameter, ...
2655  unsigned NumArgsInProto = Proto->getNumArgs();
2656  unsigned NumArgsToCheck = NumArgs;
2657  bool Invalid = false;
2658
2659  // If too few arguments are available (and we don't have default
2660  // arguments for the remaining parameters), don't make the call.
2661  if (NumArgs < NumArgsInProto) {
2662    if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
2663      return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
2664        << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
2665    // Use default arguments for missing arguments
2666    NumArgsToCheck = NumArgsInProto;
2667    Call->setNumArgs(Context, NumArgsInProto);
2668  }
2669
2670  // If too many are passed and not variadic, error on the extras and drop
2671  // them.
2672  if (NumArgs > NumArgsInProto) {
2673    if (!Proto->isVariadic()) {
2674      Diag(Args[NumArgsInProto]->getLocStart(),
2675           diag::err_typecheck_call_too_many_args)
2676        << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
2677        << SourceRange(Args[NumArgsInProto]->getLocStart(),
2678                       Args[NumArgs-1]->getLocEnd());
2679      // This deletes the extra arguments.
2680      Call->setNumArgs(Context, NumArgsInProto);
2681      Invalid = true;
2682    }
2683    NumArgsToCheck = NumArgsInProto;
2684  }
2685
2686  // Continue to check argument types (even if we have too few/many args).
2687  for (unsigned i = 0; i != NumArgsToCheck; i++) {
2688    QualType ProtoArgType = Proto->getArgType(i);
2689
2690    Expr *Arg;
2691    if (i < NumArgs) {
2692      Arg = Args[i];
2693
2694      if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2695                              ProtoArgType,
2696                              PDiag(diag::err_call_incomplete_argument)
2697                                << Arg->getSourceRange()))
2698        return true;
2699
2700      // Pass the argument.
2701      if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
2702        return true;
2703    } else {
2704      ParmVarDecl *Param = FDecl->getParamDecl(i);
2705
2706      OwningExprResult ArgExpr =
2707        BuildCXXDefaultArgExpr(Call->getSourceRange().getBegin(),
2708                               FDecl, Param);
2709      if (ArgExpr.isInvalid())
2710        return true;
2711
2712      Arg = ArgExpr.takeAs<Expr>();
2713    }
2714
2715    Call->setArg(i, Arg);
2716  }
2717
2718  // If this is a variadic call, handle args passed through "...".
2719  if (Proto->isVariadic()) {
2720    VariadicCallType CallType = VariadicFunction;
2721    if (Fn->getType()->isBlockPointerType())
2722      CallType = VariadicBlock; // Block
2723    else if (isa<MemberExpr>(Fn))
2724      CallType = VariadicMethod;
2725
2726    // Promote the arguments (C99 6.5.2.2p7).
2727    for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
2728      Expr *Arg = Args[i];
2729      Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType);
2730      Call->setArg(i, Arg);
2731    }
2732  }
2733
2734  return Invalid;
2735}
2736
2737/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
2738/// This provides the location of the left/right parens and a list of comma
2739/// locations.
2740Action::OwningExprResult
2741Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
2742                    MultiExprArg args,
2743                    SourceLocation *CommaLocs, SourceLocation RParenLoc) {
2744  unsigned NumArgs = args.size();
2745
2746  // Since this might be a postfix expression, get rid of ParenListExprs.
2747  fn = MaybeConvertParenListExprToParenExpr(S, move(fn));
2748
2749  Expr *Fn = fn.takeAs<Expr>();
2750  Expr **Args = reinterpret_cast<Expr**>(args.release());
2751  assert(Fn && "no function call expression");
2752  FunctionDecl *FDecl = NULL;
2753  NamedDecl *NDecl = NULL;
2754  DeclarationName UnqualifiedName;
2755
2756  if (getLangOptions().CPlusPlus) {
2757    // If this is a pseudo-destructor expression, build the call immediately.
2758    if (isa<CXXPseudoDestructorExpr>(Fn)) {
2759      if (NumArgs > 0) {
2760        // Pseudo-destructor calls should not have any arguments.
2761        Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
2762          << CodeModificationHint::CreateRemoval(
2763                                    SourceRange(Args[0]->getLocStart(),
2764                                                Args[NumArgs-1]->getLocEnd()));
2765
2766        for (unsigned I = 0; I != NumArgs; ++I)
2767          Args[I]->Destroy(Context);
2768
2769        NumArgs = 0;
2770      }
2771
2772      return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
2773                                          RParenLoc));
2774    }
2775
2776    // Determine whether this is a dependent call inside a C++ template,
2777    // in which case we won't do any semantic analysis now.
2778    // FIXME: Will need to cache the results of name lookup (including ADL) in
2779    // Fn.
2780    bool Dependent = false;
2781    if (Fn->isTypeDependent())
2782      Dependent = true;
2783    else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
2784      Dependent = true;
2785
2786    if (Dependent)
2787      return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
2788                                          Context.DependentTy, RParenLoc));
2789
2790    // Determine whether this is a call to an object (C++ [over.call.object]).
2791    if (Fn->getType()->isRecordType())
2792      return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
2793                                                CommaLocs, RParenLoc));
2794
2795    // Determine whether this is a call to a member function.
2796    if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens())) {
2797      NamedDecl *MemDecl = MemExpr->getMemberDecl();
2798      if (isa<OverloadedFunctionDecl>(MemDecl) ||
2799          isa<CXXMethodDecl>(MemDecl) ||
2800          (isa<FunctionTemplateDecl>(MemDecl) &&
2801           isa<CXXMethodDecl>(
2802                cast<FunctionTemplateDecl>(MemDecl)->getTemplatedDecl())))
2803        return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
2804                                               CommaLocs, RParenLoc));
2805    }
2806  }
2807
2808  // If we're directly calling a function, get the appropriate declaration.
2809  // Also, in C++, keep track of whether we should perform argument-dependent
2810  // lookup and whether there were any explicitly-specified template arguments.
2811  Expr *FnExpr = Fn;
2812  bool ADL = true;
2813  bool HasExplicitTemplateArgs = 0;
2814  const TemplateArgument *ExplicitTemplateArgs = 0;
2815  unsigned NumExplicitTemplateArgs = 0;
2816  while (true) {
2817    if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
2818      FnExpr = IcExpr->getSubExpr();
2819    else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
2820      // Parentheses around a function disable ADL
2821      // (C++0x [basic.lookup.argdep]p1).
2822      ADL = false;
2823      FnExpr = PExpr->getSubExpr();
2824    } else if (isa<UnaryOperator>(FnExpr) &&
2825               cast<UnaryOperator>(FnExpr)->getOpcode()
2826                 == UnaryOperator::AddrOf) {
2827      FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
2828    } else if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(FnExpr)) {
2829      // Qualified names disable ADL (C++0x [basic.lookup.argdep]p1).
2830      ADL &= !isa<QualifiedDeclRefExpr>(DRExpr);
2831      NDecl = dyn_cast<NamedDecl>(DRExpr->getDecl());
2832      break;
2833    } else if (UnresolvedFunctionNameExpr *DepName
2834                 = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr)) {
2835      UnqualifiedName = DepName->getName();
2836      break;
2837    } else if (TemplateIdRefExpr *TemplateIdRef
2838                 = dyn_cast<TemplateIdRefExpr>(FnExpr)) {
2839      NDecl = TemplateIdRef->getTemplateName().getAsTemplateDecl();
2840      if (!NDecl)
2841        NDecl = TemplateIdRef->getTemplateName().getAsOverloadedFunctionDecl();
2842      HasExplicitTemplateArgs = true;
2843      ExplicitTemplateArgs = TemplateIdRef->getTemplateArgs();
2844      NumExplicitTemplateArgs = TemplateIdRef->getNumTemplateArgs();
2845
2846      // C++ [temp.arg.explicit]p6:
2847      //   [Note: For simple function names, argument dependent lookup (3.4.2)
2848      //   applies even when the function name is not visible within the
2849      //   scope of the call. This is because the call still has the syntactic
2850      //   form of a function call (3.4.1). But when a function template with
2851      //   explicit template arguments is used, the call does not have the
2852      //   correct syntactic form unless there is a function template with
2853      //   that name visible at the point of the call. If no such name is
2854      //   visible, the call is not syntactically well-formed and
2855      //   argument-dependent lookup does not apply. If some such name is
2856      //   visible, argument dependent lookup applies and additional function
2857      //   templates may be found in other namespaces.
2858      //
2859      // The summary of this paragraph is that, if we get to this point and the
2860      // template-id was not a qualified name, then argument-dependent lookup
2861      // is still possible.
2862      if (TemplateIdRef->getQualifier())
2863        ADL = false;
2864      break;
2865    } else {
2866      // Any kind of name that does not refer to a declaration (or
2867      // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3).
2868      ADL = false;
2869      break;
2870    }
2871  }
2872
2873  OverloadedFunctionDecl *Ovl = 0;
2874  FunctionTemplateDecl *FunctionTemplate = 0;
2875  if (NDecl) {
2876    FDecl = dyn_cast<FunctionDecl>(NDecl);
2877    if ((FunctionTemplate = dyn_cast<FunctionTemplateDecl>(NDecl)))
2878      FDecl = FunctionTemplate->getTemplatedDecl();
2879    else
2880      FDecl = dyn_cast<FunctionDecl>(NDecl);
2881    Ovl = dyn_cast<OverloadedFunctionDecl>(NDecl);
2882  }
2883
2884  if (Ovl || FunctionTemplate ||
2885      (getLangOptions().CPlusPlus && (FDecl || UnqualifiedName))) {
2886    // We don't perform ADL for implicit declarations of builtins.
2887    if (FDecl && FDecl->getBuiltinID() && FDecl->isImplicit())
2888      ADL = false;
2889
2890    // We don't perform ADL in C.
2891    if (!getLangOptions().CPlusPlus)
2892      ADL = false;
2893
2894    if (Ovl || FunctionTemplate || ADL) {
2895      FDecl = ResolveOverloadedCallFn(Fn, NDecl, UnqualifiedName,
2896                                      HasExplicitTemplateArgs,
2897                                      ExplicitTemplateArgs,
2898                                      NumExplicitTemplateArgs,
2899                                      LParenLoc, Args, NumArgs, CommaLocs,
2900                                      RParenLoc, ADL);
2901      if (!FDecl)
2902        return ExprError();
2903
2904      // Update Fn to refer to the actual function selected.
2905      Expr *NewFn = 0;
2906      if (QualifiedDeclRefExpr *QDRExpr
2907            = dyn_cast<QualifiedDeclRefExpr>(FnExpr))
2908        NewFn = new (Context) QualifiedDeclRefExpr(FDecl, FDecl->getType(),
2909                                                   QDRExpr->getLocation(),
2910                                                   false, false,
2911                                                 QDRExpr->getQualifierRange(),
2912                                                   QDRExpr->getQualifier());
2913      else
2914        NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(),
2915                                          Fn->getSourceRange().getBegin());
2916      Fn->Destroy(Context);
2917      Fn = NewFn;
2918    }
2919  }
2920
2921  // Promote the function operand.
2922  UsualUnaryConversions(Fn);
2923
2924  // Make the call expr early, before semantic checks.  This guarantees cleanup
2925  // of arguments and function on error.
2926  ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
2927                                                               Args, NumArgs,
2928                                                               Context.BoolTy,
2929                                                               RParenLoc));
2930
2931  const FunctionType *FuncT;
2932  if (!Fn->getType()->isBlockPointerType()) {
2933    // C99 6.5.2.2p1 - "The expression that denotes the called function shall
2934    // have type pointer to function".
2935    const PointerType *PT = Fn->getType()->getAs<PointerType>();
2936    if (PT == 0)
2937      return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2938        << Fn->getType() << Fn->getSourceRange());
2939    FuncT = PT->getPointeeType()->getAsFunctionType();
2940  } else { // This is a block call.
2941    FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
2942                getAsFunctionType();
2943  }
2944  if (FuncT == 0)
2945    return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2946      << Fn->getType() << Fn->getSourceRange());
2947
2948  // Check for a valid return type
2949  if (!FuncT->getResultType()->isVoidType() &&
2950      RequireCompleteType(Fn->getSourceRange().getBegin(),
2951                          FuncT->getResultType(),
2952                          PDiag(diag::err_call_incomplete_return)
2953                            << TheCall->getSourceRange()))
2954    return ExprError();
2955
2956  // We know the result type of the call, set it.
2957  TheCall->setType(FuncT->getResultType().getNonReferenceType());
2958
2959  if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
2960    if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
2961                                RParenLoc))
2962      return ExprError();
2963  } else {
2964    assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
2965
2966    if (FDecl) {
2967      // Check if we have too few/too many template arguments, based
2968      // on our knowledge of the function definition.
2969      const FunctionDecl *Def = 0;
2970      if (FDecl->getBody(Def) && NumArgs != Def->param_size()) {
2971        const FunctionProtoType *Proto =
2972            Def->getType()->getAsFunctionProtoType();
2973        if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) {
2974          Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
2975            << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
2976        }
2977      }
2978    }
2979
2980    // Promote the arguments (C99 6.5.2.2p6).
2981    for (unsigned i = 0; i != NumArgs; i++) {
2982      Expr *Arg = Args[i];
2983      DefaultArgumentPromotion(Arg);
2984      if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2985                              Arg->getType(),
2986                              PDiag(diag::err_call_incomplete_argument)
2987                                << Arg->getSourceRange()))
2988        return ExprError();
2989      TheCall->setArg(i, Arg);
2990    }
2991  }
2992
2993  if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
2994    if (!Method->isStatic())
2995      return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
2996        << Fn->getSourceRange());
2997
2998  // Check for sentinels
2999  if (NDecl)
3000    DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
3001
3002  // Do special checking on direct calls to functions.
3003  if (FDecl) {
3004    if (CheckFunctionCall(FDecl, TheCall.get()))
3005      return ExprError();
3006
3007    if (unsigned BuiltinID = FDecl->getBuiltinID())
3008      return CheckBuiltinFunctionCall(BuiltinID, TheCall.take());
3009  } else if (NDecl) {
3010    if (CheckBlockCall(NDecl, TheCall.get()))
3011      return ExprError();
3012  }
3013
3014  return MaybeBindToTemporary(TheCall.take());
3015}
3016
3017Action::OwningExprResult
3018Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
3019                           SourceLocation RParenLoc, ExprArg InitExpr) {
3020  assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
3021  //FIXME: Preserve type source info.
3022  QualType literalType = GetTypeFromParser(Ty);
3023  // FIXME: put back this assert when initializers are worked out.
3024  //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
3025  Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
3026
3027  if (literalType->isArrayType()) {
3028    if (literalType->isVariableArrayType())
3029      return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
3030        << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
3031  } else if (!literalType->isDependentType() &&
3032             RequireCompleteType(LParenLoc, literalType,
3033                      PDiag(diag::err_typecheck_decl_incomplete_type)
3034                        << SourceRange(LParenLoc,
3035                                       literalExpr->getSourceRange().getEnd())))
3036    return ExprError();
3037
3038  if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
3039                            DeclarationName(), /*FIXME:DirectInit=*/false))
3040    return ExprError();
3041
3042  bool isFileScope = getCurFunctionOrMethodDecl() == 0;
3043  if (isFileScope) { // 6.5.2.5p3
3044    if (CheckForConstantInitializer(literalExpr, literalType))
3045      return ExprError();
3046  }
3047  InitExpr.release();
3048  return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
3049                                                 literalExpr, isFileScope));
3050}
3051
3052Action::OwningExprResult
3053Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
3054                    SourceLocation RBraceLoc) {
3055  unsigned NumInit = initlist.size();
3056  Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
3057
3058  // Semantic analysis for initializers is done by ActOnDeclarator() and
3059  // CheckInitializer() - it requires knowledge of the object being intialized.
3060
3061  InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
3062                                               RBraceLoc);
3063  E->setType(Context.VoidTy); // FIXME: just a place holder for now.
3064  return Owned(E);
3065}
3066
3067/// CheckCastTypes - Check type constraints for casting between types.
3068bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr,
3069                          CastExpr::CastKind& Kind,
3070                          CXXMethodDecl *& ConversionDecl,
3071                          bool FunctionalStyle) {
3072  if (getLangOptions().CPlusPlus)
3073    return CXXCheckCStyleCast(TyR, castType, castExpr, Kind, FunctionalStyle,
3074                              ConversionDecl);
3075
3076  DefaultFunctionArrayConversion(castExpr);
3077
3078  // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
3079  // type needs to be scalar.
3080  if (castType->isVoidType()) {
3081    // Cast to void allows any expr type.
3082  } else if (!castType->isScalarType() && !castType->isVectorType()) {
3083    if (Context.getCanonicalType(castType).getUnqualifiedType() ==
3084        Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
3085        (castType->isStructureType() || castType->isUnionType())) {
3086      // GCC struct/union extension: allow cast to self.
3087      // FIXME: Check that the cast destination type is complete.
3088      Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
3089        << castType << castExpr->getSourceRange();
3090      Kind = CastExpr::CK_NoOp;
3091    } else if (castType->isUnionType()) {
3092      // GCC cast to union extension
3093      RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
3094      RecordDecl::field_iterator Field, FieldEnd;
3095      for (Field = RD->field_begin(), FieldEnd = RD->field_end();
3096           Field != FieldEnd; ++Field) {
3097        if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
3098            Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
3099          Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
3100            << castExpr->getSourceRange();
3101          break;
3102        }
3103      }
3104      if (Field == FieldEnd)
3105        return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
3106          << castExpr->getType() << castExpr->getSourceRange();
3107      Kind = CastExpr::CK_ToUnion;
3108    } else {
3109      // Reject any other conversions to non-scalar types.
3110      return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
3111        << castType << castExpr->getSourceRange();
3112    }
3113  } else if (!castExpr->getType()->isScalarType() &&
3114             !castExpr->getType()->isVectorType()) {
3115    return Diag(castExpr->getLocStart(),
3116                diag::err_typecheck_expect_scalar_operand)
3117      << castExpr->getType() << castExpr->getSourceRange();
3118  } else if (castType->isExtVectorType()) {
3119    if (CheckExtVectorCast(TyR, castType, castExpr->getType()))
3120      return true;
3121  } else if (castType->isVectorType()) {
3122    if (CheckVectorCast(TyR, castType, castExpr->getType()))
3123      return true;
3124  } else if (castExpr->getType()->isVectorType()) {
3125    if (CheckVectorCast(TyR, castExpr->getType(), castType))
3126      return true;
3127  } else if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr)) {
3128    return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR;
3129  } else if (!castType->isArithmeticType()) {
3130    QualType castExprType = castExpr->getType();
3131    if (!castExprType->isIntegralType() && castExprType->isArithmeticType())
3132      return Diag(castExpr->getLocStart(),
3133                  diag::err_cast_pointer_from_non_pointer_int)
3134        << castExprType << castExpr->getSourceRange();
3135  } else if (!castExpr->getType()->isArithmeticType()) {
3136    if (!castType->isIntegralType() && castType->isArithmeticType())
3137      return Diag(castExpr->getLocStart(),
3138                  diag::err_cast_pointer_to_non_pointer_int)
3139        << castType << castExpr->getSourceRange();
3140  }
3141  if (isa<ObjCSelectorExpr>(castExpr))
3142    return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
3143  return false;
3144}
3145
3146bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
3147  assert(VectorTy->isVectorType() && "Not a vector type!");
3148
3149  if (Ty->isVectorType() || Ty->isIntegerType()) {
3150    if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
3151      return Diag(R.getBegin(),
3152                  Ty->isVectorType() ?
3153                  diag::err_invalid_conversion_between_vectors :
3154                  diag::err_invalid_conversion_between_vector_and_integer)
3155        << VectorTy << Ty << R;
3156  } else
3157    return Diag(R.getBegin(),
3158                diag::err_invalid_conversion_between_vector_and_scalar)
3159      << VectorTy << Ty << R;
3160
3161  return false;
3162}
3163
3164bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, QualType SrcTy) {
3165  assert(DestTy->isExtVectorType() && "Not an extended vector type!");
3166
3167  // If SrcTy is a VectorType, the total size must match to explicitly cast to
3168  // an ExtVectorType.
3169  if (SrcTy->isVectorType()) {
3170    if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
3171      return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
3172        << DestTy << SrcTy << R;
3173    return false;
3174  }
3175
3176  // All non-pointer scalars can be cast to ExtVector type.  The appropriate
3177  // conversion will take place first from scalar to elt type, and then
3178  // splat from elt type to vector.
3179  if (SrcTy->isPointerType())
3180    return Diag(R.getBegin(),
3181                diag::err_invalid_conversion_between_vector_and_scalar)
3182      << DestTy << SrcTy << R;
3183  return false;
3184}
3185
3186Action::OwningExprResult
3187Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, TypeTy *Ty,
3188                    SourceLocation RParenLoc, ExprArg Op) {
3189  CastExpr::CastKind Kind = CastExpr::CK_Unknown;
3190
3191  assert((Ty != 0) && (Op.get() != 0) &&
3192         "ActOnCastExpr(): missing type or expr");
3193
3194  Expr *castExpr = (Expr *)Op.get();
3195  //FIXME: Preserve type source info.
3196  QualType castType = GetTypeFromParser(Ty);
3197
3198  // If the Expr being casted is a ParenListExpr, handle it specially.
3199  if (isa<ParenListExpr>(castExpr))
3200    return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, move(Op),castType);
3201  CXXMethodDecl *Method = 0;
3202  if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr,
3203                     Kind, Method))
3204    return ExprError();
3205
3206  if (Method) {
3207    OwningExprResult CastArg = BuildCXXCastArgument(LParenLoc, castType, Kind,
3208                                                    Method, move(Op));
3209
3210    if (CastArg.isInvalid())
3211      return ExprError();
3212
3213    castExpr = CastArg.takeAs<Expr>();
3214  } else {
3215    Op.release();
3216  }
3217
3218  return Owned(new (Context) CStyleCastExpr(castType.getNonReferenceType(),
3219                                            Kind, castExpr, castType,
3220                                            LParenLoc, RParenLoc));
3221}
3222
3223/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
3224/// of comma binary operators.
3225Action::OwningExprResult
3226Sema::MaybeConvertParenListExprToParenExpr(Scope *S, ExprArg EA) {
3227  Expr *expr = EA.takeAs<Expr>();
3228  ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
3229  if (!E)
3230    return Owned(expr);
3231
3232  OwningExprResult Result(*this, E->getExpr(0));
3233
3234  for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
3235    Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, move(Result),
3236                        Owned(E->getExpr(i)));
3237
3238  return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), move(Result));
3239}
3240
3241Action::OwningExprResult
3242Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
3243                               SourceLocation RParenLoc, ExprArg Op,
3244                               QualType Ty) {
3245  ParenListExpr *PE = (ParenListExpr *)Op.get();
3246
3247  // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
3248  // then handle it as such.
3249  if (getLangOptions().AltiVec && Ty->isVectorType()) {
3250    if (PE->getNumExprs() == 0) {
3251      Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
3252      return ExprError();
3253    }
3254
3255    llvm::SmallVector<Expr *, 8> initExprs;
3256    for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
3257      initExprs.push_back(PE->getExpr(i));
3258
3259    // FIXME: This means that pretty-printing the final AST will produce curly
3260    // braces instead of the original commas.
3261    Op.release();
3262    InitListExpr *E = new (Context) InitListExpr(LParenLoc, &initExprs[0],
3263                                                 initExprs.size(), RParenLoc);
3264    E->setType(Ty);
3265    return ActOnCompoundLiteral(LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,
3266                                Owned(E));
3267  } else {
3268    // This is not an AltiVec-style cast, so turn the ParenListExpr into a
3269    // sequence of BinOp comma operators.
3270    Op = MaybeConvertParenListExprToParenExpr(S, move(Op));
3271    return ActOnCastExpr(S, LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,move(Op));
3272  }
3273}
3274
3275Action::OwningExprResult Sema::ActOnParenListExpr(SourceLocation L,
3276                                                  SourceLocation R,
3277                                                  MultiExprArg Val) {
3278  unsigned nexprs = Val.size();
3279  Expr **exprs = reinterpret_cast<Expr**>(Val.release());
3280  assert((exprs != 0) && "ActOnParenListExpr() missing expr list");
3281  Expr *expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
3282  return Owned(expr);
3283}
3284
3285/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
3286/// In that case, lhs = cond.
3287/// C99 6.5.15
3288QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
3289                                        SourceLocation QuestionLoc) {
3290  // C++ is sufficiently different to merit its own checker.
3291  if (getLangOptions().CPlusPlus)
3292    return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc);
3293
3294  UsualUnaryConversions(Cond);
3295  UsualUnaryConversions(LHS);
3296  UsualUnaryConversions(RHS);
3297  QualType CondTy = Cond->getType();
3298  QualType LHSTy = LHS->getType();
3299  QualType RHSTy = RHS->getType();
3300
3301  // first, check the condition.
3302  if (!CondTy->isScalarType()) { // C99 6.5.15p2
3303    Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
3304      << CondTy;
3305    return QualType();
3306  }
3307
3308  // Now check the two expressions.
3309  if (LHSTy->isVectorType() || RHSTy->isVectorType())
3310    return CheckVectorOperands(QuestionLoc, LHS, RHS);
3311
3312  // If both operands have arithmetic type, do the usual arithmetic conversions
3313  // to find a common type: C99 6.5.15p3,5.
3314  if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
3315    UsualArithmeticConversions(LHS, RHS);
3316    return LHS->getType();
3317  }
3318
3319  // If both operands are the same structure or union type, the result is that
3320  // type.
3321  if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
3322    if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
3323      if (LHSRT->getDecl() == RHSRT->getDecl())
3324        // "If both the operands have structure or union type, the result has
3325        // that type."  This implies that CV qualifiers are dropped.
3326        return LHSTy.getUnqualifiedType();
3327    // FIXME: Type of conditional expression must be complete in C mode.
3328  }
3329
3330  // C99 6.5.15p5: "If both operands have void type, the result has void type."
3331  // The following || allows only one side to be void (a GCC-ism).
3332  if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
3333    if (!LHSTy->isVoidType())
3334      Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3335        << RHS->getSourceRange();
3336    if (!RHSTy->isVoidType())
3337      Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3338        << LHS->getSourceRange();
3339    ImpCastExprToType(LHS, Context.VoidTy);
3340    ImpCastExprToType(RHS, Context.VoidTy);
3341    return Context.VoidTy;
3342  }
3343  // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
3344  // the type of the other operand."
3345  if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
3346      RHS->isNullPointerConstant(Context)) {
3347    ImpCastExprToType(RHS, LHSTy); // promote the null to a pointer.
3348    return LHSTy;
3349  }
3350  if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
3351      LHS->isNullPointerConstant(Context)) {
3352    ImpCastExprToType(LHS, RHSTy); // promote the null to a pointer.
3353    return RHSTy;
3354  }
3355  // Handle things like Class and struct objc_class*.  Here we case the result
3356  // to the pseudo-builtin, because that will be implicitly cast back to the
3357  // redefinition type if an attempt is made to access its fields.
3358  if (LHSTy->isObjCClassType() &&
3359      (RHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
3360    ImpCastExprToType(RHS, LHSTy);
3361    return LHSTy;
3362  }
3363  if (RHSTy->isObjCClassType() &&
3364      (LHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
3365    ImpCastExprToType(LHS, RHSTy);
3366    return RHSTy;
3367  }
3368  // And the same for struct objc_object* / id
3369  if (LHSTy->isObjCIdType() &&
3370      (RHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
3371    ImpCastExprToType(RHS, LHSTy);
3372    return LHSTy;
3373  }
3374  if (RHSTy->isObjCIdType() &&
3375      (LHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
3376    ImpCastExprToType(LHS, RHSTy);
3377    return RHSTy;
3378  }
3379  // Handle block pointer types.
3380  if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
3381    if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
3382      if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
3383        QualType destType = Context.getPointerType(Context.VoidTy);
3384        ImpCastExprToType(LHS, destType);
3385        ImpCastExprToType(RHS, destType);
3386        return destType;
3387      }
3388      Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3389            << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3390      return QualType();
3391    }
3392    // We have 2 block pointer types.
3393    if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3394      // Two identical block pointer types are always compatible.
3395      return LHSTy;
3396    }
3397    // The block pointer types aren't identical, continue checking.
3398    QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
3399    QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
3400
3401    if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3402                                    rhptee.getUnqualifiedType())) {
3403      Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3404        << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3405      // In this situation, we assume void* type. No especially good
3406      // reason, but this is what gcc does, and we do have to pick
3407      // to get a consistent AST.
3408      QualType incompatTy = Context.getPointerType(Context.VoidTy);
3409      ImpCastExprToType(LHS, incompatTy);
3410      ImpCastExprToType(RHS, incompatTy);
3411      return incompatTy;
3412    }
3413    // The block pointer types are compatible.
3414    ImpCastExprToType(LHS, LHSTy);
3415    ImpCastExprToType(RHS, LHSTy);
3416    return LHSTy;
3417  }
3418  // Check constraints for Objective-C object pointers types.
3419  if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
3420
3421    if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3422      // Two identical object pointer types are always compatible.
3423      return LHSTy;
3424    }
3425    const ObjCObjectPointerType *LHSOPT = LHSTy->getAsObjCObjectPointerType();
3426    const ObjCObjectPointerType *RHSOPT = RHSTy->getAsObjCObjectPointerType();
3427    QualType compositeType = LHSTy;
3428
3429    // If both operands are interfaces and either operand can be
3430    // assigned to the other, use that type as the composite
3431    // type. This allows
3432    //   xxx ? (A*) a : (B*) b
3433    // where B is a subclass of A.
3434    //
3435    // Additionally, as for assignment, if either type is 'id'
3436    // allow silent coercion. Finally, if the types are
3437    // incompatible then make sure to use 'id' as the composite
3438    // type so the result is acceptable for sending messages to.
3439
3440    // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
3441    // It could return the composite type.
3442    if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
3443      compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
3444    } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
3445      compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
3446    } else if ((LHSTy->isObjCQualifiedIdType() ||
3447                RHSTy->isObjCQualifiedIdType()) &&
3448                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
3449      // Need to handle "id<xx>" explicitly.
3450      // GCC allows qualified id and any Objective-C type to devolve to
3451      // id. Currently localizing to here until clear this should be
3452      // part of ObjCQualifiedIdTypesAreCompatible.
3453      compositeType = Context.getObjCIdType();
3454    } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
3455      compositeType = Context.getObjCIdType();
3456    } else {
3457      Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
3458        << LHSTy << RHSTy
3459        << LHS->getSourceRange() << RHS->getSourceRange();
3460      QualType incompatTy = Context.getObjCIdType();
3461      ImpCastExprToType(LHS, incompatTy);
3462      ImpCastExprToType(RHS, incompatTy);
3463      return incompatTy;
3464    }
3465    // The object pointer types are compatible.
3466    ImpCastExprToType(LHS, compositeType);
3467    ImpCastExprToType(RHS, compositeType);
3468    return compositeType;
3469  }
3470  // Check Objective-C object pointer types and 'void *'
3471  if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
3472    QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
3473    QualType rhptee = RHSTy->getAsObjCObjectPointerType()->getPointeeType();
3474    QualType destPointee = lhptee.getQualifiedType(rhptee.getCVRQualifiers());
3475    QualType destType = Context.getPointerType(destPointee);
3476    ImpCastExprToType(LHS, destType); // add qualifiers if necessary
3477    ImpCastExprToType(RHS, destType); // promote to void*
3478    return destType;
3479  }
3480  if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
3481    QualType lhptee = LHSTy->getAsObjCObjectPointerType()->getPointeeType();
3482    QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
3483    QualType destPointee = rhptee.getQualifiedType(lhptee.getCVRQualifiers());
3484    QualType destType = Context.getPointerType(destPointee);
3485    ImpCastExprToType(RHS, destType); // add qualifiers if necessary
3486    ImpCastExprToType(LHS, destType); // promote to void*
3487    return destType;
3488  }
3489  // Check constraints for C object pointers types (C99 6.5.15p3,6).
3490  if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
3491    // get the "pointed to" types
3492    QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
3493    QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
3494
3495    // ignore qualifiers on void (C99 6.5.15p3, clause 6)
3496    if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
3497      // Figure out necessary qualifiers (C99 6.5.15p6)
3498      QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
3499      QualType destType = Context.getPointerType(destPointee);
3500      ImpCastExprToType(LHS, destType); // add qualifiers if necessary
3501      ImpCastExprToType(RHS, destType); // promote to void*
3502      return destType;
3503    }
3504    if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
3505      QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
3506      QualType destType = Context.getPointerType(destPointee);
3507      ImpCastExprToType(LHS, destType); // add qualifiers if necessary
3508      ImpCastExprToType(RHS, destType); // promote to void*
3509      return destType;
3510    }
3511
3512    if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3513      // Two identical pointer types are always compatible.
3514      return LHSTy;
3515    }
3516    if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3517                                    rhptee.getUnqualifiedType())) {
3518      Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3519        << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3520      // In this situation, we assume void* type. No especially good
3521      // reason, but this is what gcc does, and we do have to pick
3522      // to get a consistent AST.
3523      QualType incompatTy = Context.getPointerType(Context.VoidTy);
3524      ImpCastExprToType(LHS, incompatTy);
3525      ImpCastExprToType(RHS, incompatTy);
3526      return incompatTy;
3527    }
3528    // The pointer types are compatible.
3529    // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
3530    // differently qualified versions of compatible types, the result type is
3531    // a pointer to an appropriately qualified version of the *composite*
3532    // type.
3533    // FIXME: Need to calculate the composite type.
3534    // FIXME: Need to add qualifiers
3535    ImpCastExprToType(LHS, LHSTy);
3536    ImpCastExprToType(RHS, LHSTy);
3537    return LHSTy;
3538  }
3539
3540  // GCC compatibility: soften pointer/integer mismatch.
3541  if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
3542    Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3543      << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3544    ImpCastExprToType(LHS, RHSTy); // promote the integer to a pointer.
3545    return RHSTy;
3546  }
3547  if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
3548    Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3549      << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3550    ImpCastExprToType(RHS, LHSTy); // promote the integer to a pointer.
3551    return LHSTy;
3552  }
3553
3554  // Otherwise, the operands are not compatible.
3555  Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3556    << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3557  return QualType();
3558}
3559
3560/// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
3561/// in the case of a the GNU conditional expr extension.
3562Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
3563                                                  SourceLocation ColonLoc,
3564                                                  ExprArg Cond, ExprArg LHS,
3565                                                  ExprArg RHS) {
3566  Expr *CondExpr = (Expr *) Cond.get();
3567  Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
3568
3569  // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
3570  // was the condition.
3571  bool isLHSNull = LHSExpr == 0;
3572  if (isLHSNull)
3573    LHSExpr = CondExpr;
3574
3575  QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
3576                                             RHSExpr, QuestionLoc);
3577  if (result.isNull())
3578    return ExprError();
3579
3580  Cond.release();
3581  LHS.release();
3582  RHS.release();
3583  return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
3584                                                 isLHSNull ? 0 : LHSExpr,
3585                                                 ColonLoc, RHSExpr, result));
3586}
3587
3588// CheckPointerTypesForAssignment - This is a very tricky routine (despite
3589// being closely modeled after the C99 spec:-). The odd characteristic of this
3590// routine is it effectively iqnores the qualifiers on the top level pointee.
3591// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
3592// FIXME: add a couple examples in this comment.
3593Sema::AssignConvertType
3594Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
3595  QualType lhptee, rhptee;
3596
3597  if ((lhsType->isObjCClassType() &&
3598       (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
3599     (rhsType->isObjCClassType() &&
3600       (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
3601      return Compatible;
3602  }
3603
3604  // get the "pointed to" type (ignoring qualifiers at the top level)
3605  lhptee = lhsType->getAs<PointerType>()->getPointeeType();
3606  rhptee = rhsType->getAs<PointerType>()->getPointeeType();
3607
3608  // make sure we operate on the canonical type
3609  lhptee = Context.getCanonicalType(lhptee);
3610  rhptee = Context.getCanonicalType(rhptee);
3611
3612  AssignConvertType ConvTy = Compatible;
3613
3614  // C99 6.5.16.1p1: This following citation is common to constraints
3615  // 3 & 4 (below). ...and the type *pointed to* by the left has all the
3616  // qualifiers of the type *pointed to* by the right;
3617  // FIXME: Handle ExtQualType
3618  if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
3619    ConvTy = CompatiblePointerDiscardsQualifiers;
3620
3621  // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
3622  // incomplete type and the other is a pointer to a qualified or unqualified
3623  // version of void...
3624  if (lhptee->isVoidType()) {
3625    if (rhptee->isIncompleteOrObjectType())
3626      return ConvTy;
3627
3628    // As an extension, we allow cast to/from void* to function pointer.
3629    assert(rhptee->isFunctionType());
3630    return FunctionVoidPointer;
3631  }
3632
3633  if (rhptee->isVoidType()) {
3634    if (lhptee->isIncompleteOrObjectType())
3635      return ConvTy;
3636
3637    // As an extension, we allow cast to/from void* to function pointer.
3638    assert(lhptee->isFunctionType());
3639    return FunctionVoidPointer;
3640  }
3641  // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
3642  // unqualified versions of compatible types, ...
3643  lhptee = lhptee.getUnqualifiedType();
3644  rhptee = rhptee.getUnqualifiedType();
3645  if (!Context.typesAreCompatible(lhptee, rhptee)) {
3646    // Check if the pointee types are compatible ignoring the sign.
3647    // We explicitly check for char so that we catch "char" vs
3648    // "unsigned char" on systems where "char" is unsigned.
3649    if (lhptee->isCharType()) {
3650      lhptee = Context.UnsignedCharTy;
3651    } else if (lhptee->isSignedIntegerType()) {
3652      lhptee = Context.getCorrespondingUnsignedType(lhptee);
3653    }
3654    if (rhptee->isCharType()) {
3655      rhptee = Context.UnsignedCharTy;
3656    } else if (rhptee->isSignedIntegerType()) {
3657      rhptee = Context.getCorrespondingUnsignedType(rhptee);
3658    }
3659    if (lhptee == rhptee) {
3660      // Types are compatible ignoring the sign. Qualifier incompatibility
3661      // takes priority over sign incompatibility because the sign
3662      // warning can be disabled.
3663      if (ConvTy != Compatible)
3664        return ConvTy;
3665      return IncompatiblePointerSign;
3666    }
3667    // General pointer incompatibility takes priority over qualifiers.
3668    return IncompatiblePointer;
3669  }
3670  return ConvTy;
3671}
3672
3673/// CheckBlockPointerTypesForAssignment - This routine determines whether two
3674/// block pointer types are compatible or whether a block and normal pointer
3675/// are compatible. It is more restrict than comparing two function pointer
3676// types.
3677Sema::AssignConvertType
3678Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
3679                                          QualType rhsType) {
3680  QualType lhptee, rhptee;
3681
3682  // get the "pointed to" type (ignoring qualifiers at the top level)
3683  lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType();
3684  rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType();
3685
3686  // make sure we operate on the canonical type
3687  lhptee = Context.getCanonicalType(lhptee);
3688  rhptee = Context.getCanonicalType(rhptee);
3689
3690  AssignConvertType ConvTy = Compatible;
3691
3692  // For blocks we enforce that qualifiers are identical.
3693  if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
3694    ConvTy = CompatiblePointerDiscardsQualifiers;
3695
3696  if (!Context.typesAreCompatible(lhptee, rhptee))
3697    return IncompatibleBlockPointer;
3698  return ConvTy;
3699}
3700
3701/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
3702/// has code to accommodate several GCC extensions when type checking
3703/// pointers. Here are some objectionable examples that GCC considers warnings:
3704///
3705///  int a, *pint;
3706///  short *pshort;
3707///  struct foo *pfoo;
3708///
3709///  pint = pshort; // warning: assignment from incompatible pointer type
3710///  a = pint; // warning: assignment makes integer from pointer without a cast
3711///  pint = a; // warning: assignment makes pointer from integer without a cast
3712///  pint = pfoo; // warning: assignment from incompatible pointer type
3713///
3714/// As a result, the code for dealing with pointers is more complex than the
3715/// C99 spec dictates.
3716///
3717Sema::AssignConvertType
3718Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
3719  // Get canonical types.  We're not formatting these types, just comparing
3720  // them.
3721  lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
3722  rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
3723
3724  if (lhsType == rhsType)
3725    return Compatible; // Common case: fast path an exact match.
3726
3727  if ((lhsType->isObjCClassType() &&
3728       (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
3729     (rhsType->isObjCClassType() &&
3730       (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
3731      return Compatible;
3732  }
3733
3734  // If the left-hand side is a reference type, then we are in a
3735  // (rare!) case where we've allowed the use of references in C,
3736  // e.g., as a parameter type in a built-in function. In this case,
3737  // just make sure that the type referenced is compatible with the
3738  // right-hand side type. The caller is responsible for adjusting
3739  // lhsType so that the resulting expression does not have reference
3740  // type.
3741  if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
3742    if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
3743      return Compatible;
3744    return Incompatible;
3745  }
3746  // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
3747  // to the same ExtVector type.
3748  if (lhsType->isExtVectorType()) {
3749    if (rhsType->isExtVectorType())
3750      return lhsType == rhsType ? Compatible : Incompatible;
3751    if (!rhsType->isVectorType() && rhsType->isArithmeticType())
3752      return Compatible;
3753  }
3754
3755  if (lhsType->isVectorType() || rhsType->isVectorType()) {
3756    // If we are allowing lax vector conversions, and LHS and RHS are both
3757    // vectors, the total size only needs to be the same. This is a bitcast;
3758    // no bits are changed but the result type is different.
3759    if (getLangOptions().LaxVectorConversions &&
3760        lhsType->isVectorType() && rhsType->isVectorType()) {
3761      if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
3762        return IncompatibleVectors;
3763    }
3764    return Incompatible;
3765  }
3766
3767  if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
3768    return Compatible;
3769
3770  if (isa<PointerType>(lhsType)) {
3771    if (rhsType->isIntegerType())
3772      return IntToPointer;
3773
3774    if (isa<PointerType>(rhsType))
3775      return CheckPointerTypesForAssignment(lhsType, rhsType);
3776
3777    // In general, C pointers are not compatible with ObjC object pointers.
3778    if (isa<ObjCObjectPointerType>(rhsType)) {
3779      if (lhsType->isVoidPointerType()) // an exception to the rule.
3780        return Compatible;
3781      return IncompatiblePointer;
3782    }
3783    if (rhsType->getAs<BlockPointerType>()) {
3784      if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
3785        return Compatible;
3786
3787      // Treat block pointers as objects.
3788      if (getLangOptions().ObjC1 && lhsType->isObjCIdType())
3789        return Compatible;
3790    }
3791    return Incompatible;
3792  }
3793
3794  if (isa<BlockPointerType>(lhsType)) {
3795    if (rhsType->isIntegerType())
3796      return IntToBlockPointer;
3797
3798    // Treat block pointers as objects.
3799    if (getLangOptions().ObjC1 && rhsType->isObjCIdType())
3800      return Compatible;
3801
3802    if (rhsType->isBlockPointerType())
3803      return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
3804
3805    if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
3806      if (RHSPT->getPointeeType()->isVoidType())
3807        return Compatible;
3808    }
3809    return Incompatible;
3810  }
3811
3812  if (isa<ObjCObjectPointerType>(lhsType)) {
3813    if (rhsType->isIntegerType())
3814      return IntToPointer;
3815
3816    // In general, C pointers are not compatible with ObjC object pointers.
3817    if (isa<PointerType>(rhsType)) {
3818      if (rhsType->isVoidPointerType()) // an exception to the rule.
3819        return Compatible;
3820      return IncompatiblePointer;
3821    }
3822    if (rhsType->isObjCObjectPointerType()) {
3823      if (lhsType->isObjCBuiltinType() || rhsType->isObjCBuiltinType())
3824        return Compatible;
3825      if (Context.typesAreCompatible(lhsType, rhsType))
3826        return Compatible;
3827      if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
3828        return IncompatibleObjCQualifiedId;
3829      return IncompatiblePointer;
3830    }
3831    if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
3832      if (RHSPT->getPointeeType()->isVoidType())
3833        return Compatible;
3834    }
3835    // Treat block pointers as objects.
3836    if (rhsType->isBlockPointerType())
3837      return Compatible;
3838    return Incompatible;
3839  }
3840  if (isa<PointerType>(rhsType)) {
3841    // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
3842    if (lhsType == Context.BoolTy)
3843      return Compatible;
3844
3845    if (lhsType->isIntegerType())
3846      return PointerToInt;
3847
3848    if (isa<PointerType>(lhsType))
3849      return CheckPointerTypesForAssignment(lhsType, rhsType);
3850
3851    if (isa<BlockPointerType>(lhsType) &&
3852        rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
3853      return Compatible;
3854    return Incompatible;
3855  }
3856  if (isa<ObjCObjectPointerType>(rhsType)) {
3857    // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
3858    if (lhsType == Context.BoolTy)
3859      return Compatible;
3860
3861    if (lhsType->isIntegerType())
3862      return PointerToInt;
3863
3864    // In general, C pointers are not compatible with ObjC object pointers.
3865    if (isa<PointerType>(lhsType)) {
3866      if (lhsType->isVoidPointerType()) // an exception to the rule.
3867        return Compatible;
3868      return IncompatiblePointer;
3869    }
3870    if (isa<BlockPointerType>(lhsType) &&
3871        rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
3872      return Compatible;
3873    return Incompatible;
3874  }
3875
3876  if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
3877    if (Context.typesAreCompatible(lhsType, rhsType))
3878      return Compatible;
3879  }
3880  return Incompatible;
3881}
3882
3883/// \brief Constructs a transparent union from an expression that is
3884/// used to initialize the transparent union.
3885static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
3886                                      QualType UnionType, FieldDecl *Field) {
3887  // Build an initializer list that designates the appropriate member
3888  // of the transparent union.
3889  InitListExpr *Initializer = new (C) InitListExpr(SourceLocation(),
3890                                                   &E, 1,
3891                                                   SourceLocation());
3892  Initializer->setType(UnionType);
3893  Initializer->setInitializedFieldInUnion(Field);
3894
3895  // Build a compound literal constructing a value of the transparent
3896  // union type from this initializer list.
3897  E = new (C) CompoundLiteralExpr(SourceLocation(), UnionType, Initializer,
3898                                  false);
3899}
3900
3901Sema::AssignConvertType
3902Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
3903  QualType FromType = rExpr->getType();
3904
3905  // If the ArgType is a Union type, we want to handle a potential
3906  // transparent_union GCC extension.
3907  const RecordType *UT = ArgType->getAsUnionType();
3908  if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
3909    return Incompatible;
3910
3911  // The field to initialize within the transparent union.
3912  RecordDecl *UD = UT->getDecl();
3913  FieldDecl *InitField = 0;
3914  // It's compatible if the expression matches any of the fields.
3915  for (RecordDecl::field_iterator it = UD->field_begin(),
3916         itend = UD->field_end();
3917       it != itend; ++it) {
3918    if (it->getType()->isPointerType()) {
3919      // If the transparent union contains a pointer type, we allow:
3920      // 1) void pointer
3921      // 2) null pointer constant
3922      if (FromType->isPointerType())
3923        if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
3924          ImpCastExprToType(rExpr, it->getType());
3925          InitField = *it;
3926          break;
3927        }
3928
3929      if (rExpr->isNullPointerConstant(Context)) {
3930        ImpCastExprToType(rExpr, it->getType());
3931        InitField = *it;
3932        break;
3933      }
3934    }
3935
3936    if (CheckAssignmentConstraints(it->getType(), rExpr->getType())
3937          == Compatible) {
3938      InitField = *it;
3939      break;
3940    }
3941  }
3942
3943  if (!InitField)
3944    return Incompatible;
3945
3946  ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
3947  return Compatible;
3948}
3949
3950Sema::AssignConvertType
3951Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
3952  if (getLangOptions().CPlusPlus) {
3953    if (!lhsType->isRecordType()) {
3954      // C++ 5.17p3: If the left operand is not of class type, the
3955      // expression is implicitly converted (C++ 4) to the
3956      // cv-unqualified type of the left operand.
3957      if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
3958                                    "assigning"))
3959        return Incompatible;
3960      return Compatible;
3961    }
3962
3963    // FIXME: Currently, we fall through and treat C++ classes like C
3964    // structures.
3965  }
3966
3967  // C99 6.5.16.1p1: the left operand is a pointer and the right is
3968  // a null pointer constant.
3969  if ((lhsType->isPointerType() ||
3970       lhsType->isObjCObjectPointerType() ||
3971       lhsType->isBlockPointerType())
3972      && rExpr->isNullPointerConstant(Context)) {
3973    ImpCastExprToType(rExpr, lhsType);
3974    return Compatible;
3975  }
3976
3977  // This check seems unnatural, however it is necessary to ensure the proper
3978  // conversion of functions/arrays. If the conversion were done for all
3979  // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
3980  // expressions that surpress this implicit conversion (&, sizeof).
3981  //
3982  // Suppress this for references: C++ 8.5.3p5.
3983  if (!lhsType->isReferenceType())
3984    DefaultFunctionArrayConversion(rExpr);
3985
3986  Sema::AssignConvertType result =
3987    CheckAssignmentConstraints(lhsType, rExpr->getType());
3988
3989  // C99 6.5.16.1p2: The value of the right operand is converted to the
3990  // type of the assignment expression.
3991  // CheckAssignmentConstraints allows the left-hand side to be a reference,
3992  // so that we can use references in built-in functions even in C.
3993  // The getNonReferenceType() call makes sure that the resulting expression
3994  // does not have reference type.
3995  if (result != Incompatible && rExpr->getType() != lhsType)
3996    ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
3997  return result;
3998}
3999
4000QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
4001  Diag(Loc, diag::err_typecheck_invalid_operands)
4002    << lex->getType() << rex->getType()
4003    << lex->getSourceRange() << rex->getSourceRange();
4004  return QualType();
4005}
4006
4007inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
4008                                                              Expr *&rex) {
4009  // For conversion purposes, we ignore any qualifiers.
4010  // For example, "const float" and "float" are equivalent.
4011  QualType lhsType =
4012    Context.getCanonicalType(lex->getType()).getUnqualifiedType();
4013  QualType rhsType =
4014    Context.getCanonicalType(rex->getType()).getUnqualifiedType();
4015
4016  // If the vector types are identical, return.
4017  if (lhsType == rhsType)
4018    return lhsType;
4019
4020  // Handle the case of a vector & extvector type of the same size and element
4021  // type.  It would be nice if we only had one vector type someday.
4022  if (getLangOptions().LaxVectorConversions) {
4023    // FIXME: Should we warn here?
4024    if (const VectorType *LV = lhsType->getAsVectorType()) {
4025      if (const VectorType *RV = rhsType->getAsVectorType())
4026        if (LV->getElementType() == RV->getElementType() &&
4027            LV->getNumElements() == RV->getNumElements()) {
4028          return lhsType->isExtVectorType() ? lhsType : rhsType;
4029        }
4030    }
4031  }
4032
4033  // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
4034  // swap back (so that we don't reverse the inputs to a subtract, for instance.
4035  bool swapped = false;
4036  if (rhsType->isExtVectorType()) {
4037    swapped = true;
4038    std::swap(rex, lex);
4039    std::swap(rhsType, lhsType);
4040  }
4041
4042  // Handle the case of an ext vector and scalar.
4043  if (const ExtVectorType *LV = lhsType->getAsExtVectorType()) {
4044    QualType EltTy = LV->getElementType();
4045    if (EltTy->isIntegralType() && rhsType->isIntegralType()) {
4046      if (Context.getIntegerTypeOrder(EltTy, rhsType) >= 0) {
4047        ImpCastExprToType(rex, lhsType);
4048        if (swapped) std::swap(rex, lex);
4049        return lhsType;
4050      }
4051    }
4052    if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
4053        rhsType->isRealFloatingType()) {
4054      if (Context.getFloatingTypeOrder(EltTy, rhsType) >= 0) {
4055        ImpCastExprToType(rex, lhsType);
4056        if (swapped) std::swap(rex, lex);
4057        return lhsType;
4058      }
4059    }
4060  }
4061
4062  // Vectors of different size or scalar and non-ext-vector are errors.
4063  Diag(Loc, diag::err_typecheck_vector_not_convertable)
4064    << lex->getType() << rex->getType()
4065    << lex->getSourceRange() << rex->getSourceRange();
4066  return QualType();
4067}
4068
4069inline QualType Sema::CheckMultiplyDivideOperands(
4070  Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
4071  if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
4072    return CheckVectorOperands(Loc, lex, rex);
4073
4074  QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
4075
4076  if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
4077    return compType;
4078  return InvalidOperands(Loc, lex, rex);
4079}
4080
4081inline QualType Sema::CheckRemainderOperands(
4082  Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
4083  if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4084    if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
4085      return CheckVectorOperands(Loc, lex, rex);
4086    return InvalidOperands(Loc, lex, rex);
4087  }
4088
4089  QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
4090
4091  if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
4092    return compType;
4093  return InvalidOperands(Loc, lex, rex);
4094}
4095
4096inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
4097  Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) {
4098  if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4099    QualType compType = CheckVectorOperands(Loc, lex, rex);
4100    if (CompLHSTy) *CompLHSTy = compType;
4101    return compType;
4102  }
4103
4104  QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
4105
4106  // handle the common case first (both operands are arithmetic).
4107  if (lex->getType()->isArithmeticType() &&
4108      rex->getType()->isArithmeticType()) {
4109    if (CompLHSTy) *CompLHSTy = compType;
4110    return compType;
4111  }
4112
4113  // Put any potential pointer into PExp
4114  Expr* PExp = lex, *IExp = rex;
4115  if (IExp->getType()->isAnyPointerType())
4116    std::swap(PExp, IExp);
4117
4118  if (PExp->getType()->isAnyPointerType()) {
4119
4120    if (IExp->getType()->isIntegerType()) {
4121      QualType PointeeTy = PExp->getType()->getPointeeType();
4122
4123      // Check for arithmetic on pointers to incomplete types.
4124      if (PointeeTy->isVoidType()) {
4125        if (getLangOptions().CPlusPlus) {
4126          Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4127            << lex->getSourceRange() << rex->getSourceRange();
4128          return QualType();
4129        }
4130
4131        // GNU extension: arithmetic on pointer to void
4132        Diag(Loc, diag::ext_gnu_void_ptr)
4133          << lex->getSourceRange() << rex->getSourceRange();
4134      } else if (PointeeTy->isFunctionType()) {
4135        if (getLangOptions().CPlusPlus) {
4136          Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
4137            << lex->getType() << lex->getSourceRange();
4138          return QualType();
4139        }
4140
4141        // GNU extension: arithmetic on pointer to function
4142        Diag(Loc, diag::ext_gnu_ptr_func_arith)
4143          << lex->getType() << lex->getSourceRange();
4144      } else {
4145        // Check if we require a complete type.
4146        if (((PExp->getType()->isPointerType() &&
4147              !PExp->getType()->isDependentType()) ||
4148              PExp->getType()->isObjCObjectPointerType()) &&
4149             RequireCompleteType(Loc, PointeeTy,
4150                           PDiag(diag::err_typecheck_arithmetic_incomplete_type)
4151                             << PExp->getSourceRange()
4152                             << PExp->getType()))
4153          return QualType();
4154      }
4155      // Diagnose bad cases where we step over interface counts.
4156      if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4157        Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4158          << PointeeTy << PExp->getSourceRange();
4159        return QualType();
4160      }
4161
4162      if (CompLHSTy) {
4163        QualType LHSTy = Context.isPromotableBitField(lex);
4164        if (LHSTy.isNull()) {
4165          LHSTy = lex->getType();
4166          if (LHSTy->isPromotableIntegerType())
4167            LHSTy = Context.getPromotedIntegerType(LHSTy);
4168        }
4169        *CompLHSTy = LHSTy;
4170      }
4171      return PExp->getType();
4172    }
4173  }
4174
4175  return InvalidOperands(Loc, lex, rex);
4176}
4177
4178// C99 6.5.6
4179QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
4180                                        SourceLocation Loc, QualType* CompLHSTy) {
4181  if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4182    QualType compType = CheckVectorOperands(Loc, lex, rex);
4183    if (CompLHSTy) *CompLHSTy = compType;
4184    return compType;
4185  }
4186
4187  QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
4188
4189  // Enforce type constraints: C99 6.5.6p3.
4190
4191  // Handle the common case first (both operands are arithmetic).
4192  if (lex->getType()->isArithmeticType()
4193      && rex->getType()->isArithmeticType()) {
4194    if (CompLHSTy) *CompLHSTy = compType;
4195    return compType;
4196  }
4197
4198  // Either ptr - int   or   ptr - ptr.
4199  if (lex->getType()->isAnyPointerType()) {
4200    QualType lpointee = lex->getType()->getPointeeType();
4201
4202    // The LHS must be an completely-defined object type.
4203
4204    bool ComplainAboutVoid = false;
4205    Expr *ComplainAboutFunc = 0;
4206    if (lpointee->isVoidType()) {
4207      if (getLangOptions().CPlusPlus) {
4208        Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4209          << lex->getSourceRange() << rex->getSourceRange();
4210        return QualType();
4211      }
4212
4213      // GNU C extension: arithmetic on pointer to void
4214      ComplainAboutVoid = true;
4215    } else if (lpointee->isFunctionType()) {
4216      if (getLangOptions().CPlusPlus) {
4217        Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
4218          << lex->getType() << lex->getSourceRange();
4219        return QualType();
4220      }
4221
4222      // GNU C extension: arithmetic on pointer to function
4223      ComplainAboutFunc = lex;
4224    } else if (!lpointee->isDependentType() &&
4225               RequireCompleteType(Loc, lpointee,
4226                                   PDiag(diag::err_typecheck_sub_ptr_object)
4227                                     << lex->getSourceRange()
4228                                     << lex->getType()))
4229      return QualType();
4230
4231    // Diagnose bad cases where we step over interface counts.
4232    if (lpointee->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4233      Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4234        << lpointee << lex->getSourceRange();
4235      return QualType();
4236    }
4237
4238    // The result type of a pointer-int computation is the pointer type.
4239    if (rex->getType()->isIntegerType()) {
4240      if (ComplainAboutVoid)
4241        Diag(Loc, diag::ext_gnu_void_ptr)
4242          << lex->getSourceRange() << rex->getSourceRange();
4243      if (ComplainAboutFunc)
4244        Diag(Loc, diag::ext_gnu_ptr_func_arith)
4245          << ComplainAboutFunc->getType()
4246          << ComplainAboutFunc->getSourceRange();
4247
4248      if (CompLHSTy) *CompLHSTy = lex->getType();
4249      return lex->getType();
4250    }
4251
4252    // Handle pointer-pointer subtractions.
4253    if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
4254      QualType rpointee = RHSPTy->getPointeeType();
4255
4256      // RHS must be a completely-type object type.
4257      // Handle the GNU void* extension.
4258      if (rpointee->isVoidType()) {
4259        if (getLangOptions().CPlusPlus) {
4260          Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4261            << lex->getSourceRange() << rex->getSourceRange();
4262          return QualType();
4263        }
4264
4265        ComplainAboutVoid = true;
4266      } else if (rpointee->isFunctionType()) {
4267        if (getLangOptions().CPlusPlus) {
4268          Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
4269            << rex->getType() << rex->getSourceRange();
4270          return QualType();
4271        }
4272
4273        // GNU extension: arithmetic on pointer to function
4274        if (!ComplainAboutFunc)
4275          ComplainAboutFunc = rex;
4276      } else if (!rpointee->isDependentType() &&
4277                 RequireCompleteType(Loc, rpointee,
4278                                     PDiag(diag::err_typecheck_sub_ptr_object)
4279                                       << rex->getSourceRange()
4280                                       << rex->getType()))
4281        return QualType();
4282
4283      if (getLangOptions().CPlusPlus) {
4284        // Pointee types must be the same: C++ [expr.add]
4285        if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
4286          Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4287            << lex->getType() << rex->getType()
4288            << lex->getSourceRange() << rex->getSourceRange();
4289          return QualType();
4290        }
4291      } else {
4292        // Pointee types must be compatible C99 6.5.6p3
4293        if (!Context.typesAreCompatible(
4294                Context.getCanonicalType(lpointee).getUnqualifiedType(),
4295                Context.getCanonicalType(rpointee).getUnqualifiedType())) {
4296          Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4297            << lex->getType() << rex->getType()
4298            << lex->getSourceRange() << rex->getSourceRange();
4299          return QualType();
4300        }
4301      }
4302
4303      if (ComplainAboutVoid)
4304        Diag(Loc, diag::ext_gnu_void_ptr)
4305          << lex->getSourceRange() << rex->getSourceRange();
4306      if (ComplainAboutFunc)
4307        Diag(Loc, diag::ext_gnu_ptr_func_arith)
4308          << ComplainAboutFunc->getType()
4309          << ComplainAboutFunc->getSourceRange();
4310
4311      if (CompLHSTy) *CompLHSTy = lex->getType();
4312      return Context.getPointerDiffType();
4313    }
4314  }
4315
4316  return InvalidOperands(Loc, lex, rex);
4317}
4318
4319// C99 6.5.7
4320QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
4321                                  bool isCompAssign) {
4322  // C99 6.5.7p2: Each of the operands shall have integer type.
4323  if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
4324    return InvalidOperands(Loc, lex, rex);
4325
4326  // Shifts don't perform usual arithmetic conversions, they just do integer
4327  // promotions on each operand. C99 6.5.7p3
4328  QualType LHSTy = Context.isPromotableBitField(lex);
4329  if (LHSTy.isNull()) {
4330    LHSTy = lex->getType();
4331    if (LHSTy->isPromotableIntegerType())
4332      LHSTy = Context.getPromotedIntegerType(LHSTy);
4333  }
4334  if (!isCompAssign)
4335    ImpCastExprToType(lex, LHSTy);
4336
4337  UsualUnaryConversions(rex);
4338
4339  // Sanity-check shift operands
4340  llvm::APSInt Right;
4341  // Check right/shifter operand
4342  if (rex->isIntegerConstantExpr(Right, Context)) {
4343    if (Right.isNegative())
4344      Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
4345    else {
4346      llvm::APInt LeftBits(Right.getBitWidth(),
4347                          Context.getTypeSize(lex->getType()));
4348      if (Right.uge(LeftBits))
4349        Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
4350    }
4351  }
4352
4353  // "The type of the result is that of the promoted left operand."
4354  return LHSTy;
4355}
4356
4357// C99 6.5.8, C++ [expr.rel]
4358QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
4359                                    unsigned OpaqueOpc, bool isRelational) {
4360  BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
4361
4362  if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
4363    return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
4364
4365  // C99 6.5.8p3 / C99 6.5.9p4
4366  if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
4367    UsualArithmeticConversions(lex, rex);
4368  else {
4369    UsualUnaryConversions(lex);
4370    UsualUnaryConversions(rex);
4371  }
4372  QualType lType = lex->getType();
4373  QualType rType = rex->getType();
4374
4375  if (!lType->isFloatingType()
4376      && !(lType->isBlockPointerType() && isRelational)) {
4377    // For non-floating point types, check for self-comparisons of the form
4378    // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
4379    // often indicate logic errors in the program.
4380    // NOTE: Don't warn about comparisons of enum constants. These can arise
4381    //  from macro expansions, and are usually quite deliberate.
4382    Expr *LHSStripped = lex->IgnoreParens();
4383    Expr *RHSStripped = rex->IgnoreParens();
4384    if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
4385      if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
4386        if (DRL->getDecl() == DRR->getDecl() &&
4387            !isa<EnumConstantDecl>(DRL->getDecl()))
4388          Diag(Loc, diag::warn_selfcomparison);
4389
4390    if (isa<CastExpr>(LHSStripped))
4391      LHSStripped = LHSStripped->IgnoreParenCasts();
4392    if (isa<CastExpr>(RHSStripped))
4393      RHSStripped = RHSStripped->IgnoreParenCasts();
4394
4395    // Warn about comparisons against a string constant (unless the other
4396    // operand is null), the user probably wants strcmp.
4397    Expr *literalString = 0;
4398    Expr *literalStringStripped = 0;
4399    if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
4400        !RHSStripped->isNullPointerConstant(Context)) {
4401      literalString = lex;
4402      literalStringStripped = LHSStripped;
4403    } else if ((isa<StringLiteral>(RHSStripped) ||
4404                isa<ObjCEncodeExpr>(RHSStripped)) &&
4405               !LHSStripped->isNullPointerConstant(Context)) {
4406      literalString = rex;
4407      literalStringStripped = RHSStripped;
4408    }
4409
4410    if (literalString) {
4411      std::string resultComparison;
4412      switch (Opc) {
4413      case BinaryOperator::LT: resultComparison = ") < 0"; break;
4414      case BinaryOperator::GT: resultComparison = ") > 0"; break;
4415      case BinaryOperator::LE: resultComparison = ") <= 0"; break;
4416      case BinaryOperator::GE: resultComparison = ") >= 0"; break;
4417      case BinaryOperator::EQ: resultComparison = ") == 0"; break;
4418      case BinaryOperator::NE: resultComparison = ") != 0"; break;
4419      default: assert(false && "Invalid comparison operator");
4420      }
4421      Diag(Loc, diag::warn_stringcompare)
4422        << isa<ObjCEncodeExpr>(literalStringStripped)
4423        << literalString->getSourceRange()
4424        << CodeModificationHint::CreateReplacement(SourceRange(Loc), ", ")
4425        << CodeModificationHint::CreateInsertion(lex->getLocStart(),
4426                                                 "strcmp(")
4427        << CodeModificationHint::CreateInsertion(
4428                                       PP.getLocForEndOfToken(rex->getLocEnd()),
4429                                       resultComparison);
4430    }
4431  }
4432
4433  // The result of comparisons is 'bool' in C++, 'int' in C.
4434  QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy :Context.IntTy;
4435
4436  if (isRelational) {
4437    if (lType->isRealType() && rType->isRealType())
4438      return ResultTy;
4439  } else {
4440    // Check for comparisons of floating point operands using != and ==.
4441    if (lType->isFloatingType()) {
4442      assert(rType->isFloatingType());
4443      CheckFloatComparison(Loc,lex,rex);
4444    }
4445
4446    if (lType->isArithmeticType() && rType->isArithmeticType())
4447      return ResultTy;
4448  }
4449
4450  bool LHSIsNull = lex->isNullPointerConstant(Context);
4451  bool RHSIsNull = rex->isNullPointerConstant(Context);
4452
4453  // All of the following pointer related warnings are GCC extensions, except
4454  // when handling null pointer constants. One day, we can consider making them
4455  // errors (when -pedantic-errors is enabled).
4456  if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
4457    QualType LCanPointeeTy =
4458      Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
4459    QualType RCanPointeeTy =
4460      Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
4461
4462    if (getLangOptions().CPlusPlus) {
4463      if (LCanPointeeTy == RCanPointeeTy)
4464        return ResultTy;
4465
4466      // C++ [expr.rel]p2:
4467      //   [...] Pointer conversions (4.10) and qualification
4468      //   conversions (4.4) are performed on pointer operands (or on
4469      //   a pointer operand and a null pointer constant) to bring
4470      //   them to their composite pointer type. [...]
4471      //
4472      // C++ [expr.eq]p1 uses the same notion for (in)equality
4473      // comparisons of pointers.
4474      QualType T = FindCompositePointerType(lex, rex);
4475      if (T.isNull()) {
4476        Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
4477          << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4478        return QualType();
4479      }
4480
4481      ImpCastExprToType(lex, T);
4482      ImpCastExprToType(rex, T);
4483      return ResultTy;
4484    }
4485    // C99 6.5.9p2 and C99 6.5.8p2
4486    if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
4487                                   RCanPointeeTy.getUnqualifiedType())) {
4488      // Valid unless a relational comparison of function pointers
4489      if (isRelational && LCanPointeeTy->isFunctionType()) {
4490        Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
4491          << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4492      }
4493    } else if (!isRelational &&
4494               (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
4495      // Valid unless comparison between non-null pointer and function pointer
4496      if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
4497          && !LHSIsNull && !RHSIsNull) {
4498        Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
4499          << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4500      }
4501    } else {
4502      // Invalid
4503      Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
4504        << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4505    }
4506    if (LCanPointeeTy != RCanPointeeTy)
4507      ImpCastExprToType(rex, lType); // promote the pointer to pointer
4508    return ResultTy;
4509  }
4510
4511  if (getLangOptions().CPlusPlus) {
4512    // Comparison of pointers with null pointer constants and equality
4513    // comparisons of member pointers to null pointer constants.
4514    if (RHSIsNull &&
4515        (lType->isPointerType() ||
4516         (!isRelational && lType->isMemberPointerType()))) {
4517      ImpCastExprToType(rex, lType, CastExpr::CK_NullToMemberPointer);
4518      return ResultTy;
4519    }
4520    if (LHSIsNull &&
4521        (rType->isPointerType() ||
4522         (!isRelational && rType->isMemberPointerType()))) {
4523      ImpCastExprToType(lex, rType, CastExpr::CK_NullToMemberPointer);
4524      return ResultTy;
4525    }
4526
4527    // Comparison of member pointers.
4528    if (!isRelational &&
4529        lType->isMemberPointerType() && rType->isMemberPointerType()) {
4530      // C++ [expr.eq]p2:
4531      //   In addition, pointers to members can be compared, or a pointer to
4532      //   member and a null pointer constant. Pointer to member conversions
4533      //   (4.11) and qualification conversions (4.4) are performed to bring
4534      //   them to a common type. If one operand is a null pointer constant,
4535      //   the common type is the type of the other operand. Otherwise, the
4536      //   common type is a pointer to member type similar (4.4) to the type
4537      //   of one of the operands, with a cv-qualification signature (4.4)
4538      //   that is the union of the cv-qualification signatures of the operand
4539      //   types.
4540      QualType T = FindCompositePointerType(lex, rex);
4541      if (T.isNull()) {
4542        Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
4543        << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4544        return QualType();
4545      }
4546
4547      ImpCastExprToType(lex, T);
4548      ImpCastExprToType(rex, T);
4549      return ResultTy;
4550    }
4551
4552    // Comparison of nullptr_t with itself.
4553    if (lType->isNullPtrType() && rType->isNullPtrType())
4554      return ResultTy;
4555  }
4556
4557  // Handle block pointer types.
4558  if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
4559    QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
4560    QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
4561
4562    if (!LHSIsNull && !RHSIsNull &&
4563        !Context.typesAreCompatible(lpointee, rpointee)) {
4564      Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
4565        << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4566    }
4567    ImpCastExprToType(rex, lType); // promote the pointer to pointer
4568    return ResultTy;
4569  }
4570  // Allow block pointers to be compared with null pointer constants.
4571  if (!isRelational
4572      && ((lType->isBlockPointerType() && rType->isPointerType())
4573          || (lType->isPointerType() && rType->isBlockPointerType()))) {
4574    if (!LHSIsNull && !RHSIsNull) {
4575      if (!((rType->isPointerType() && rType->getAs<PointerType>()
4576             ->getPointeeType()->isVoidType())
4577            || (lType->isPointerType() && lType->getAs<PointerType>()
4578                ->getPointeeType()->isVoidType())))
4579        Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
4580          << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4581    }
4582    ImpCastExprToType(rex, lType); // promote the pointer to pointer
4583    return ResultTy;
4584  }
4585
4586  if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
4587    if (lType->isPointerType() || rType->isPointerType()) {
4588      const PointerType *LPT = lType->getAs<PointerType>();
4589      const PointerType *RPT = rType->getAs<PointerType>();
4590      bool LPtrToVoid = LPT ?
4591        Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
4592      bool RPtrToVoid = RPT ?
4593        Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
4594
4595      if (!LPtrToVoid && !RPtrToVoid &&
4596          !Context.typesAreCompatible(lType, rType)) {
4597        Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
4598          << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4599      }
4600      ImpCastExprToType(rex, lType);
4601      return ResultTy;
4602    }
4603    if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
4604      if (!Context.areComparableObjCPointerTypes(lType, rType))
4605        Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
4606          << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4607      ImpCastExprToType(rex, lType);
4608      return ResultTy;
4609    }
4610  }
4611  if (lType->isAnyPointerType() && rType->isIntegerType()) {
4612    unsigned DiagID = 0;
4613    if (RHSIsNull) {
4614      if (isRelational)
4615        DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
4616    } else if (isRelational)
4617      DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
4618    else
4619      DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
4620
4621    if (DiagID) {
4622      Diag(Loc, DiagID)
4623        << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4624    }
4625    ImpCastExprToType(rex, lType); // promote the integer to pointer
4626    return ResultTy;
4627  }
4628  if (lType->isIntegerType() && rType->isAnyPointerType()) {
4629    unsigned DiagID = 0;
4630    if (LHSIsNull) {
4631      if (isRelational)
4632        DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
4633    } else if (isRelational)
4634      DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
4635    else
4636      DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
4637
4638    if (DiagID) {
4639      Diag(Loc, DiagID)
4640        << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4641    }
4642    ImpCastExprToType(lex, rType); // promote the integer to pointer
4643    return ResultTy;
4644  }
4645  // Handle block pointers.
4646  if (!isRelational && RHSIsNull
4647      && lType->isBlockPointerType() && rType->isIntegerType()) {
4648    ImpCastExprToType(rex, lType); // promote the integer to pointer
4649    return ResultTy;
4650  }
4651  if (!isRelational && LHSIsNull
4652      && lType->isIntegerType() && rType->isBlockPointerType()) {
4653    ImpCastExprToType(lex, rType); // promote the integer to pointer
4654    return ResultTy;
4655  }
4656  return InvalidOperands(Loc, lex, rex);
4657}
4658
4659/// CheckVectorCompareOperands - vector comparisons are a clang extension that
4660/// operates on extended vector types.  Instead of producing an IntTy result,
4661/// like a scalar comparison, a vector comparison produces a vector of integer
4662/// types.
4663QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
4664                                          SourceLocation Loc,
4665                                          bool isRelational) {
4666  // Check to make sure we're operating on vectors of the same type and width,
4667  // Allowing one side to be a scalar of element type.
4668  QualType vType = CheckVectorOperands(Loc, lex, rex);
4669  if (vType.isNull())
4670    return vType;
4671
4672  QualType lType = lex->getType();
4673  QualType rType = rex->getType();
4674
4675  // For non-floating point types, check for self-comparisons of the form
4676  // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
4677  // often indicate logic errors in the program.
4678  if (!lType->isFloatingType()) {
4679    if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
4680      if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
4681        if (DRL->getDecl() == DRR->getDecl())
4682          Diag(Loc, diag::warn_selfcomparison);
4683  }
4684
4685  // Check for comparisons of floating point operands using != and ==.
4686  if (!isRelational && lType->isFloatingType()) {
4687    assert (rType->isFloatingType());
4688    CheckFloatComparison(Loc,lex,rex);
4689  }
4690
4691  // Return the type for the comparison, which is the same as vector type for
4692  // integer vectors, or an integer type of identical size and number of
4693  // elements for floating point vectors.
4694  if (lType->isIntegerType())
4695    return lType;
4696
4697  const VectorType *VTy = lType->getAsVectorType();
4698  unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
4699  if (TypeSize == Context.getTypeSize(Context.IntTy))
4700    return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
4701  if (TypeSize == Context.getTypeSize(Context.LongTy))
4702    return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
4703
4704  assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
4705         "Unhandled vector element size in vector compare");
4706  return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
4707}
4708
4709inline QualType Sema::CheckBitwiseOperands(
4710  Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
4711  if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
4712    return CheckVectorOperands(Loc, lex, rex);
4713
4714  QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
4715
4716  if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
4717    return compType;
4718  return InvalidOperands(Loc, lex, rex);
4719}
4720
4721inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
4722  Expr *&lex, Expr *&rex, SourceLocation Loc) {
4723  UsualUnaryConversions(lex);
4724  UsualUnaryConversions(rex);
4725
4726  if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
4727    return Context.IntTy;
4728  return InvalidOperands(Loc, lex, rex);
4729}
4730
4731/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
4732/// is a read-only property; return true if so. A readonly property expression
4733/// depends on various declarations and thus must be treated specially.
4734///
4735static bool IsReadonlyProperty(Expr *E, Sema &S) {
4736  if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
4737    const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
4738    if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
4739      QualType BaseType = PropExpr->getBase()->getType();
4740      if (const ObjCObjectPointerType *OPT =
4741            BaseType->getAsObjCInterfacePointerType())
4742        if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
4743          if (S.isPropertyReadonly(PDecl, IFace))
4744            return true;
4745    }
4746  }
4747  return false;
4748}
4749
4750/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
4751/// emit an error and return true.  If so, return false.
4752static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
4753  SourceLocation OrigLoc = Loc;
4754  Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
4755                                                              &Loc);
4756  if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
4757    IsLV = Expr::MLV_ReadonlyProperty;
4758  if (IsLV == Expr::MLV_Valid)
4759    return false;
4760
4761  unsigned Diag = 0;
4762  bool NeedType = false;
4763  switch (IsLV) { // C99 6.5.16p2
4764  default: assert(0 && "Unknown result from isModifiableLvalue!");
4765  case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
4766  case Expr::MLV_ArrayType:
4767    Diag = diag::err_typecheck_array_not_modifiable_lvalue;
4768    NeedType = true;
4769    break;
4770  case Expr::MLV_NotObjectType:
4771    Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
4772    NeedType = true;
4773    break;
4774  case Expr::MLV_LValueCast:
4775    Diag = diag::err_typecheck_lvalue_casts_not_supported;
4776    break;
4777  case Expr::MLV_InvalidExpression:
4778    Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
4779    break;
4780  case Expr::MLV_IncompleteType:
4781  case Expr::MLV_IncompleteVoidType:
4782    return S.RequireCompleteType(Loc, E->getType(),
4783                PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
4784                  << E->getSourceRange());
4785  case Expr::MLV_DuplicateVectorComponents:
4786    Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
4787    break;
4788  case Expr::MLV_NotBlockQualified:
4789    Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
4790    break;
4791  case Expr::MLV_ReadonlyProperty:
4792    Diag = diag::error_readonly_property_assignment;
4793    break;
4794  case Expr::MLV_NoSetterProperty:
4795    Diag = diag::error_nosetter_property_assignment;
4796    break;
4797  }
4798
4799  SourceRange Assign;
4800  if (Loc != OrigLoc)
4801    Assign = SourceRange(OrigLoc, OrigLoc);
4802  if (NeedType)
4803    S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
4804  else
4805    S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
4806  return true;
4807}
4808
4809
4810
4811// C99 6.5.16.1
4812QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
4813                                       SourceLocation Loc,
4814                                       QualType CompoundType) {
4815  // Verify that LHS is a modifiable lvalue, and emit error if not.
4816  if (CheckForModifiableLvalue(LHS, Loc, *this))
4817    return QualType();
4818
4819  QualType LHSType = LHS->getType();
4820  QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
4821
4822  AssignConvertType ConvTy;
4823  if (CompoundType.isNull()) {
4824    // Simple assignment "x = y".
4825    ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
4826    // Special case of NSObject attributes on c-style pointer types.
4827    if (ConvTy == IncompatiblePointer &&
4828        ((Context.isObjCNSObjectType(LHSType) &&
4829          RHSType->isObjCObjectPointerType()) ||
4830         (Context.isObjCNSObjectType(RHSType) &&
4831          LHSType->isObjCObjectPointerType())))
4832      ConvTy = Compatible;
4833
4834    // If the RHS is a unary plus or minus, check to see if they = and + are
4835    // right next to each other.  If so, the user may have typo'd "x =+ 4"
4836    // instead of "x += 4".
4837    Expr *RHSCheck = RHS;
4838    if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
4839      RHSCheck = ICE->getSubExpr();
4840    if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
4841      if ((UO->getOpcode() == UnaryOperator::Plus ||
4842           UO->getOpcode() == UnaryOperator::Minus) &&
4843          Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
4844          // Only if the two operators are exactly adjacent.
4845          Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
4846          // And there is a space or other character before the subexpr of the
4847          // unary +/-.  We don't want to warn on "x=-1".
4848          Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
4849          UO->getSubExpr()->getLocStart().isFileID()) {
4850        Diag(Loc, diag::warn_not_compound_assign)
4851          << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
4852          << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
4853      }
4854    }
4855  } else {
4856    // Compound assignment "x += y"
4857    ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
4858  }
4859
4860  if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
4861                               RHS, "assigning"))
4862    return QualType();
4863
4864  // C99 6.5.16p3: The type of an assignment expression is the type of the
4865  // left operand unless the left operand has qualified type, in which case
4866  // it is the unqualified version of the type of the left operand.
4867  // C99 6.5.16.1p2: In simple assignment, the value of the right operand
4868  // is converted to the type of the assignment expression (above).
4869  // C++ 5.17p1: the type of the assignment expression is that of its left
4870  // operand.
4871  return LHSType.getUnqualifiedType();
4872}
4873
4874// C99 6.5.17
4875QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
4876  // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
4877  DefaultFunctionArrayConversion(RHS);
4878
4879  // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
4880  // incomplete in C++).
4881
4882  return RHS->getType();
4883}
4884
4885/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
4886/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
4887QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
4888                                              bool isInc) {
4889  if (Op->isTypeDependent())
4890    return Context.DependentTy;
4891
4892  QualType ResType = Op->getType();
4893  assert(!ResType.isNull() && "no type for increment/decrement expression");
4894
4895  if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
4896    // Decrement of bool is not allowed.
4897    if (!isInc) {
4898      Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
4899      return QualType();
4900    }
4901    // Increment of bool sets it to true, but is deprecated.
4902    Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
4903  } else if (ResType->isRealType()) {
4904    // OK!
4905  } else if (ResType->isAnyPointerType()) {
4906    QualType PointeeTy = ResType->getPointeeType();
4907
4908    // C99 6.5.2.4p2, 6.5.6p2
4909    if (PointeeTy->isVoidType()) {
4910      if (getLangOptions().CPlusPlus) {
4911        Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
4912          << Op->getSourceRange();
4913        return QualType();
4914      }
4915
4916      // Pointer to void is a GNU extension in C.
4917      Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
4918    } else if (PointeeTy->isFunctionType()) {
4919      if (getLangOptions().CPlusPlus) {
4920        Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
4921          << Op->getType() << Op->getSourceRange();
4922        return QualType();
4923      }
4924
4925      Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
4926        << ResType << Op->getSourceRange();
4927    } else if (RequireCompleteType(OpLoc, PointeeTy,
4928                           PDiag(diag::err_typecheck_arithmetic_incomplete_type)
4929                             << Op->getSourceRange()
4930                             << ResType))
4931      return QualType();
4932    // Diagnose bad cases where we step over interface counts.
4933    else if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4934      Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
4935        << PointeeTy << Op->getSourceRange();
4936      return QualType();
4937    }
4938  } else if (ResType->isComplexType()) {
4939    // C99 does not support ++/-- on complex types, we allow as an extension.
4940    Diag(OpLoc, diag::ext_integer_increment_complex)
4941      << ResType << Op->getSourceRange();
4942  } else {
4943    Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
4944      << ResType << Op->getSourceRange();
4945    return QualType();
4946  }
4947  // At this point, we know we have a real, complex or pointer type.
4948  // Now make sure the operand is a modifiable lvalue.
4949  if (CheckForModifiableLvalue(Op, OpLoc, *this))
4950    return QualType();
4951  return ResType;
4952}
4953
4954/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
4955/// This routine allows us to typecheck complex/recursive expressions
4956/// where the declaration is needed for type checking. We only need to
4957/// handle cases when the expression references a function designator
4958/// or is an lvalue. Here are some examples:
4959///  - &(x) => x
4960///  - &*****f => f for f a function designator.
4961///  - &s.xx => s
4962///  - &s.zz[1].yy -> s, if zz is an array
4963///  - *(x + 1) -> x, if x is an array
4964///  - &"123"[2] -> 0
4965///  - & __real__ x -> x
4966static NamedDecl *getPrimaryDecl(Expr *E) {
4967  switch (E->getStmtClass()) {
4968  case Stmt::DeclRefExprClass:
4969  case Stmt::QualifiedDeclRefExprClass:
4970    return cast<DeclRefExpr>(E)->getDecl();
4971  case Stmt::MemberExprClass:
4972    // If this is an arrow operator, the address is an offset from
4973    // the base's value, so the object the base refers to is
4974    // irrelevant.
4975    if (cast<MemberExpr>(E)->isArrow())
4976      return 0;
4977    // Otherwise, the expression refers to a part of the base
4978    return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
4979  case Stmt::ArraySubscriptExprClass: {
4980    // FIXME: This code shouldn't be necessary!  We should catch the implicit
4981    // promotion of register arrays earlier.
4982    Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
4983    if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
4984      if (ICE->getSubExpr()->getType()->isArrayType())
4985        return getPrimaryDecl(ICE->getSubExpr());
4986    }
4987    return 0;
4988  }
4989  case Stmt::UnaryOperatorClass: {
4990    UnaryOperator *UO = cast<UnaryOperator>(E);
4991
4992    switch(UO->getOpcode()) {
4993    case UnaryOperator::Real:
4994    case UnaryOperator::Imag:
4995    case UnaryOperator::Extension:
4996      return getPrimaryDecl(UO->getSubExpr());
4997    default:
4998      return 0;
4999    }
5000  }
5001  case Stmt::ParenExprClass:
5002    return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
5003  case Stmt::ImplicitCastExprClass:
5004    // If the result of an implicit cast is an l-value, we care about
5005    // the sub-expression; otherwise, the result here doesn't matter.
5006    return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
5007  default:
5008    return 0;
5009  }
5010}
5011
5012/// CheckAddressOfOperand - The operand of & must be either a function
5013/// designator or an lvalue designating an object. If it is an lvalue, the
5014/// object cannot be declared with storage class register or be a bit field.
5015/// Note: The usual conversions are *not* applied to the operand of the &
5016/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
5017/// In C++, the operand might be an overloaded function name, in which case
5018/// we allow the '&' but retain the overloaded-function type.
5019QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
5020  // Make sure to ignore parentheses in subsequent checks
5021  op = op->IgnoreParens();
5022
5023  if (op->isTypeDependent())
5024    return Context.DependentTy;
5025
5026  if (getLangOptions().C99) {
5027    // Implement C99-only parts of addressof rules.
5028    if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
5029      if (uOp->getOpcode() == UnaryOperator::Deref)
5030        // Per C99 6.5.3.2, the address of a deref always returns a valid result
5031        // (assuming the deref expression is valid).
5032        return uOp->getSubExpr()->getType();
5033    }
5034    // Technically, there should be a check for array subscript
5035    // expressions here, but the result of one is always an lvalue anyway.
5036  }
5037  NamedDecl *dcl = getPrimaryDecl(op);
5038  Expr::isLvalueResult lval = op->isLvalue(Context);
5039
5040  if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
5041    // C99 6.5.3.2p1
5042    // The operand must be either an l-value or a function designator
5043    if (!op->getType()->isFunctionType()) {
5044      // FIXME: emit more specific diag...
5045      Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
5046        << op->getSourceRange();
5047      return QualType();
5048    }
5049  } else if (op->getBitField()) { // C99 6.5.3.2p1
5050    // The operand cannot be a bit-field
5051    Diag(OpLoc, diag::err_typecheck_address_of)
5052      << "bit-field" << op->getSourceRange();
5053        return QualType();
5054  } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
5055           cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
5056    // The operand cannot be an element of a vector
5057    Diag(OpLoc, diag::err_typecheck_address_of)
5058      << "vector element" << op->getSourceRange();
5059    return QualType();
5060  } else if (isa<ObjCPropertyRefExpr>(op)) {
5061    // cannot take address of a property expression.
5062    Diag(OpLoc, diag::err_typecheck_address_of)
5063      << "property expression" << op->getSourceRange();
5064    return QualType();
5065  } else if (dcl) { // C99 6.5.3.2p1
5066    // We have an lvalue with a decl. Make sure the decl is not declared
5067    // with the register storage-class specifier.
5068    if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
5069      if (vd->getStorageClass() == VarDecl::Register) {
5070        Diag(OpLoc, diag::err_typecheck_address_of)
5071          << "register variable" << op->getSourceRange();
5072        return QualType();
5073      }
5074    } else if (isa<OverloadedFunctionDecl>(dcl) ||
5075               isa<FunctionTemplateDecl>(dcl)) {
5076      return Context.OverloadTy;
5077    } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
5078      // Okay: we can take the address of a field.
5079      // Could be a pointer to member, though, if there is an explicit
5080      // scope qualifier for the class.
5081      if (isa<QualifiedDeclRefExpr>(op)) {
5082        DeclContext *Ctx = dcl->getDeclContext();
5083        if (Ctx && Ctx->isRecord()) {
5084          if (FD->getType()->isReferenceType()) {
5085            Diag(OpLoc,
5086                 diag::err_cannot_form_pointer_to_member_of_reference_type)
5087              << FD->getDeclName() << FD->getType();
5088            return QualType();
5089          }
5090
5091          return Context.getMemberPointerType(op->getType(),
5092                Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
5093        }
5094      }
5095    } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(dcl)) {
5096      // Okay: we can take the address of a function.
5097      // As above.
5098      if (isa<QualifiedDeclRefExpr>(op) && MD->isInstance())
5099        return Context.getMemberPointerType(op->getType(),
5100              Context.getTypeDeclType(MD->getParent()).getTypePtr());
5101    } else if (!isa<FunctionDecl>(dcl))
5102      assert(0 && "Unknown/unexpected decl type");
5103  }
5104
5105  if (lval == Expr::LV_IncompleteVoidType) {
5106    // Taking the address of a void variable is technically illegal, but we
5107    // allow it in cases which are otherwise valid.
5108    // Example: "extern void x; void* y = &x;".
5109    Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
5110  }
5111
5112  // If the operand has type "type", the result has type "pointer to type".
5113  return Context.getPointerType(op->getType());
5114}
5115
5116QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
5117  if (Op->isTypeDependent())
5118    return Context.DependentTy;
5119
5120  UsualUnaryConversions(Op);
5121  QualType Ty = Op->getType();
5122
5123  // Note that per both C89 and C99, this is always legal, even if ptype is an
5124  // incomplete type or void.  It would be possible to warn about dereferencing
5125  // a void pointer, but it's completely well-defined, and such a warning is
5126  // unlikely to catch any mistakes.
5127  if (const PointerType *PT = Ty->getAs<PointerType>())
5128    return PT->getPointeeType();
5129
5130  if (const ObjCObjectPointerType *OPT = Ty->getAsObjCObjectPointerType())
5131    return OPT->getPointeeType();
5132
5133  Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
5134    << Ty << Op->getSourceRange();
5135  return QualType();
5136}
5137
5138static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
5139  tok::TokenKind Kind) {
5140  BinaryOperator::Opcode Opc;
5141  switch (Kind) {
5142  default: assert(0 && "Unknown binop!");
5143  case tok::periodstar:           Opc = BinaryOperator::PtrMemD; break;
5144  case tok::arrowstar:            Opc = BinaryOperator::PtrMemI; break;
5145  case tok::star:                 Opc = BinaryOperator::Mul; break;
5146  case tok::slash:                Opc = BinaryOperator::Div; break;
5147  case tok::percent:              Opc = BinaryOperator::Rem; break;
5148  case tok::plus:                 Opc = BinaryOperator::Add; break;
5149  case tok::minus:                Opc = BinaryOperator::Sub; break;
5150  case tok::lessless:             Opc = BinaryOperator::Shl; break;
5151  case tok::greatergreater:       Opc = BinaryOperator::Shr; break;
5152  case tok::lessequal:            Opc = BinaryOperator::LE; break;
5153  case tok::less:                 Opc = BinaryOperator::LT; break;
5154  case tok::greaterequal:         Opc = BinaryOperator::GE; break;
5155  case tok::greater:              Opc = BinaryOperator::GT; break;
5156  case tok::exclaimequal:         Opc = BinaryOperator::NE; break;
5157  case tok::equalequal:           Opc = BinaryOperator::EQ; break;
5158  case tok::amp:                  Opc = BinaryOperator::And; break;
5159  case tok::caret:                Opc = BinaryOperator::Xor; break;
5160  case tok::pipe:                 Opc = BinaryOperator::Or; break;
5161  case tok::ampamp:               Opc = BinaryOperator::LAnd; break;
5162  case tok::pipepipe:             Opc = BinaryOperator::LOr; break;
5163  case tok::equal:                Opc = BinaryOperator::Assign; break;
5164  case tok::starequal:            Opc = BinaryOperator::MulAssign; break;
5165  case tok::slashequal:           Opc = BinaryOperator::DivAssign; break;
5166  case tok::percentequal:         Opc = BinaryOperator::RemAssign; break;
5167  case tok::plusequal:            Opc = BinaryOperator::AddAssign; break;
5168  case tok::minusequal:           Opc = BinaryOperator::SubAssign; break;
5169  case tok::lesslessequal:        Opc = BinaryOperator::ShlAssign; break;
5170  case tok::greatergreaterequal:  Opc = BinaryOperator::ShrAssign; break;
5171  case tok::ampequal:             Opc = BinaryOperator::AndAssign; break;
5172  case tok::caretequal:           Opc = BinaryOperator::XorAssign; break;
5173  case tok::pipeequal:            Opc = BinaryOperator::OrAssign; break;
5174  case tok::comma:                Opc = BinaryOperator::Comma; break;
5175  }
5176  return Opc;
5177}
5178
5179static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
5180  tok::TokenKind Kind) {
5181  UnaryOperator::Opcode Opc;
5182  switch (Kind) {
5183  default: assert(0 && "Unknown unary op!");
5184  case tok::plusplus:     Opc = UnaryOperator::PreInc; break;
5185  case tok::minusminus:   Opc = UnaryOperator::PreDec; break;
5186  case tok::amp:          Opc = UnaryOperator::AddrOf; break;
5187  case tok::star:         Opc = UnaryOperator::Deref; break;
5188  case tok::plus:         Opc = UnaryOperator::Plus; break;
5189  case tok::minus:        Opc = UnaryOperator::Minus; break;
5190  case tok::tilde:        Opc = UnaryOperator::Not; break;
5191  case tok::exclaim:      Opc = UnaryOperator::LNot; break;
5192  case tok::kw___real:    Opc = UnaryOperator::Real; break;
5193  case tok::kw___imag:    Opc = UnaryOperator::Imag; break;
5194  case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
5195  }
5196  return Opc;
5197}
5198
5199/// CreateBuiltinBinOp - Creates a new built-in binary operation with
5200/// operator @p Opc at location @c TokLoc. This routine only supports
5201/// built-in operations; ActOnBinOp handles overloaded operators.
5202Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
5203                                                  unsigned Op,
5204                                                  Expr *lhs, Expr *rhs) {
5205  QualType ResultTy;     // Result type of the binary operator.
5206  BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
5207  // The following two variables are used for compound assignment operators
5208  QualType CompLHSTy;    // Type of LHS after promotions for computation
5209  QualType CompResultTy; // Type of computation result
5210
5211  switch (Opc) {
5212  case BinaryOperator::Assign:
5213    ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
5214    break;
5215  case BinaryOperator::PtrMemD:
5216  case BinaryOperator::PtrMemI:
5217    ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
5218                                            Opc == BinaryOperator::PtrMemI);
5219    break;
5220  case BinaryOperator::Mul:
5221  case BinaryOperator::Div:
5222    ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
5223    break;
5224  case BinaryOperator::Rem:
5225    ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
5226    break;
5227  case BinaryOperator::Add:
5228    ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
5229    break;
5230  case BinaryOperator::Sub:
5231    ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
5232    break;
5233  case BinaryOperator::Shl:
5234  case BinaryOperator::Shr:
5235    ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
5236    break;
5237  case BinaryOperator::LE:
5238  case BinaryOperator::LT:
5239  case BinaryOperator::GE:
5240  case BinaryOperator::GT:
5241    ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
5242    break;
5243  case BinaryOperator::EQ:
5244  case BinaryOperator::NE:
5245    ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
5246    break;
5247  case BinaryOperator::And:
5248  case BinaryOperator::Xor:
5249  case BinaryOperator::Or:
5250    ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
5251    break;
5252  case BinaryOperator::LAnd:
5253  case BinaryOperator::LOr:
5254    ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
5255    break;
5256  case BinaryOperator::MulAssign:
5257  case BinaryOperator::DivAssign:
5258    CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
5259    CompLHSTy = CompResultTy;
5260    if (!CompResultTy.isNull())
5261      ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
5262    break;
5263  case BinaryOperator::RemAssign:
5264    CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
5265    CompLHSTy = CompResultTy;
5266    if (!CompResultTy.isNull())
5267      ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
5268    break;
5269  case BinaryOperator::AddAssign:
5270    CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5271    if (!CompResultTy.isNull())
5272      ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
5273    break;
5274  case BinaryOperator::SubAssign:
5275    CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5276    if (!CompResultTy.isNull())
5277      ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
5278    break;
5279  case BinaryOperator::ShlAssign:
5280  case BinaryOperator::ShrAssign:
5281    CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
5282    CompLHSTy = CompResultTy;
5283    if (!CompResultTy.isNull())
5284      ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
5285    break;
5286  case BinaryOperator::AndAssign:
5287  case BinaryOperator::XorAssign:
5288  case BinaryOperator::OrAssign:
5289    CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
5290    CompLHSTy = CompResultTy;
5291    if (!CompResultTy.isNull())
5292      ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
5293    break;
5294  case BinaryOperator::Comma:
5295    ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
5296    break;
5297  }
5298  if (ResultTy.isNull())
5299    return ExprError();
5300  if (CompResultTy.isNull())
5301    return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
5302  else
5303    return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
5304                                                      CompLHSTy, CompResultTy,
5305                                                      OpLoc));
5306}
5307
5308// Binary Operators.  'Tok' is the token for the operator.
5309Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
5310                                          tok::TokenKind Kind,
5311                                          ExprArg LHS, ExprArg RHS) {
5312  BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
5313  Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>();
5314
5315  assert((lhs != 0) && "ActOnBinOp(): missing left expression");
5316  assert((rhs != 0) && "ActOnBinOp(): missing right expression");
5317
5318  if (getLangOptions().CPlusPlus &&
5319      (lhs->getType()->isOverloadableType() ||
5320       rhs->getType()->isOverloadableType())) {
5321    // Find all of the overloaded operators visible from this
5322    // point. We perform both an operator-name lookup from the local
5323    // scope and an argument-dependent lookup based on the types of
5324    // the arguments.
5325    FunctionSet Functions;
5326    OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
5327    if (OverOp != OO_None) {
5328      LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
5329                                   Functions);
5330      Expr *Args[2] = { lhs, rhs };
5331      DeclarationName OpName
5332        = Context.DeclarationNames.getCXXOperatorName(OverOp);
5333      ArgumentDependentLookup(OpName, Args, 2, Functions);
5334    }
5335
5336    // Build the (potentially-overloaded, potentially-dependent)
5337    // binary operation.
5338    return CreateOverloadedBinOp(TokLoc, Opc, Functions, lhs, rhs);
5339  }
5340
5341  // Build a built-in binary operation.
5342  return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
5343}
5344
5345Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
5346                                                    unsigned OpcIn,
5347                                                    ExprArg InputArg) {
5348  UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
5349
5350  // FIXME: Input is modified below, but InputArg is not updated appropriately.
5351  Expr *Input = (Expr *)InputArg.get();
5352  QualType resultType;
5353  switch (Opc) {
5354  case UnaryOperator::OffsetOf:
5355    assert(false && "Invalid unary operator");
5356    break;
5357
5358  case UnaryOperator::PreInc:
5359  case UnaryOperator::PreDec:
5360  case UnaryOperator::PostInc:
5361  case UnaryOperator::PostDec:
5362    resultType = CheckIncrementDecrementOperand(Input, OpLoc,
5363                                                Opc == UnaryOperator::PreInc ||
5364                                                Opc == UnaryOperator::PostInc);
5365    break;
5366  case UnaryOperator::AddrOf:
5367    resultType = CheckAddressOfOperand(Input, OpLoc);
5368    break;
5369  case UnaryOperator::Deref:
5370    DefaultFunctionArrayConversion(Input);
5371    resultType = CheckIndirectionOperand(Input, OpLoc);
5372    break;
5373  case UnaryOperator::Plus:
5374  case UnaryOperator::Minus:
5375    UsualUnaryConversions(Input);
5376    resultType = Input->getType();
5377    if (resultType->isDependentType())
5378      break;
5379    if (resultType->isArithmeticType()) // C99 6.5.3.3p1
5380      break;
5381    else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
5382             resultType->isEnumeralType())
5383      break;
5384    else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
5385             Opc == UnaryOperator::Plus &&
5386             resultType->isPointerType())
5387      break;
5388
5389    return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5390      << resultType << Input->getSourceRange());
5391  case UnaryOperator::Not: // bitwise complement
5392    UsualUnaryConversions(Input);
5393    resultType = Input->getType();
5394    if (resultType->isDependentType())
5395      break;
5396    // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
5397    if (resultType->isComplexType() || resultType->isComplexIntegerType())
5398      // C99 does not support '~' for complex conjugation.
5399      Diag(OpLoc, diag::ext_integer_complement_complex)
5400        << resultType << Input->getSourceRange();
5401    else if (!resultType->isIntegerType())
5402      return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5403        << resultType << Input->getSourceRange());
5404    break;
5405  case UnaryOperator::LNot: // logical negation
5406    // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
5407    DefaultFunctionArrayConversion(Input);
5408    resultType = Input->getType();
5409    if (resultType->isDependentType())
5410      break;
5411    if (!resultType->isScalarType()) // C99 6.5.3.3p1
5412      return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5413        << resultType << Input->getSourceRange());
5414    // LNot always has type int. C99 6.5.3.3p5.
5415    // In C++, it's bool. C++ 5.3.1p8
5416    resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
5417    break;
5418  case UnaryOperator::Real:
5419  case UnaryOperator::Imag:
5420    resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
5421    break;
5422  case UnaryOperator::Extension:
5423    resultType = Input->getType();
5424    break;
5425  }
5426  if (resultType.isNull())
5427    return ExprError();
5428
5429  InputArg.release();
5430  return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
5431}
5432
5433// Unary Operators.  'Tok' is the token for the operator.
5434Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
5435                                            tok::TokenKind Op, ExprArg input) {
5436  Expr *Input = (Expr*)input.get();
5437  UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
5438
5439  if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType()) {
5440    // Find all of the overloaded operators visible from this
5441    // point. We perform both an operator-name lookup from the local
5442    // scope and an argument-dependent lookup based on the types of
5443    // the arguments.
5444    FunctionSet Functions;
5445    OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
5446    if (OverOp != OO_None) {
5447      LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
5448                                   Functions);
5449      DeclarationName OpName
5450        = Context.DeclarationNames.getCXXOperatorName(OverOp);
5451      ArgumentDependentLookup(OpName, &Input, 1, Functions);
5452    }
5453
5454    return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
5455  }
5456
5457  return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
5458}
5459
5460/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
5461Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
5462                                            SourceLocation LabLoc,
5463                                            IdentifierInfo *LabelII) {
5464  // Look up the record for this label identifier.
5465  LabelStmt *&LabelDecl = getLabelMap()[LabelII];
5466
5467  // If we haven't seen this label yet, create a forward reference. It
5468  // will be validated and/or cleaned up in ActOnFinishFunctionBody.
5469  if (LabelDecl == 0)
5470    LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
5471
5472  // Create the AST node.  The address of a label always has type 'void*'.
5473  return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
5474                                       Context.getPointerType(Context.VoidTy)));
5475}
5476
5477Sema::OwningExprResult
5478Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
5479                    SourceLocation RPLoc) { // "({..})"
5480  Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
5481  assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
5482  CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
5483
5484  bool isFileScope = getCurFunctionOrMethodDecl() == 0;
5485  if (isFileScope)
5486    return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
5487
5488  // FIXME: there are a variety of strange constraints to enforce here, for
5489  // example, it is not possible to goto into a stmt expression apparently.
5490  // More semantic analysis is needed.
5491
5492  // If there are sub stmts in the compound stmt, take the type of the last one
5493  // as the type of the stmtexpr.
5494  QualType Ty = Context.VoidTy;
5495
5496  if (!Compound->body_empty()) {
5497    Stmt *LastStmt = Compound->body_back();
5498    // If LastStmt is a label, skip down through into the body.
5499    while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
5500      LastStmt = Label->getSubStmt();
5501
5502    if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
5503      Ty = LastExpr->getType();
5504  }
5505
5506  // FIXME: Check that expression type is complete/non-abstract; statement
5507  // expressions are not lvalues.
5508
5509  substmt.release();
5510  return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
5511}
5512
5513Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
5514                                                  SourceLocation BuiltinLoc,
5515                                                  SourceLocation TypeLoc,
5516                                                  TypeTy *argty,
5517                                                  OffsetOfComponent *CompPtr,
5518                                                  unsigned NumComponents,
5519                                                  SourceLocation RPLoc) {
5520  // FIXME: This function leaks all expressions in the offset components on
5521  // error.
5522  // FIXME: Preserve type source info.
5523  QualType ArgTy = GetTypeFromParser(argty);
5524  assert(!ArgTy.isNull() && "Missing type argument!");
5525
5526  bool Dependent = ArgTy->isDependentType();
5527
5528  // We must have at least one component that refers to the type, and the first
5529  // one is known to be a field designator.  Verify that the ArgTy represents
5530  // a struct/union/class.
5531  if (!Dependent && !ArgTy->isRecordType())
5532    return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
5533
5534  // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
5535  // with an incomplete type would be illegal.
5536
5537  // Otherwise, create a null pointer as the base, and iteratively process
5538  // the offsetof designators.
5539  QualType ArgTyPtr = Context.getPointerType(ArgTy);
5540  Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
5541  Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
5542                                    ArgTy, SourceLocation());
5543
5544  // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
5545  // GCC extension, diagnose them.
5546  // FIXME: This diagnostic isn't actually visible because the location is in
5547  // a system header!
5548  if (NumComponents != 1)
5549    Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
5550      << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
5551
5552  if (!Dependent) {
5553    bool DidWarnAboutNonPOD = false;
5554
5555    // FIXME: Dependent case loses a lot of information here. And probably
5556    // leaks like a sieve.
5557    for (unsigned i = 0; i != NumComponents; ++i) {
5558      const OffsetOfComponent &OC = CompPtr[i];
5559      if (OC.isBrackets) {
5560        // Offset of an array sub-field.  TODO: Should we allow vector elements?
5561        const ArrayType *AT = Context.getAsArrayType(Res->getType());
5562        if (!AT) {
5563          Res->Destroy(Context);
5564          return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
5565            << Res->getType());
5566        }
5567
5568        // FIXME: C++: Verify that operator[] isn't overloaded.
5569
5570        // Promote the array so it looks more like a normal array subscript
5571        // expression.
5572        DefaultFunctionArrayConversion(Res);
5573
5574        // C99 6.5.2.1p1
5575        Expr *Idx = static_cast<Expr*>(OC.U.E);
5576        // FIXME: Leaks Res
5577        if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
5578          return ExprError(Diag(Idx->getLocStart(),
5579                                diag::err_typecheck_subscript_not_integer)
5580            << Idx->getSourceRange());
5581
5582        Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
5583                                               OC.LocEnd);
5584        continue;
5585      }
5586
5587      const RecordType *RC = Res->getType()->getAs<RecordType>();
5588      if (!RC) {
5589        Res->Destroy(Context);
5590        return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
5591          << Res->getType());
5592      }
5593
5594      // Get the decl corresponding to this.
5595      RecordDecl *RD = RC->getDecl();
5596      if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
5597        if (!CRD->isPOD() && !DidWarnAboutNonPOD) {
5598          ExprError(Diag(BuiltinLoc, diag::warn_offsetof_non_pod_type)
5599            << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
5600            << Res->getType());
5601          DidWarnAboutNonPOD = true;
5602        }
5603      }
5604
5605      FieldDecl *MemberDecl
5606        = dyn_cast_or_null<FieldDecl>(LookupQualifiedName(RD, OC.U.IdentInfo,
5607                                                          LookupMemberName)
5608                                        .getAsDecl());
5609      // FIXME: Leaks Res
5610      if (!MemberDecl)
5611        return ExprError(Diag(BuiltinLoc, diag::err_typecheck_no_member_deprecated)
5612         << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd));
5613
5614      // FIXME: C++: Verify that MemberDecl isn't a static field.
5615      // FIXME: Verify that MemberDecl isn't a bitfield.
5616      if (cast<RecordDecl>(MemberDecl->getDeclContext())->isAnonymousStructOrUnion()) {
5617        Res = BuildAnonymousStructUnionMemberReference(
5618            SourceLocation(), MemberDecl, Res, SourceLocation()).takeAs<Expr>();
5619      } else {
5620        // MemberDecl->getType() doesn't get the right qualifiers, but it
5621        // doesn't matter here.
5622        Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
5623                MemberDecl->getType().getNonReferenceType());
5624      }
5625    }
5626  }
5627
5628  return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
5629                                           Context.getSizeType(), BuiltinLoc));
5630}
5631
5632
5633Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
5634                                                      TypeTy *arg1,TypeTy *arg2,
5635                                                      SourceLocation RPLoc) {
5636  // FIXME: Preserve type source info.
5637  QualType argT1 = GetTypeFromParser(arg1);
5638  QualType argT2 = GetTypeFromParser(arg2);
5639
5640  assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
5641
5642  if (getLangOptions().CPlusPlus) {
5643    Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus)
5644      << SourceRange(BuiltinLoc, RPLoc);
5645    return ExprError();
5646  }
5647
5648  return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
5649                                                 argT1, argT2, RPLoc));
5650}
5651
5652Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
5653                                             ExprArg cond,
5654                                             ExprArg expr1, ExprArg expr2,
5655                                             SourceLocation RPLoc) {
5656  Expr *CondExpr = static_cast<Expr*>(cond.get());
5657  Expr *LHSExpr = static_cast<Expr*>(expr1.get());
5658  Expr *RHSExpr = static_cast<Expr*>(expr2.get());
5659
5660  assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
5661
5662  QualType resType;
5663  if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
5664    resType = Context.DependentTy;
5665  } else {
5666    // The conditional expression is required to be a constant expression.
5667    llvm::APSInt condEval(32);
5668    SourceLocation ExpLoc;
5669    if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
5670      return ExprError(Diag(ExpLoc,
5671                       diag::err_typecheck_choose_expr_requires_constant)
5672        << CondExpr->getSourceRange());
5673
5674    // If the condition is > zero, then the AST type is the same as the LSHExpr.
5675    resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
5676  }
5677
5678  cond.release(); expr1.release(); expr2.release();
5679  return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
5680                                        resType, RPLoc));
5681}
5682
5683//===----------------------------------------------------------------------===//
5684// Clang Extensions.
5685//===----------------------------------------------------------------------===//
5686
5687/// ActOnBlockStart - This callback is invoked when a block literal is started.
5688void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
5689  // Analyze block parameters.
5690  BlockSemaInfo *BSI = new BlockSemaInfo();
5691
5692  // Add BSI to CurBlock.
5693  BSI->PrevBlockInfo = CurBlock;
5694  CurBlock = BSI;
5695
5696  BSI->ReturnType = QualType();
5697  BSI->TheScope = BlockScope;
5698  BSI->hasBlockDeclRefExprs = false;
5699  BSI->hasPrototype = false;
5700  BSI->SavedFunctionNeedsScopeChecking = CurFunctionNeedsScopeChecking;
5701  CurFunctionNeedsScopeChecking = false;
5702
5703  BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
5704  PushDeclContext(BlockScope, BSI->TheDecl);
5705}
5706
5707void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
5708  assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
5709
5710  if (ParamInfo.getNumTypeObjects() == 0
5711      || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
5712    ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
5713    QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
5714
5715    if (T->isArrayType()) {
5716      Diag(ParamInfo.getSourceRange().getBegin(),
5717           diag::err_block_returns_array);
5718      return;
5719    }
5720
5721    // The parameter list is optional, if there was none, assume ().
5722    if (!T->isFunctionType())
5723      T = Context.getFunctionType(T, NULL, 0, 0, 0);
5724
5725    CurBlock->hasPrototype = true;
5726    CurBlock->isVariadic = false;
5727    // Check for a valid sentinel attribute on this block.
5728    if (CurBlock->TheDecl->getAttr<SentinelAttr>()) {
5729      Diag(ParamInfo.getAttributes()->getLoc(),
5730           diag::warn_attribute_sentinel_not_variadic) << 1;
5731      // FIXME: remove the attribute.
5732    }
5733    QualType RetTy = T.getTypePtr()->getAsFunctionType()->getResultType();
5734
5735    // Do not allow returning a objc interface by-value.
5736    if (RetTy->isObjCInterfaceType()) {
5737      Diag(ParamInfo.getSourceRange().getBegin(),
5738           diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
5739      return;
5740    }
5741    return;
5742  }
5743
5744  // Analyze arguments to block.
5745  assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
5746         "Not a function declarator!");
5747  DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
5748
5749  CurBlock->hasPrototype = FTI.hasPrototype;
5750  CurBlock->isVariadic = true;
5751
5752  // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
5753  // no arguments, not a function that takes a single void argument.
5754  if (FTI.hasPrototype &&
5755      FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5756     (!FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType().getCVRQualifiers()&&
5757        FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType())) {
5758    // empty arg list, don't push any params.
5759    CurBlock->isVariadic = false;
5760  } else if (FTI.hasPrototype) {
5761    for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
5762      CurBlock->Params.push_back(FTI.ArgInfo[i].Param.getAs<ParmVarDecl>());
5763    CurBlock->isVariadic = FTI.isVariadic;
5764  }
5765  CurBlock->TheDecl->setParams(Context, CurBlock->Params.data(),
5766                               CurBlock->Params.size());
5767  CurBlock->TheDecl->setIsVariadic(CurBlock->isVariadic);
5768  ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
5769  for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
5770       E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
5771    // If this has an identifier, add it to the scope stack.
5772    if ((*AI)->getIdentifier())
5773      PushOnScopeChains(*AI, CurBlock->TheScope);
5774
5775  // Check for a valid sentinel attribute on this block.
5776  if (!CurBlock->isVariadic &&
5777      CurBlock->TheDecl->getAttr<SentinelAttr>()) {
5778    Diag(ParamInfo.getAttributes()->getLoc(),
5779         diag::warn_attribute_sentinel_not_variadic) << 1;
5780    // FIXME: remove the attribute.
5781  }
5782
5783  // Analyze the return type.
5784  QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
5785  QualType RetTy = T->getAsFunctionType()->getResultType();
5786
5787  // Do not allow returning a objc interface by-value.
5788  if (RetTy->isObjCInterfaceType()) {
5789    Diag(ParamInfo.getSourceRange().getBegin(),
5790         diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
5791  } else if (!RetTy->isDependentType())
5792    CurBlock->ReturnType = RetTy;
5793}
5794
5795/// ActOnBlockError - If there is an error parsing a block, this callback
5796/// is invoked to pop the information about the block from the action impl.
5797void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
5798  // Ensure that CurBlock is deleted.
5799  llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
5800
5801  CurFunctionNeedsScopeChecking = CurBlock->SavedFunctionNeedsScopeChecking;
5802
5803  // Pop off CurBlock, handle nested blocks.
5804  PopDeclContext();
5805  CurBlock = CurBlock->PrevBlockInfo;
5806  // FIXME: Delete the ParmVarDecl objects as well???
5807}
5808
5809/// ActOnBlockStmtExpr - This is called when the body of a block statement
5810/// literal was successfully completed.  ^(int x){...}
5811Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
5812                                                StmtArg body, Scope *CurScope) {
5813  // If blocks are disabled, emit an error.
5814  if (!LangOpts.Blocks)
5815    Diag(CaretLoc, diag::err_blocks_disable);
5816
5817  // Ensure that CurBlock is deleted.
5818  llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
5819
5820  PopDeclContext();
5821
5822  // Pop off CurBlock, handle nested blocks.
5823  CurBlock = CurBlock->PrevBlockInfo;
5824
5825  QualType RetTy = Context.VoidTy;
5826  if (!BSI->ReturnType.isNull())
5827    RetTy = BSI->ReturnType;
5828
5829  llvm::SmallVector<QualType, 8> ArgTypes;
5830  for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
5831    ArgTypes.push_back(BSI->Params[i]->getType());
5832
5833  bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
5834  QualType BlockTy;
5835  if (!BSI->hasPrototype)
5836    BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0, false, false, 0, 0,
5837                                      NoReturn);
5838  else
5839    BlockTy = Context.getFunctionType(RetTy, ArgTypes.data(), ArgTypes.size(),
5840                                      BSI->isVariadic, 0, false, false, 0, 0,
5841                                      NoReturn);
5842
5843  // FIXME: Check that return/parameter types are complete/non-abstract
5844  DiagnoseUnusedParameters(BSI->Params.begin(), BSI->Params.end());
5845  BlockTy = Context.getBlockPointerType(BlockTy);
5846
5847  // If needed, diagnose invalid gotos and switches in the block.
5848  if (CurFunctionNeedsScopeChecking)
5849    DiagnoseInvalidJumps(static_cast<CompoundStmt*>(body.get()));
5850  CurFunctionNeedsScopeChecking = BSI->SavedFunctionNeedsScopeChecking;
5851
5852  BSI->TheDecl->setBody(body.takeAs<CompoundStmt>());
5853  CheckFallThroughForBlock(BlockTy, BSI->TheDecl->getBody());
5854  return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy,
5855                                       BSI->hasBlockDeclRefExprs));
5856}
5857
5858Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
5859                                        ExprArg expr, TypeTy *type,
5860                                        SourceLocation RPLoc) {
5861  QualType T = GetTypeFromParser(type);
5862  Expr *E = static_cast<Expr*>(expr.get());
5863  Expr *OrigExpr = E;
5864
5865  InitBuiltinVaListType();
5866
5867  // Get the va_list type
5868  QualType VaListType = Context.getBuiltinVaListType();
5869  if (VaListType->isArrayType()) {
5870    // Deal with implicit array decay; for example, on x86-64,
5871    // va_list is an array, but it's supposed to decay to
5872    // a pointer for va_arg.
5873    VaListType = Context.getArrayDecayedType(VaListType);
5874    // Make sure the input expression also decays appropriately.
5875    UsualUnaryConversions(E);
5876  } else {
5877    // Otherwise, the va_list argument must be an l-value because
5878    // it is modified by va_arg.
5879    if (!E->isTypeDependent() &&
5880        CheckForModifiableLvalue(E, BuiltinLoc, *this))
5881      return ExprError();
5882  }
5883
5884  if (!E->isTypeDependent() &&
5885      !Context.hasSameType(VaListType, E->getType())) {
5886    return ExprError(Diag(E->getLocStart(),
5887                         diag::err_first_argument_to_va_arg_not_of_type_va_list)
5888      << OrigExpr->getType() << E->getSourceRange());
5889  }
5890
5891  // FIXME: Check that type is complete/non-abstract
5892  // FIXME: Warn if a non-POD type is passed in.
5893
5894  expr.release();
5895  return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
5896                                       RPLoc));
5897}
5898
5899Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
5900  // The type of __null will be int or long, depending on the size of
5901  // pointers on the target.
5902  QualType Ty;
5903  if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
5904    Ty = Context.IntTy;
5905  else
5906    Ty = Context.LongTy;
5907
5908  return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
5909}
5910
5911bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
5912                                    SourceLocation Loc,
5913                                    QualType DstType, QualType SrcType,
5914                                    Expr *SrcExpr, const char *Flavor) {
5915  // Decode the result (notice that AST's are still created for extensions).
5916  bool isInvalid = false;
5917  unsigned DiagKind;
5918  switch (ConvTy) {
5919  default: assert(0 && "Unknown conversion type");
5920  case Compatible: return false;
5921  case PointerToInt:
5922    DiagKind = diag::ext_typecheck_convert_pointer_int;
5923    break;
5924  case IntToPointer:
5925    DiagKind = diag::ext_typecheck_convert_int_pointer;
5926    break;
5927  case IncompatiblePointer:
5928    DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
5929    break;
5930  case IncompatiblePointerSign:
5931    DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
5932    break;
5933  case FunctionVoidPointer:
5934    DiagKind = diag::ext_typecheck_convert_pointer_void_func;
5935    break;
5936  case CompatiblePointerDiscardsQualifiers:
5937    // If the qualifiers lost were because we were applying the
5938    // (deprecated) C++ conversion from a string literal to a char*
5939    // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
5940    // Ideally, this check would be performed in
5941    // CheckPointerTypesForAssignment. However, that would require a
5942    // bit of refactoring (so that the second argument is an
5943    // expression, rather than a type), which should be done as part
5944    // of a larger effort to fix CheckPointerTypesForAssignment for
5945    // C++ semantics.
5946    if (getLangOptions().CPlusPlus &&
5947        IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
5948      return false;
5949    DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
5950    break;
5951  case IntToBlockPointer:
5952    DiagKind = diag::err_int_to_block_pointer;
5953    break;
5954  case IncompatibleBlockPointer:
5955    DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
5956    break;
5957  case IncompatibleObjCQualifiedId:
5958    // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
5959    // it can give a more specific diagnostic.
5960    DiagKind = diag::warn_incompatible_qualified_id;
5961    break;
5962  case IncompatibleVectors:
5963    DiagKind = diag::warn_incompatible_vectors;
5964    break;
5965  case Incompatible:
5966    DiagKind = diag::err_typecheck_convert_incompatible;
5967    isInvalid = true;
5968    break;
5969  }
5970
5971  Diag(Loc, DiagKind) << DstType << SrcType << Flavor
5972    << SrcExpr->getSourceRange();
5973  return isInvalid;
5974}
5975
5976bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
5977  llvm::APSInt ICEResult;
5978  if (E->isIntegerConstantExpr(ICEResult, Context)) {
5979    if (Result)
5980      *Result = ICEResult;
5981    return false;
5982  }
5983
5984  Expr::EvalResult EvalResult;
5985
5986  if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
5987      EvalResult.HasSideEffects) {
5988    Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
5989
5990    if (EvalResult.Diag) {
5991      // We only show the note if it's not the usual "invalid subexpression"
5992      // or if it's actually in a subexpression.
5993      if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
5994          E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
5995        Diag(EvalResult.DiagLoc, EvalResult.Diag);
5996    }
5997
5998    return true;
5999  }
6000
6001  Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
6002    E->getSourceRange();
6003
6004  if (EvalResult.Diag &&
6005      Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
6006    Diag(EvalResult.DiagLoc, EvalResult.Diag);
6007
6008  if (Result)
6009    *Result = EvalResult.Val.getInt();
6010  return false;
6011}
6012
6013Sema::ExpressionEvaluationContext
6014Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
6015  // Introduce a new set of potentially referenced declarations to the stack.
6016  if (NewContext == PotentiallyPotentiallyEvaluated)
6017    PotentiallyReferencedDeclStack.push_back(PotentiallyReferencedDecls());
6018
6019  std::swap(ExprEvalContext, NewContext);
6020  return NewContext;
6021}
6022
6023void
6024Sema::PopExpressionEvaluationContext(ExpressionEvaluationContext OldContext,
6025                                     ExpressionEvaluationContext NewContext) {
6026  ExprEvalContext = NewContext;
6027
6028  if (OldContext == PotentiallyPotentiallyEvaluated) {
6029    // Mark any remaining declarations in the current position of the stack
6030    // as "referenced". If they were not meant to be referenced, semantic
6031    // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
6032    PotentiallyReferencedDecls RemainingDecls;
6033    RemainingDecls.swap(PotentiallyReferencedDeclStack.back());
6034    PotentiallyReferencedDeclStack.pop_back();
6035
6036    for (PotentiallyReferencedDecls::iterator I = RemainingDecls.begin(),
6037                                           IEnd = RemainingDecls.end();
6038         I != IEnd; ++I)
6039      MarkDeclarationReferenced(I->first, I->second);
6040  }
6041}
6042
6043/// \brief Note that the given declaration was referenced in the source code.
6044///
6045/// This routine should be invoke whenever a given declaration is referenced
6046/// in the source code, and where that reference occurred. If this declaration
6047/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
6048/// C99 6.9p3), then the declaration will be marked as used.
6049///
6050/// \param Loc the location where the declaration was referenced.
6051///
6052/// \param D the declaration that has been referenced by the source code.
6053void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
6054  assert(D && "No declaration?");
6055
6056  if (D->isUsed())
6057    return;
6058
6059  // Mark a parameter declaration "used", regardless of whether we're in a
6060  // template or not.
6061  if (isa<ParmVarDecl>(D))
6062    D->setUsed(true);
6063
6064  // Do not mark anything as "used" within a dependent context; wait for
6065  // an instantiation.
6066  if (CurContext->isDependentContext())
6067    return;
6068
6069  switch (ExprEvalContext) {
6070    case Unevaluated:
6071      // We are in an expression that is not potentially evaluated; do nothing.
6072      return;
6073
6074    case PotentiallyEvaluated:
6075      // We are in a potentially-evaluated expression, so this declaration is
6076      // "used"; handle this below.
6077      break;
6078
6079    case PotentiallyPotentiallyEvaluated:
6080      // We are in an expression that may be potentially evaluated; queue this
6081      // declaration reference until we know whether the expression is
6082      // potentially evaluated.
6083      PotentiallyReferencedDeclStack.back().push_back(std::make_pair(Loc, D));
6084      return;
6085  }
6086
6087  // Note that this declaration has been used.
6088  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
6089    unsigned TypeQuals;
6090    if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
6091        if (!Constructor->isUsed())
6092          DefineImplicitDefaultConstructor(Loc, Constructor);
6093    } else if (Constructor->isImplicit() &&
6094               Constructor->isCopyConstructor(Context, TypeQuals)) {
6095      if (!Constructor->isUsed())
6096        DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
6097    }
6098  } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
6099    if (Destructor->isImplicit() && !Destructor->isUsed())
6100      DefineImplicitDestructor(Loc, Destructor);
6101
6102  } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
6103    if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
6104        MethodDecl->getOverloadedOperator() == OO_Equal) {
6105      if (!MethodDecl->isUsed())
6106        DefineImplicitOverloadedAssign(Loc, MethodDecl);
6107    }
6108  }
6109  if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
6110    // Implicit instantiation of function templates and member functions of
6111    // class templates.
6112    if (!Function->getBody()) {
6113      // FIXME: distinguish between implicit instantiations of function
6114      // templates and explicit specializations (the latter don't get
6115      // instantiated, naturally).
6116      if (Function->getInstantiatedFromMemberFunction() ||
6117          Function->getPrimaryTemplate())
6118        PendingImplicitInstantiations.push_back(std::make_pair(Function, Loc));
6119    }
6120
6121
6122    // FIXME: keep track of references to static functions
6123    Function->setUsed(true);
6124    return;
6125  }
6126
6127  if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
6128    // Implicit instantiation of static data members of class templates.
6129    // FIXME: distinguish between implicit instantiations (which we need to
6130    // actually instantiate) and explicit specializations.
6131    // FIXME: extern templates
6132    if (Var->isStaticDataMember() &&
6133        Var->getInstantiatedFromStaticDataMember())
6134      PendingImplicitInstantiations.push_back(std::make_pair(Var, Loc));
6135
6136    // FIXME: keep track of references to static data?
6137
6138    D->setUsed(true);
6139    return;
6140  }
6141}
6142
6143