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