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