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