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