SemaExpr.cpp revision 7bc38e309657a5b406c2a66addc6bd1806f2e8a9
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()->getAs<FunctionType>()
136      : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
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->getAs<BuiltinType>())
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->getAs<FunctionProtoType>())
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()->getAs<ComplexType>())
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()->getAs<FunctionType>()->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()->getAs<FunctionType>()->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->getAs<ObjCObjectPointerType>()) {
1763    BaseExpr = LHSExp;
1764    IndexExpr = RHSExp;
1765    ResultType = PTy->getPointeeType();
1766  } else if (const ObjCObjectPointerType *PTy =
1767               RHSTy->getAs<ObjCObjectPointerType>()) {
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->getAs<VectorType>()) {
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  if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
1813       IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
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->getAs<ExtVectorType>();
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->getAs<ObjCObjectPointerType>();
2359    const ObjCInterfaceType *IFaceT =
2360      OPT ? OPT->getInterfaceType() : BaseType->getAs<ObjCInterfaceType>();
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->getAs<ObjCObjectPointerType>();
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/// \brief "Deconstruct" the function argument of a call expression to find
2738/// the underlying declaration (if any), the name of the called function,
2739/// whether argument-dependent lookup is available, whether it has explicit
2740/// template arguments, etc.
2741void Sema::DeconstructCallFunction(Expr *FnExpr,
2742                                   NamedDecl *&Function,
2743                                   DeclarationName &Name,
2744                                   NestedNameSpecifier *&Qualifier,
2745                                   SourceRange &QualifierRange,
2746                                   bool &ArgumentDependentLookup,
2747                                   bool &HasExplicitTemplateArguments,
2748                                 const TemplateArgument *&ExplicitTemplateArgs,
2749                                   unsigned &NumExplicitTemplateArgs) {
2750  // Set defaults for all of the output parameters.
2751  Function = 0;
2752  Name = DeclarationName();
2753  Qualifier = 0;
2754  QualifierRange = SourceRange();
2755  ArgumentDependentLookup = getLangOptions().CPlusPlus;
2756  HasExplicitTemplateArguments = false;
2757
2758  // If we're directly calling a function, get the appropriate declaration.
2759  // Also, in C++, keep track of whether we should perform argument-dependent
2760  // lookup and whether there were any explicitly-specified template arguments.
2761  while (true) {
2762    if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
2763      FnExpr = IcExpr->getSubExpr();
2764    else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
2765      // Parentheses around a function disable ADL
2766      // (C++0x [basic.lookup.argdep]p1).
2767      ArgumentDependentLookup = false;
2768      FnExpr = PExpr->getSubExpr();
2769    } else if (isa<UnaryOperator>(FnExpr) &&
2770               cast<UnaryOperator>(FnExpr)->getOpcode()
2771               == UnaryOperator::AddrOf) {
2772      FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
2773    } else if (QualifiedDeclRefExpr *QDRExpr
2774                 = dyn_cast<QualifiedDeclRefExpr>(FnExpr)) {
2775      // Qualified names disable ADL (C++0x [basic.lookup.argdep]p1).
2776      ArgumentDependentLookup = false;
2777      Qualifier = QDRExpr->getQualifier();
2778      QualifierRange = QDRExpr->getQualifierRange();
2779      Function = dyn_cast<NamedDecl>(QDRExpr->getDecl());
2780      break;
2781    } else if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(FnExpr)) {
2782      Function = dyn_cast<NamedDecl>(DRExpr->getDecl());
2783      break;
2784    } else if (UnresolvedFunctionNameExpr *DepName
2785               = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr)) {
2786      Name = DepName->getName();
2787      break;
2788    } else if (TemplateIdRefExpr *TemplateIdRef
2789               = dyn_cast<TemplateIdRefExpr>(FnExpr)) {
2790      Function = TemplateIdRef->getTemplateName().getAsTemplateDecl();
2791      if (!Function)
2792        Function = TemplateIdRef->getTemplateName().getAsOverloadedFunctionDecl();
2793      HasExplicitTemplateArguments = true;
2794      ExplicitTemplateArgs = TemplateIdRef->getTemplateArgs();
2795      NumExplicitTemplateArgs = TemplateIdRef->getNumTemplateArgs();
2796
2797      // C++ [temp.arg.explicit]p6:
2798      //   [Note: For simple function names, argument dependent lookup (3.4.2)
2799      //   applies even when the function name is not visible within the
2800      //   scope of the call. This is because the call still has the syntactic
2801      //   form of a function call (3.4.1). But when a function template with
2802      //   explicit template arguments is used, the call does not have the
2803      //   correct syntactic form unless there is a function template with
2804      //   that name visible at the point of the call. If no such name is
2805      //   visible, the call is not syntactically well-formed and
2806      //   argument-dependent lookup does not apply. If some such name is
2807      //   visible, argument dependent lookup applies and additional function
2808      //   templates may be found in other namespaces.
2809      //
2810      // The summary of this paragraph is that, if we get to this point and the
2811      // template-id was not a qualified name, then argument-dependent lookup
2812      // is still possible.
2813      if ((Qualifier = TemplateIdRef->getQualifier())) {
2814        ArgumentDependentLookup = false;
2815        QualifierRange = TemplateIdRef->getQualifierRange();
2816      }
2817      break;
2818    } else {
2819      // Any kind of name that does not refer to a declaration (or
2820      // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3).
2821      ArgumentDependentLookup = false;
2822      break;
2823    }
2824  }
2825}
2826
2827/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
2828/// This provides the location of the left/right parens and a list of comma
2829/// locations.
2830Action::OwningExprResult
2831Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
2832                    MultiExprArg args,
2833                    SourceLocation *CommaLocs, SourceLocation RParenLoc) {
2834  unsigned NumArgs = args.size();
2835
2836  // Since this might be a postfix expression, get rid of ParenListExprs.
2837  fn = MaybeConvertParenListExprToParenExpr(S, move(fn));
2838
2839  Expr *Fn = fn.takeAs<Expr>();
2840  Expr **Args = reinterpret_cast<Expr**>(args.release());
2841  assert(Fn && "no function call expression");
2842  FunctionDecl *FDecl = NULL;
2843  NamedDecl *NDecl = NULL;
2844  DeclarationName UnqualifiedName;
2845
2846  if (getLangOptions().CPlusPlus) {
2847    // If this is a pseudo-destructor expression, build the call immediately.
2848    if (isa<CXXPseudoDestructorExpr>(Fn)) {
2849      if (NumArgs > 0) {
2850        // Pseudo-destructor calls should not have any arguments.
2851        Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
2852          << CodeModificationHint::CreateRemoval(
2853                                    SourceRange(Args[0]->getLocStart(),
2854                                                Args[NumArgs-1]->getLocEnd()));
2855
2856        for (unsigned I = 0; I != NumArgs; ++I)
2857          Args[I]->Destroy(Context);
2858
2859        NumArgs = 0;
2860      }
2861
2862      return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
2863                                          RParenLoc));
2864    }
2865
2866    // Determine whether this is a dependent call inside a C++ template,
2867    // in which case we won't do any semantic analysis now.
2868    // FIXME: Will need to cache the results of name lookup (including ADL) in
2869    // Fn.
2870    bool Dependent = false;
2871    if (Fn->isTypeDependent())
2872      Dependent = true;
2873    else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
2874      Dependent = true;
2875
2876    if (Dependent)
2877      return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
2878                                          Context.DependentTy, RParenLoc));
2879
2880    // Determine whether this is a call to an object (C++ [over.call.object]).
2881    if (Fn->getType()->isRecordType())
2882      return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
2883                                                CommaLocs, RParenLoc));
2884
2885    // Determine whether this is a call to a member function.
2886    if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens())) {
2887      NamedDecl *MemDecl = MemExpr->getMemberDecl();
2888      if (isa<OverloadedFunctionDecl>(MemDecl) ||
2889          isa<CXXMethodDecl>(MemDecl) ||
2890          (isa<FunctionTemplateDecl>(MemDecl) &&
2891           isa<CXXMethodDecl>(
2892                cast<FunctionTemplateDecl>(MemDecl)->getTemplatedDecl())))
2893        return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
2894                                               CommaLocs, RParenLoc));
2895    }
2896  }
2897
2898  // If we're directly calling a function, get the appropriate declaration.
2899  // Also, in C++, keep track of whether we should perform argument-dependent
2900  // lookup and whether there were any explicitly-specified template arguments.
2901  bool ADL = true;
2902  bool HasExplicitTemplateArgs = 0;
2903  const TemplateArgument *ExplicitTemplateArgs = 0;
2904  unsigned NumExplicitTemplateArgs = 0;
2905  NestedNameSpecifier *Qualifier = 0;
2906  SourceRange QualifierRange;
2907  DeconstructCallFunction(Fn, NDecl, UnqualifiedName, Qualifier, QualifierRange,
2908                          ADL,HasExplicitTemplateArgs, ExplicitTemplateArgs,
2909                          NumExplicitTemplateArgs);
2910
2911  OverloadedFunctionDecl *Ovl = 0;
2912  FunctionTemplateDecl *FunctionTemplate = 0;
2913  if (NDecl) {
2914    FDecl = dyn_cast<FunctionDecl>(NDecl);
2915    if ((FunctionTemplate = dyn_cast<FunctionTemplateDecl>(NDecl)))
2916      FDecl = FunctionTemplate->getTemplatedDecl();
2917    else
2918      FDecl = dyn_cast<FunctionDecl>(NDecl);
2919    Ovl = dyn_cast<OverloadedFunctionDecl>(NDecl);
2920  }
2921
2922  if (Ovl || FunctionTemplate ||
2923      (getLangOptions().CPlusPlus && (FDecl || UnqualifiedName))) {
2924    // We don't perform ADL for implicit declarations of builtins.
2925    if (FDecl && FDecl->getBuiltinID() && FDecl->isImplicit())
2926      ADL = false;
2927
2928    // We don't perform ADL in C.
2929    if (!getLangOptions().CPlusPlus)
2930      ADL = false;
2931
2932    if (Ovl || FunctionTemplate || ADL) {
2933      FDecl = ResolveOverloadedCallFn(Fn, NDecl, UnqualifiedName,
2934                                      HasExplicitTemplateArgs,
2935                                      ExplicitTemplateArgs,
2936                                      NumExplicitTemplateArgs,
2937                                      LParenLoc, Args, NumArgs, CommaLocs,
2938                                      RParenLoc, ADL);
2939      if (!FDecl)
2940        return ExprError();
2941
2942      // Update Fn to refer to the actual function selected.
2943      Expr *NewFn = 0;
2944      if (Qualifier)
2945        NewFn = new (Context) QualifiedDeclRefExpr(FDecl, FDecl->getType(),
2946                                                   Fn->getLocStart(),
2947                                                   false, false,
2948                                                   QualifierRange,
2949                                                   Qualifier);
2950      else
2951        NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(),
2952                                          Fn->getLocStart());
2953      Fn->Destroy(Context);
2954      Fn = NewFn;
2955    }
2956  }
2957
2958  // Promote the function operand.
2959  UsualUnaryConversions(Fn);
2960
2961  // Make the call expr early, before semantic checks.  This guarantees cleanup
2962  // of arguments and function on error.
2963  ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
2964                                                               Args, NumArgs,
2965                                                               Context.BoolTy,
2966                                                               RParenLoc));
2967
2968  const FunctionType *FuncT;
2969  if (!Fn->getType()->isBlockPointerType()) {
2970    // C99 6.5.2.2p1 - "The expression that denotes the called function shall
2971    // have type pointer to function".
2972    const PointerType *PT = Fn->getType()->getAs<PointerType>();
2973    if (PT == 0)
2974      return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2975        << Fn->getType() << Fn->getSourceRange());
2976    FuncT = PT->getPointeeType()->getAs<FunctionType>();
2977  } else { // This is a block call.
2978    FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
2979                getAs<FunctionType>();
2980  }
2981  if (FuncT == 0)
2982    return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2983      << Fn->getType() << Fn->getSourceRange());
2984
2985  // Check for a valid return type
2986  if (!FuncT->getResultType()->isVoidType() &&
2987      RequireCompleteType(Fn->getSourceRange().getBegin(),
2988                          FuncT->getResultType(),
2989                          PDiag(diag::err_call_incomplete_return)
2990                            << TheCall->getSourceRange()))
2991    return ExprError();
2992
2993  // We know the result type of the call, set it.
2994  TheCall->setType(FuncT->getResultType().getNonReferenceType());
2995
2996  if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
2997    if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
2998                                RParenLoc))
2999      return ExprError();
3000  } else {
3001    assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
3002
3003    if (FDecl) {
3004      // Check if we have too few/too many template arguments, based
3005      // on our knowledge of the function definition.
3006      const FunctionDecl *Def = 0;
3007      if (FDecl->getBody(Def) && NumArgs != Def->param_size()) {
3008        const FunctionProtoType *Proto =
3009            Def->getType()->getAs<FunctionProtoType>();
3010        if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) {
3011          Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
3012            << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
3013        }
3014      }
3015    }
3016
3017    // Promote the arguments (C99 6.5.2.2p6).
3018    for (unsigned i = 0; i != NumArgs; i++) {
3019      Expr *Arg = Args[i];
3020      DefaultArgumentPromotion(Arg);
3021      if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3022                              Arg->getType(),
3023                              PDiag(diag::err_call_incomplete_argument)
3024                                << Arg->getSourceRange()))
3025        return ExprError();
3026      TheCall->setArg(i, Arg);
3027    }
3028  }
3029
3030  if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3031    if (!Method->isStatic())
3032      return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3033        << Fn->getSourceRange());
3034
3035  // Check for sentinels
3036  if (NDecl)
3037    DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
3038
3039  // Do special checking on direct calls to functions.
3040  if (FDecl) {
3041    if (CheckFunctionCall(FDecl, TheCall.get()))
3042      return ExprError();
3043
3044    if (unsigned BuiltinID = FDecl->getBuiltinID())
3045      return CheckBuiltinFunctionCall(BuiltinID, TheCall.take());
3046  } else if (NDecl) {
3047    if (CheckBlockCall(NDecl, TheCall.get()))
3048      return ExprError();
3049  }
3050
3051  return MaybeBindToTemporary(TheCall.take());
3052}
3053
3054Action::OwningExprResult
3055Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
3056                           SourceLocation RParenLoc, ExprArg InitExpr) {
3057  assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
3058  //FIXME: Preserve type source info.
3059  QualType literalType = GetTypeFromParser(Ty);
3060  // FIXME: put back this assert when initializers are worked out.
3061  //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
3062  Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
3063
3064  if (literalType->isArrayType()) {
3065    if (literalType->isVariableArrayType())
3066      return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
3067        << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
3068  } else if (!literalType->isDependentType() &&
3069             RequireCompleteType(LParenLoc, literalType,
3070                      PDiag(diag::err_typecheck_decl_incomplete_type)
3071                        << SourceRange(LParenLoc,
3072                                       literalExpr->getSourceRange().getEnd())))
3073    return ExprError();
3074
3075  if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
3076                            DeclarationName(), /*FIXME:DirectInit=*/false))
3077    return ExprError();
3078
3079  bool isFileScope = getCurFunctionOrMethodDecl() == 0;
3080  if (isFileScope) { // 6.5.2.5p3
3081    if (CheckForConstantInitializer(literalExpr, literalType))
3082      return ExprError();
3083  }
3084  InitExpr.release();
3085  return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
3086                                                 literalExpr, isFileScope));
3087}
3088
3089Action::OwningExprResult
3090Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
3091                    SourceLocation RBraceLoc) {
3092  unsigned NumInit = initlist.size();
3093  Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
3094
3095  // Semantic analysis for initializers is done by ActOnDeclarator() and
3096  // CheckInitializer() - it requires knowledge of the object being intialized.
3097
3098  InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
3099                                               RBraceLoc);
3100  E->setType(Context.VoidTy); // FIXME: just a place holder for now.
3101  return Owned(E);
3102}
3103
3104/// CheckCastTypes - Check type constraints for casting between types.
3105bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr,
3106                          CastExpr::CastKind& Kind,
3107                          CXXMethodDecl *& ConversionDecl,
3108                          bool FunctionalStyle) {
3109  if (getLangOptions().CPlusPlus)
3110    return CXXCheckCStyleCast(TyR, castType, castExpr, Kind, FunctionalStyle,
3111                              ConversionDecl);
3112
3113  DefaultFunctionArrayConversion(castExpr);
3114
3115  // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
3116  // type needs to be scalar.
3117  if (castType->isVoidType()) {
3118    // Cast to void allows any expr type.
3119  } else if (!castType->isScalarType() && !castType->isVectorType()) {
3120    if (Context.getCanonicalType(castType).getUnqualifiedType() ==
3121        Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
3122        (castType->isStructureType() || castType->isUnionType())) {
3123      // GCC struct/union extension: allow cast to self.
3124      // FIXME: Check that the cast destination type is complete.
3125      Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
3126        << castType << castExpr->getSourceRange();
3127      Kind = CastExpr::CK_NoOp;
3128    } else if (castType->isUnionType()) {
3129      // GCC cast to union extension
3130      RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
3131      RecordDecl::field_iterator Field, FieldEnd;
3132      for (Field = RD->field_begin(), FieldEnd = RD->field_end();
3133           Field != FieldEnd; ++Field) {
3134        if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
3135            Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
3136          Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
3137            << castExpr->getSourceRange();
3138          break;
3139        }
3140      }
3141      if (Field == FieldEnd)
3142        return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
3143          << castExpr->getType() << castExpr->getSourceRange();
3144      Kind = CastExpr::CK_ToUnion;
3145    } else {
3146      // Reject any other conversions to non-scalar types.
3147      return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
3148        << castType << castExpr->getSourceRange();
3149    }
3150  } else if (!castExpr->getType()->isScalarType() &&
3151             !castExpr->getType()->isVectorType()) {
3152    return Diag(castExpr->getLocStart(),
3153                diag::err_typecheck_expect_scalar_operand)
3154      << castExpr->getType() << castExpr->getSourceRange();
3155  } else if (castType->isExtVectorType()) {
3156    if (CheckExtVectorCast(TyR, castType, castExpr->getType()))
3157      return true;
3158  } else if (castType->isVectorType()) {
3159    if (CheckVectorCast(TyR, castType, castExpr->getType()))
3160      return true;
3161  } else if (castExpr->getType()->isVectorType()) {
3162    if (CheckVectorCast(TyR, castExpr->getType(), castType))
3163      return true;
3164  } else if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr)) {
3165    return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR;
3166  } else if (!castType->isArithmeticType()) {
3167    QualType castExprType = castExpr->getType();
3168    if (!castExprType->isIntegralType() && castExprType->isArithmeticType())
3169      return Diag(castExpr->getLocStart(),
3170                  diag::err_cast_pointer_from_non_pointer_int)
3171        << castExprType << castExpr->getSourceRange();
3172  } else if (!castExpr->getType()->isArithmeticType()) {
3173    if (!castType->isIntegralType() && castType->isArithmeticType())
3174      return Diag(castExpr->getLocStart(),
3175                  diag::err_cast_pointer_to_non_pointer_int)
3176        << castType << castExpr->getSourceRange();
3177  }
3178  if (isa<ObjCSelectorExpr>(castExpr))
3179    return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
3180  return false;
3181}
3182
3183bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
3184  assert(VectorTy->isVectorType() && "Not a vector type!");
3185
3186  if (Ty->isVectorType() || Ty->isIntegerType()) {
3187    if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
3188      return Diag(R.getBegin(),
3189                  Ty->isVectorType() ?
3190                  diag::err_invalid_conversion_between_vectors :
3191                  diag::err_invalid_conversion_between_vector_and_integer)
3192        << VectorTy << Ty << R;
3193  } else
3194    return Diag(R.getBegin(),
3195                diag::err_invalid_conversion_between_vector_and_scalar)
3196      << VectorTy << Ty << R;
3197
3198  return false;
3199}
3200
3201bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, QualType SrcTy) {
3202  assert(DestTy->isExtVectorType() && "Not an extended vector type!");
3203
3204  // If SrcTy is a VectorType, the total size must match to explicitly cast to
3205  // an ExtVectorType.
3206  if (SrcTy->isVectorType()) {
3207    if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
3208      return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
3209        << DestTy << SrcTy << R;
3210    return false;
3211  }
3212
3213  // All non-pointer scalars can be cast to ExtVector type.  The appropriate
3214  // conversion will take place first from scalar to elt type, and then
3215  // splat from elt type to vector.
3216  if (SrcTy->isPointerType())
3217    return Diag(R.getBegin(),
3218                diag::err_invalid_conversion_between_vector_and_scalar)
3219      << DestTy << SrcTy << R;
3220  return false;
3221}
3222
3223Action::OwningExprResult
3224Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, TypeTy *Ty,
3225                    SourceLocation RParenLoc, ExprArg Op) {
3226  CastExpr::CastKind Kind = CastExpr::CK_Unknown;
3227
3228  assert((Ty != 0) && (Op.get() != 0) &&
3229         "ActOnCastExpr(): missing type or expr");
3230
3231  Expr *castExpr = (Expr *)Op.get();
3232  //FIXME: Preserve type source info.
3233  QualType castType = GetTypeFromParser(Ty);
3234
3235  // If the Expr being casted is a ParenListExpr, handle it specially.
3236  if (isa<ParenListExpr>(castExpr))
3237    return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, move(Op),castType);
3238  CXXMethodDecl *Method = 0;
3239  if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr,
3240                     Kind, Method))
3241    return ExprError();
3242
3243  if (Method) {
3244    OwningExprResult CastArg = BuildCXXCastArgument(LParenLoc, castType, Kind,
3245                                                    Method, move(Op));
3246
3247    if (CastArg.isInvalid())
3248      return ExprError();
3249
3250    castExpr = CastArg.takeAs<Expr>();
3251  } else {
3252    Op.release();
3253  }
3254
3255  return Owned(new (Context) CStyleCastExpr(castType.getNonReferenceType(),
3256                                            Kind, castExpr, castType,
3257                                            LParenLoc, RParenLoc));
3258}
3259
3260/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
3261/// of comma binary operators.
3262Action::OwningExprResult
3263Sema::MaybeConvertParenListExprToParenExpr(Scope *S, ExprArg EA) {
3264  Expr *expr = EA.takeAs<Expr>();
3265  ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
3266  if (!E)
3267    return Owned(expr);
3268
3269  OwningExprResult Result(*this, E->getExpr(0));
3270
3271  for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
3272    Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, move(Result),
3273                        Owned(E->getExpr(i)));
3274
3275  return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), move(Result));
3276}
3277
3278Action::OwningExprResult
3279Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
3280                               SourceLocation RParenLoc, ExprArg Op,
3281                               QualType Ty) {
3282  ParenListExpr *PE = (ParenListExpr *)Op.get();
3283
3284  // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
3285  // then handle it as such.
3286  if (getLangOptions().AltiVec && Ty->isVectorType()) {
3287    if (PE->getNumExprs() == 0) {
3288      Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
3289      return ExprError();
3290    }
3291
3292    llvm::SmallVector<Expr *, 8> initExprs;
3293    for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
3294      initExprs.push_back(PE->getExpr(i));
3295
3296    // FIXME: This means that pretty-printing the final AST will produce curly
3297    // braces instead of the original commas.
3298    Op.release();
3299    InitListExpr *E = new (Context) InitListExpr(LParenLoc, &initExprs[0],
3300                                                 initExprs.size(), RParenLoc);
3301    E->setType(Ty);
3302    return ActOnCompoundLiteral(LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,
3303                                Owned(E));
3304  } else {
3305    // This is not an AltiVec-style cast, so turn the ParenListExpr into a
3306    // sequence of BinOp comma operators.
3307    Op = MaybeConvertParenListExprToParenExpr(S, move(Op));
3308    return ActOnCastExpr(S, LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,move(Op));
3309  }
3310}
3311
3312Action::OwningExprResult Sema::ActOnParenListExpr(SourceLocation L,
3313                                                  SourceLocation R,
3314                                                  MultiExprArg Val) {
3315  unsigned nexprs = Val.size();
3316  Expr **exprs = reinterpret_cast<Expr**>(Val.release());
3317  assert((exprs != 0) && "ActOnParenListExpr() missing expr list");
3318  Expr *expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
3319  return Owned(expr);
3320}
3321
3322/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
3323/// In that case, lhs = cond.
3324/// C99 6.5.15
3325QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
3326                                        SourceLocation QuestionLoc) {
3327  // C++ is sufficiently different to merit its own checker.
3328  if (getLangOptions().CPlusPlus)
3329    return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc);
3330
3331  UsualUnaryConversions(Cond);
3332  UsualUnaryConversions(LHS);
3333  UsualUnaryConversions(RHS);
3334  QualType CondTy = Cond->getType();
3335  QualType LHSTy = LHS->getType();
3336  QualType RHSTy = RHS->getType();
3337
3338  // first, check the condition.
3339  if (!CondTy->isScalarType()) { // C99 6.5.15p2
3340    Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
3341      << CondTy;
3342    return QualType();
3343  }
3344
3345  // Now check the two expressions.
3346  if (LHSTy->isVectorType() || RHSTy->isVectorType())
3347    return CheckVectorOperands(QuestionLoc, LHS, RHS);
3348
3349  // If both operands have arithmetic type, do the usual arithmetic conversions
3350  // to find a common type: C99 6.5.15p3,5.
3351  if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
3352    UsualArithmeticConversions(LHS, RHS);
3353    return LHS->getType();
3354  }
3355
3356  // If both operands are the same structure or union type, the result is that
3357  // type.
3358  if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
3359    if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
3360      if (LHSRT->getDecl() == RHSRT->getDecl())
3361        // "If both the operands have structure or union type, the result has
3362        // that type."  This implies that CV qualifiers are dropped.
3363        return LHSTy.getUnqualifiedType();
3364    // FIXME: Type of conditional expression must be complete in C mode.
3365  }
3366
3367  // C99 6.5.15p5: "If both operands have void type, the result has void type."
3368  // The following || allows only one side to be void (a GCC-ism).
3369  if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
3370    if (!LHSTy->isVoidType())
3371      Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3372        << RHS->getSourceRange();
3373    if (!RHSTy->isVoidType())
3374      Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3375        << LHS->getSourceRange();
3376    ImpCastExprToType(LHS, Context.VoidTy);
3377    ImpCastExprToType(RHS, Context.VoidTy);
3378    return Context.VoidTy;
3379  }
3380  // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
3381  // the type of the other operand."
3382  if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
3383      RHS->isNullPointerConstant(Context)) {
3384    ImpCastExprToType(RHS, LHSTy); // promote the null to a pointer.
3385    return LHSTy;
3386  }
3387  if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
3388      LHS->isNullPointerConstant(Context)) {
3389    ImpCastExprToType(LHS, RHSTy); // promote the null to a pointer.
3390    return RHSTy;
3391  }
3392  // Handle things like Class and struct objc_class*.  Here we case the result
3393  // to the pseudo-builtin, because that will be implicitly cast back to the
3394  // redefinition type if an attempt is made to access its fields.
3395  if (LHSTy->isObjCClassType() &&
3396      (RHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
3397    ImpCastExprToType(RHS, LHSTy);
3398    return LHSTy;
3399  }
3400  if (RHSTy->isObjCClassType() &&
3401      (LHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
3402    ImpCastExprToType(LHS, RHSTy);
3403    return RHSTy;
3404  }
3405  // And the same for struct objc_object* / id
3406  if (LHSTy->isObjCIdType() &&
3407      (RHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
3408    ImpCastExprToType(RHS, LHSTy);
3409    return LHSTy;
3410  }
3411  if (RHSTy->isObjCIdType() &&
3412      (LHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
3413    ImpCastExprToType(LHS, RHSTy);
3414    return RHSTy;
3415  }
3416  // Handle block pointer types.
3417  if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
3418    if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
3419      if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
3420        QualType destType = Context.getPointerType(Context.VoidTy);
3421        ImpCastExprToType(LHS, destType);
3422        ImpCastExprToType(RHS, destType);
3423        return destType;
3424      }
3425      Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3426            << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3427      return QualType();
3428    }
3429    // We have 2 block pointer types.
3430    if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3431      // Two identical block pointer types are always compatible.
3432      return LHSTy;
3433    }
3434    // The block pointer types aren't identical, continue checking.
3435    QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
3436    QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
3437
3438    if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3439                                    rhptee.getUnqualifiedType())) {
3440      Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3441        << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3442      // In this situation, we assume void* type. No especially good
3443      // reason, but this is what gcc does, and we do have to pick
3444      // to get a consistent AST.
3445      QualType incompatTy = Context.getPointerType(Context.VoidTy);
3446      ImpCastExprToType(LHS, incompatTy);
3447      ImpCastExprToType(RHS, incompatTy);
3448      return incompatTy;
3449    }
3450    // The block pointer types are compatible.
3451    ImpCastExprToType(LHS, LHSTy);
3452    ImpCastExprToType(RHS, LHSTy);
3453    return LHSTy;
3454  }
3455  // Check constraints for Objective-C object pointers types.
3456  if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
3457
3458    if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3459      // Two identical object pointer types are always compatible.
3460      return LHSTy;
3461    }
3462    const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
3463    const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
3464    QualType compositeType = LHSTy;
3465
3466    // If both operands are interfaces and either operand can be
3467    // assigned to the other, use that type as the composite
3468    // type. This allows
3469    //   xxx ? (A*) a : (B*) b
3470    // where B is a subclass of A.
3471    //
3472    // Additionally, as for assignment, if either type is 'id'
3473    // allow silent coercion. Finally, if the types are
3474    // incompatible then make sure to use 'id' as the composite
3475    // type so the result is acceptable for sending messages to.
3476
3477    // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
3478    // It could return the composite type.
3479    if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
3480      compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
3481    } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
3482      compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
3483    } else if ((LHSTy->isObjCQualifiedIdType() ||
3484                RHSTy->isObjCQualifiedIdType()) &&
3485                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
3486      // Need to handle "id<xx>" explicitly.
3487      // GCC allows qualified id and any Objective-C type to devolve to
3488      // id. Currently localizing to here until clear this should be
3489      // part of ObjCQualifiedIdTypesAreCompatible.
3490      compositeType = Context.getObjCIdType();
3491    } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
3492      compositeType = Context.getObjCIdType();
3493    } else {
3494      Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
3495        << LHSTy << RHSTy
3496        << LHS->getSourceRange() << RHS->getSourceRange();
3497      QualType incompatTy = Context.getObjCIdType();
3498      ImpCastExprToType(LHS, incompatTy);
3499      ImpCastExprToType(RHS, incompatTy);
3500      return incompatTy;
3501    }
3502    // The object pointer types are compatible.
3503    ImpCastExprToType(LHS, compositeType);
3504    ImpCastExprToType(RHS, compositeType);
3505    return compositeType;
3506  }
3507  // Check Objective-C object pointer types and 'void *'
3508  if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
3509    QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
3510    QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
3511    QualType destPointee = lhptee.getQualifiedType(rhptee.getCVRQualifiers());
3512    QualType destType = Context.getPointerType(destPointee);
3513    ImpCastExprToType(LHS, destType); // add qualifiers if necessary
3514    ImpCastExprToType(RHS, destType); // promote to void*
3515    return destType;
3516  }
3517  if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
3518    QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
3519    QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
3520    QualType destPointee = rhptee.getQualifiedType(lhptee.getCVRQualifiers());
3521    QualType destType = Context.getPointerType(destPointee);
3522    ImpCastExprToType(RHS, destType); // add qualifiers if necessary
3523    ImpCastExprToType(LHS, destType); // promote to void*
3524    return destType;
3525  }
3526  // Check constraints for C object pointers types (C99 6.5.15p3,6).
3527  if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
3528    // get the "pointed to" types
3529    QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
3530    QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
3531
3532    // ignore qualifiers on void (C99 6.5.15p3, clause 6)
3533    if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
3534      // Figure out necessary qualifiers (C99 6.5.15p6)
3535      QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
3536      QualType destType = Context.getPointerType(destPointee);
3537      ImpCastExprToType(LHS, destType); // add qualifiers if necessary
3538      ImpCastExprToType(RHS, destType); // promote to void*
3539      return destType;
3540    }
3541    if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
3542      QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
3543      QualType destType = Context.getPointerType(destPointee);
3544      ImpCastExprToType(LHS, destType); // add qualifiers if necessary
3545      ImpCastExprToType(RHS, destType); // promote to void*
3546      return destType;
3547    }
3548
3549    if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3550      // Two identical pointer types are always compatible.
3551      return LHSTy;
3552    }
3553    if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3554                                    rhptee.getUnqualifiedType())) {
3555      Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3556        << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3557      // In this situation, we assume void* type. No especially good
3558      // reason, but this is what gcc does, and we do have to pick
3559      // to get a consistent AST.
3560      QualType incompatTy = Context.getPointerType(Context.VoidTy);
3561      ImpCastExprToType(LHS, incompatTy);
3562      ImpCastExprToType(RHS, incompatTy);
3563      return incompatTy;
3564    }
3565    // The pointer types are compatible.
3566    // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
3567    // differently qualified versions of compatible types, the result type is
3568    // a pointer to an appropriately qualified version of the *composite*
3569    // type.
3570    // FIXME: Need to calculate the composite type.
3571    // FIXME: Need to add qualifiers
3572    ImpCastExprToType(LHS, LHSTy);
3573    ImpCastExprToType(RHS, LHSTy);
3574    return LHSTy;
3575  }
3576
3577  // GCC compatibility: soften pointer/integer mismatch.
3578  if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
3579    Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3580      << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3581    ImpCastExprToType(LHS, RHSTy); // promote the integer to a pointer.
3582    return RHSTy;
3583  }
3584  if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
3585    Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3586      << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3587    ImpCastExprToType(RHS, LHSTy); // promote the integer to a pointer.
3588    return LHSTy;
3589  }
3590
3591  // Otherwise, the operands are not compatible.
3592  Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3593    << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3594  return QualType();
3595}
3596
3597/// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
3598/// in the case of a the GNU conditional expr extension.
3599Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
3600                                                  SourceLocation ColonLoc,
3601                                                  ExprArg Cond, ExprArg LHS,
3602                                                  ExprArg RHS) {
3603  Expr *CondExpr = (Expr *) Cond.get();
3604  Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
3605
3606  // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
3607  // was the condition.
3608  bool isLHSNull = LHSExpr == 0;
3609  if (isLHSNull)
3610    LHSExpr = CondExpr;
3611
3612  QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
3613                                             RHSExpr, QuestionLoc);
3614  if (result.isNull())
3615    return ExprError();
3616
3617  Cond.release();
3618  LHS.release();
3619  RHS.release();
3620  return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
3621                                                 isLHSNull ? 0 : LHSExpr,
3622                                                 ColonLoc, RHSExpr, result));
3623}
3624
3625// CheckPointerTypesForAssignment - This is a very tricky routine (despite
3626// being closely modeled after the C99 spec:-). The odd characteristic of this
3627// routine is it effectively iqnores the qualifiers on the top level pointee.
3628// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
3629// FIXME: add a couple examples in this comment.
3630Sema::AssignConvertType
3631Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
3632  QualType lhptee, rhptee;
3633
3634  if ((lhsType->isObjCClassType() &&
3635       (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
3636     (rhsType->isObjCClassType() &&
3637       (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
3638      return Compatible;
3639  }
3640
3641  // get the "pointed to" type (ignoring qualifiers at the top level)
3642  lhptee = lhsType->getAs<PointerType>()->getPointeeType();
3643  rhptee = rhsType->getAs<PointerType>()->getPointeeType();
3644
3645  // make sure we operate on the canonical type
3646  lhptee = Context.getCanonicalType(lhptee);
3647  rhptee = Context.getCanonicalType(rhptee);
3648
3649  AssignConvertType ConvTy = Compatible;
3650
3651  // C99 6.5.16.1p1: This following citation is common to constraints
3652  // 3 & 4 (below). ...and the type *pointed to* by the left has all the
3653  // qualifiers of the type *pointed to* by the right;
3654  // FIXME: Handle ExtQualType
3655  if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
3656    ConvTy = CompatiblePointerDiscardsQualifiers;
3657
3658  // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
3659  // incomplete type and the other is a pointer to a qualified or unqualified
3660  // version of void...
3661  if (lhptee->isVoidType()) {
3662    if (rhptee->isIncompleteOrObjectType())
3663      return ConvTy;
3664
3665    // As an extension, we allow cast to/from void* to function pointer.
3666    assert(rhptee->isFunctionType());
3667    return FunctionVoidPointer;
3668  }
3669
3670  if (rhptee->isVoidType()) {
3671    if (lhptee->isIncompleteOrObjectType())
3672      return ConvTy;
3673
3674    // As an extension, we allow cast to/from void* to function pointer.
3675    assert(lhptee->isFunctionType());
3676    return FunctionVoidPointer;
3677  }
3678  // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
3679  // unqualified versions of compatible types, ...
3680  lhptee = lhptee.getUnqualifiedType();
3681  rhptee = rhptee.getUnqualifiedType();
3682  if (!Context.typesAreCompatible(lhptee, rhptee)) {
3683    // Check if the pointee types are compatible ignoring the sign.
3684    // We explicitly check for char so that we catch "char" vs
3685    // "unsigned char" on systems where "char" is unsigned.
3686    if (lhptee->isCharType()) {
3687      lhptee = Context.UnsignedCharTy;
3688    } else if (lhptee->isSignedIntegerType()) {
3689      lhptee = Context.getCorrespondingUnsignedType(lhptee);
3690    }
3691    if (rhptee->isCharType()) {
3692      rhptee = Context.UnsignedCharTy;
3693    } else if (rhptee->isSignedIntegerType()) {
3694      rhptee = Context.getCorrespondingUnsignedType(rhptee);
3695    }
3696    if (lhptee == rhptee) {
3697      // Types are compatible ignoring the sign. Qualifier incompatibility
3698      // takes priority over sign incompatibility because the sign
3699      // warning can be disabled.
3700      if (ConvTy != Compatible)
3701        return ConvTy;
3702      return IncompatiblePointerSign;
3703    }
3704    // General pointer incompatibility takes priority over qualifiers.
3705    return IncompatiblePointer;
3706  }
3707  return ConvTy;
3708}
3709
3710/// CheckBlockPointerTypesForAssignment - This routine determines whether two
3711/// block pointer types are compatible or whether a block and normal pointer
3712/// are compatible. It is more restrict than comparing two function pointer
3713// types.
3714Sema::AssignConvertType
3715Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
3716                                          QualType rhsType) {
3717  QualType lhptee, rhptee;
3718
3719  // get the "pointed to" type (ignoring qualifiers at the top level)
3720  lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType();
3721  rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType();
3722
3723  // make sure we operate on the canonical type
3724  lhptee = Context.getCanonicalType(lhptee);
3725  rhptee = Context.getCanonicalType(rhptee);
3726
3727  AssignConvertType ConvTy = Compatible;
3728
3729  // For blocks we enforce that qualifiers are identical.
3730  if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
3731    ConvTy = CompatiblePointerDiscardsQualifiers;
3732
3733  if (!Context.typesAreCompatible(lhptee, rhptee))
3734    return IncompatibleBlockPointer;
3735  return ConvTy;
3736}
3737
3738/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
3739/// has code to accommodate several GCC extensions when type checking
3740/// pointers. Here are some objectionable examples that GCC considers warnings:
3741///
3742///  int a, *pint;
3743///  short *pshort;
3744///  struct foo *pfoo;
3745///
3746///  pint = pshort; // warning: assignment from incompatible pointer type
3747///  a = pint; // warning: assignment makes integer from pointer without a cast
3748///  pint = a; // warning: assignment makes pointer from integer without a cast
3749///  pint = pfoo; // warning: assignment from incompatible pointer type
3750///
3751/// As a result, the code for dealing with pointers is more complex than the
3752/// C99 spec dictates.
3753///
3754Sema::AssignConvertType
3755Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
3756  // Get canonical types.  We're not formatting these types, just comparing
3757  // them.
3758  lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
3759  rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
3760
3761  if (lhsType == rhsType)
3762    return Compatible; // Common case: fast path an exact match.
3763
3764  if ((lhsType->isObjCClassType() &&
3765       (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
3766     (rhsType->isObjCClassType() &&
3767       (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
3768      return Compatible;
3769  }
3770
3771  // If the left-hand side is a reference type, then we are in a
3772  // (rare!) case where we've allowed the use of references in C,
3773  // e.g., as a parameter type in a built-in function. In this case,
3774  // just make sure that the type referenced is compatible with the
3775  // right-hand side type. The caller is responsible for adjusting
3776  // lhsType so that the resulting expression does not have reference
3777  // type.
3778  if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
3779    if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
3780      return Compatible;
3781    return Incompatible;
3782  }
3783  // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
3784  // to the same ExtVector type.
3785  if (lhsType->isExtVectorType()) {
3786    if (rhsType->isExtVectorType())
3787      return lhsType == rhsType ? Compatible : Incompatible;
3788    if (!rhsType->isVectorType() && rhsType->isArithmeticType())
3789      return Compatible;
3790  }
3791
3792  if (lhsType->isVectorType() || rhsType->isVectorType()) {
3793    // If we are allowing lax vector conversions, and LHS and RHS are both
3794    // vectors, the total size only needs to be the same. This is a bitcast;
3795    // no bits are changed but the result type is different.
3796    if (getLangOptions().LaxVectorConversions &&
3797        lhsType->isVectorType() && rhsType->isVectorType()) {
3798      if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
3799        return IncompatibleVectors;
3800    }
3801    return Incompatible;
3802  }
3803
3804  if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
3805    return Compatible;
3806
3807  if (isa<PointerType>(lhsType)) {
3808    if (rhsType->isIntegerType())
3809      return IntToPointer;
3810
3811    if (isa<PointerType>(rhsType))
3812      return CheckPointerTypesForAssignment(lhsType, rhsType);
3813
3814    // In general, C pointers are not compatible with ObjC object pointers.
3815    if (isa<ObjCObjectPointerType>(rhsType)) {
3816      if (lhsType->isVoidPointerType()) // an exception to the rule.
3817        return Compatible;
3818      return IncompatiblePointer;
3819    }
3820    if (rhsType->getAs<BlockPointerType>()) {
3821      if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
3822        return Compatible;
3823
3824      // Treat block pointers as objects.
3825      if (getLangOptions().ObjC1 && lhsType->isObjCIdType())
3826        return Compatible;
3827    }
3828    return Incompatible;
3829  }
3830
3831  if (isa<BlockPointerType>(lhsType)) {
3832    if (rhsType->isIntegerType())
3833      return IntToBlockPointer;
3834
3835    // Treat block pointers as objects.
3836    if (getLangOptions().ObjC1 && rhsType->isObjCIdType())
3837      return Compatible;
3838
3839    if (rhsType->isBlockPointerType())
3840      return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
3841
3842    if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
3843      if (RHSPT->getPointeeType()->isVoidType())
3844        return Compatible;
3845    }
3846    return Incompatible;
3847  }
3848
3849  if (isa<ObjCObjectPointerType>(lhsType)) {
3850    if (rhsType->isIntegerType())
3851      return IntToPointer;
3852
3853    // In general, C pointers are not compatible with ObjC object pointers.
3854    if (isa<PointerType>(rhsType)) {
3855      if (rhsType->isVoidPointerType()) // an exception to the rule.
3856        return Compatible;
3857      return IncompatiblePointer;
3858    }
3859    if (rhsType->isObjCObjectPointerType()) {
3860      if (lhsType->isObjCBuiltinType() || rhsType->isObjCBuiltinType())
3861        return Compatible;
3862      if (Context.typesAreCompatible(lhsType, rhsType))
3863        return Compatible;
3864      if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
3865        return IncompatibleObjCQualifiedId;
3866      return IncompatiblePointer;
3867    }
3868    if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
3869      if (RHSPT->getPointeeType()->isVoidType())
3870        return Compatible;
3871    }
3872    // Treat block pointers as objects.
3873    if (rhsType->isBlockPointerType())
3874      return Compatible;
3875    return Incompatible;
3876  }
3877  if (isa<PointerType>(rhsType)) {
3878    // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
3879    if (lhsType == Context.BoolTy)
3880      return Compatible;
3881
3882    if (lhsType->isIntegerType())
3883      return PointerToInt;
3884
3885    if (isa<PointerType>(lhsType))
3886      return CheckPointerTypesForAssignment(lhsType, rhsType);
3887
3888    if (isa<BlockPointerType>(lhsType) &&
3889        rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
3890      return Compatible;
3891    return Incompatible;
3892  }
3893  if (isa<ObjCObjectPointerType>(rhsType)) {
3894    // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
3895    if (lhsType == Context.BoolTy)
3896      return Compatible;
3897
3898    if (lhsType->isIntegerType())
3899      return PointerToInt;
3900
3901    // In general, C pointers are not compatible with ObjC object pointers.
3902    if (isa<PointerType>(lhsType)) {
3903      if (lhsType->isVoidPointerType()) // an exception to the rule.
3904        return Compatible;
3905      return IncompatiblePointer;
3906    }
3907    if (isa<BlockPointerType>(lhsType) &&
3908        rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
3909      return Compatible;
3910    return Incompatible;
3911  }
3912
3913  if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
3914    if (Context.typesAreCompatible(lhsType, rhsType))
3915      return Compatible;
3916  }
3917  return Incompatible;
3918}
3919
3920/// \brief Constructs a transparent union from an expression that is
3921/// used to initialize the transparent union.
3922static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
3923                                      QualType UnionType, FieldDecl *Field) {
3924  // Build an initializer list that designates the appropriate member
3925  // of the transparent union.
3926  InitListExpr *Initializer = new (C) InitListExpr(SourceLocation(),
3927                                                   &E, 1,
3928                                                   SourceLocation());
3929  Initializer->setType(UnionType);
3930  Initializer->setInitializedFieldInUnion(Field);
3931
3932  // Build a compound literal constructing a value of the transparent
3933  // union type from this initializer list.
3934  E = new (C) CompoundLiteralExpr(SourceLocation(), UnionType, Initializer,
3935                                  false);
3936}
3937
3938Sema::AssignConvertType
3939Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
3940  QualType FromType = rExpr->getType();
3941
3942  // If the ArgType is a Union type, we want to handle a potential
3943  // transparent_union GCC extension.
3944  const RecordType *UT = ArgType->getAsUnionType();
3945  if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
3946    return Incompatible;
3947
3948  // The field to initialize within the transparent union.
3949  RecordDecl *UD = UT->getDecl();
3950  FieldDecl *InitField = 0;
3951  // It's compatible if the expression matches any of the fields.
3952  for (RecordDecl::field_iterator it = UD->field_begin(),
3953         itend = UD->field_end();
3954       it != itend; ++it) {
3955    if (it->getType()->isPointerType()) {
3956      // If the transparent union contains a pointer type, we allow:
3957      // 1) void pointer
3958      // 2) null pointer constant
3959      if (FromType->isPointerType())
3960        if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
3961          ImpCastExprToType(rExpr, it->getType());
3962          InitField = *it;
3963          break;
3964        }
3965
3966      if (rExpr->isNullPointerConstant(Context)) {
3967        ImpCastExprToType(rExpr, it->getType());
3968        InitField = *it;
3969        break;
3970      }
3971    }
3972
3973    if (CheckAssignmentConstraints(it->getType(), rExpr->getType())
3974          == Compatible) {
3975      InitField = *it;
3976      break;
3977    }
3978  }
3979
3980  if (!InitField)
3981    return Incompatible;
3982
3983  ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
3984  return Compatible;
3985}
3986
3987Sema::AssignConvertType
3988Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
3989  if (getLangOptions().CPlusPlus) {
3990    if (!lhsType->isRecordType()) {
3991      // C++ 5.17p3: If the left operand is not of class type, the
3992      // expression is implicitly converted (C++ 4) to the
3993      // cv-unqualified type of the left operand.
3994      if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
3995                                    "assigning"))
3996        return Incompatible;
3997      return Compatible;
3998    }
3999
4000    // FIXME: Currently, we fall through and treat C++ classes like C
4001    // structures.
4002  }
4003
4004  // C99 6.5.16.1p1: the left operand is a pointer and the right is
4005  // a null pointer constant.
4006  if ((lhsType->isPointerType() ||
4007       lhsType->isObjCObjectPointerType() ||
4008       lhsType->isBlockPointerType())
4009      && rExpr->isNullPointerConstant(Context)) {
4010    ImpCastExprToType(rExpr, lhsType);
4011    return Compatible;
4012  }
4013
4014  // This check seems unnatural, however it is necessary to ensure the proper
4015  // conversion of functions/arrays. If the conversion were done for all
4016  // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
4017  // expressions that surpress this implicit conversion (&, sizeof).
4018  //
4019  // Suppress this for references: C++ 8.5.3p5.
4020  if (!lhsType->isReferenceType())
4021    DefaultFunctionArrayConversion(rExpr);
4022
4023  Sema::AssignConvertType result =
4024    CheckAssignmentConstraints(lhsType, rExpr->getType());
4025
4026  // C99 6.5.16.1p2: The value of the right operand is converted to the
4027  // type of the assignment expression.
4028  // CheckAssignmentConstraints allows the left-hand side to be a reference,
4029  // so that we can use references in built-in functions even in C.
4030  // The getNonReferenceType() call makes sure that the resulting expression
4031  // does not have reference type.
4032  if (result != Incompatible && rExpr->getType() != lhsType)
4033    ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
4034  return result;
4035}
4036
4037QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
4038  Diag(Loc, diag::err_typecheck_invalid_operands)
4039    << lex->getType() << rex->getType()
4040    << lex->getSourceRange() << rex->getSourceRange();
4041  return QualType();
4042}
4043
4044inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
4045                                                              Expr *&rex) {
4046  // For conversion purposes, we ignore any qualifiers.
4047  // For example, "const float" and "float" are equivalent.
4048  QualType lhsType =
4049    Context.getCanonicalType(lex->getType()).getUnqualifiedType();
4050  QualType rhsType =
4051    Context.getCanonicalType(rex->getType()).getUnqualifiedType();
4052
4053  // If the vector types are identical, return.
4054  if (lhsType == rhsType)
4055    return lhsType;
4056
4057  // Handle the case of a vector & extvector type of the same size and element
4058  // type.  It would be nice if we only had one vector type someday.
4059  if (getLangOptions().LaxVectorConversions) {
4060    // FIXME: Should we warn here?
4061    if (const VectorType *LV = lhsType->getAs<VectorType>()) {
4062      if (const VectorType *RV = rhsType->getAs<VectorType>())
4063        if (LV->getElementType() == RV->getElementType() &&
4064            LV->getNumElements() == RV->getNumElements()) {
4065          return lhsType->isExtVectorType() ? lhsType : rhsType;
4066        }
4067    }
4068  }
4069
4070  // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
4071  // swap back (so that we don't reverse the inputs to a subtract, for instance.
4072  bool swapped = false;
4073  if (rhsType->isExtVectorType()) {
4074    swapped = true;
4075    std::swap(rex, lex);
4076    std::swap(rhsType, lhsType);
4077  }
4078
4079  // Handle the case of an ext vector and scalar.
4080  if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
4081    QualType EltTy = LV->getElementType();
4082    if (EltTy->isIntegralType() && rhsType->isIntegralType()) {
4083      if (Context.getIntegerTypeOrder(EltTy, rhsType) >= 0) {
4084        ImpCastExprToType(rex, lhsType);
4085        if (swapped) std::swap(rex, lex);
4086        return lhsType;
4087      }
4088    }
4089    if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
4090        rhsType->isRealFloatingType()) {
4091      if (Context.getFloatingTypeOrder(EltTy, rhsType) >= 0) {
4092        ImpCastExprToType(rex, lhsType);
4093        if (swapped) std::swap(rex, lex);
4094        return lhsType;
4095      }
4096    }
4097  }
4098
4099  // Vectors of different size or scalar and non-ext-vector are errors.
4100  Diag(Loc, diag::err_typecheck_vector_not_convertable)
4101    << lex->getType() << rex->getType()
4102    << lex->getSourceRange() << rex->getSourceRange();
4103  return QualType();
4104}
4105
4106inline QualType Sema::CheckMultiplyDivideOperands(
4107  Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
4108  if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
4109    return CheckVectorOperands(Loc, lex, rex);
4110
4111  QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
4112
4113  if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
4114    return compType;
4115  return InvalidOperands(Loc, lex, rex);
4116}
4117
4118inline QualType Sema::CheckRemainderOperands(
4119  Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
4120  if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4121    if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
4122      return CheckVectorOperands(Loc, lex, rex);
4123    return InvalidOperands(Loc, lex, rex);
4124  }
4125
4126  QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
4127
4128  if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
4129    return compType;
4130  return InvalidOperands(Loc, lex, rex);
4131}
4132
4133inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
4134  Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) {
4135  if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4136    QualType compType = CheckVectorOperands(Loc, lex, rex);
4137    if (CompLHSTy) *CompLHSTy = compType;
4138    return compType;
4139  }
4140
4141  QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
4142
4143  // handle the common case first (both operands are arithmetic).
4144  if (lex->getType()->isArithmeticType() &&
4145      rex->getType()->isArithmeticType()) {
4146    if (CompLHSTy) *CompLHSTy = compType;
4147    return compType;
4148  }
4149
4150  // Put any potential pointer into PExp
4151  Expr* PExp = lex, *IExp = rex;
4152  if (IExp->getType()->isAnyPointerType())
4153    std::swap(PExp, IExp);
4154
4155  if (PExp->getType()->isAnyPointerType()) {
4156
4157    if (IExp->getType()->isIntegerType()) {
4158      QualType PointeeTy = PExp->getType()->getPointeeType();
4159
4160      // Check for arithmetic on pointers to incomplete types.
4161      if (PointeeTy->isVoidType()) {
4162        if (getLangOptions().CPlusPlus) {
4163          Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4164            << lex->getSourceRange() << rex->getSourceRange();
4165          return QualType();
4166        }
4167
4168        // GNU extension: arithmetic on pointer to void
4169        Diag(Loc, diag::ext_gnu_void_ptr)
4170          << lex->getSourceRange() << rex->getSourceRange();
4171      } else if (PointeeTy->isFunctionType()) {
4172        if (getLangOptions().CPlusPlus) {
4173          Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
4174            << lex->getType() << lex->getSourceRange();
4175          return QualType();
4176        }
4177
4178        // GNU extension: arithmetic on pointer to function
4179        Diag(Loc, diag::ext_gnu_ptr_func_arith)
4180          << lex->getType() << lex->getSourceRange();
4181      } else {
4182        // Check if we require a complete type.
4183        if (((PExp->getType()->isPointerType() &&
4184              !PExp->getType()->isDependentType()) ||
4185              PExp->getType()->isObjCObjectPointerType()) &&
4186             RequireCompleteType(Loc, PointeeTy,
4187                           PDiag(diag::err_typecheck_arithmetic_incomplete_type)
4188                             << PExp->getSourceRange()
4189                             << PExp->getType()))
4190          return QualType();
4191      }
4192      // Diagnose bad cases where we step over interface counts.
4193      if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4194        Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4195          << PointeeTy << PExp->getSourceRange();
4196        return QualType();
4197      }
4198
4199      if (CompLHSTy) {
4200        QualType LHSTy = Context.isPromotableBitField(lex);
4201        if (LHSTy.isNull()) {
4202          LHSTy = lex->getType();
4203          if (LHSTy->isPromotableIntegerType())
4204            LHSTy = Context.getPromotedIntegerType(LHSTy);
4205        }
4206        *CompLHSTy = LHSTy;
4207      }
4208      return PExp->getType();
4209    }
4210  }
4211
4212  return InvalidOperands(Loc, lex, rex);
4213}
4214
4215// C99 6.5.6
4216QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
4217                                        SourceLocation Loc, QualType* CompLHSTy) {
4218  if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4219    QualType compType = CheckVectorOperands(Loc, lex, rex);
4220    if (CompLHSTy) *CompLHSTy = compType;
4221    return compType;
4222  }
4223
4224  QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
4225
4226  // Enforce type constraints: C99 6.5.6p3.
4227
4228  // Handle the common case first (both operands are arithmetic).
4229  if (lex->getType()->isArithmeticType()
4230      && rex->getType()->isArithmeticType()) {
4231    if (CompLHSTy) *CompLHSTy = compType;
4232    return compType;
4233  }
4234
4235  // Either ptr - int   or   ptr - ptr.
4236  if (lex->getType()->isAnyPointerType()) {
4237    QualType lpointee = lex->getType()->getPointeeType();
4238
4239    // The LHS must be an completely-defined object type.
4240
4241    bool ComplainAboutVoid = false;
4242    Expr *ComplainAboutFunc = 0;
4243    if (lpointee->isVoidType()) {
4244      if (getLangOptions().CPlusPlus) {
4245        Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4246          << lex->getSourceRange() << rex->getSourceRange();
4247        return QualType();
4248      }
4249
4250      // GNU C extension: arithmetic on pointer to void
4251      ComplainAboutVoid = true;
4252    } else if (lpointee->isFunctionType()) {
4253      if (getLangOptions().CPlusPlus) {
4254        Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
4255          << lex->getType() << lex->getSourceRange();
4256        return QualType();
4257      }
4258
4259      // GNU C extension: arithmetic on pointer to function
4260      ComplainAboutFunc = lex;
4261    } else if (!lpointee->isDependentType() &&
4262               RequireCompleteType(Loc, lpointee,
4263                                   PDiag(diag::err_typecheck_sub_ptr_object)
4264                                     << lex->getSourceRange()
4265                                     << lex->getType()))
4266      return QualType();
4267
4268    // Diagnose bad cases where we step over interface counts.
4269    if (lpointee->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4270      Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4271        << lpointee << lex->getSourceRange();
4272      return QualType();
4273    }
4274
4275    // The result type of a pointer-int computation is the pointer type.
4276    if (rex->getType()->isIntegerType()) {
4277      if (ComplainAboutVoid)
4278        Diag(Loc, diag::ext_gnu_void_ptr)
4279          << lex->getSourceRange() << rex->getSourceRange();
4280      if (ComplainAboutFunc)
4281        Diag(Loc, diag::ext_gnu_ptr_func_arith)
4282          << ComplainAboutFunc->getType()
4283          << ComplainAboutFunc->getSourceRange();
4284
4285      if (CompLHSTy) *CompLHSTy = lex->getType();
4286      return lex->getType();
4287    }
4288
4289    // Handle pointer-pointer subtractions.
4290    if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
4291      QualType rpointee = RHSPTy->getPointeeType();
4292
4293      // RHS must be a completely-type object type.
4294      // Handle the GNU void* extension.
4295      if (rpointee->isVoidType()) {
4296        if (getLangOptions().CPlusPlus) {
4297          Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4298            << lex->getSourceRange() << rex->getSourceRange();
4299          return QualType();
4300        }
4301
4302        ComplainAboutVoid = true;
4303      } else if (rpointee->isFunctionType()) {
4304        if (getLangOptions().CPlusPlus) {
4305          Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
4306            << rex->getType() << rex->getSourceRange();
4307          return QualType();
4308        }
4309
4310        // GNU extension: arithmetic on pointer to function
4311        if (!ComplainAboutFunc)
4312          ComplainAboutFunc = rex;
4313      } else if (!rpointee->isDependentType() &&
4314                 RequireCompleteType(Loc, rpointee,
4315                                     PDiag(diag::err_typecheck_sub_ptr_object)
4316                                       << rex->getSourceRange()
4317                                       << rex->getType()))
4318        return QualType();
4319
4320      if (getLangOptions().CPlusPlus) {
4321        // Pointee types must be the same: C++ [expr.add]
4322        if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
4323          Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4324            << lex->getType() << rex->getType()
4325            << lex->getSourceRange() << rex->getSourceRange();
4326          return QualType();
4327        }
4328      } else {
4329        // Pointee types must be compatible C99 6.5.6p3
4330        if (!Context.typesAreCompatible(
4331                Context.getCanonicalType(lpointee).getUnqualifiedType(),
4332                Context.getCanonicalType(rpointee).getUnqualifiedType())) {
4333          Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4334            << lex->getType() << rex->getType()
4335            << lex->getSourceRange() << rex->getSourceRange();
4336          return QualType();
4337        }
4338      }
4339
4340      if (ComplainAboutVoid)
4341        Diag(Loc, diag::ext_gnu_void_ptr)
4342          << lex->getSourceRange() << rex->getSourceRange();
4343      if (ComplainAboutFunc)
4344        Diag(Loc, diag::ext_gnu_ptr_func_arith)
4345          << ComplainAboutFunc->getType()
4346          << ComplainAboutFunc->getSourceRange();
4347
4348      if (CompLHSTy) *CompLHSTy = lex->getType();
4349      return Context.getPointerDiffType();
4350    }
4351  }
4352
4353  return InvalidOperands(Loc, lex, rex);
4354}
4355
4356// C99 6.5.7
4357QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
4358                                  bool isCompAssign) {
4359  // C99 6.5.7p2: Each of the operands shall have integer type.
4360  if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
4361    return InvalidOperands(Loc, lex, rex);
4362
4363  // Shifts don't perform usual arithmetic conversions, they just do integer
4364  // promotions on each operand. C99 6.5.7p3
4365  QualType LHSTy = Context.isPromotableBitField(lex);
4366  if (LHSTy.isNull()) {
4367    LHSTy = lex->getType();
4368    if (LHSTy->isPromotableIntegerType())
4369      LHSTy = Context.getPromotedIntegerType(LHSTy);
4370  }
4371  if (!isCompAssign)
4372    ImpCastExprToType(lex, LHSTy);
4373
4374  UsualUnaryConversions(rex);
4375
4376  // Sanity-check shift operands
4377  llvm::APSInt Right;
4378  // Check right/shifter operand
4379  if (!rex->isValueDependent() &&
4380      rex->isIntegerConstantExpr(Right, Context)) {
4381    if (Right.isNegative())
4382      Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
4383    else {
4384      llvm::APInt LeftBits(Right.getBitWidth(),
4385                          Context.getTypeSize(lex->getType()));
4386      if (Right.uge(LeftBits))
4387        Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
4388    }
4389  }
4390
4391  // "The type of the result is that of the promoted left operand."
4392  return LHSTy;
4393}
4394
4395// C99 6.5.8, C++ [expr.rel]
4396QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
4397                                    unsigned OpaqueOpc, bool isRelational) {
4398  BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
4399
4400  if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
4401    return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
4402
4403  // C99 6.5.8p3 / C99 6.5.9p4
4404  if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
4405    UsualArithmeticConversions(lex, rex);
4406  else {
4407    UsualUnaryConversions(lex);
4408    UsualUnaryConversions(rex);
4409  }
4410  QualType lType = lex->getType();
4411  QualType rType = rex->getType();
4412
4413  if (!lType->isFloatingType()
4414      && !(lType->isBlockPointerType() && isRelational)) {
4415    // For non-floating point types, check for self-comparisons of the form
4416    // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
4417    // often indicate logic errors in the program.
4418    // NOTE: Don't warn about comparisons of enum constants. These can arise
4419    //  from macro expansions, and are usually quite deliberate.
4420    Expr *LHSStripped = lex->IgnoreParens();
4421    Expr *RHSStripped = rex->IgnoreParens();
4422    if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
4423      if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
4424        if (DRL->getDecl() == DRR->getDecl() &&
4425            !isa<EnumConstantDecl>(DRL->getDecl()))
4426          Diag(Loc, diag::warn_selfcomparison);
4427
4428    if (isa<CastExpr>(LHSStripped))
4429      LHSStripped = LHSStripped->IgnoreParenCasts();
4430    if (isa<CastExpr>(RHSStripped))
4431      RHSStripped = RHSStripped->IgnoreParenCasts();
4432
4433    // Warn about comparisons against a string constant (unless the other
4434    // operand is null), the user probably wants strcmp.
4435    Expr *literalString = 0;
4436    Expr *literalStringStripped = 0;
4437    if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
4438        !RHSStripped->isNullPointerConstant(Context)) {
4439      literalString = lex;
4440      literalStringStripped = LHSStripped;
4441    } else if ((isa<StringLiteral>(RHSStripped) ||
4442                isa<ObjCEncodeExpr>(RHSStripped)) &&
4443               !LHSStripped->isNullPointerConstant(Context)) {
4444      literalString = rex;
4445      literalStringStripped = RHSStripped;
4446    }
4447
4448    if (literalString) {
4449      std::string resultComparison;
4450      switch (Opc) {
4451      case BinaryOperator::LT: resultComparison = ") < 0"; break;
4452      case BinaryOperator::GT: resultComparison = ") > 0"; break;
4453      case BinaryOperator::LE: resultComparison = ") <= 0"; break;
4454      case BinaryOperator::GE: resultComparison = ") >= 0"; break;
4455      case BinaryOperator::EQ: resultComparison = ") == 0"; break;
4456      case BinaryOperator::NE: resultComparison = ") != 0"; break;
4457      default: assert(false && "Invalid comparison operator");
4458      }
4459      Diag(Loc, diag::warn_stringcompare)
4460        << isa<ObjCEncodeExpr>(literalStringStripped)
4461        << literalString->getSourceRange()
4462        << CodeModificationHint::CreateReplacement(SourceRange(Loc), ", ")
4463        << CodeModificationHint::CreateInsertion(lex->getLocStart(),
4464                                                 "strcmp(")
4465        << CodeModificationHint::CreateInsertion(
4466                                       PP.getLocForEndOfToken(rex->getLocEnd()),
4467                                       resultComparison);
4468    }
4469  }
4470
4471  // The result of comparisons is 'bool' in C++, 'int' in C.
4472  QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy :Context.IntTy;
4473
4474  if (isRelational) {
4475    if (lType->isRealType() && rType->isRealType())
4476      return ResultTy;
4477  } else {
4478    // Check for comparisons of floating point operands using != and ==.
4479    if (lType->isFloatingType()) {
4480      assert(rType->isFloatingType());
4481      CheckFloatComparison(Loc,lex,rex);
4482    }
4483
4484    if (lType->isArithmeticType() && rType->isArithmeticType())
4485      return ResultTy;
4486  }
4487
4488  bool LHSIsNull = lex->isNullPointerConstant(Context);
4489  bool RHSIsNull = rex->isNullPointerConstant(Context);
4490
4491  // All of the following pointer related warnings are GCC extensions, except
4492  // when handling null pointer constants. One day, we can consider making them
4493  // errors (when -pedantic-errors is enabled).
4494  if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
4495    QualType LCanPointeeTy =
4496      Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
4497    QualType RCanPointeeTy =
4498      Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
4499
4500    if (getLangOptions().CPlusPlus) {
4501      if (LCanPointeeTy == RCanPointeeTy)
4502        return ResultTy;
4503
4504      // C++ [expr.rel]p2:
4505      //   [...] Pointer conversions (4.10) and qualification
4506      //   conversions (4.4) are performed on pointer operands (or on
4507      //   a pointer operand and a null pointer constant) to bring
4508      //   them to their composite pointer type. [...]
4509      //
4510      // C++ [expr.eq]p1 uses the same notion for (in)equality
4511      // comparisons of pointers.
4512      QualType T = FindCompositePointerType(lex, rex);
4513      if (T.isNull()) {
4514        Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
4515          << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4516        return QualType();
4517      }
4518
4519      ImpCastExprToType(lex, T);
4520      ImpCastExprToType(rex, T);
4521      return ResultTy;
4522    }
4523    // C99 6.5.9p2 and C99 6.5.8p2
4524    if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
4525                                   RCanPointeeTy.getUnqualifiedType())) {
4526      // Valid unless a relational comparison of function pointers
4527      if (isRelational && LCanPointeeTy->isFunctionType()) {
4528        Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
4529          << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4530      }
4531    } else if (!isRelational &&
4532               (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
4533      // Valid unless comparison between non-null pointer and function pointer
4534      if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
4535          && !LHSIsNull && !RHSIsNull) {
4536        Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
4537          << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4538      }
4539    } else {
4540      // Invalid
4541      Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
4542        << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4543    }
4544    if (LCanPointeeTy != RCanPointeeTy)
4545      ImpCastExprToType(rex, lType); // promote the pointer to pointer
4546    return ResultTy;
4547  }
4548
4549  if (getLangOptions().CPlusPlus) {
4550    // Comparison of pointers with null pointer constants and equality
4551    // comparisons of member pointers to null pointer constants.
4552    if (RHSIsNull &&
4553        (lType->isPointerType() ||
4554         (!isRelational && lType->isMemberPointerType()))) {
4555      ImpCastExprToType(rex, lType, CastExpr::CK_NullToMemberPointer);
4556      return ResultTy;
4557    }
4558    if (LHSIsNull &&
4559        (rType->isPointerType() ||
4560         (!isRelational && rType->isMemberPointerType()))) {
4561      ImpCastExprToType(lex, rType, CastExpr::CK_NullToMemberPointer);
4562      return ResultTy;
4563    }
4564
4565    // Comparison of member pointers.
4566    if (!isRelational &&
4567        lType->isMemberPointerType() && rType->isMemberPointerType()) {
4568      // C++ [expr.eq]p2:
4569      //   In addition, pointers to members can be compared, or a pointer to
4570      //   member and a null pointer constant. Pointer to member conversions
4571      //   (4.11) and qualification conversions (4.4) are performed to bring
4572      //   them to a common type. If one operand is a null pointer constant,
4573      //   the common type is the type of the other operand. Otherwise, the
4574      //   common type is a pointer to member type similar (4.4) to the type
4575      //   of one of the operands, with a cv-qualification signature (4.4)
4576      //   that is the union of the cv-qualification signatures of the operand
4577      //   types.
4578      QualType T = FindCompositePointerType(lex, rex);
4579      if (T.isNull()) {
4580        Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
4581        << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4582        return QualType();
4583      }
4584
4585      ImpCastExprToType(lex, T);
4586      ImpCastExprToType(rex, T);
4587      return ResultTy;
4588    }
4589
4590    // Comparison of nullptr_t with itself.
4591    if (lType->isNullPtrType() && rType->isNullPtrType())
4592      return ResultTy;
4593  }
4594
4595  // Handle block pointer types.
4596  if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
4597    QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
4598    QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
4599
4600    if (!LHSIsNull && !RHSIsNull &&
4601        !Context.typesAreCompatible(lpointee, rpointee)) {
4602      Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
4603        << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4604    }
4605    ImpCastExprToType(rex, lType); // promote the pointer to pointer
4606    return ResultTy;
4607  }
4608  // Allow block pointers to be compared with null pointer constants.
4609  if (!isRelational
4610      && ((lType->isBlockPointerType() && rType->isPointerType())
4611          || (lType->isPointerType() && rType->isBlockPointerType()))) {
4612    if (!LHSIsNull && !RHSIsNull) {
4613      if (!((rType->isPointerType() && rType->getAs<PointerType>()
4614             ->getPointeeType()->isVoidType())
4615            || (lType->isPointerType() && lType->getAs<PointerType>()
4616                ->getPointeeType()->isVoidType())))
4617        Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
4618          << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4619    }
4620    ImpCastExprToType(rex, lType); // promote the pointer to pointer
4621    return ResultTy;
4622  }
4623
4624  if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
4625    if (lType->isPointerType() || rType->isPointerType()) {
4626      const PointerType *LPT = lType->getAs<PointerType>();
4627      const PointerType *RPT = rType->getAs<PointerType>();
4628      bool LPtrToVoid = LPT ?
4629        Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
4630      bool RPtrToVoid = RPT ?
4631        Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
4632
4633      if (!LPtrToVoid && !RPtrToVoid &&
4634          !Context.typesAreCompatible(lType, rType)) {
4635        Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
4636          << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4637      }
4638      ImpCastExprToType(rex, lType);
4639      return ResultTy;
4640    }
4641    if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
4642      if (!Context.areComparableObjCPointerTypes(lType, rType))
4643        Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
4644          << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4645      ImpCastExprToType(rex, lType);
4646      return ResultTy;
4647    }
4648  }
4649  if (lType->isAnyPointerType() && rType->isIntegerType()) {
4650    unsigned DiagID = 0;
4651    if (RHSIsNull) {
4652      if (isRelational)
4653        DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
4654    } else if (isRelational)
4655      DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
4656    else
4657      DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
4658
4659    if (DiagID) {
4660      Diag(Loc, DiagID)
4661        << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4662    }
4663    ImpCastExprToType(rex, lType); // promote the integer to pointer
4664    return ResultTy;
4665  }
4666  if (lType->isIntegerType() && rType->isAnyPointerType()) {
4667    unsigned DiagID = 0;
4668    if (LHSIsNull) {
4669      if (isRelational)
4670        DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
4671    } else if (isRelational)
4672      DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
4673    else
4674      DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
4675
4676    if (DiagID) {
4677      Diag(Loc, DiagID)
4678        << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4679    }
4680    ImpCastExprToType(lex, rType); // promote the integer to pointer
4681    return ResultTy;
4682  }
4683  // Handle block pointers.
4684  if (!isRelational && RHSIsNull
4685      && lType->isBlockPointerType() && rType->isIntegerType()) {
4686    ImpCastExprToType(rex, lType); // promote the integer to pointer
4687    return ResultTy;
4688  }
4689  if (!isRelational && LHSIsNull
4690      && lType->isIntegerType() && rType->isBlockPointerType()) {
4691    ImpCastExprToType(lex, rType); // promote the integer to pointer
4692    return ResultTy;
4693  }
4694  return InvalidOperands(Loc, lex, rex);
4695}
4696
4697/// CheckVectorCompareOperands - vector comparisons are a clang extension that
4698/// operates on extended vector types.  Instead of producing an IntTy result,
4699/// like a scalar comparison, a vector comparison produces a vector of integer
4700/// types.
4701QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
4702                                          SourceLocation Loc,
4703                                          bool isRelational) {
4704  // Check to make sure we're operating on vectors of the same type and width,
4705  // Allowing one side to be a scalar of element type.
4706  QualType vType = CheckVectorOperands(Loc, lex, rex);
4707  if (vType.isNull())
4708    return vType;
4709
4710  QualType lType = lex->getType();
4711  QualType rType = rex->getType();
4712
4713  // For non-floating point types, check for self-comparisons of the form
4714  // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
4715  // often indicate logic errors in the program.
4716  if (!lType->isFloatingType()) {
4717    if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
4718      if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
4719        if (DRL->getDecl() == DRR->getDecl())
4720          Diag(Loc, diag::warn_selfcomparison);
4721  }
4722
4723  // Check for comparisons of floating point operands using != and ==.
4724  if (!isRelational && lType->isFloatingType()) {
4725    assert (rType->isFloatingType());
4726    CheckFloatComparison(Loc,lex,rex);
4727  }
4728
4729  // Return the type for the comparison, which is the same as vector type for
4730  // integer vectors, or an integer type of identical size and number of
4731  // elements for floating point vectors.
4732  if (lType->isIntegerType())
4733    return lType;
4734
4735  const VectorType *VTy = lType->getAs<VectorType>();
4736  unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
4737  if (TypeSize == Context.getTypeSize(Context.IntTy))
4738    return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
4739  if (TypeSize == Context.getTypeSize(Context.LongTy))
4740    return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
4741
4742  assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
4743         "Unhandled vector element size in vector compare");
4744  return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
4745}
4746
4747inline QualType Sema::CheckBitwiseOperands(
4748  Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
4749  if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
4750    return CheckVectorOperands(Loc, lex, rex);
4751
4752  QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
4753
4754  if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
4755    return compType;
4756  return InvalidOperands(Loc, lex, rex);
4757}
4758
4759inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
4760  Expr *&lex, Expr *&rex, SourceLocation Loc) {
4761  UsualUnaryConversions(lex);
4762  UsualUnaryConversions(rex);
4763
4764  if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
4765    return Context.IntTy;
4766  return InvalidOperands(Loc, lex, rex);
4767}
4768
4769/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
4770/// is a read-only property; return true if so. A readonly property expression
4771/// depends on various declarations and thus must be treated specially.
4772///
4773static bool IsReadonlyProperty(Expr *E, Sema &S) {
4774  if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
4775    const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
4776    if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
4777      QualType BaseType = PropExpr->getBase()->getType();
4778      if (const ObjCObjectPointerType *OPT =
4779            BaseType->getAsObjCInterfacePointerType())
4780        if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
4781          if (S.isPropertyReadonly(PDecl, IFace))
4782            return true;
4783    }
4784  }
4785  return false;
4786}
4787
4788/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
4789/// emit an error and return true.  If so, return false.
4790static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
4791  SourceLocation OrigLoc = Loc;
4792  Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
4793                                                              &Loc);
4794  if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
4795    IsLV = Expr::MLV_ReadonlyProperty;
4796  if (IsLV == Expr::MLV_Valid)
4797    return false;
4798
4799  unsigned Diag = 0;
4800  bool NeedType = false;
4801  switch (IsLV) { // C99 6.5.16p2
4802  default: assert(0 && "Unknown result from isModifiableLvalue!");
4803  case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
4804  case Expr::MLV_ArrayType:
4805    Diag = diag::err_typecheck_array_not_modifiable_lvalue;
4806    NeedType = true;
4807    break;
4808  case Expr::MLV_NotObjectType:
4809    Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
4810    NeedType = true;
4811    break;
4812  case Expr::MLV_LValueCast:
4813    Diag = diag::err_typecheck_lvalue_casts_not_supported;
4814    break;
4815  case Expr::MLV_InvalidExpression:
4816    Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
4817    break;
4818  case Expr::MLV_IncompleteType:
4819  case Expr::MLV_IncompleteVoidType:
4820    return S.RequireCompleteType(Loc, E->getType(),
4821                PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
4822                  << E->getSourceRange());
4823  case Expr::MLV_DuplicateVectorComponents:
4824    Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
4825    break;
4826  case Expr::MLV_NotBlockQualified:
4827    Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
4828    break;
4829  case Expr::MLV_ReadonlyProperty:
4830    Diag = diag::error_readonly_property_assignment;
4831    break;
4832  case Expr::MLV_NoSetterProperty:
4833    Diag = diag::error_nosetter_property_assignment;
4834    break;
4835  }
4836
4837  SourceRange Assign;
4838  if (Loc != OrigLoc)
4839    Assign = SourceRange(OrigLoc, OrigLoc);
4840  if (NeedType)
4841    S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
4842  else
4843    S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
4844  return true;
4845}
4846
4847
4848
4849// C99 6.5.16.1
4850QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
4851                                       SourceLocation Loc,
4852                                       QualType CompoundType) {
4853  // Verify that LHS is a modifiable lvalue, and emit error if not.
4854  if (CheckForModifiableLvalue(LHS, Loc, *this))
4855    return QualType();
4856
4857  QualType LHSType = LHS->getType();
4858  QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
4859
4860  AssignConvertType ConvTy;
4861  if (CompoundType.isNull()) {
4862    // Simple assignment "x = y".
4863    ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
4864    // Special case of NSObject attributes on c-style pointer types.
4865    if (ConvTy == IncompatiblePointer &&
4866        ((Context.isObjCNSObjectType(LHSType) &&
4867          RHSType->isObjCObjectPointerType()) ||
4868         (Context.isObjCNSObjectType(RHSType) &&
4869          LHSType->isObjCObjectPointerType())))
4870      ConvTy = Compatible;
4871
4872    // If the RHS is a unary plus or minus, check to see if they = and + are
4873    // right next to each other.  If so, the user may have typo'd "x =+ 4"
4874    // instead of "x += 4".
4875    Expr *RHSCheck = RHS;
4876    if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
4877      RHSCheck = ICE->getSubExpr();
4878    if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
4879      if ((UO->getOpcode() == UnaryOperator::Plus ||
4880           UO->getOpcode() == UnaryOperator::Minus) &&
4881          Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
4882          // Only if the two operators are exactly adjacent.
4883          Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
4884          // And there is a space or other character before the subexpr of the
4885          // unary +/-.  We don't want to warn on "x=-1".
4886          Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
4887          UO->getSubExpr()->getLocStart().isFileID()) {
4888        Diag(Loc, diag::warn_not_compound_assign)
4889          << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
4890          << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
4891      }
4892    }
4893  } else {
4894    // Compound assignment "x += y"
4895    ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
4896  }
4897
4898  if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
4899                               RHS, "assigning"))
4900    return QualType();
4901
4902  // C99 6.5.16p3: The type of an assignment expression is the type of the
4903  // left operand unless the left operand has qualified type, in which case
4904  // it is the unqualified version of the type of the left operand.
4905  // C99 6.5.16.1p2: In simple assignment, the value of the right operand
4906  // is converted to the type of the assignment expression (above).
4907  // C++ 5.17p1: the type of the assignment expression is that of its left
4908  // operand.
4909  return LHSType.getUnqualifiedType();
4910}
4911
4912// C99 6.5.17
4913QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
4914  // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
4915  DefaultFunctionArrayConversion(RHS);
4916
4917  // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
4918  // incomplete in C++).
4919
4920  return RHS->getType();
4921}
4922
4923/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
4924/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
4925QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
4926                                              bool isInc) {
4927  if (Op->isTypeDependent())
4928    return Context.DependentTy;
4929
4930  QualType ResType = Op->getType();
4931  assert(!ResType.isNull() && "no type for increment/decrement expression");
4932
4933  if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
4934    // Decrement of bool is not allowed.
4935    if (!isInc) {
4936      Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
4937      return QualType();
4938    }
4939    // Increment of bool sets it to true, but is deprecated.
4940    Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
4941  } else if (ResType->isRealType()) {
4942    // OK!
4943  } else if (ResType->isAnyPointerType()) {
4944    QualType PointeeTy = ResType->getPointeeType();
4945
4946    // C99 6.5.2.4p2, 6.5.6p2
4947    if (PointeeTy->isVoidType()) {
4948      if (getLangOptions().CPlusPlus) {
4949        Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
4950          << Op->getSourceRange();
4951        return QualType();
4952      }
4953
4954      // Pointer to void is a GNU extension in C.
4955      Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
4956    } else if (PointeeTy->isFunctionType()) {
4957      if (getLangOptions().CPlusPlus) {
4958        Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
4959          << Op->getType() << Op->getSourceRange();
4960        return QualType();
4961      }
4962
4963      Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
4964        << ResType << Op->getSourceRange();
4965    } else if (RequireCompleteType(OpLoc, PointeeTy,
4966                           PDiag(diag::err_typecheck_arithmetic_incomplete_type)
4967                             << Op->getSourceRange()
4968                             << ResType))
4969      return QualType();
4970    // Diagnose bad cases where we step over interface counts.
4971    else if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4972      Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
4973        << PointeeTy << Op->getSourceRange();
4974      return QualType();
4975    }
4976  } else if (ResType->isComplexType()) {
4977    // C99 does not support ++/-- on complex types, we allow as an extension.
4978    Diag(OpLoc, diag::ext_integer_increment_complex)
4979      << ResType << Op->getSourceRange();
4980  } else {
4981    Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
4982      << ResType << Op->getSourceRange();
4983    return QualType();
4984  }
4985  // At this point, we know we have a real, complex or pointer type.
4986  // Now make sure the operand is a modifiable lvalue.
4987  if (CheckForModifiableLvalue(Op, OpLoc, *this))
4988    return QualType();
4989  return ResType;
4990}
4991
4992/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
4993/// This routine allows us to typecheck complex/recursive expressions
4994/// where the declaration is needed for type checking. We only need to
4995/// handle cases when the expression references a function designator
4996/// or is an lvalue. Here are some examples:
4997///  - &(x) => x
4998///  - &*****f => f for f a function designator.
4999///  - &s.xx => s
5000///  - &s.zz[1].yy -> s, if zz is an array
5001///  - *(x + 1) -> x, if x is an array
5002///  - &"123"[2] -> 0
5003///  - & __real__ x -> x
5004static NamedDecl *getPrimaryDecl(Expr *E) {
5005  switch (E->getStmtClass()) {
5006  case Stmt::DeclRefExprClass:
5007  case Stmt::QualifiedDeclRefExprClass:
5008    return cast<DeclRefExpr>(E)->getDecl();
5009  case Stmt::MemberExprClass:
5010    // If this is an arrow operator, the address is an offset from
5011    // the base's value, so the object the base refers to is
5012    // irrelevant.
5013    if (cast<MemberExpr>(E)->isArrow())
5014      return 0;
5015    // Otherwise, the expression refers to a part of the base
5016    return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
5017  case Stmt::ArraySubscriptExprClass: {
5018    // FIXME: This code shouldn't be necessary!  We should catch the implicit
5019    // promotion of register arrays earlier.
5020    Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
5021    if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
5022      if (ICE->getSubExpr()->getType()->isArrayType())
5023        return getPrimaryDecl(ICE->getSubExpr());
5024    }
5025    return 0;
5026  }
5027  case Stmt::UnaryOperatorClass: {
5028    UnaryOperator *UO = cast<UnaryOperator>(E);
5029
5030    switch(UO->getOpcode()) {
5031    case UnaryOperator::Real:
5032    case UnaryOperator::Imag:
5033    case UnaryOperator::Extension:
5034      return getPrimaryDecl(UO->getSubExpr());
5035    default:
5036      return 0;
5037    }
5038  }
5039  case Stmt::ParenExprClass:
5040    return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
5041  case Stmt::ImplicitCastExprClass:
5042    // If the result of an implicit cast is an l-value, we care about
5043    // the sub-expression; otherwise, the result here doesn't matter.
5044    return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
5045  default:
5046    return 0;
5047  }
5048}
5049
5050/// CheckAddressOfOperand - The operand of & must be either a function
5051/// designator or an lvalue designating an object. If it is an lvalue, the
5052/// object cannot be declared with storage class register or be a bit field.
5053/// Note: The usual conversions are *not* applied to the operand of the &
5054/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
5055/// In C++, the operand might be an overloaded function name, in which case
5056/// we allow the '&' but retain the overloaded-function type.
5057QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
5058  // Make sure to ignore parentheses in subsequent checks
5059  op = op->IgnoreParens();
5060
5061  if (op->isTypeDependent())
5062    return Context.DependentTy;
5063
5064  if (getLangOptions().C99) {
5065    // Implement C99-only parts of addressof rules.
5066    if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
5067      if (uOp->getOpcode() == UnaryOperator::Deref)
5068        // Per C99 6.5.3.2, the address of a deref always returns a valid result
5069        // (assuming the deref expression is valid).
5070        return uOp->getSubExpr()->getType();
5071    }
5072    // Technically, there should be a check for array subscript
5073    // expressions here, but the result of one is always an lvalue anyway.
5074  }
5075  NamedDecl *dcl = getPrimaryDecl(op);
5076  Expr::isLvalueResult lval = op->isLvalue(Context);
5077
5078  if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
5079    // C99 6.5.3.2p1
5080    // The operand must be either an l-value or a function designator
5081    if (!op->getType()->isFunctionType()) {
5082      // FIXME: emit more specific diag...
5083      Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
5084        << op->getSourceRange();
5085      return QualType();
5086    }
5087  } else if (op->getBitField()) { // C99 6.5.3.2p1
5088    // The operand cannot be a bit-field
5089    Diag(OpLoc, diag::err_typecheck_address_of)
5090      << "bit-field" << op->getSourceRange();
5091        return QualType();
5092  } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
5093           cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
5094    // The operand cannot be an element of a vector
5095    Diag(OpLoc, diag::err_typecheck_address_of)
5096      << "vector element" << op->getSourceRange();
5097    return QualType();
5098  } else if (isa<ObjCPropertyRefExpr>(op)) {
5099    // cannot take address of a property expression.
5100    Diag(OpLoc, diag::err_typecheck_address_of)
5101      << "property expression" << op->getSourceRange();
5102    return QualType();
5103  } else if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(op)) {
5104    // FIXME: Can LHS ever be null here?
5105    if (!CheckAddressOfOperand(CO->getTrueExpr(), OpLoc).isNull())
5106      return CheckAddressOfOperand(CO->getFalseExpr(), OpLoc);
5107  } else if (dcl) { // C99 6.5.3.2p1
5108    // We have an lvalue with a decl. Make sure the decl is not declared
5109    // with the register storage-class specifier.
5110    if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
5111      if (vd->getStorageClass() == VarDecl::Register) {
5112        Diag(OpLoc, diag::err_typecheck_address_of)
5113          << "register variable" << op->getSourceRange();
5114        return QualType();
5115      }
5116    } else if (isa<OverloadedFunctionDecl>(dcl) ||
5117               isa<FunctionTemplateDecl>(dcl)) {
5118      return Context.OverloadTy;
5119    } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
5120      // Okay: we can take the address of a field.
5121      // Could be a pointer to member, though, if there is an explicit
5122      // scope qualifier for the class.
5123      if (isa<QualifiedDeclRefExpr>(op)) {
5124        DeclContext *Ctx = dcl->getDeclContext();
5125        if (Ctx && Ctx->isRecord()) {
5126          if (FD->getType()->isReferenceType()) {
5127            Diag(OpLoc,
5128                 diag::err_cannot_form_pointer_to_member_of_reference_type)
5129              << FD->getDeclName() << FD->getType();
5130            return QualType();
5131          }
5132
5133          return Context.getMemberPointerType(op->getType(),
5134                Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
5135        }
5136      }
5137    } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(dcl)) {
5138      // Okay: we can take the address of a function.
5139      // As above.
5140      if (isa<QualifiedDeclRefExpr>(op) && MD->isInstance())
5141        return Context.getMemberPointerType(op->getType(),
5142              Context.getTypeDeclType(MD->getParent()).getTypePtr());
5143    } else if (!isa<FunctionDecl>(dcl))
5144      assert(0 && "Unknown/unexpected decl type");
5145  }
5146
5147  if (lval == Expr::LV_IncompleteVoidType) {
5148    // Taking the address of a void variable is technically illegal, but we
5149    // allow it in cases which are otherwise valid.
5150    // Example: "extern void x; void* y = &x;".
5151    Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
5152  }
5153
5154  // If the operand has type "type", the result has type "pointer to type".
5155  return Context.getPointerType(op->getType());
5156}
5157
5158QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
5159  if (Op->isTypeDependent())
5160    return Context.DependentTy;
5161
5162  UsualUnaryConversions(Op);
5163  QualType Ty = Op->getType();
5164
5165  // Note that per both C89 and C99, this is always legal, even if ptype is an
5166  // incomplete type or void.  It would be possible to warn about dereferencing
5167  // a void pointer, but it's completely well-defined, and such a warning is
5168  // unlikely to catch any mistakes.
5169  if (const PointerType *PT = Ty->getAs<PointerType>())
5170    return PT->getPointeeType();
5171
5172  if (const ObjCObjectPointerType *OPT = Ty->getAs<ObjCObjectPointerType>())
5173    return OPT->getPointeeType();
5174
5175  Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
5176    << Ty << Op->getSourceRange();
5177  return QualType();
5178}
5179
5180static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
5181  tok::TokenKind Kind) {
5182  BinaryOperator::Opcode Opc;
5183  switch (Kind) {
5184  default: assert(0 && "Unknown binop!");
5185  case tok::periodstar:           Opc = BinaryOperator::PtrMemD; break;
5186  case tok::arrowstar:            Opc = BinaryOperator::PtrMemI; break;
5187  case tok::star:                 Opc = BinaryOperator::Mul; break;
5188  case tok::slash:                Opc = BinaryOperator::Div; break;
5189  case tok::percent:              Opc = BinaryOperator::Rem; break;
5190  case tok::plus:                 Opc = BinaryOperator::Add; break;
5191  case tok::minus:                Opc = BinaryOperator::Sub; break;
5192  case tok::lessless:             Opc = BinaryOperator::Shl; break;
5193  case tok::greatergreater:       Opc = BinaryOperator::Shr; break;
5194  case tok::lessequal:            Opc = BinaryOperator::LE; break;
5195  case tok::less:                 Opc = BinaryOperator::LT; break;
5196  case tok::greaterequal:         Opc = BinaryOperator::GE; break;
5197  case tok::greater:              Opc = BinaryOperator::GT; break;
5198  case tok::exclaimequal:         Opc = BinaryOperator::NE; break;
5199  case tok::equalequal:           Opc = BinaryOperator::EQ; break;
5200  case tok::amp:                  Opc = BinaryOperator::And; break;
5201  case tok::caret:                Opc = BinaryOperator::Xor; break;
5202  case tok::pipe:                 Opc = BinaryOperator::Or; break;
5203  case tok::ampamp:               Opc = BinaryOperator::LAnd; break;
5204  case tok::pipepipe:             Opc = BinaryOperator::LOr; break;
5205  case tok::equal:                Opc = BinaryOperator::Assign; break;
5206  case tok::starequal:            Opc = BinaryOperator::MulAssign; break;
5207  case tok::slashequal:           Opc = BinaryOperator::DivAssign; break;
5208  case tok::percentequal:         Opc = BinaryOperator::RemAssign; break;
5209  case tok::plusequal:            Opc = BinaryOperator::AddAssign; break;
5210  case tok::minusequal:           Opc = BinaryOperator::SubAssign; break;
5211  case tok::lesslessequal:        Opc = BinaryOperator::ShlAssign; break;
5212  case tok::greatergreaterequal:  Opc = BinaryOperator::ShrAssign; break;
5213  case tok::ampequal:             Opc = BinaryOperator::AndAssign; break;
5214  case tok::caretequal:           Opc = BinaryOperator::XorAssign; break;
5215  case tok::pipeequal:            Opc = BinaryOperator::OrAssign; break;
5216  case tok::comma:                Opc = BinaryOperator::Comma; break;
5217  }
5218  return Opc;
5219}
5220
5221static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
5222  tok::TokenKind Kind) {
5223  UnaryOperator::Opcode Opc;
5224  switch (Kind) {
5225  default: assert(0 && "Unknown unary op!");
5226  case tok::plusplus:     Opc = UnaryOperator::PreInc; break;
5227  case tok::minusminus:   Opc = UnaryOperator::PreDec; break;
5228  case tok::amp:          Opc = UnaryOperator::AddrOf; break;
5229  case tok::star:         Opc = UnaryOperator::Deref; break;
5230  case tok::plus:         Opc = UnaryOperator::Plus; break;
5231  case tok::minus:        Opc = UnaryOperator::Minus; break;
5232  case tok::tilde:        Opc = UnaryOperator::Not; break;
5233  case tok::exclaim:      Opc = UnaryOperator::LNot; break;
5234  case tok::kw___real:    Opc = UnaryOperator::Real; break;
5235  case tok::kw___imag:    Opc = UnaryOperator::Imag; break;
5236  case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
5237  }
5238  return Opc;
5239}
5240
5241/// CreateBuiltinBinOp - Creates a new built-in binary operation with
5242/// operator @p Opc at location @c TokLoc. This routine only supports
5243/// built-in operations; ActOnBinOp handles overloaded operators.
5244Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
5245                                                  unsigned Op,
5246                                                  Expr *lhs, Expr *rhs) {
5247  QualType ResultTy;     // Result type of the binary operator.
5248  BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
5249  // The following two variables are used for compound assignment operators
5250  QualType CompLHSTy;    // Type of LHS after promotions for computation
5251  QualType CompResultTy; // Type of computation result
5252
5253  switch (Opc) {
5254  case BinaryOperator::Assign:
5255    ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
5256    break;
5257  case BinaryOperator::PtrMemD:
5258  case BinaryOperator::PtrMemI:
5259    ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
5260                                            Opc == BinaryOperator::PtrMemI);
5261    break;
5262  case BinaryOperator::Mul:
5263  case BinaryOperator::Div:
5264    ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
5265    break;
5266  case BinaryOperator::Rem:
5267    ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
5268    break;
5269  case BinaryOperator::Add:
5270    ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
5271    break;
5272  case BinaryOperator::Sub:
5273    ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
5274    break;
5275  case BinaryOperator::Shl:
5276  case BinaryOperator::Shr:
5277    ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
5278    break;
5279  case BinaryOperator::LE:
5280  case BinaryOperator::LT:
5281  case BinaryOperator::GE:
5282  case BinaryOperator::GT:
5283    ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
5284    break;
5285  case BinaryOperator::EQ:
5286  case BinaryOperator::NE:
5287    ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
5288    break;
5289  case BinaryOperator::And:
5290  case BinaryOperator::Xor:
5291  case BinaryOperator::Or:
5292    ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
5293    break;
5294  case BinaryOperator::LAnd:
5295  case BinaryOperator::LOr:
5296    ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
5297    break;
5298  case BinaryOperator::MulAssign:
5299  case BinaryOperator::DivAssign:
5300    CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
5301    CompLHSTy = CompResultTy;
5302    if (!CompResultTy.isNull())
5303      ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
5304    break;
5305  case BinaryOperator::RemAssign:
5306    CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
5307    CompLHSTy = CompResultTy;
5308    if (!CompResultTy.isNull())
5309      ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
5310    break;
5311  case BinaryOperator::AddAssign:
5312    CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5313    if (!CompResultTy.isNull())
5314      ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
5315    break;
5316  case BinaryOperator::SubAssign:
5317    CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5318    if (!CompResultTy.isNull())
5319      ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
5320    break;
5321  case BinaryOperator::ShlAssign:
5322  case BinaryOperator::ShrAssign:
5323    CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
5324    CompLHSTy = CompResultTy;
5325    if (!CompResultTy.isNull())
5326      ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
5327    break;
5328  case BinaryOperator::AndAssign:
5329  case BinaryOperator::XorAssign:
5330  case BinaryOperator::OrAssign:
5331    CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
5332    CompLHSTy = CompResultTy;
5333    if (!CompResultTy.isNull())
5334      ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
5335    break;
5336  case BinaryOperator::Comma:
5337    ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
5338    break;
5339  }
5340  if (ResultTy.isNull())
5341    return ExprError();
5342  if (CompResultTy.isNull())
5343    return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
5344  else
5345    return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
5346                                                      CompLHSTy, CompResultTy,
5347                                                      OpLoc));
5348}
5349
5350// Binary Operators.  'Tok' is the token for the operator.
5351Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
5352                                          tok::TokenKind Kind,
5353                                          ExprArg LHS, ExprArg RHS) {
5354  BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
5355  Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>();
5356
5357  assert((lhs != 0) && "ActOnBinOp(): missing left expression");
5358  assert((rhs != 0) && "ActOnBinOp(): missing right expression");
5359
5360  if (getLangOptions().CPlusPlus &&
5361      (lhs->getType()->isOverloadableType() ||
5362       rhs->getType()->isOverloadableType())) {
5363    // Find all of the overloaded operators visible from this
5364    // point. We perform both an operator-name lookup from the local
5365    // scope and an argument-dependent lookup based on the types of
5366    // the arguments.
5367    FunctionSet Functions;
5368    OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
5369    if (OverOp != OO_None) {
5370      LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
5371                                   Functions);
5372      Expr *Args[2] = { lhs, rhs };
5373      DeclarationName OpName
5374        = Context.DeclarationNames.getCXXOperatorName(OverOp);
5375      ArgumentDependentLookup(OpName, Args, 2, Functions);
5376    }
5377
5378    // Build the (potentially-overloaded, potentially-dependent)
5379    // binary operation.
5380    return CreateOverloadedBinOp(TokLoc, Opc, Functions, lhs, rhs);
5381  }
5382
5383  // Build a built-in binary operation.
5384  return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
5385}
5386
5387Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
5388                                                    unsigned OpcIn,
5389                                                    ExprArg InputArg) {
5390  UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
5391
5392  // FIXME: Input is modified below, but InputArg is not updated appropriately.
5393  Expr *Input = (Expr *)InputArg.get();
5394  QualType resultType;
5395  switch (Opc) {
5396  case UnaryOperator::OffsetOf:
5397    assert(false && "Invalid unary operator");
5398    break;
5399
5400  case UnaryOperator::PreInc:
5401  case UnaryOperator::PreDec:
5402  case UnaryOperator::PostInc:
5403  case UnaryOperator::PostDec:
5404    resultType = CheckIncrementDecrementOperand(Input, OpLoc,
5405                                                Opc == UnaryOperator::PreInc ||
5406                                                Opc == UnaryOperator::PostInc);
5407    break;
5408  case UnaryOperator::AddrOf:
5409    resultType = CheckAddressOfOperand(Input, OpLoc);
5410    break;
5411  case UnaryOperator::Deref:
5412    DefaultFunctionArrayConversion(Input);
5413    resultType = CheckIndirectionOperand(Input, OpLoc);
5414    break;
5415  case UnaryOperator::Plus:
5416  case UnaryOperator::Minus:
5417    UsualUnaryConversions(Input);
5418    resultType = Input->getType();
5419    if (resultType->isDependentType())
5420      break;
5421    if (resultType->isArithmeticType()) // C99 6.5.3.3p1
5422      break;
5423    else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
5424             resultType->isEnumeralType())
5425      break;
5426    else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
5427             Opc == UnaryOperator::Plus &&
5428             resultType->isPointerType())
5429      break;
5430
5431    return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5432      << resultType << Input->getSourceRange());
5433  case UnaryOperator::Not: // bitwise complement
5434    UsualUnaryConversions(Input);
5435    resultType = Input->getType();
5436    if (resultType->isDependentType())
5437      break;
5438    // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
5439    if (resultType->isComplexType() || resultType->isComplexIntegerType())
5440      // C99 does not support '~' for complex conjugation.
5441      Diag(OpLoc, diag::ext_integer_complement_complex)
5442        << resultType << Input->getSourceRange();
5443    else if (!resultType->isIntegerType())
5444      return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5445        << resultType << Input->getSourceRange());
5446    break;
5447  case UnaryOperator::LNot: // logical negation
5448    // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
5449    DefaultFunctionArrayConversion(Input);
5450    resultType = Input->getType();
5451    if (resultType->isDependentType())
5452      break;
5453    if (!resultType->isScalarType()) // C99 6.5.3.3p1
5454      return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5455        << resultType << Input->getSourceRange());
5456    // LNot always has type int. C99 6.5.3.3p5.
5457    // In C++, it's bool. C++ 5.3.1p8
5458    resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
5459    break;
5460  case UnaryOperator::Real:
5461  case UnaryOperator::Imag:
5462    resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
5463    break;
5464  case UnaryOperator::Extension:
5465    resultType = Input->getType();
5466    break;
5467  }
5468  if (resultType.isNull())
5469    return ExprError();
5470
5471  InputArg.release();
5472  return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
5473}
5474
5475// Unary Operators.  'Tok' is the token for the operator.
5476Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
5477                                            tok::TokenKind Op, ExprArg input) {
5478  Expr *Input = (Expr*)input.get();
5479  UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
5480
5481  if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType()) {
5482    // Find all of the overloaded operators visible from this
5483    // point. We perform both an operator-name lookup from the local
5484    // scope and an argument-dependent lookup based on the types of
5485    // the arguments.
5486    FunctionSet Functions;
5487    OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
5488    if (OverOp != OO_None) {
5489      LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
5490                                   Functions);
5491      DeclarationName OpName
5492        = Context.DeclarationNames.getCXXOperatorName(OverOp);
5493      ArgumentDependentLookup(OpName, &Input, 1, Functions);
5494    }
5495
5496    return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
5497  }
5498
5499  return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
5500}
5501
5502/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
5503Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
5504                                            SourceLocation LabLoc,
5505                                            IdentifierInfo *LabelII) {
5506  // Look up the record for this label identifier.
5507  LabelStmt *&LabelDecl = getLabelMap()[LabelII];
5508
5509  // If we haven't seen this label yet, create a forward reference. It
5510  // will be validated and/or cleaned up in ActOnFinishFunctionBody.
5511  if (LabelDecl == 0)
5512    LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
5513
5514  // Create the AST node.  The address of a label always has type 'void*'.
5515  return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
5516                                       Context.getPointerType(Context.VoidTy)));
5517}
5518
5519Sema::OwningExprResult
5520Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
5521                    SourceLocation RPLoc) { // "({..})"
5522  Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
5523  assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
5524  CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
5525
5526  bool isFileScope = getCurFunctionOrMethodDecl() == 0;
5527  if (isFileScope)
5528    return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
5529
5530  // FIXME: there are a variety of strange constraints to enforce here, for
5531  // example, it is not possible to goto into a stmt expression apparently.
5532  // More semantic analysis is needed.
5533
5534  // If there are sub stmts in the compound stmt, take the type of the last one
5535  // as the type of the stmtexpr.
5536  QualType Ty = Context.VoidTy;
5537
5538  if (!Compound->body_empty()) {
5539    Stmt *LastStmt = Compound->body_back();
5540    // If LastStmt is a label, skip down through into the body.
5541    while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
5542      LastStmt = Label->getSubStmt();
5543
5544    if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
5545      Ty = LastExpr->getType();
5546  }
5547
5548  // FIXME: Check that expression type is complete/non-abstract; statement
5549  // expressions are not lvalues.
5550
5551  substmt.release();
5552  return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
5553}
5554
5555Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
5556                                                  SourceLocation BuiltinLoc,
5557                                                  SourceLocation TypeLoc,
5558                                                  TypeTy *argty,
5559                                                  OffsetOfComponent *CompPtr,
5560                                                  unsigned NumComponents,
5561                                                  SourceLocation RPLoc) {
5562  // FIXME: This function leaks all expressions in the offset components on
5563  // error.
5564  // FIXME: Preserve type source info.
5565  QualType ArgTy = GetTypeFromParser(argty);
5566  assert(!ArgTy.isNull() && "Missing type argument!");
5567
5568  bool Dependent = ArgTy->isDependentType();
5569
5570  // We must have at least one component that refers to the type, and the first
5571  // one is known to be a field designator.  Verify that the ArgTy represents
5572  // a struct/union/class.
5573  if (!Dependent && !ArgTy->isRecordType())
5574    return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
5575
5576  // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
5577  // with an incomplete type would be illegal.
5578
5579  // Otherwise, create a null pointer as the base, and iteratively process
5580  // the offsetof designators.
5581  QualType ArgTyPtr = Context.getPointerType(ArgTy);
5582  Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
5583  Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
5584                                    ArgTy, SourceLocation());
5585
5586  // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
5587  // GCC extension, diagnose them.
5588  // FIXME: This diagnostic isn't actually visible because the location is in
5589  // a system header!
5590  if (NumComponents != 1)
5591    Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
5592      << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
5593
5594  if (!Dependent) {
5595    bool DidWarnAboutNonPOD = false;
5596
5597    // FIXME: Dependent case loses a lot of information here. And probably
5598    // leaks like a sieve.
5599    for (unsigned i = 0; i != NumComponents; ++i) {
5600      const OffsetOfComponent &OC = CompPtr[i];
5601      if (OC.isBrackets) {
5602        // Offset of an array sub-field.  TODO: Should we allow vector elements?
5603        const ArrayType *AT = Context.getAsArrayType(Res->getType());
5604        if (!AT) {
5605          Res->Destroy(Context);
5606          return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
5607            << Res->getType());
5608        }
5609
5610        // FIXME: C++: Verify that operator[] isn't overloaded.
5611
5612        // Promote the array so it looks more like a normal array subscript
5613        // expression.
5614        DefaultFunctionArrayConversion(Res);
5615
5616        // C99 6.5.2.1p1
5617        Expr *Idx = static_cast<Expr*>(OC.U.E);
5618        // FIXME: Leaks Res
5619        if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
5620          return ExprError(Diag(Idx->getLocStart(),
5621                                diag::err_typecheck_subscript_not_integer)
5622            << Idx->getSourceRange());
5623
5624        Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
5625                                               OC.LocEnd);
5626        continue;
5627      }
5628
5629      const RecordType *RC = Res->getType()->getAs<RecordType>();
5630      if (!RC) {
5631        Res->Destroy(Context);
5632        return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
5633          << Res->getType());
5634      }
5635
5636      // Get the decl corresponding to this.
5637      RecordDecl *RD = RC->getDecl();
5638      if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
5639        if (!CRD->isPOD() && !DidWarnAboutNonPOD) {
5640          ExprError(Diag(BuiltinLoc, diag::warn_offsetof_non_pod_type)
5641            << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
5642            << Res->getType());
5643          DidWarnAboutNonPOD = true;
5644        }
5645      }
5646
5647      FieldDecl *MemberDecl
5648        = dyn_cast_or_null<FieldDecl>(LookupQualifiedName(RD, OC.U.IdentInfo,
5649                                                          LookupMemberName)
5650                                        .getAsDecl());
5651      // FIXME: Leaks Res
5652      if (!MemberDecl)
5653        return ExprError(Diag(BuiltinLoc, diag::err_typecheck_no_member_deprecated)
5654         << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd));
5655
5656      // FIXME: C++: Verify that MemberDecl isn't a static field.
5657      // FIXME: Verify that MemberDecl isn't a bitfield.
5658      if (cast<RecordDecl>(MemberDecl->getDeclContext())->isAnonymousStructOrUnion()) {
5659        Res = BuildAnonymousStructUnionMemberReference(
5660            SourceLocation(), MemberDecl, Res, SourceLocation()).takeAs<Expr>();
5661      } else {
5662        // MemberDecl->getType() doesn't get the right qualifiers, but it
5663        // doesn't matter here.
5664        Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
5665                MemberDecl->getType().getNonReferenceType());
5666      }
5667    }
5668  }
5669
5670  return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
5671                                           Context.getSizeType(), BuiltinLoc));
5672}
5673
5674
5675Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
5676                                                      TypeTy *arg1,TypeTy *arg2,
5677                                                      SourceLocation RPLoc) {
5678  // FIXME: Preserve type source info.
5679  QualType argT1 = GetTypeFromParser(arg1);
5680  QualType argT2 = GetTypeFromParser(arg2);
5681
5682  assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
5683
5684  if (getLangOptions().CPlusPlus) {
5685    Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus)
5686      << SourceRange(BuiltinLoc, RPLoc);
5687    return ExprError();
5688  }
5689
5690  return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
5691                                                 argT1, argT2, RPLoc));
5692}
5693
5694Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
5695                                             ExprArg cond,
5696                                             ExprArg expr1, ExprArg expr2,
5697                                             SourceLocation RPLoc) {
5698  Expr *CondExpr = static_cast<Expr*>(cond.get());
5699  Expr *LHSExpr = static_cast<Expr*>(expr1.get());
5700  Expr *RHSExpr = static_cast<Expr*>(expr2.get());
5701
5702  assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
5703
5704  QualType resType;
5705  if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
5706    resType = Context.DependentTy;
5707  } else {
5708    // The conditional expression is required to be a constant expression.
5709    llvm::APSInt condEval(32);
5710    SourceLocation ExpLoc;
5711    if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
5712      return ExprError(Diag(ExpLoc,
5713                       diag::err_typecheck_choose_expr_requires_constant)
5714        << CondExpr->getSourceRange());
5715
5716    // If the condition is > zero, then the AST type is the same as the LSHExpr.
5717    resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
5718  }
5719
5720  cond.release(); expr1.release(); expr2.release();
5721  return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
5722                                        resType, RPLoc));
5723}
5724
5725//===----------------------------------------------------------------------===//
5726// Clang Extensions.
5727//===----------------------------------------------------------------------===//
5728
5729/// ActOnBlockStart - This callback is invoked when a block literal is started.
5730void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
5731  // Analyze block parameters.
5732  BlockSemaInfo *BSI = new BlockSemaInfo();
5733
5734  // Add BSI to CurBlock.
5735  BSI->PrevBlockInfo = CurBlock;
5736  CurBlock = BSI;
5737
5738  BSI->ReturnType = QualType();
5739  BSI->TheScope = BlockScope;
5740  BSI->hasBlockDeclRefExprs = false;
5741  BSI->hasPrototype = false;
5742  BSI->SavedFunctionNeedsScopeChecking = CurFunctionNeedsScopeChecking;
5743  CurFunctionNeedsScopeChecking = false;
5744
5745  BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
5746  PushDeclContext(BlockScope, BSI->TheDecl);
5747}
5748
5749void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
5750  assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
5751
5752  if (ParamInfo.getNumTypeObjects() == 0
5753      || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
5754    ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
5755    QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
5756
5757    if (T->isArrayType()) {
5758      Diag(ParamInfo.getSourceRange().getBegin(),
5759           diag::err_block_returns_array);
5760      return;
5761    }
5762
5763    // The parameter list is optional, if there was none, assume ().
5764    if (!T->isFunctionType())
5765      T = Context.getFunctionType(T, NULL, 0, 0, 0);
5766
5767    CurBlock->hasPrototype = true;
5768    CurBlock->isVariadic = false;
5769    // Check for a valid sentinel attribute on this block.
5770    if (CurBlock->TheDecl->getAttr<SentinelAttr>()) {
5771      Diag(ParamInfo.getAttributes()->getLoc(),
5772           diag::warn_attribute_sentinel_not_variadic) << 1;
5773      // FIXME: remove the attribute.
5774    }
5775    QualType RetTy = T.getTypePtr()->getAs<FunctionType>()->getResultType();
5776
5777    // Do not allow returning a objc interface by-value.
5778    if (RetTy->isObjCInterfaceType()) {
5779      Diag(ParamInfo.getSourceRange().getBegin(),
5780           diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
5781      return;
5782    }
5783    return;
5784  }
5785
5786  // Analyze arguments to block.
5787  assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
5788         "Not a function declarator!");
5789  DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
5790
5791  CurBlock->hasPrototype = FTI.hasPrototype;
5792  CurBlock->isVariadic = true;
5793
5794  // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
5795  // no arguments, not a function that takes a single void argument.
5796  if (FTI.hasPrototype &&
5797      FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5798     (!FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType().getCVRQualifiers()&&
5799        FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType())) {
5800    // empty arg list, don't push any params.
5801    CurBlock->isVariadic = false;
5802  } else if (FTI.hasPrototype) {
5803    for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
5804      CurBlock->Params.push_back(FTI.ArgInfo[i].Param.getAs<ParmVarDecl>());
5805    CurBlock->isVariadic = FTI.isVariadic;
5806  }
5807  CurBlock->TheDecl->setParams(Context, CurBlock->Params.data(),
5808                               CurBlock->Params.size());
5809  CurBlock->TheDecl->setIsVariadic(CurBlock->isVariadic);
5810  ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
5811  for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
5812       E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
5813    // If this has an identifier, add it to the scope stack.
5814    if ((*AI)->getIdentifier())
5815      PushOnScopeChains(*AI, CurBlock->TheScope);
5816
5817  // Check for a valid sentinel attribute on this block.
5818  if (!CurBlock->isVariadic &&
5819      CurBlock->TheDecl->getAttr<SentinelAttr>()) {
5820    Diag(ParamInfo.getAttributes()->getLoc(),
5821         diag::warn_attribute_sentinel_not_variadic) << 1;
5822    // FIXME: remove the attribute.
5823  }
5824
5825  // Analyze the return type.
5826  QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
5827  QualType RetTy = T->getAs<FunctionType>()->getResultType();
5828
5829  // Do not allow returning a objc interface by-value.
5830  if (RetTy->isObjCInterfaceType()) {
5831    Diag(ParamInfo.getSourceRange().getBegin(),
5832         diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
5833  } else if (!RetTy->isDependentType())
5834    CurBlock->ReturnType = RetTy;
5835}
5836
5837/// ActOnBlockError - If there is an error parsing a block, this callback
5838/// is invoked to pop the information about the block from the action impl.
5839void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
5840  // Ensure that CurBlock is deleted.
5841  llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
5842
5843  CurFunctionNeedsScopeChecking = CurBlock->SavedFunctionNeedsScopeChecking;
5844
5845  // Pop off CurBlock, handle nested blocks.
5846  PopDeclContext();
5847  CurBlock = CurBlock->PrevBlockInfo;
5848  // FIXME: Delete the ParmVarDecl objects as well???
5849}
5850
5851/// ActOnBlockStmtExpr - This is called when the body of a block statement
5852/// literal was successfully completed.  ^(int x){...}
5853Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
5854                                                StmtArg body, Scope *CurScope) {
5855  // If blocks are disabled, emit an error.
5856  if (!LangOpts.Blocks)
5857    Diag(CaretLoc, diag::err_blocks_disable);
5858
5859  // Ensure that CurBlock is deleted.
5860  llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
5861
5862  PopDeclContext();
5863
5864  // Pop off CurBlock, handle nested blocks.
5865  CurBlock = CurBlock->PrevBlockInfo;
5866
5867  QualType RetTy = Context.VoidTy;
5868  if (!BSI->ReturnType.isNull())
5869    RetTy = BSI->ReturnType;
5870
5871  llvm::SmallVector<QualType, 8> ArgTypes;
5872  for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
5873    ArgTypes.push_back(BSI->Params[i]->getType());
5874
5875  bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
5876  QualType BlockTy;
5877  if (!BSI->hasPrototype)
5878    BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0, false, false, 0, 0,
5879                                      NoReturn);
5880  else
5881    BlockTy = Context.getFunctionType(RetTy, ArgTypes.data(), ArgTypes.size(),
5882                                      BSI->isVariadic, 0, false, false, 0, 0,
5883                                      NoReturn);
5884
5885  // FIXME: Check that return/parameter types are complete/non-abstract
5886  DiagnoseUnusedParameters(BSI->Params.begin(), BSI->Params.end());
5887  BlockTy = Context.getBlockPointerType(BlockTy);
5888
5889  // If needed, diagnose invalid gotos and switches in the block.
5890  if (CurFunctionNeedsScopeChecking)
5891    DiagnoseInvalidJumps(static_cast<CompoundStmt*>(body.get()));
5892  CurFunctionNeedsScopeChecking = BSI->SavedFunctionNeedsScopeChecking;
5893
5894  BSI->TheDecl->setBody(body.takeAs<CompoundStmt>());
5895  CheckFallThroughForBlock(BlockTy, BSI->TheDecl->getBody());
5896  return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy,
5897                                       BSI->hasBlockDeclRefExprs));
5898}
5899
5900Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
5901                                        ExprArg expr, TypeTy *type,
5902                                        SourceLocation RPLoc) {
5903  QualType T = GetTypeFromParser(type);
5904  Expr *E = static_cast<Expr*>(expr.get());
5905  Expr *OrigExpr = E;
5906
5907  InitBuiltinVaListType();
5908
5909  // Get the va_list type
5910  QualType VaListType = Context.getBuiltinVaListType();
5911  if (VaListType->isArrayType()) {
5912    // Deal with implicit array decay; for example, on x86-64,
5913    // va_list is an array, but it's supposed to decay to
5914    // a pointer for va_arg.
5915    VaListType = Context.getArrayDecayedType(VaListType);
5916    // Make sure the input expression also decays appropriately.
5917    UsualUnaryConversions(E);
5918  } else {
5919    // Otherwise, the va_list argument must be an l-value because
5920    // it is modified by va_arg.
5921    if (!E->isTypeDependent() &&
5922        CheckForModifiableLvalue(E, BuiltinLoc, *this))
5923      return ExprError();
5924  }
5925
5926  if (!E->isTypeDependent() &&
5927      !Context.hasSameType(VaListType, E->getType())) {
5928    return ExprError(Diag(E->getLocStart(),
5929                         diag::err_first_argument_to_va_arg_not_of_type_va_list)
5930      << OrigExpr->getType() << E->getSourceRange());
5931  }
5932
5933  // FIXME: Check that type is complete/non-abstract
5934  // FIXME: Warn if a non-POD type is passed in.
5935
5936  expr.release();
5937  return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
5938                                       RPLoc));
5939}
5940
5941Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
5942  // The type of __null will be int or long, depending on the size of
5943  // pointers on the target.
5944  QualType Ty;
5945  if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
5946    Ty = Context.IntTy;
5947  else
5948    Ty = Context.LongTy;
5949
5950  return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
5951}
5952
5953bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
5954                                    SourceLocation Loc,
5955                                    QualType DstType, QualType SrcType,
5956                                    Expr *SrcExpr, const char *Flavor) {
5957  // Decode the result (notice that AST's are still created for extensions).
5958  bool isInvalid = false;
5959  unsigned DiagKind;
5960  switch (ConvTy) {
5961  default: assert(0 && "Unknown conversion type");
5962  case Compatible: return false;
5963  case PointerToInt:
5964    DiagKind = diag::ext_typecheck_convert_pointer_int;
5965    break;
5966  case IntToPointer:
5967    DiagKind = diag::ext_typecheck_convert_int_pointer;
5968    break;
5969  case IncompatiblePointer:
5970    DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
5971    break;
5972  case IncompatiblePointerSign:
5973    DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
5974    break;
5975  case FunctionVoidPointer:
5976    DiagKind = diag::ext_typecheck_convert_pointer_void_func;
5977    break;
5978  case CompatiblePointerDiscardsQualifiers:
5979    // If the qualifiers lost were because we were applying the
5980    // (deprecated) C++ conversion from a string literal to a char*
5981    // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
5982    // Ideally, this check would be performed in
5983    // CheckPointerTypesForAssignment. However, that would require a
5984    // bit of refactoring (so that the second argument is an
5985    // expression, rather than a type), which should be done as part
5986    // of a larger effort to fix CheckPointerTypesForAssignment for
5987    // C++ semantics.
5988    if (getLangOptions().CPlusPlus &&
5989        IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
5990      return false;
5991    DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
5992    break;
5993  case IntToBlockPointer:
5994    DiagKind = diag::err_int_to_block_pointer;
5995    break;
5996  case IncompatibleBlockPointer:
5997    DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
5998    break;
5999  case IncompatibleObjCQualifiedId:
6000    // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
6001    // it can give a more specific diagnostic.
6002    DiagKind = diag::warn_incompatible_qualified_id;
6003    break;
6004  case IncompatibleVectors:
6005    DiagKind = diag::warn_incompatible_vectors;
6006    break;
6007  case Incompatible:
6008    DiagKind = diag::err_typecheck_convert_incompatible;
6009    isInvalid = true;
6010    break;
6011  }
6012
6013  Diag(Loc, DiagKind) << DstType << SrcType << Flavor
6014    << SrcExpr->getSourceRange();
6015  return isInvalid;
6016}
6017
6018bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
6019  llvm::APSInt ICEResult;
6020  if (E->isIntegerConstantExpr(ICEResult, Context)) {
6021    if (Result)
6022      *Result = ICEResult;
6023    return false;
6024  }
6025
6026  Expr::EvalResult EvalResult;
6027
6028  if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
6029      EvalResult.HasSideEffects) {
6030    Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
6031
6032    if (EvalResult.Diag) {
6033      // We only show the note if it's not the usual "invalid subexpression"
6034      // or if it's actually in a subexpression.
6035      if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
6036          E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
6037        Diag(EvalResult.DiagLoc, EvalResult.Diag);
6038    }
6039
6040    return true;
6041  }
6042
6043  Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
6044    E->getSourceRange();
6045
6046  if (EvalResult.Diag &&
6047      Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
6048    Diag(EvalResult.DiagLoc, EvalResult.Diag);
6049
6050  if (Result)
6051    *Result = EvalResult.Val.getInt();
6052  return false;
6053}
6054
6055Sema::ExpressionEvaluationContext
6056Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
6057  // Introduce a new set of potentially referenced declarations to the stack.
6058  if (NewContext == PotentiallyPotentiallyEvaluated)
6059    PotentiallyReferencedDeclStack.push_back(PotentiallyReferencedDecls());
6060
6061  std::swap(ExprEvalContext, NewContext);
6062  return NewContext;
6063}
6064
6065void
6066Sema::PopExpressionEvaluationContext(ExpressionEvaluationContext OldContext,
6067                                     ExpressionEvaluationContext NewContext) {
6068  ExprEvalContext = NewContext;
6069
6070  if (OldContext == PotentiallyPotentiallyEvaluated) {
6071    // Mark any remaining declarations in the current position of the stack
6072    // as "referenced". If they were not meant to be referenced, semantic
6073    // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
6074    PotentiallyReferencedDecls RemainingDecls;
6075    RemainingDecls.swap(PotentiallyReferencedDeclStack.back());
6076    PotentiallyReferencedDeclStack.pop_back();
6077
6078    for (PotentiallyReferencedDecls::iterator I = RemainingDecls.begin(),
6079                                           IEnd = RemainingDecls.end();
6080         I != IEnd; ++I)
6081      MarkDeclarationReferenced(I->first, I->second);
6082  }
6083}
6084
6085/// \brief Note that the given declaration was referenced in the source code.
6086///
6087/// This routine should be invoke whenever a given declaration is referenced
6088/// in the source code, and where that reference occurred. If this declaration
6089/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
6090/// C99 6.9p3), then the declaration will be marked as used.
6091///
6092/// \param Loc the location where the declaration was referenced.
6093///
6094/// \param D the declaration that has been referenced by the source code.
6095void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
6096  assert(D && "No declaration?");
6097
6098  if (D->isUsed())
6099    return;
6100
6101  // Mark a parameter declaration "used", regardless of whether we're in a
6102  // template or not.
6103  if (isa<ParmVarDecl>(D))
6104    D->setUsed(true);
6105
6106  // Do not mark anything as "used" within a dependent context; wait for
6107  // an instantiation.
6108  if (CurContext->isDependentContext())
6109    return;
6110
6111  switch (ExprEvalContext) {
6112    case Unevaluated:
6113      // We are in an expression that is not potentially evaluated; do nothing.
6114      return;
6115
6116    case PotentiallyEvaluated:
6117      // We are in a potentially-evaluated expression, so this declaration is
6118      // "used"; handle this below.
6119      break;
6120
6121    case PotentiallyPotentiallyEvaluated:
6122      // We are in an expression that may be potentially evaluated; queue this
6123      // declaration reference until we know whether the expression is
6124      // potentially evaluated.
6125      PotentiallyReferencedDeclStack.back().push_back(std::make_pair(Loc, D));
6126      return;
6127  }
6128
6129  // Note that this declaration has been used.
6130  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
6131    unsigned TypeQuals;
6132    if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
6133        if (!Constructor->isUsed())
6134          DefineImplicitDefaultConstructor(Loc, Constructor);
6135    } else if (Constructor->isImplicit() &&
6136               Constructor->isCopyConstructor(Context, TypeQuals)) {
6137      if (!Constructor->isUsed())
6138        DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
6139    }
6140  } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
6141    if (Destructor->isImplicit() && !Destructor->isUsed())
6142      DefineImplicitDestructor(Loc, Destructor);
6143
6144  } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
6145    if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
6146        MethodDecl->getOverloadedOperator() == OO_Equal) {
6147      if (!MethodDecl->isUsed())
6148        DefineImplicitOverloadedAssign(Loc, MethodDecl);
6149    }
6150  }
6151  if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
6152    // Implicit instantiation of function templates and member functions of
6153    // class templates.
6154    if (!Function->getBody()) {
6155      // FIXME: distinguish between implicit instantiations of function
6156      // templates and explicit specializations (the latter don't get
6157      // instantiated, naturally).
6158      if (Function->getInstantiatedFromMemberFunction() ||
6159          Function->getPrimaryTemplate())
6160        PendingImplicitInstantiations.push_back(std::make_pair(Function, Loc));
6161    }
6162
6163
6164    // FIXME: keep track of references to static functions
6165    Function->setUsed(true);
6166    return;
6167  }
6168
6169  if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
6170    // Implicit instantiation of static data members of class templates.
6171    // FIXME: distinguish between implicit instantiations (which we need to
6172    // actually instantiate) and explicit specializations.
6173    // FIXME: extern templates
6174    if (Var->isStaticDataMember() &&
6175        Var->getInstantiatedFromStaticDataMember())
6176      PendingImplicitInstantiations.push_back(std::make_pair(Var, Loc));
6177
6178    // FIXME: keep track of references to static data?
6179
6180    D->setUsed(true);
6181    return;
6182  }
6183}
6184