SemaExpr.cpp revision f580b4df6d1834c8774322274184d046729e5ccc
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/Lex/Preprocessor.h"
20#include "clang/Lex/LiteralSupport.h"
21#include "clang/Basic/Diagnostic.h"
22#include "clang/Basic/SourceManager.h"
23#include "clang/Basic/TargetInfo.h"
24#include "clang/Parse/DeclSpec.h"
25#include "clang/Parse/Scope.h"
26using namespace clang;
27
28//===----------------------------------------------------------------------===//
29//  Standard Promotions and Conversions
30//===----------------------------------------------------------------------===//
31
32/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
33void Sema::DefaultFunctionArrayConversion(Expr *&E) {
34  QualType Ty = E->getType();
35  assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
36
37  if (const ReferenceType *ref = Ty->getAsReferenceType()) {
38    ImpCastExprToType(E, ref->getPointeeType()); // C++ [expr]
39    Ty = E->getType();
40  }
41  if (Ty->isFunctionType())
42    ImpCastExprToType(E, Context.getPointerType(Ty));
43  else if (Ty->isArrayType()) {
44    // In C90 mode, arrays only promote to pointers if the array expression is
45    // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
46    // type 'array of type' is converted to an expression that has type 'pointer
47    // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
48    // that has type 'array of type' ...".  The relevant change is "an lvalue"
49    // (C90) to "an expression" (C99).
50    //
51    // C++ 4.2p1:
52    // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
53    // T" can be converted to an rvalue of type "pointer to T".
54    //
55    if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
56        E->isLvalue(Context) == Expr::LV_Valid)
57      ImpCastExprToType(E, Context.getArrayDecayedType(Ty));
58  }
59}
60
61/// UsualUnaryConversions - Performs various conversions that are common to most
62/// operators (C99 6.3). The conversions of array and function types are
63/// sometimes surpressed. For example, the array->pointer conversion doesn't
64/// apply if the array is an argument to the sizeof or address (&) operators.
65/// In these instances, this routine should *not* be called.
66Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
67  QualType Ty = Expr->getType();
68  assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
69
70  if (const ReferenceType *Ref = Ty->getAsReferenceType()) {
71    ImpCastExprToType(Expr, Ref->getPointeeType()); // C++ [expr]
72    Ty = Expr->getType();
73  }
74  if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
75    ImpCastExprToType(Expr, Context.IntTy);
76  else
77    DefaultFunctionArrayConversion(Expr);
78
79  return Expr;
80}
81
82/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
83/// do not have a prototype. Arguments that have type float are promoted to
84/// double. All other argument types are converted by UsualUnaryConversions().
85void Sema::DefaultArgumentPromotion(Expr *&Expr) {
86  QualType Ty = Expr->getType();
87  assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
88
89  // If this is a 'float' (CVR qualified or typedef) promote to double.
90  if (const BuiltinType *BT = Ty->getAsBuiltinType())
91    if (BT->getKind() == BuiltinType::Float)
92      return ImpCastExprToType(Expr, Context.DoubleTy);
93
94  UsualUnaryConversions(Expr);
95}
96
97/// UsualArithmeticConversions - Performs various conversions that are common to
98/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
99/// routine returns the first non-arithmetic type found. The client is
100/// responsible for emitting appropriate error diagnostics.
101/// FIXME: verify the conversion rules for "complex int" are consistent with
102/// GCC.
103QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
104                                          bool isCompAssign) {
105  if (!isCompAssign) {
106    UsualUnaryConversions(lhsExpr);
107    UsualUnaryConversions(rhsExpr);
108  }
109  // For conversion purposes, we ignore any qualifiers.
110  // For example, "const float" and "float" are equivalent.
111  QualType lhs =
112    Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
113  QualType rhs =
114    Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
115
116  // If both types are identical, no conversion is needed.
117  if (lhs == rhs)
118    return lhs;
119
120  // If either side is a non-arithmetic type (e.g. a pointer), we are done.
121  // The caller can deal with this (e.g. pointer + int).
122  if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
123    return lhs;
124
125  // At this point, we have two different arithmetic types.
126
127  // Handle complex types first (C99 6.3.1.8p1).
128  if (lhs->isComplexType() || rhs->isComplexType()) {
129    // if we have an integer operand, the result is the complex type.
130    if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
131      // convert the rhs to the lhs complex type.
132      if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
133      return lhs;
134    }
135    if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
136      // convert the lhs to the rhs complex type.
137      if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
138      return rhs;
139    }
140    // This handles complex/complex, complex/float, or float/complex.
141    // When both operands are complex, the shorter operand is converted to the
142    // type of the longer, and that is the type of the result. This corresponds
143    // to what is done when combining two real floating-point operands.
144    // The fun begins when size promotion occur across type domains.
145    // From H&S 6.3.4: When one operand is complex and the other is a real
146    // floating-point type, the less precise type is converted, within it's
147    // real or complex domain, to the precision of the other type. For example,
148    // when combining a "long double" with a "double _Complex", the
149    // "double _Complex" is promoted to "long double _Complex".
150    int result = Context.getFloatingTypeOrder(lhs, rhs);
151
152    if (result > 0) { // The left side is bigger, convert rhs.
153      rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
154      if (!isCompAssign)
155        ImpCastExprToType(rhsExpr, rhs);
156    } else if (result < 0) { // The right side is bigger, convert lhs.
157      lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
158      if (!isCompAssign)
159        ImpCastExprToType(lhsExpr, lhs);
160    }
161    // At this point, lhs and rhs have the same rank/size. Now, make sure the
162    // domains match. This is a requirement for our implementation, C99
163    // does not require this promotion.
164    if (lhs != rhs) { // Domains don't match, we have complex/float mix.
165      if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
166        if (!isCompAssign)
167          ImpCastExprToType(lhsExpr, rhs);
168        return rhs;
169      } else { // handle "_Complex double, double".
170        if (!isCompAssign)
171          ImpCastExprToType(rhsExpr, lhs);
172        return lhs;
173      }
174    }
175    return lhs; // The domain/size match exactly.
176  }
177  // Now handle "real" floating types (i.e. float, double, long double).
178  if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
179    // if we have an integer operand, the result is the real floating type.
180    if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
181      // convert rhs to the lhs floating point type.
182      if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
183      return lhs;
184    }
185    if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
186      // convert lhs to the rhs floating point type.
187      if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
188      return rhs;
189    }
190    // We have two real floating types, float/complex combos were handled above.
191    // Convert the smaller operand to the bigger result.
192    int result = Context.getFloatingTypeOrder(lhs, rhs);
193
194    if (result > 0) { // convert the rhs
195      if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
196      return lhs;
197    }
198    if (result < 0) { // convert the lhs
199      if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs); // convert the lhs
200      return rhs;
201    }
202    assert(0 && "Sema::UsualArithmeticConversions(): illegal float comparison");
203  }
204  if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
205    // Handle GCC complex int extension.
206    const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
207    const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
208
209    if (lhsComplexInt && rhsComplexInt) {
210      if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
211                                      rhsComplexInt->getElementType()) >= 0) {
212        // convert the rhs
213        if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
214        return lhs;
215      }
216      if (!isCompAssign)
217        ImpCastExprToType(lhsExpr, rhs); // convert the lhs
218      return rhs;
219    } else if (lhsComplexInt && rhs->isIntegerType()) {
220      // convert the rhs to the lhs complex type.
221      if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
222      return lhs;
223    } else if (rhsComplexInt && lhs->isIntegerType()) {
224      // convert the lhs to the rhs complex type.
225      if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
226      return rhs;
227    }
228  }
229  // Finally, we have two differing integer types.
230  // The rules for this case are in C99 6.3.1.8
231  int compare = Context.getIntegerTypeOrder(lhs, rhs);
232  bool lhsSigned = lhs->isSignedIntegerType(),
233       rhsSigned = rhs->isSignedIntegerType();
234  QualType destType;
235  if (lhsSigned == rhsSigned) {
236    // Same signedness; use the higher-ranked type
237    destType = compare >= 0 ? lhs : rhs;
238  } else if (compare != (lhsSigned ? 1 : -1)) {
239    // The unsigned type has greater than or equal rank to the
240    // signed type, so use the unsigned type
241    destType = lhsSigned ? rhs : lhs;
242  } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
243    // The two types are different widths; if we are here, that
244    // means the signed type is larger than the unsigned type, so
245    // use the signed type.
246    destType = lhsSigned ? lhs : rhs;
247  } else {
248    // The signed type is higher-ranked than the unsigned type,
249    // but isn't actually any bigger (like unsigned int and long
250    // on most 32-bit systems).  Use the unsigned type corresponding
251    // to the signed type.
252    destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
253  }
254  if (!isCompAssign) {
255    ImpCastExprToType(lhsExpr, destType);
256    ImpCastExprToType(rhsExpr, destType);
257  }
258  return destType;
259}
260
261//===----------------------------------------------------------------------===//
262//  Semantic Analysis for various Expression Types
263//===----------------------------------------------------------------------===//
264
265
266/// ActOnStringLiteral - The specified tokens were lexed as pasted string
267/// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
268/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
269/// multiple tokens.  However, the common case is that StringToks points to one
270/// string.
271///
272Action::ExprResult
273Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
274  assert(NumStringToks && "Must have at least one string!");
275
276  StringLiteralParser Literal(StringToks, NumStringToks, PP, Context.Target);
277  if (Literal.hadError)
278    return ExprResult(true);
279
280  llvm::SmallVector<SourceLocation, 4> StringTokLocs;
281  for (unsigned i = 0; i != NumStringToks; ++i)
282    StringTokLocs.push_back(StringToks[i].getLocation());
283
284  // Verify that pascal strings aren't too large.
285  if (Literal.Pascal && Literal.GetStringLength() > 256)
286    return Diag(StringToks[0].getLocation(), diag::err_pascal_string_too_long,
287                SourceRange(StringToks[0].getLocation(),
288                            StringToks[NumStringToks-1].getLocation()));
289
290  QualType StrTy = Context.CharTy;
291  if (Literal.AnyWide) StrTy = Context.getWCharType();
292  if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
293
294  // Get an array type for the string, according to C99 6.4.5.  This includes
295  // the nul terminator character as well as the string length for pascal
296  // strings.
297  StrTy = Context.getConstantArrayType(StrTy,
298                                   llvm::APInt(32, Literal.GetStringLength()+1),
299                                       ArrayType::Normal, 0);
300
301  // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
302  return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
303                           Literal.AnyWide, StrTy,
304                           StringToks[0].getLocation(),
305                           StringToks[NumStringToks-1].getLocation());
306}
307
308/// DeclDefinedWithinScope - Return true if the specified decl is defined at or
309/// within the 'Within' scope.  The current Scope is CurScope.
310///
311/// NOTE: This method is extremely inefficient (linear scan), this should not be
312/// used in common cases.
313///
314static bool DeclDefinedWithinScope(ScopedDecl *D, Scope *Within,
315                                   Scope *CurScope) {
316  while (1) {
317    assert(CurScope && "CurScope not nested within 'Within'?");
318
319    // Check this scope for the decl.
320    if (CurScope->isDeclScope(D)) return true;
321
322    if (CurScope == Within) return false;
323    CurScope = CurScope->getParent();
324  }
325}
326
327/// ActOnIdentifierExpr - The parser read an identifier in expression context,
328/// validate it per-C99 6.5.1.  HasTrailingLParen indicates whether this
329/// identifier is used in a function call context.
330Sema::ExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
331                                           IdentifierInfo &II,
332                                           bool HasTrailingLParen) {
333  // Could be enum-constant, value decl, instance variable, etc.
334  Decl *D = LookupDecl(&II, Decl::IDNS_Ordinary, S);
335
336  // If this reference is in an Objective-C method, then ivar lookup happens as
337  // well.
338  if (getCurMethodDecl()) {
339    ScopedDecl *SD = dyn_cast_or_null<ScopedDecl>(D);
340    // There are two cases to handle here.  1) scoped lookup could have failed,
341    // in which case we should look for an ivar.  2) scoped lookup could have
342    // found a decl, but that decl is outside the current method (i.e. a global
343    // variable).  In these two cases, we do a lookup for an ivar with this
344    // name, if the lookup suceeds, we replace it our current decl.
345    if (SD == 0 || SD->isDefinedOutsideFunctionOrMethod()) {
346      ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
347      if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(&II)) {
348        // FIXME: This should use a new expr for a direct reference, don't turn
349        // this into Self->ivar, just return a BareIVarExpr or something.
350        IdentifierInfo &II = Context.Idents.get("self");
351        ExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
352        return new ObjCIvarRefExpr(IV, IV->getType(), Loc,
353                                 static_cast<Expr*>(SelfExpr.Val), true, true);
354      }
355    }
356    // Needed to implement property "super.method" notation.
357    if (SD == 0 && &II == SuperID) {
358      QualType T = Context.getPointerType(Context.getObjCInterfaceType(
359                     getCurMethodDecl()->getClassInterface()));
360      return new PredefinedExpr(Loc, T, PredefinedExpr::ObjCSuper);
361    }
362  }
363  // If we are parsing a block, check the block parameter list.
364  if (CurBlock) {
365    for (unsigned i = 0, e = CurBlock->Params.size(); i != e; ++i)
366      if (CurBlock->Params[i]->getIdentifier() == &II)
367        D = CurBlock->Params[i];
368  }
369  if (D == 0) {
370    // Otherwise, this could be an implicitly declared function reference (legal
371    // in C90, extension in C99).
372    if (HasTrailingLParen &&
373        !getLangOptions().CPlusPlus) // Not in C++.
374      D = ImplicitlyDefineFunction(Loc, II, S);
375    else {
376      // If this name wasn't predeclared and if this is not a function call,
377      // diagnose the problem.
378      return Diag(Loc, diag::err_undeclared_var_use, II.getName());
379    }
380  }
381
382  if (CXXFieldDecl *FD = dyn_cast<CXXFieldDecl>(D)) {
383    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
384      if (MD->isStatic())
385        // "invalid use of member 'x' in static member function"
386        return Diag(Loc, diag::err_invalid_member_use_in_static_method,
387                    FD->getName());
388      if (cast<CXXRecordDecl>(MD->getParent()) != FD->getParent())
389        // "invalid use of nonstatic data member 'x'"
390        return Diag(Loc, diag::err_invalid_non_static_member_use,
391                    FD->getName());
392
393      if (FD->isInvalidDecl())
394        return true;
395
396      // FIXME: Use DeclRefExpr or a new Expr for a direct CXXField reference.
397      ExprResult ThisExpr = ActOnCXXThis(SourceLocation());
398      return new MemberExpr(static_cast<Expr*>(ThisExpr.Val),
399                            true, FD, Loc, FD->getType());
400    }
401
402    return Diag(Loc, diag::err_invalid_non_static_member_use, FD->getName());
403  }
404  if (isa<TypedefDecl>(D))
405    return Diag(Loc, diag::err_unexpected_typedef, II.getName());
406  if (isa<ObjCInterfaceDecl>(D))
407    return Diag(Loc, diag::err_unexpected_interface, II.getName());
408  if (isa<NamespaceDecl>(D))
409    return Diag(Loc, diag::err_unexpected_namespace, II.getName());
410
411  // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
412  ValueDecl *VD = cast<ValueDecl>(D);
413
414  // check if referencing an identifier with __attribute__((deprecated)).
415  if (VD->getAttr<DeprecatedAttr>())
416    Diag(Loc, diag::warn_deprecated, VD->getName());
417
418  // Only create DeclRefExpr's for valid Decl's.
419  if (VD->isInvalidDecl())
420    return true;
421
422  // If this reference is not in a block or if the referenced variable is
423  // within the block, create a normal DeclRefExpr.
424  //
425  // FIXME: This will create BlockDeclRefExprs for global variables,
426  // function references, enums constants, etc which is suboptimal :) and breaks
427  // things like "integer constant expression" tests.
428  //
429  if (!CurBlock || DeclDefinedWithinScope(VD, CurBlock->TheScope, S))
430    return new DeclRefExpr(VD, VD->getType(), Loc);
431
432  // If we are in a block and the variable is outside the current block,
433  // bind the variable reference with a BlockDeclRefExpr.
434
435  // If the variable is in the byref set, bind it directly, otherwise it will be
436  // bound by-copy, thus we make it const within the closure.
437  if (!CurBlock->ByRefVars.count(VD))
438    VD->getType().addConst();
439
440  return new BlockDeclRefExpr(VD, VD->getType(), Loc, false);
441}
442
443Sema::ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
444                                           tok::TokenKind Kind) {
445  PredefinedExpr::IdentType IT;
446
447  switch (Kind) {
448  default: assert(0 && "Unknown simple primary expr!");
449  case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
450  case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
451  case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
452  }
453
454  // Verify that this is in a function context.
455  if (getCurFunctionDecl() == 0 && getCurMethodDecl() == 0)
456    return Diag(Loc, diag::err_predef_outside_function);
457
458  // Pre-defined identifiers are of type char[x], where x is the length of the
459  // string.
460  unsigned Length;
461  if (getCurFunctionDecl())
462    Length = getCurFunctionDecl()->getIdentifier()->getLength();
463  else
464    Length = getCurMethodDecl()->getSynthesizedMethodSize();
465
466  llvm::APInt LengthI(32, Length + 1);
467  QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
468  ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
469  return new PredefinedExpr(Loc, ResTy, IT);
470}
471
472Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
473  llvm::SmallString<16> CharBuffer;
474  CharBuffer.resize(Tok.getLength());
475  const char *ThisTokBegin = &CharBuffer[0];
476  unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
477
478  CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
479                            Tok.getLocation(), PP);
480  if (Literal.hadError())
481    return ExprResult(true);
482
483  QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
484
485  return new CharacterLiteral(Literal.getValue(), Literal.isWide(), type,
486                              Tok.getLocation());
487}
488
489Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
490  // fast path for a single digit (which is quite common). A single digit
491  // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
492  if (Tok.getLength() == 1) {
493    const char *Ty = PP.getSourceManager().getCharacterData(Tok.getLocation());
494
495    unsigned IntSize =static_cast<unsigned>(Context.getTypeSize(Context.IntTy));
496    return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *Ty-'0'),
497                                         Context.IntTy,
498                                         Tok.getLocation()));
499  }
500  llvm::SmallString<512> IntegerBuffer;
501  IntegerBuffer.resize(Tok.getLength());
502  const char *ThisTokBegin = &IntegerBuffer[0];
503
504  // Get the spelling of the token, which eliminates trigraphs, etc.
505  unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
506  NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
507                               Tok.getLocation(), PP);
508  if (Literal.hadError)
509    return ExprResult(true);
510
511  Expr *Res;
512
513  if (Literal.isFloatingLiteral()) {
514    QualType Ty;
515    if (Literal.isFloat)
516      Ty = Context.FloatTy;
517    else if (!Literal.isLong)
518      Ty = Context.DoubleTy;
519    else
520      Ty = Context.LongDoubleTy;
521
522    const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
523
524    // isExact will be set by GetFloatValue().
525    bool isExact = false;
526    Res = new FloatingLiteral(Literal.GetFloatValue(Format, &isExact), &isExact,
527                              Ty, Tok.getLocation());
528
529  } else if (!Literal.isIntegerLiteral()) {
530    return ExprResult(true);
531  } else {
532    QualType Ty;
533
534    // long long is a C99 feature.
535    if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
536        Literal.isLongLong)
537      Diag(Tok.getLocation(), diag::ext_longlong);
538
539    // Get the value in the widest-possible width.
540    llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
541
542    if (Literal.GetIntegerValue(ResultVal)) {
543      // If this value didn't fit into uintmax_t, warn and force to ull.
544      Diag(Tok.getLocation(), diag::warn_integer_too_large);
545      Ty = Context.UnsignedLongLongTy;
546      assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
547             "long long is not intmax_t?");
548    } else {
549      // If this value fits into a ULL, try to figure out what else it fits into
550      // according to the rules of C99 6.4.4.1p5.
551
552      // Octal, Hexadecimal, and integers with a U suffix are allowed to
553      // be an unsigned int.
554      bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
555
556      // Check from smallest to largest, picking the smallest type we can.
557      unsigned Width = 0;
558      if (!Literal.isLong && !Literal.isLongLong) {
559        // Are int/unsigned possibilities?
560        unsigned IntSize = Context.Target.getIntWidth();
561
562        // Does it fit in a unsigned int?
563        if (ResultVal.isIntN(IntSize)) {
564          // Does it fit in a signed int?
565          if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
566            Ty = Context.IntTy;
567          else if (AllowUnsigned)
568            Ty = Context.UnsignedIntTy;
569          Width = IntSize;
570        }
571      }
572
573      // Are long/unsigned long possibilities?
574      if (Ty.isNull() && !Literal.isLongLong) {
575        unsigned LongSize = Context.Target.getLongWidth();
576
577        // Does it fit in a unsigned long?
578        if (ResultVal.isIntN(LongSize)) {
579          // Does it fit in a signed long?
580          if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
581            Ty = Context.LongTy;
582          else if (AllowUnsigned)
583            Ty = Context.UnsignedLongTy;
584          Width = LongSize;
585        }
586      }
587
588      // Finally, check long long if needed.
589      if (Ty.isNull()) {
590        unsigned LongLongSize = Context.Target.getLongLongWidth();
591
592        // Does it fit in a unsigned long long?
593        if (ResultVal.isIntN(LongLongSize)) {
594          // Does it fit in a signed long long?
595          if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
596            Ty = Context.LongLongTy;
597          else if (AllowUnsigned)
598            Ty = Context.UnsignedLongLongTy;
599          Width = LongLongSize;
600        }
601      }
602
603      // If we still couldn't decide a type, we probably have something that
604      // does not fit in a signed long long, but has no U suffix.
605      if (Ty.isNull()) {
606        Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
607        Ty = Context.UnsignedLongLongTy;
608        Width = Context.Target.getLongLongWidth();
609      }
610
611      if (ResultVal.getBitWidth() != Width)
612        ResultVal.trunc(Width);
613    }
614
615    Res = new IntegerLiteral(ResultVal, Ty, Tok.getLocation());
616  }
617
618  // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
619  if (Literal.isImaginary)
620    Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
621
622  return Res;
623}
624
625Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
626                                        ExprTy *Val) {
627  Expr *E = (Expr *)Val;
628  assert((E != 0) && "ActOnParenExpr() missing expr");
629  return new ParenExpr(L, R, E);
630}
631
632/// The UsualUnaryConversions() function is *not* called by this routine.
633/// See C99 6.3.2.1p[2-4] for more details.
634QualType Sema::CheckSizeOfAlignOfOperand(QualType exprType,
635                                         SourceLocation OpLoc,
636                                         const SourceRange &ExprRange,
637                                         bool isSizeof) {
638  // C99 6.5.3.4p1:
639  if (isa<FunctionType>(exprType) && isSizeof)
640    // alignof(function) is allowed.
641    Diag(OpLoc, diag::ext_sizeof_function_type, ExprRange);
642  else if (exprType->isVoidType())
643    Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof",
644         ExprRange);
645  else if (exprType->isIncompleteType()) {
646    Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
647                           diag::err_alignof_incomplete_type,
648         exprType.getAsString(), ExprRange);
649    return QualType(); // error
650  }
651  // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
652  return Context.getSizeType();
653}
654
655Action::ExprResult Sema::
656ActOnSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
657                           SourceLocation LPLoc, TypeTy *Ty,
658                           SourceLocation RPLoc) {
659  // If error parsing type, ignore.
660  if (Ty == 0) return true;
661
662  // Verify that this is a valid expression.
663  QualType ArgTy = QualType::getFromOpaquePtr(Ty);
664
665  QualType resultType =
666    CheckSizeOfAlignOfOperand(ArgTy, OpLoc, SourceRange(LPLoc, RPLoc),isSizeof);
667
668  if (resultType.isNull())
669    return true;
670  return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType, OpLoc, RPLoc);
671}
672
673QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
674  DefaultFunctionArrayConversion(V);
675
676  // These operators return the element type of a complex type.
677  if (const ComplexType *CT = V->getType()->getAsComplexType())
678    return CT->getElementType();
679
680  // Otherwise they pass through real integer and floating point types here.
681  if (V->getType()->isArithmeticType())
682    return V->getType();
683
684  // Reject anything else.
685  Diag(Loc, diag::err_realimag_invalid_type, V->getType().getAsString());
686  return QualType();
687}
688
689
690
691Action::ExprResult Sema::ActOnPostfixUnaryOp(SourceLocation OpLoc,
692                                             tok::TokenKind Kind,
693                                             ExprTy *Input) {
694  UnaryOperator::Opcode Opc;
695  switch (Kind) {
696  default: assert(0 && "Unknown unary op!");
697  case tok::plusplus:   Opc = UnaryOperator::PostInc; break;
698  case tok::minusminus: Opc = UnaryOperator::PostDec; break;
699  }
700  QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
701  if (result.isNull())
702    return true;
703  return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
704}
705
706Action::ExprResult Sema::
707ActOnArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
708                        ExprTy *Idx, SourceLocation RLoc) {
709  Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
710
711  // Perform default conversions.
712  DefaultFunctionArrayConversion(LHSExp);
713  DefaultFunctionArrayConversion(RHSExp);
714
715  QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
716
717  // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
718  // to the expression *((e1)+(e2)). This means the array "Base" may actually be
719  // in the subscript position. As a result, we need to derive the array base
720  // and index from the expression types.
721  Expr *BaseExpr, *IndexExpr;
722  QualType ResultType;
723  if (const PointerType *PTy = LHSTy->getAsPointerType()) {
724    BaseExpr = LHSExp;
725    IndexExpr = RHSExp;
726    // FIXME: need to deal with const...
727    ResultType = PTy->getPointeeType();
728  } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
729     // Handle the uncommon case of "123[Ptr]".
730    BaseExpr = RHSExp;
731    IndexExpr = LHSExp;
732    // FIXME: need to deal with const...
733    ResultType = PTy->getPointeeType();
734  } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
735    BaseExpr = LHSExp;    // vectors: V[123]
736    IndexExpr = RHSExp;
737
738    // Component access limited to variables (reject vec4.rg[1]).
739    if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
740        !isa<ExtVectorElementExpr>(BaseExpr))
741      return Diag(LLoc, diag::err_ext_vector_component_access,
742                  SourceRange(LLoc, RLoc));
743    // FIXME: need to deal with const...
744    ResultType = VTy->getElementType();
745  } else {
746    return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
747                RHSExp->getSourceRange());
748  }
749  // C99 6.5.2.1p1
750  if (!IndexExpr->getType()->isIntegerType())
751    return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
752                IndexExpr->getSourceRange());
753
754  // C99 6.5.2.1p1: "shall have type "pointer to *object* type".  In practice,
755  // the following check catches trying to index a pointer to a function (e.g.
756  // void (*)(int)) and pointers to incomplete types.  Functions are not
757  // objects in C99.
758  if (!ResultType->isObjectType())
759    return Diag(BaseExpr->getLocStart(),
760                diag::err_typecheck_subscript_not_object,
761                BaseExpr->getType().getAsString(), BaseExpr->getSourceRange());
762
763  return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
764}
765
766QualType Sema::
767CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
768                        IdentifierInfo &CompName, SourceLocation CompLoc) {
769  const ExtVectorType *vecType = baseType->getAsExtVectorType();
770
771  // This flag determines whether or not the component is to be treated as a
772  // special name, or a regular GLSL-style component access.
773  bool SpecialComponent = false;
774
775  // The vector accessor can't exceed the number of elements.
776  const char *compStr = CompName.getName();
777  if (strlen(compStr) > vecType->getNumElements()) {
778    Diag(OpLoc, diag::err_ext_vector_component_exceeds_length,
779                baseType.getAsString(), SourceRange(CompLoc));
780    return QualType();
781  }
782
783  // Check that we've found one of the special components, or that the component
784  // names must come from the same set.
785  if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
786      !strcmp(compStr, "e") || !strcmp(compStr, "o")) {
787    SpecialComponent = true;
788  } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
789    do
790      compStr++;
791    while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
792  } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
793    do
794      compStr++;
795    while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
796  } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
797    do
798      compStr++;
799    while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
800  }
801
802  if (!SpecialComponent && *compStr) {
803    // We didn't get to the end of the string. This means the component names
804    // didn't come from the same set *or* we encountered an illegal name.
805    Diag(OpLoc, diag::err_ext_vector_component_name_illegal,
806         std::string(compStr,compStr+1), SourceRange(CompLoc));
807    return QualType();
808  }
809  // Each component accessor can't exceed the vector type.
810  compStr = CompName.getName();
811  while (*compStr) {
812    if (vecType->isAccessorWithinNumElements(*compStr))
813      compStr++;
814    else
815      break;
816  }
817  if (!SpecialComponent && *compStr) {
818    // We didn't get to the end of the string. This means a component accessor
819    // exceeds the number of elements in the vector.
820    Diag(OpLoc, diag::err_ext_vector_component_exceeds_length,
821                baseType.getAsString(), SourceRange(CompLoc));
822    return QualType();
823  }
824
825  // If we have a special component name, verify that the current vector length
826  // is an even number, since all special component names return exactly half
827  // the elements.
828  if (SpecialComponent && (vecType->getNumElements() & 1U)) {
829    return QualType();
830  }
831
832  // The component accessor looks fine - now we need to compute the actual type.
833  // The vector type is implied by the component accessor. For example,
834  // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
835  // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
836  unsigned CompSize = SpecialComponent ? vecType->getNumElements() / 2
837                                       : strlen(CompName.getName());
838  if (CompSize == 1)
839    return vecType->getElementType();
840
841  QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
842  // Now look up the TypeDefDecl from the vector type. Without this,
843  // diagostics look bad. We want extended vector types to appear built-in.
844  for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
845    if (ExtVectorDecls[i]->getUnderlyingType() == VT)
846      return Context.getTypedefType(ExtVectorDecls[i]);
847  }
848  return VT; // should never get here (a typedef type should always be found).
849}
850
851/// constructSetterName - Return the setter name for the given
852/// identifier, i.e. "set" + Name where the initial character of Name
853/// has been capitalized.
854// FIXME: Merge with same routine in Parser. But where should this
855// live?
856static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
857                                           const IdentifierInfo *Name) {
858  unsigned N = Name->getLength();
859  char *SelectorName = new char[3 + N];
860  memcpy(SelectorName, "set", 3);
861  memcpy(&SelectorName[3], Name->getName(), N);
862  SelectorName[3] = toupper(SelectorName[3]);
863
864  IdentifierInfo *Setter =
865    &Idents.get(SelectorName, &SelectorName[3 + N]);
866  delete[] SelectorName;
867  return Setter;
868}
869
870Action::ExprResult Sema::
871ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
872                         tok::TokenKind OpKind, SourceLocation MemberLoc,
873                         IdentifierInfo &Member) {
874  Expr *BaseExpr = static_cast<Expr *>(Base);
875  assert(BaseExpr && "no record expression");
876
877  // Perform default conversions.
878  DefaultFunctionArrayConversion(BaseExpr);
879
880  QualType BaseType = BaseExpr->getType();
881  assert(!BaseType.isNull() && "no type for member expression");
882
883  // Get the type being accessed in BaseType.  If this is an arrow, the BaseExpr
884  // must have pointer type, and the accessed type is the pointee.
885  if (OpKind == tok::arrow) {
886    if (const PointerType *PT = BaseType->getAsPointerType())
887      BaseType = PT->getPointeeType();
888    else
889      return Diag(MemberLoc, diag::err_typecheck_member_reference_arrow,
890                  BaseType.getAsString(), BaseExpr->getSourceRange());
891  }
892
893  // Handle field access to simple records.  This also handles access to fields
894  // of the ObjC 'id' struct.
895  if (const RecordType *RTy = BaseType->getAsRecordType()) {
896    RecordDecl *RDecl = RTy->getDecl();
897    if (RTy->isIncompleteType())
898      return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(),
899                  BaseExpr->getSourceRange());
900    // The record definition is complete, now make sure the member is valid.
901    FieldDecl *MemberDecl = RDecl->getMember(&Member);
902    if (!MemberDecl)
903      return Diag(MemberLoc, diag::err_typecheck_no_member, Member.getName(),
904                  BaseExpr->getSourceRange());
905
906    // Figure out the type of the member; see C99 6.5.2.3p3
907    // FIXME: Handle address space modifiers
908    QualType MemberType = MemberDecl->getType();
909    unsigned combinedQualifiers =
910        MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
911    MemberType = MemberType.getQualifiedType(combinedQualifiers);
912
913    return new MemberExpr(BaseExpr, OpKind == tok::arrow, MemberDecl,
914                          MemberLoc, MemberType);
915  }
916
917  // Handle access to Objective-C instance variables, such as "Obj->ivar" and
918  // (*Obj).ivar.
919  if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
920    if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member))
921      return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr,
922                                 OpKind == tok::arrow);
923    return Diag(MemberLoc, diag::err_typecheck_member_reference_ivar,
924                IFTy->getDecl()->getName(), Member.getName(),
925                BaseExpr->getSourceRange());
926  }
927
928  // Handle Objective-C property access, which is "Obj.property" where Obj is a
929  // pointer to a (potentially qualified) interface type.
930  const PointerType *PTy;
931  const ObjCInterfaceType *IFTy;
932  if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
933      (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
934    ObjCInterfaceDecl *IFace = IFTy->getDecl();
935
936    // Search for a declared property first.
937    if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member))
938      return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
939
940    // Check protocols on qualified interfaces.
941    for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
942         E = IFTy->qual_end(); I != E; ++I)
943      if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
944        return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
945
946    // If that failed, look for an "implicit" property by seeing if the nullary
947    // selector is implemented.
948
949    // FIXME: The logic for looking up nullary and unary selectors should be
950    // shared with the code in ActOnInstanceMessage.
951
952    Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
953    ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
954
955    // If this reference is in an @implementation, check for 'private' methods.
956    if (!Getter)
957      if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
958        if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
959          if (ObjCImplementationDecl *ImpDecl =
960              ObjCImplementations[ClassDecl->getIdentifier()])
961            Getter = ImpDecl->getInstanceMethod(Sel);
962
963    if (Getter) {
964      // If we found a getter then this may be a valid dot-reference, we
965      // need to also look for the matching setter.
966      IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
967                                                       &Member);
968      Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
969      ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
970
971      if (!Setter) {
972        if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
973          if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
974            if (ObjCImplementationDecl *ImpDecl =
975                ObjCImplementations[ClassDecl->getIdentifier()])
976              Setter = ImpDecl->getInstanceMethod(SetterSel);
977      }
978
979      // FIXME: There are some issues here. First, we are not
980      // diagnosing accesses to read-only properties because we do not
981      // know if this is a getter or setter yet. Second, we are
982      // checking that the type of the setter matches the type we
983      // expect.
984      return new ObjCPropertyRefExpr(Getter, Setter, Getter->getResultType(),
985                                     MemberLoc, BaseExpr);
986    }
987  }
988
989  // Handle 'field access' to vectors, such as 'V.xx'.
990  if (BaseType->isExtVectorType() && OpKind == tok::period) {
991    // Component access limited to variables (reject vec4.rg.g).
992    if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
993        !isa<ExtVectorElementExpr>(BaseExpr))
994      return Diag(MemberLoc, diag::err_ext_vector_component_access,
995                  BaseExpr->getSourceRange());
996    QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
997    if (ret.isNull())
998      return true;
999    return new ExtVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
1000  }
1001
1002  return Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union,
1003              BaseType.getAsString(), BaseExpr->getSourceRange());
1004}
1005
1006/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
1007/// This provides the location of the left/right parens and a list of comma
1008/// locations.
1009Action::ExprResult Sema::
1010ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc,
1011              ExprTy **args, unsigned NumArgs,
1012              SourceLocation *CommaLocs, SourceLocation RParenLoc) {
1013  Expr *Fn = static_cast<Expr *>(fn);
1014  Expr **Args = reinterpret_cast<Expr**>(args);
1015  assert(Fn && "no function call expression");
1016  FunctionDecl *FDecl = NULL;
1017
1018  // Promote the function operand.
1019  UsualUnaryConversions(Fn);
1020
1021  // If we're directly calling a function, get the declaration for
1022  // that function.
1023  if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
1024    if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr()))
1025      FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
1026
1027  // Make the call expr early, before semantic checks.  This guarantees cleanup
1028  // of arguments and function on error.
1029  llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs,
1030                                                 Context.BoolTy, RParenLoc));
1031  const FunctionType *FuncT;
1032  if (!Fn->getType()->isBlockPointerType()) {
1033    // C99 6.5.2.2p1 - "The expression that denotes the called function shall
1034    // have type pointer to function".
1035    const PointerType *PT = Fn->getType()->getAsPointerType();
1036    if (PT == 0)
1037      return Diag(LParenLoc, diag::err_typecheck_call_not_function,
1038                  Fn->getSourceRange());
1039    FuncT = PT->getPointeeType()->getAsFunctionType();
1040  } else { // This is a block call.
1041    FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
1042                getAsFunctionType();
1043  }
1044  if (FuncT == 0)
1045    return Diag(LParenLoc, diag::err_typecheck_call_not_function,
1046                Fn->getSourceRange());
1047
1048  // We know the result type of the call, set it.
1049  TheCall->setType(FuncT->getResultType());
1050
1051  if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
1052    // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
1053    // assignment, to the types of the corresponding parameter, ...
1054    unsigned NumArgsInProto = Proto->getNumArgs();
1055    unsigned NumArgsToCheck = NumArgs;
1056
1057    // If too few arguments are available (and we don't have default
1058    // arguments for the remaining parameters), don't make the call.
1059    if (NumArgs < NumArgsInProto) {
1060      if (FDecl && NumArgs >= FDecl->getMinRequiredArguments()) {
1061        // Use default arguments for missing arguments
1062        NumArgsToCheck = NumArgsInProto;
1063        TheCall->setNumArgs(NumArgsInProto);
1064      } else
1065        return Diag(RParenLoc,
1066                    !Fn->getType()->isBlockPointerType()
1067                      ? diag::err_typecheck_call_too_few_args
1068                      : diag::err_typecheck_block_too_few_args,
1069                    Fn->getSourceRange());
1070    }
1071
1072    // If too many are passed and not variadic, error on the extras and drop
1073    // them.
1074    if (NumArgs > NumArgsInProto) {
1075      if (!Proto->isVariadic()) {
1076        Diag(Args[NumArgsInProto]->getLocStart(),
1077               !Fn->getType()->isBlockPointerType()
1078                 ? diag::err_typecheck_call_too_many_args
1079                 : diag::err_typecheck_block_too_many_args,
1080             Fn->getSourceRange(),
1081             SourceRange(Args[NumArgsInProto]->getLocStart(),
1082                         Args[NumArgs-1]->getLocEnd()));
1083        // This deletes the extra arguments.
1084        TheCall->setNumArgs(NumArgsInProto);
1085      }
1086      NumArgsToCheck = NumArgsInProto;
1087    }
1088
1089    // Continue to check argument types (even if we have too few/many args).
1090    for (unsigned i = 0; i != NumArgsToCheck; i++) {
1091      QualType ProtoArgType = Proto->getArgType(i);
1092
1093      Expr *Arg;
1094      if (i < NumArgs)
1095        Arg = Args[i];
1096      else
1097        Arg = new CXXDefaultArgExpr(FDecl->getParamDecl(i));
1098      QualType ArgType = Arg->getType();
1099
1100      // Compute implicit casts from the operand to the formal argument type.
1101      AssignConvertType ConvTy =
1102        CheckSingleAssignmentConstraints(ProtoArgType, Arg);
1103      TheCall->setArg(i, Arg);
1104
1105      if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), ProtoArgType,
1106                                   ArgType, Arg, "passing"))
1107        return true;
1108    }
1109
1110    // If this is a variadic call, handle args passed through "...".
1111    if (Proto->isVariadic()) {
1112      // Promote the arguments (C99 6.5.2.2p7).
1113      for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1114        Expr *Arg = Args[i];
1115        DefaultArgumentPromotion(Arg);
1116        TheCall->setArg(i, Arg);
1117      }
1118    }
1119  } else {
1120    assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
1121
1122    // Promote the arguments (C99 6.5.2.2p6).
1123    for (unsigned i = 0; i != NumArgs; i++) {
1124      Expr *Arg = Args[i];
1125      DefaultArgumentPromotion(Arg);
1126      TheCall->setArg(i, Arg);
1127    }
1128  }
1129
1130  // Do special checking on direct calls to functions.
1131  if (FDecl)
1132    return CheckFunctionCall(FDecl, TheCall.take());
1133
1134  return TheCall.take();
1135}
1136
1137Action::ExprResult Sema::
1138ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
1139                     SourceLocation RParenLoc, ExprTy *InitExpr) {
1140  assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
1141  QualType literalType = QualType::getFromOpaquePtr(Ty);
1142  // FIXME: put back this assert when initializers are worked out.
1143  //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
1144  Expr *literalExpr = static_cast<Expr*>(InitExpr);
1145
1146  if (literalType->isArrayType()) {
1147    if (literalType->isVariableArrayType())
1148      return Diag(LParenLoc,
1149                  diag::err_variable_object_no_init,
1150                  SourceRange(LParenLoc,
1151                              literalExpr->getSourceRange().getEnd()));
1152  } else if (literalType->isIncompleteType()) {
1153    return Diag(LParenLoc,
1154                diag::err_typecheck_decl_incomplete_type,
1155                literalType.getAsString(),
1156                SourceRange(LParenLoc,
1157                            literalExpr->getSourceRange().getEnd()));
1158  }
1159
1160  if (CheckInitializerTypes(literalExpr, literalType))
1161    return true;
1162
1163  bool isFileScope = !getCurFunctionDecl() && !getCurMethodDecl();
1164  if (isFileScope) { // 6.5.2.5p3
1165    if (CheckForConstantInitializer(literalExpr, literalType))
1166      return true;
1167  }
1168  return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr, isFileScope);
1169}
1170
1171Action::ExprResult Sema::
1172ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
1173              SourceLocation RBraceLoc) {
1174  Expr **InitList = reinterpret_cast<Expr**>(initlist);
1175
1176  // Semantic analysis for initializers is done by ActOnDeclarator() and
1177  // CheckInitializer() - it requires knowledge of the object being intialized.
1178
1179  InitListExpr *E = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc);
1180  E->setType(Context.VoidTy); // FIXME: just a place holder for now.
1181  return E;
1182}
1183
1184/// CheckCastTypes - Check type constraints for casting between types.
1185bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
1186  UsualUnaryConversions(castExpr);
1187
1188  // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
1189  // type needs to be scalar.
1190  if (castType->isVoidType()) {
1191    // Cast to void allows any expr type.
1192  } else if (!castType->isScalarType() && !castType->isVectorType()) {
1193    // GCC struct/union extension: allow cast to self.
1194    if (Context.getCanonicalType(castType) !=
1195        Context.getCanonicalType(castExpr->getType()) ||
1196        (!castType->isStructureType() && !castType->isUnionType())) {
1197      // Reject any other conversions to non-scalar types.
1198      return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar,
1199                  castType.getAsString(), castExpr->getSourceRange());
1200    }
1201
1202    // accept this, but emit an ext-warn.
1203    Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar,
1204         castType.getAsString(), castExpr->getSourceRange());
1205  } else if (!castExpr->getType()->isScalarType() &&
1206             !castExpr->getType()->isVectorType()) {
1207    return Diag(castExpr->getLocStart(),
1208                diag::err_typecheck_expect_scalar_operand,
1209                castExpr->getType().getAsString(),castExpr->getSourceRange());
1210  } else if (castExpr->getType()->isVectorType()) {
1211    if (CheckVectorCast(TyR, castExpr->getType(), castType))
1212      return true;
1213  } else if (castType->isVectorType()) {
1214    if (CheckVectorCast(TyR, castType, castExpr->getType()))
1215      return true;
1216  }
1217  return false;
1218}
1219
1220bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
1221  assert(VectorTy->isVectorType() && "Not a vector type!");
1222
1223  if (Ty->isVectorType() || Ty->isIntegerType()) {
1224    if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
1225      return Diag(R.getBegin(),
1226                  Ty->isVectorType() ?
1227                  diag::err_invalid_conversion_between_vectors :
1228                  diag::err_invalid_conversion_between_vector_and_integer,
1229                  VectorTy.getAsString().c_str(),
1230                  Ty.getAsString().c_str(), R);
1231  } else
1232    return Diag(R.getBegin(),
1233                diag::err_invalid_conversion_between_vector_and_scalar,
1234                VectorTy.getAsString().c_str(),
1235                Ty.getAsString().c_str(), R);
1236
1237  return false;
1238}
1239
1240Action::ExprResult Sema::
1241ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
1242              SourceLocation RParenLoc, ExprTy *Op) {
1243  assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
1244
1245  Expr *castExpr = static_cast<Expr*>(Op);
1246  QualType castType = QualType::getFromOpaquePtr(Ty);
1247
1248  if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
1249    return true;
1250  return new ExplicitCastExpr(castType, castExpr, LParenLoc);
1251}
1252
1253/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
1254/// In that case, lex = cond.
1255inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
1256  Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
1257  UsualUnaryConversions(cond);
1258  UsualUnaryConversions(lex);
1259  UsualUnaryConversions(rex);
1260  QualType condT = cond->getType();
1261  QualType lexT = lex->getType();
1262  QualType rexT = rex->getType();
1263
1264  // first, check the condition.
1265  if (!condT->isScalarType()) { // C99 6.5.15p2
1266    Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
1267         condT.getAsString());
1268    return QualType();
1269  }
1270
1271  // Now check the two expressions.
1272
1273  // If both operands have arithmetic type, do the usual arithmetic conversions
1274  // to find a common type: C99 6.5.15p3,5.
1275  if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
1276    UsualArithmeticConversions(lex, rex);
1277    return lex->getType();
1278  }
1279
1280  // If both operands are the same structure or union type, the result is that
1281  // type.
1282  if (const RecordType *LHSRT = lexT->getAsRecordType()) {    // C99 6.5.15p3
1283    if (const RecordType *RHSRT = rexT->getAsRecordType())
1284      if (LHSRT->getDecl() == RHSRT->getDecl())
1285        // "If both the operands have structure or union type, the result has
1286        // that type."  This implies that CV qualifiers are dropped.
1287        return lexT.getUnqualifiedType();
1288  }
1289
1290  // C99 6.5.15p5: "If both operands have void type, the result has void type."
1291  // The following || allows only one side to be void (a GCC-ism).
1292  if (lexT->isVoidType() || rexT->isVoidType()) {
1293    if (!lexT->isVoidType())
1294      Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void,
1295           rex->getSourceRange());
1296    if (!rexT->isVoidType())
1297      Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void,
1298           lex->getSourceRange());
1299    ImpCastExprToType(lex, Context.VoidTy);
1300    ImpCastExprToType(rex, Context.VoidTy);
1301    return Context.VoidTy;
1302  }
1303  // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
1304  // the type of the other operand."
1305  if ((lexT->isPointerType() || lexT->isBlockPointerType()) &&
1306      rex->isNullPointerConstant(Context)) {
1307    ImpCastExprToType(rex, lexT); // promote the null to a pointer.
1308    return lexT;
1309  }
1310  if ((rexT->isPointerType() || rexT->isBlockPointerType()) &&
1311      lex->isNullPointerConstant(Context)) {
1312    ImpCastExprToType(lex, rexT); // promote the null to a pointer.
1313    return rexT;
1314  }
1315  // Allow any Objective-C types to devolve to id type.
1316  // FIXME: This seems to match gcc behavior, although that is very
1317  // arguably incorrect. For example, (xxx ? (id<P>) : (id<P>)) has
1318  // type id, which seems broken.
1319  if (Context.isObjCObjectPointerType(lexT) &&
1320      Context.isObjCObjectPointerType(rexT)) {
1321    // FIXME: This is not the correct composite type. This only
1322    // happens to work because id can more or less be used anywhere,
1323    // however this may change the type of method sends.
1324    // FIXME: gcc adds some type-checking of the arguments and emits
1325    // (confusing) incompatible comparison warnings in some
1326    // cases. Investigate.
1327    QualType compositeType = Context.getObjCIdType();
1328    ImpCastExprToType(lex, compositeType);
1329    ImpCastExprToType(rex, compositeType);
1330    return compositeType;
1331  }
1332  // Handle the case where both operands are pointers before we handle null
1333  // pointer constants in case both operands are null pointer constants.
1334  if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
1335    if (const PointerType *RHSPT = rexT->getAsPointerType()) {
1336      // get the "pointed to" types
1337      QualType lhptee = LHSPT->getPointeeType();
1338      QualType rhptee = RHSPT->getPointeeType();
1339
1340      // ignore qualifiers on void (C99 6.5.15p3, clause 6)
1341      if (lhptee->isVoidType() &&
1342          rhptee->isIncompleteOrObjectType()) {
1343        // Figure out necessary qualifiers (C99 6.5.15p6)
1344        QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
1345        QualType destType = Context.getPointerType(destPointee);
1346        ImpCastExprToType(lex, destType); // add qualifiers if necessary
1347        ImpCastExprToType(rex, destType); // promote to void*
1348        return destType;
1349      }
1350      if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
1351        QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
1352        QualType destType = Context.getPointerType(destPointee);
1353        ImpCastExprToType(lex, destType); // add qualifiers if necessary
1354        ImpCastExprToType(rex, destType); // promote to void*
1355        return destType;
1356      }
1357
1358      if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1359                                      rhptee.getUnqualifiedType())) {
1360        Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers,
1361             lexT.getAsString(), rexT.getAsString(),
1362             lex->getSourceRange(), rex->getSourceRange());
1363        // In this situation, assume a conservative type; in general
1364        // we assume void* type. No especially good reason, but this
1365        // is what gcc does, and we do have to pick to get a
1366        // consistent AST. However, if either type is an Objective-C
1367        // object type then use id.
1368        QualType incompatTy;
1369        if (Context.isObjCObjectPointerType(lexT) ||
1370            Context.isObjCObjectPointerType(rexT)) {
1371          incompatTy = Context.getObjCIdType();
1372        } else {
1373          incompatTy = Context.getPointerType(Context.VoidTy);
1374        }
1375        ImpCastExprToType(lex, incompatTy);
1376        ImpCastExprToType(rex, incompatTy);
1377        return incompatTy;
1378      }
1379      // The pointer types are compatible.
1380      // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
1381      // differently qualified versions of compatible types, the result type is
1382      // a pointer to an appropriately qualified version of the *composite*
1383      // type.
1384      // FIXME: Need to calculate the composite type.
1385      // FIXME: Need to add qualifiers
1386      QualType compositeType = lexT;
1387      ImpCastExprToType(lex, compositeType);
1388      ImpCastExprToType(rex, compositeType);
1389      return compositeType;
1390    }
1391  }
1392  // Selection between block pointer types is ok as long as they are the same.
1393  if (lexT->isBlockPointerType() && rexT->isBlockPointerType() &&
1394      Context.getCanonicalType(lexT) == Context.getCanonicalType(rexT))
1395    return lexT;
1396
1397  // Otherwise, the operands are not compatible.
1398  Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
1399       lexT.getAsString(), rexT.getAsString(),
1400       lex->getSourceRange(), rex->getSourceRange());
1401  return QualType();
1402}
1403
1404/// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
1405/// in the case of a the GNU conditional expr extension.
1406Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
1407                                            SourceLocation ColonLoc,
1408                                            ExprTy *Cond, ExprTy *LHS,
1409                                            ExprTy *RHS) {
1410  Expr *CondExpr = (Expr *) Cond;
1411  Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
1412
1413  // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
1414  // was the condition.
1415  bool isLHSNull = LHSExpr == 0;
1416  if (isLHSNull)
1417    LHSExpr = CondExpr;
1418
1419  QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
1420                                             RHSExpr, QuestionLoc);
1421  if (result.isNull())
1422    return true;
1423  return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
1424                                 RHSExpr, result);
1425}
1426
1427
1428// CheckPointerTypesForAssignment - This is a very tricky routine (despite
1429// being closely modeled after the C99 spec:-). The odd characteristic of this
1430// routine is it effectively iqnores the qualifiers on the top level pointee.
1431// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
1432// FIXME: add a couple examples in this comment.
1433Sema::AssignConvertType
1434Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
1435  QualType lhptee, rhptee;
1436
1437  // get the "pointed to" type (ignoring qualifiers at the top level)
1438  lhptee = lhsType->getAsPointerType()->getPointeeType();
1439  rhptee = rhsType->getAsPointerType()->getPointeeType();
1440
1441  // make sure we operate on the canonical type
1442  lhptee = Context.getCanonicalType(lhptee);
1443  rhptee = Context.getCanonicalType(rhptee);
1444
1445  AssignConvertType ConvTy = Compatible;
1446
1447  // C99 6.5.16.1p1: This following citation is common to constraints
1448  // 3 & 4 (below). ...and the type *pointed to* by the left has all the
1449  // qualifiers of the type *pointed to* by the right;
1450  // FIXME: Handle ASQualType
1451  if ((lhptee.getCVRQualifiers() & rhptee.getCVRQualifiers()) !=
1452       rhptee.getCVRQualifiers())
1453    ConvTy = CompatiblePointerDiscardsQualifiers;
1454
1455  // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
1456  // incomplete type and the other is a pointer to a qualified or unqualified
1457  // version of void...
1458  if (lhptee->isVoidType()) {
1459    if (rhptee->isIncompleteOrObjectType())
1460      return ConvTy;
1461
1462    // As an extension, we allow cast to/from void* to function pointer.
1463    assert(rhptee->isFunctionType());
1464    return FunctionVoidPointer;
1465  }
1466
1467  if (rhptee->isVoidType()) {
1468    if (lhptee->isIncompleteOrObjectType())
1469      return ConvTy;
1470
1471    // As an extension, we allow cast to/from void* to function pointer.
1472    assert(lhptee->isFunctionType());
1473    return FunctionVoidPointer;
1474  }
1475
1476  // Check for ObjC interfaces
1477  const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
1478  const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
1479  if (LHSIface && RHSIface &&
1480      Context.canAssignObjCInterfaces(LHSIface, RHSIface))
1481    return ConvTy;
1482
1483  // ID acts sort of like void* for ObjC interfaces
1484  if (LHSIface && Context.isObjCIdType(rhptee))
1485    return ConvTy;
1486  if (RHSIface && Context.isObjCIdType(lhptee))
1487    return ConvTy;
1488
1489  // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
1490  // unqualified versions of compatible types, ...
1491  if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1492                                  rhptee.getUnqualifiedType()))
1493    return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
1494  return ConvTy;
1495}
1496
1497/// CheckBlockPointerTypesForAssignment - This routine determines whether two
1498/// block pointer types are compatible or whether a block and normal pointer
1499/// are compatible. It is more restrict than comparing two function pointer
1500// types.
1501Sema::AssignConvertType
1502Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
1503                                          QualType rhsType) {
1504  QualType lhptee, rhptee;
1505
1506  // get the "pointed to" type (ignoring qualifiers at the top level)
1507  lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
1508  rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
1509
1510  // make sure we operate on the canonical type
1511  lhptee = Context.getCanonicalType(lhptee);
1512  rhptee = Context.getCanonicalType(rhptee);
1513
1514  AssignConvertType ConvTy = Compatible;
1515
1516  // For blocks we enforce that qualifiers are identical.
1517  if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
1518    ConvTy = CompatiblePointerDiscardsQualifiers;
1519
1520  if (!Context.typesAreBlockCompatible(lhptee, rhptee))
1521    return IncompatibleBlockPointer;
1522  return ConvTy;
1523}
1524
1525/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
1526/// has code to accommodate several GCC extensions when type checking
1527/// pointers. Here are some objectionable examples that GCC considers warnings:
1528///
1529///  int a, *pint;
1530///  short *pshort;
1531///  struct foo *pfoo;
1532///
1533///  pint = pshort; // warning: assignment from incompatible pointer type
1534///  a = pint; // warning: assignment makes integer from pointer without a cast
1535///  pint = a; // warning: assignment makes pointer from integer without a cast
1536///  pint = pfoo; // warning: assignment from incompatible pointer type
1537///
1538/// As a result, the code for dealing with pointers is more complex than the
1539/// C99 spec dictates.
1540///
1541Sema::AssignConvertType
1542Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
1543  // Get canonical types.  We're not formatting these types, just comparing
1544  // them.
1545  lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
1546  rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
1547
1548  if (lhsType == rhsType)
1549    return Compatible; // Common case: fast path an exact match.
1550
1551  if (lhsType->isReferenceType() || rhsType->isReferenceType()) {
1552    if (Context.typesAreCompatible(lhsType, rhsType))
1553      return Compatible;
1554    return Incompatible;
1555  }
1556
1557  if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
1558    if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
1559      return Compatible;
1560    // Relax integer conversions like we do for pointers below.
1561    if (rhsType->isIntegerType())
1562      return IntToPointer;
1563    if (lhsType->isIntegerType())
1564      return PointerToInt;
1565    return Incompatible;
1566  }
1567
1568  if (lhsType->isVectorType() || rhsType->isVectorType()) {
1569    // For ExtVector, allow vector splats; float -> <n x float>
1570    if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
1571      if (LV->getElementType() == rhsType)
1572        return Compatible;
1573
1574    // If we are allowing lax vector conversions, and LHS and RHS are both
1575    // vectors, the total size only needs to be the same. This is a bitcast;
1576    // no bits are changed but the result type is different.
1577    if (getLangOptions().LaxVectorConversions &&
1578        lhsType->isVectorType() && rhsType->isVectorType()) {
1579      if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
1580        return Compatible;
1581    }
1582    return Incompatible;
1583  }
1584
1585  if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
1586    return Compatible;
1587
1588  if (isa<PointerType>(lhsType)) {
1589    if (rhsType->isIntegerType())
1590      return IntToPointer;
1591
1592    if (isa<PointerType>(rhsType))
1593      return CheckPointerTypesForAssignment(lhsType, rhsType);
1594
1595    if (rhsType->getAsBlockPointerType())
1596      if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
1597        return BlockVoidPointer;
1598
1599    return Incompatible;
1600  }
1601
1602  if (isa<BlockPointerType>(lhsType)) {
1603    if (rhsType->isIntegerType())
1604      return IntToPointer;
1605
1606    if (rhsType->isBlockPointerType())
1607      return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
1608
1609    if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
1610      if (RHSPT->getPointeeType()->isVoidType())
1611        return BlockVoidPointer;
1612    }
1613    return Incompatible;
1614  }
1615
1616  if (isa<PointerType>(rhsType)) {
1617    // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
1618    if (lhsType == Context.BoolTy)
1619      return Compatible;
1620
1621    if (lhsType->isIntegerType())
1622      return PointerToInt;
1623
1624    if (isa<PointerType>(lhsType))
1625      return CheckPointerTypesForAssignment(lhsType, rhsType);
1626
1627    if (isa<BlockPointerType>(lhsType) &&
1628        rhsType->getAsPointerType()->getPointeeType()->isVoidType())
1629      return BlockVoidPointer;
1630    return Incompatible;
1631  }
1632
1633  if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
1634    if (Context.typesAreCompatible(lhsType, rhsType))
1635      return Compatible;
1636  }
1637  return Incompatible;
1638}
1639
1640Sema::AssignConvertType
1641Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
1642  // C99 6.5.16.1p1: the left operand is a pointer and the right is
1643  // a null pointer constant.
1644  if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType() ||
1645       lhsType->isBlockPointerType())
1646      && rExpr->isNullPointerConstant(Context)) {
1647    ImpCastExprToType(rExpr, lhsType);
1648    return Compatible;
1649  }
1650
1651  // We don't allow conversion of non-null-pointer constants to integers.
1652  if (lhsType->isBlockPointerType() && rExpr->getType()->isIntegerType())
1653    return IntToBlockPointer;
1654
1655  // This check seems unnatural, however it is necessary to ensure the proper
1656  // conversion of functions/arrays. If the conversion were done for all
1657  // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
1658  // expressions that surpress this implicit conversion (&, sizeof).
1659  //
1660  // Suppress this for references: C99 8.5.3p5.  FIXME: revisit when references
1661  // are better understood.
1662  if (!lhsType->isReferenceType())
1663    DefaultFunctionArrayConversion(rExpr);
1664
1665  Sema::AssignConvertType result =
1666    CheckAssignmentConstraints(lhsType, rExpr->getType());
1667
1668  // C99 6.5.16.1p2: The value of the right operand is converted to the
1669  // type of the assignment expression.
1670  if (rExpr->getType() != lhsType)
1671    ImpCastExprToType(rExpr, lhsType);
1672  return result;
1673}
1674
1675Sema::AssignConvertType
1676Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1677  return CheckAssignmentConstraints(lhsType, rhsType);
1678}
1679
1680QualType Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
1681  Diag(loc, diag::err_typecheck_invalid_operands,
1682       lex->getType().getAsString(), rex->getType().getAsString(),
1683       lex->getSourceRange(), rex->getSourceRange());
1684  return QualType();
1685}
1686
1687inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
1688                                                              Expr *&rex) {
1689  // For conversion purposes, we ignore any qualifiers.
1690  // For example, "const float" and "float" are equivalent.
1691  QualType lhsType =
1692    Context.getCanonicalType(lex->getType()).getUnqualifiedType();
1693  QualType rhsType =
1694    Context.getCanonicalType(rex->getType()).getUnqualifiedType();
1695
1696  // If the vector types are identical, return.
1697  if (lhsType == rhsType)
1698    return lhsType;
1699
1700  // Handle the case of a vector & extvector type of the same size and element
1701  // type.  It would be nice if we only had one vector type someday.
1702  if (getLangOptions().LaxVectorConversions)
1703    if (const VectorType *LV = lhsType->getAsVectorType())
1704      if (const VectorType *RV = rhsType->getAsVectorType())
1705        if (LV->getElementType() == RV->getElementType() &&
1706            LV->getNumElements() == RV->getNumElements())
1707          return lhsType->isExtVectorType() ? lhsType : rhsType;
1708
1709  // If the lhs is an extended vector and the rhs is a scalar of the same type
1710  // or a literal, promote the rhs to the vector type.
1711  if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
1712    QualType eltType = V->getElementType();
1713
1714    if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
1715        (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
1716        (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
1717      ImpCastExprToType(rex, lhsType);
1718      return lhsType;
1719    }
1720  }
1721
1722  // If the rhs is an extended vector and the lhs is a scalar of the same type,
1723  // promote the lhs to the vector type.
1724  if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
1725    QualType eltType = V->getElementType();
1726
1727    if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
1728        (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
1729        (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
1730      ImpCastExprToType(lex, rhsType);
1731      return rhsType;
1732    }
1733  }
1734
1735  // You cannot convert between vector values of different size.
1736  Diag(loc, diag::err_typecheck_vector_not_convertable,
1737       lex->getType().getAsString(), rex->getType().getAsString(),
1738       lex->getSourceRange(), rex->getSourceRange());
1739  return QualType();
1740}
1741
1742inline QualType Sema::CheckMultiplyDivideOperands(
1743  Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
1744{
1745  QualType lhsType = lex->getType(), rhsType = rex->getType();
1746
1747  if (lhsType->isVectorType() || rhsType->isVectorType())
1748    return CheckVectorOperands(loc, lex, rex);
1749
1750  QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
1751
1752  if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1753    return compType;
1754  return InvalidOperands(loc, lex, rex);
1755}
1756
1757inline QualType Sema::CheckRemainderOperands(
1758  Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
1759{
1760  QualType lhsType = lex->getType(), rhsType = rex->getType();
1761
1762  QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
1763
1764  if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
1765    return compType;
1766  return InvalidOperands(loc, lex, rex);
1767}
1768
1769inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
1770  Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
1771{
1772  if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1773    return CheckVectorOperands(loc, lex, rex);
1774
1775  QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
1776
1777  // handle the common case first (both operands are arithmetic).
1778  if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1779    return compType;
1780
1781  // Put any potential pointer into PExp
1782  Expr* PExp = lex, *IExp = rex;
1783  if (IExp->getType()->isPointerType())
1784    std::swap(PExp, IExp);
1785
1786  if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
1787    if (IExp->getType()->isIntegerType()) {
1788      // Check for arithmetic on pointers to incomplete types
1789      if (!PTy->getPointeeType()->isObjectType()) {
1790        if (PTy->getPointeeType()->isVoidType()) {
1791          Diag(loc, diag::ext_gnu_void_ptr,
1792               lex->getSourceRange(), rex->getSourceRange());
1793        } else {
1794          Diag(loc, diag::err_typecheck_arithmetic_incomplete_type,
1795               lex->getType().getAsString(), lex->getSourceRange());
1796          return QualType();
1797        }
1798      }
1799      return PExp->getType();
1800    }
1801  }
1802
1803  return InvalidOperands(loc, lex, rex);
1804}
1805
1806// C99 6.5.6
1807QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
1808                                        SourceLocation loc, bool isCompAssign) {
1809  if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1810    return CheckVectorOperands(loc, lex, rex);
1811
1812  QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
1813
1814  // Enforce type constraints: C99 6.5.6p3.
1815
1816  // Handle the common case first (both operands are arithmetic).
1817  if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1818    return compType;
1819
1820  // Either ptr - int   or   ptr - ptr.
1821  if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
1822    QualType lpointee = LHSPTy->getPointeeType();
1823
1824    // The LHS must be an object type, not incomplete, function, etc.
1825    if (!lpointee->isObjectType()) {
1826      // Handle the GNU void* extension.
1827      if (lpointee->isVoidType()) {
1828        Diag(loc, diag::ext_gnu_void_ptr,
1829             lex->getSourceRange(), rex->getSourceRange());
1830      } else {
1831        Diag(loc, diag::err_typecheck_sub_ptr_object,
1832             lex->getType().getAsString(), lex->getSourceRange());
1833        return QualType();
1834      }
1835    }
1836
1837    // The result type of a pointer-int computation is the pointer type.
1838    if (rex->getType()->isIntegerType())
1839      return lex->getType();
1840
1841    // Handle pointer-pointer subtractions.
1842    if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
1843      QualType rpointee = RHSPTy->getPointeeType();
1844
1845      // RHS must be an object type, unless void (GNU).
1846      if (!rpointee->isObjectType()) {
1847        // Handle the GNU void* extension.
1848        if (rpointee->isVoidType()) {
1849          if (!lpointee->isVoidType())
1850            Diag(loc, diag::ext_gnu_void_ptr,
1851                 lex->getSourceRange(), rex->getSourceRange());
1852        } else {
1853          Diag(loc, diag::err_typecheck_sub_ptr_object,
1854               rex->getType().getAsString(), rex->getSourceRange());
1855          return QualType();
1856        }
1857      }
1858
1859      // Pointee types must be compatible.
1860      if (!Context.typesAreCompatible(
1861              Context.getCanonicalType(lpointee).getUnqualifiedType(),
1862              Context.getCanonicalType(rpointee).getUnqualifiedType())) {
1863        Diag(loc, diag::err_typecheck_sub_ptr_compatible,
1864             lex->getType().getAsString(), rex->getType().getAsString(),
1865             lex->getSourceRange(), rex->getSourceRange());
1866        return QualType();
1867      }
1868
1869      return Context.getPointerDiffType();
1870    }
1871  }
1872
1873  return InvalidOperands(loc, lex, rex);
1874}
1875
1876// C99 6.5.7
1877QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
1878                                  bool isCompAssign) {
1879  // C99 6.5.7p2: Each of the operands shall have integer type.
1880  if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
1881    return InvalidOperands(loc, lex, rex);
1882
1883  // Shifts don't perform usual arithmetic conversions, they just do integer
1884  // promotions on each operand. C99 6.5.7p3
1885  if (!isCompAssign)
1886    UsualUnaryConversions(lex);
1887  UsualUnaryConversions(rex);
1888
1889  // "The type of the result is that of the promoted left operand."
1890  return lex->getType();
1891}
1892
1893static bool areComparableObjCInterfaces(QualType LHS, QualType RHS,
1894                                        ASTContext& Context) {
1895  const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
1896  const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
1897  // ID acts sort of like void* for ObjC interfaces
1898  if (LHSIface && Context.isObjCIdType(RHS))
1899    return true;
1900  if (RHSIface && Context.isObjCIdType(LHS))
1901    return true;
1902  if (!LHSIface || !RHSIface)
1903    return false;
1904  return Context.canAssignObjCInterfaces(LHSIface, RHSIface) ||
1905         Context.canAssignObjCInterfaces(RHSIface, LHSIface);
1906}
1907
1908// C99 6.5.8
1909QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
1910                                    bool isRelational) {
1911  if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1912    return CheckVectorCompareOperands(lex, rex, loc, isRelational);
1913
1914  // C99 6.5.8p3 / C99 6.5.9p4
1915  if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1916    UsualArithmeticConversions(lex, rex);
1917  else {
1918    UsualUnaryConversions(lex);
1919    UsualUnaryConversions(rex);
1920  }
1921  QualType lType = lex->getType();
1922  QualType rType = rex->getType();
1923
1924  // For non-floating point types, check for self-comparisons of the form
1925  // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
1926  // often indicate logic errors in the program.
1927  if (!lType->isFloatingType()) {
1928    if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
1929      if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
1930        if (DRL->getDecl() == DRR->getDecl())
1931          Diag(loc, diag::warn_selfcomparison);
1932  }
1933
1934  if (isRelational) {
1935    if (lType->isRealType() && rType->isRealType())
1936      return Context.IntTy;
1937  } else {
1938    // Check for comparisons of floating point operands using != and ==.
1939    if (lType->isFloatingType()) {
1940      assert (rType->isFloatingType());
1941      CheckFloatComparison(loc,lex,rex);
1942    }
1943
1944    if (lType->isArithmeticType() && rType->isArithmeticType())
1945      return Context.IntTy;
1946  }
1947
1948  bool LHSIsNull = lex->isNullPointerConstant(Context);
1949  bool RHSIsNull = rex->isNullPointerConstant(Context);
1950
1951  // All of the following pointer related warnings are GCC extensions, except
1952  // when handling null pointer constants. One day, we can consider making them
1953  // errors (when -pedantic-errors is enabled).
1954  if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
1955    QualType LCanPointeeTy =
1956      Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
1957    QualType RCanPointeeTy =
1958      Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
1959
1960    if (!LHSIsNull && !RHSIsNull &&                       // C99 6.5.9p2
1961        !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
1962        !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
1963                                    RCanPointeeTy.getUnqualifiedType()) &&
1964        !areComparableObjCInterfaces(LCanPointeeTy, RCanPointeeTy, Context)) {
1965      Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
1966           lType.getAsString(), rType.getAsString(),
1967           lex->getSourceRange(), rex->getSourceRange());
1968    }
1969    ImpCastExprToType(rex, lType); // promote the pointer to pointer
1970    return Context.IntTy;
1971  }
1972  // Handle block pointer types.
1973  if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
1974    QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
1975    QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
1976
1977    if (!LHSIsNull && !RHSIsNull &&
1978        !Context.typesAreBlockCompatible(lpointee, rpointee)) {
1979      Diag(loc, diag::err_typecheck_comparison_of_distinct_blocks,
1980           lType.getAsString(), rType.getAsString(),
1981           lex->getSourceRange(), rex->getSourceRange());
1982    }
1983    ImpCastExprToType(rex, lType); // promote the pointer to pointer
1984    return Context.IntTy;
1985  }
1986
1987  if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
1988    if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
1989      ImpCastExprToType(rex, lType);
1990      return Context.IntTy;
1991    }
1992  }
1993  if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
1994       rType->isIntegerType()) {
1995    if (!RHSIsNull)
1996      Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1997           lType.getAsString(), rType.getAsString(),
1998           lex->getSourceRange(), rex->getSourceRange());
1999    ImpCastExprToType(rex, lType); // promote the integer to pointer
2000    return Context.IntTy;
2001  }
2002  if (lType->isIntegerType() &&
2003      (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
2004    if (!LHSIsNull)
2005      Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2006           lType.getAsString(), rType.getAsString(),
2007           lex->getSourceRange(), rex->getSourceRange());
2008    ImpCastExprToType(lex, rType); // promote the integer to pointer
2009    return Context.IntTy;
2010  }
2011  // Handle block pointers.
2012  if (lType->isBlockPointerType() && rType->isIntegerType()) {
2013    if (!RHSIsNull)
2014      Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2015           lType.getAsString(), rType.getAsString(),
2016           lex->getSourceRange(), rex->getSourceRange());
2017    ImpCastExprToType(rex, lType); // promote the integer to pointer
2018    return Context.IntTy;
2019  }
2020  if (lType->isIntegerType() && rType->isBlockPointerType()) {
2021    if (!LHSIsNull)
2022      Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2023           lType.getAsString(), rType.getAsString(),
2024           lex->getSourceRange(), rex->getSourceRange());
2025    ImpCastExprToType(lex, rType); // promote the integer to pointer
2026    return Context.IntTy;
2027  }
2028  return InvalidOperands(loc, lex, rex);
2029}
2030
2031/// CheckVectorCompareOperands - vector comparisons are a clang extension that
2032/// operates on extended vector types.  Instead of producing an IntTy result,
2033/// like a scalar comparison, a vector comparison produces a vector of integer
2034/// types.
2035QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
2036                                          SourceLocation loc,
2037                                          bool isRelational) {
2038  // Check to make sure we're operating on vectors of the same type and width,
2039  // Allowing one side to be a scalar of element type.
2040  QualType vType = CheckVectorOperands(loc, lex, rex);
2041  if (vType.isNull())
2042    return vType;
2043
2044  QualType lType = lex->getType();
2045  QualType rType = rex->getType();
2046
2047  // For non-floating point types, check for self-comparisons of the form
2048  // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
2049  // often indicate logic errors in the program.
2050  if (!lType->isFloatingType()) {
2051    if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2052      if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
2053        if (DRL->getDecl() == DRR->getDecl())
2054          Diag(loc, diag::warn_selfcomparison);
2055  }
2056
2057  // Check for comparisons of floating point operands using != and ==.
2058  if (!isRelational && lType->isFloatingType()) {
2059    assert (rType->isFloatingType());
2060    CheckFloatComparison(loc,lex,rex);
2061  }
2062
2063  // Return the type for the comparison, which is the same as vector type for
2064  // integer vectors, or an integer type of identical size and number of
2065  // elements for floating point vectors.
2066  if (lType->isIntegerType())
2067    return lType;
2068
2069  const VectorType *VTy = lType->getAsVectorType();
2070
2071  // FIXME: need to deal with non-32b int / non-64b long long
2072  unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
2073  if (TypeSize == 32) {
2074    return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
2075  }
2076  assert(TypeSize == 64 && "Unhandled vector element size in vector compare");
2077  return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
2078}
2079
2080inline QualType Sema::CheckBitwiseOperands(
2081  Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
2082{
2083  if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
2084    return CheckVectorOperands(loc, lex, rex);
2085
2086  QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
2087
2088  if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
2089    return compType;
2090  return InvalidOperands(loc, lex, rex);
2091}
2092
2093inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
2094  Expr *&lex, Expr *&rex, SourceLocation loc)
2095{
2096  UsualUnaryConversions(lex);
2097  UsualUnaryConversions(rex);
2098
2099  if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
2100    return Context.IntTy;
2101  return InvalidOperands(loc, lex, rex);
2102}
2103
2104inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
2105  Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType)
2106{
2107  QualType lhsType = lex->getType();
2108  QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
2109  Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue(Context);
2110
2111  switch (mlval) { // C99 6.5.16p2
2112  case Expr::MLV_Valid:
2113    break;
2114  case Expr::MLV_ConstQualified:
2115    Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
2116    return QualType();
2117  case Expr::MLV_ArrayType:
2118    Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
2119         lhsType.getAsString(), lex->getSourceRange());
2120    return QualType();
2121  case Expr::MLV_NotObjectType:
2122    Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
2123         lhsType.getAsString(), lex->getSourceRange());
2124    return QualType();
2125  case Expr::MLV_InvalidExpression:
2126    Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
2127         lex->getSourceRange());
2128    return QualType();
2129  case Expr::MLV_IncompleteType:
2130  case Expr::MLV_IncompleteVoidType:
2131    Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
2132         lhsType.getAsString(), lex->getSourceRange());
2133    return QualType();
2134  case Expr::MLV_DuplicateVectorComponents:
2135    Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
2136         lex->getSourceRange());
2137    return QualType();
2138  }
2139
2140  AssignConvertType ConvTy;
2141  if (compoundType.isNull()) {
2142    // Simple assignment "x = y".
2143    ConvTy = CheckSingleAssignmentConstraints(lhsType, rex);
2144
2145    // If the RHS is a unary plus or minus, check to see if they = and + are
2146    // right next to each other.  If so, the user may have typo'd "x =+ 4"
2147    // instead of "x += 4".
2148    Expr *RHSCheck = rex;
2149    if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
2150      RHSCheck = ICE->getSubExpr();
2151    if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
2152      if ((UO->getOpcode() == UnaryOperator::Plus ||
2153           UO->getOpcode() == UnaryOperator::Minus) &&
2154          loc.isFileID() && UO->getOperatorLoc().isFileID() &&
2155          // Only if the two operators are exactly adjacent.
2156          loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
2157        Diag(loc, diag::warn_not_compound_assign,
2158             UO->getOpcode() == UnaryOperator::Plus ? "+" : "-",
2159             SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()));
2160    }
2161  } else {
2162    // Compound assignment "x += y"
2163    ConvTy = CheckCompoundAssignmentConstraints(lhsType, rhsType);
2164  }
2165
2166  if (DiagnoseAssignmentResult(ConvTy, loc, lhsType, rhsType,
2167                               rex, "assigning"))
2168    return QualType();
2169
2170  // C99 6.5.16p3: The type of an assignment expression is the type of the
2171  // left operand unless the left operand has qualified type, in which case
2172  // it is the unqualified version of the type of the left operand.
2173  // C99 6.5.16.1p2: In simple assignment, the value of the right operand
2174  // is converted to the type of the assignment expression (above).
2175  // C++ 5.17p1: the type of the assignment expression is that of its left
2176  // oprdu.
2177  return lhsType.getUnqualifiedType();
2178}
2179
2180inline QualType Sema::CheckCommaOperands( // C99 6.5.17
2181  Expr *&lex, Expr *&rex, SourceLocation loc) {
2182
2183  // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
2184  DefaultFunctionArrayConversion(rex);
2185  return rex->getType();
2186}
2187
2188/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
2189/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
2190QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
2191  QualType resType = op->getType();
2192  assert(!resType.isNull() && "no type for increment/decrement expression");
2193
2194  // C99 6.5.2.4p1: We allow complex as a GCC extension.
2195  if (const PointerType *pt = resType->getAsPointerType()) {
2196    if (pt->getPointeeType()->isVoidType()) {
2197      Diag(OpLoc, diag::ext_gnu_void_ptr, op->getSourceRange());
2198    } else if (!pt->getPointeeType()->isObjectType()) {
2199      // C99 6.5.2.4p2, 6.5.6p2
2200      Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
2201           resType.getAsString(), op->getSourceRange());
2202      return QualType();
2203    }
2204  } else if (!resType->isRealType()) {
2205    if (resType->isComplexType())
2206      // C99 does not support ++/-- on complex types.
2207      Diag(OpLoc, diag::ext_integer_increment_complex,
2208           resType.getAsString(), op->getSourceRange());
2209    else {
2210      Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
2211           resType.getAsString(), op->getSourceRange());
2212      return QualType();
2213    }
2214  }
2215  // At this point, we know we have a real, complex or pointer type.
2216  // Now make sure the operand is a modifiable lvalue.
2217  Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue(Context);
2218  if (mlval != Expr::MLV_Valid) {
2219    // FIXME: emit a more precise diagnostic...
2220    Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
2221         op->getSourceRange());
2222    return QualType();
2223  }
2224  return resType;
2225}
2226
2227/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
2228/// This routine allows us to typecheck complex/recursive expressions
2229/// where the declaration is needed for type checking. We only need to
2230/// handle cases when the expression references a function designator
2231/// or is an lvalue. Here are some examples:
2232///  - &(x) => x
2233///  - &*****f => f for f a function designator.
2234///  - &s.xx => s
2235///  - &s.zz[1].yy -> s, if zz is an array
2236///  - *(x + 1) -> x, if x is an array
2237///  - &"123"[2] -> 0
2238///  - & __real__ x -> x
2239static ValueDecl *getPrimaryDecl(Expr *E) {
2240  switch (E->getStmtClass()) {
2241  case Stmt::DeclRefExprClass:
2242    return cast<DeclRefExpr>(E)->getDecl();
2243  case Stmt::MemberExprClass:
2244    // Fields cannot be declared with a 'register' storage class.
2245    // &X->f is always ok, even if X is declared register.
2246    if (cast<MemberExpr>(E)->isArrow())
2247      return 0;
2248    return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
2249  case Stmt::ArraySubscriptExprClass: {
2250    // &X[4] and &4[X] refers to X if X is not a pointer.
2251
2252    ValueDecl *VD = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
2253    if (!VD || VD->getType()->isPointerType())
2254      return 0;
2255    else
2256      return VD;
2257  }
2258  case Stmt::UnaryOperatorClass: {
2259    UnaryOperator *UO = cast<UnaryOperator>(E);
2260
2261    switch(UO->getOpcode()) {
2262    case UnaryOperator::Deref: {
2263      // *(X + 1) refers to X if X is not a pointer.
2264      ValueDecl *VD = getPrimaryDecl(UO->getSubExpr());
2265      if (!VD || VD->getType()->isPointerType())
2266        return 0;
2267      return VD;
2268    }
2269    case UnaryOperator::Real:
2270    case UnaryOperator::Imag:
2271    case UnaryOperator::Extension:
2272      return getPrimaryDecl(UO->getSubExpr());
2273    default:
2274      return 0;
2275    }
2276  }
2277  case Stmt::BinaryOperatorClass: {
2278    BinaryOperator *BO = cast<BinaryOperator>(E);
2279
2280    // Handle cases involving pointer arithmetic. The result of an
2281    // Assign or AddAssign is not an lvalue so they can be ignored.
2282
2283    // (x + n) or (n + x) => x
2284    if (BO->getOpcode() == BinaryOperator::Add) {
2285      if (BO->getLHS()->getType()->isPointerType()) {
2286        return getPrimaryDecl(BO->getLHS());
2287      } else if (BO->getRHS()->getType()->isPointerType()) {
2288        return getPrimaryDecl(BO->getRHS());
2289      }
2290    }
2291
2292    return 0;
2293  }
2294  case Stmt::ParenExprClass:
2295    return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
2296  case Stmt::ImplicitCastExprClass:
2297    // &X[4] when X is an array, has an implicit cast from array to pointer.
2298    return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
2299  default:
2300    return 0;
2301  }
2302}
2303
2304/// CheckAddressOfOperand - The operand of & must be either a function
2305/// designator or an lvalue designating an object. If it is an lvalue, the
2306/// object cannot be declared with storage class register or be a bit field.
2307/// Note: The usual conversions are *not* applied to the operand of the &
2308/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
2309QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
2310  if (getLangOptions().C99) {
2311    // Implement C99-only parts of addressof rules.
2312    if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
2313      if (uOp->getOpcode() == UnaryOperator::Deref)
2314        // Per C99 6.5.3.2, the address of a deref always returns a valid result
2315        // (assuming the deref expression is valid).
2316        return uOp->getSubExpr()->getType();
2317    }
2318    // Technically, there should be a check for array subscript
2319    // expressions here, but the result of one is always an lvalue anyway.
2320  }
2321  ValueDecl *dcl = getPrimaryDecl(op);
2322  Expr::isLvalueResult lval = op->isLvalue(Context);
2323
2324  if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
2325    if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
2326      // FIXME: emit more specific diag...
2327      Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
2328           op->getSourceRange());
2329      return QualType();
2330    }
2331  } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
2332    if (MemExpr->getMemberDecl()->isBitField()) {
2333      Diag(OpLoc, diag::err_typecheck_address_of,
2334           std::string("bit-field"), op->getSourceRange());
2335      return QualType();
2336    }
2337  // Check for Apple extension for accessing vector components.
2338  } else if (isa<ArraySubscriptExpr>(op) &&
2339           cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
2340    Diag(OpLoc, diag::err_typecheck_address_of,
2341         std::string("vector"), op->getSourceRange());
2342    return QualType();
2343  } else if (dcl) { // C99 6.5.3.2p1
2344    // We have an lvalue with a decl. Make sure the decl is not declared
2345    // with the register storage-class specifier.
2346    if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
2347      if (vd->getStorageClass() == VarDecl::Register) {
2348        Diag(OpLoc, diag::err_typecheck_address_of,
2349             std::string("register variable"), op->getSourceRange());
2350        return QualType();
2351      }
2352    } else
2353      assert(0 && "Unknown/unexpected decl type");
2354  }
2355
2356  // If the operand has type "type", the result has type "pointer to type".
2357  return Context.getPointerType(op->getType());
2358}
2359
2360QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
2361  UsualUnaryConversions(op);
2362  QualType qType = op->getType();
2363
2364  if (const PointerType *PT = qType->getAsPointerType()) {
2365    // Note that per both C89 and C99, this is always legal, even
2366    // if ptype is an incomplete type or void.
2367    // It would be possible to warn about dereferencing a
2368    // void pointer, but it's completely well-defined,
2369    // and such a warning is unlikely to catch any mistakes.
2370    return PT->getPointeeType();
2371  }
2372  Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
2373       qType.getAsString(), op->getSourceRange());
2374  return QualType();
2375}
2376
2377static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
2378  tok::TokenKind Kind) {
2379  BinaryOperator::Opcode Opc;
2380  switch (Kind) {
2381  default: assert(0 && "Unknown binop!");
2382  case tok::star:                 Opc = BinaryOperator::Mul; break;
2383  case tok::slash:                Opc = BinaryOperator::Div; break;
2384  case tok::percent:              Opc = BinaryOperator::Rem; break;
2385  case tok::plus:                 Opc = BinaryOperator::Add; break;
2386  case tok::minus:                Opc = BinaryOperator::Sub; break;
2387  case tok::lessless:             Opc = BinaryOperator::Shl; break;
2388  case tok::greatergreater:       Opc = BinaryOperator::Shr; break;
2389  case tok::lessequal:            Opc = BinaryOperator::LE; break;
2390  case tok::less:                 Opc = BinaryOperator::LT; break;
2391  case tok::greaterequal:         Opc = BinaryOperator::GE; break;
2392  case tok::greater:              Opc = BinaryOperator::GT; break;
2393  case tok::exclaimequal:         Opc = BinaryOperator::NE; break;
2394  case tok::equalequal:           Opc = BinaryOperator::EQ; break;
2395  case tok::amp:                  Opc = BinaryOperator::And; break;
2396  case tok::caret:                Opc = BinaryOperator::Xor; break;
2397  case tok::pipe:                 Opc = BinaryOperator::Or; break;
2398  case tok::ampamp:               Opc = BinaryOperator::LAnd; break;
2399  case tok::pipepipe:             Opc = BinaryOperator::LOr; break;
2400  case tok::equal:                Opc = BinaryOperator::Assign; break;
2401  case tok::starequal:            Opc = BinaryOperator::MulAssign; break;
2402  case tok::slashequal:           Opc = BinaryOperator::DivAssign; break;
2403  case tok::percentequal:         Opc = BinaryOperator::RemAssign; break;
2404  case tok::plusequal:            Opc = BinaryOperator::AddAssign; break;
2405  case tok::minusequal:           Opc = BinaryOperator::SubAssign; break;
2406  case tok::lesslessequal:        Opc = BinaryOperator::ShlAssign; break;
2407  case tok::greatergreaterequal:  Opc = BinaryOperator::ShrAssign; break;
2408  case tok::ampequal:             Opc = BinaryOperator::AndAssign; break;
2409  case tok::caretequal:           Opc = BinaryOperator::XorAssign; break;
2410  case tok::pipeequal:            Opc = BinaryOperator::OrAssign; break;
2411  case tok::comma:                Opc = BinaryOperator::Comma; break;
2412  }
2413  return Opc;
2414}
2415
2416static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
2417  tok::TokenKind Kind) {
2418  UnaryOperator::Opcode Opc;
2419  switch (Kind) {
2420  default: assert(0 && "Unknown unary op!");
2421  case tok::plusplus:     Opc = UnaryOperator::PreInc; break;
2422  case tok::minusminus:   Opc = UnaryOperator::PreDec; break;
2423  case tok::amp:          Opc = UnaryOperator::AddrOf; break;
2424  case tok::star:         Opc = UnaryOperator::Deref; break;
2425  case tok::plus:         Opc = UnaryOperator::Plus; break;
2426  case tok::minus:        Opc = UnaryOperator::Minus; break;
2427  case tok::tilde:        Opc = UnaryOperator::Not; break;
2428  case tok::exclaim:      Opc = UnaryOperator::LNot; break;
2429  case tok::kw_sizeof:    Opc = UnaryOperator::SizeOf; break;
2430  case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
2431  case tok::kw___real:    Opc = UnaryOperator::Real; break;
2432  case tok::kw___imag:    Opc = UnaryOperator::Imag; break;
2433  case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
2434  }
2435  return Opc;
2436}
2437
2438// Binary Operators.  'Tok' is the token for the operator.
2439Action::ExprResult Sema::ActOnBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
2440                                    ExprTy *LHS, ExprTy *RHS) {
2441  BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
2442  Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
2443
2444  assert((lhs != 0) && "ActOnBinOp(): missing left expression");
2445  assert((rhs != 0) && "ActOnBinOp(): missing right expression");
2446
2447  QualType ResultTy;  // Result type of the binary operator.
2448  QualType CompTy;    // Computation type for compound assignments (e.g. '+=')
2449
2450  switch (Opc) {
2451  default:
2452    assert(0 && "Unknown binary expr!");
2453  case BinaryOperator::Assign:
2454    ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
2455    break;
2456  case BinaryOperator::Mul:
2457  case BinaryOperator::Div:
2458    ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
2459    break;
2460  case BinaryOperator::Rem:
2461    ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
2462    break;
2463  case BinaryOperator::Add:
2464    ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
2465    break;
2466  case BinaryOperator::Sub:
2467    ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
2468    break;
2469  case BinaryOperator::Shl:
2470  case BinaryOperator::Shr:
2471    ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
2472    break;
2473  case BinaryOperator::LE:
2474  case BinaryOperator::LT:
2475  case BinaryOperator::GE:
2476  case BinaryOperator::GT:
2477    ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, true);
2478    break;
2479  case BinaryOperator::EQ:
2480  case BinaryOperator::NE:
2481    ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, false);
2482    break;
2483  case BinaryOperator::And:
2484  case BinaryOperator::Xor:
2485  case BinaryOperator::Or:
2486    ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
2487    break;
2488  case BinaryOperator::LAnd:
2489  case BinaryOperator::LOr:
2490    ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
2491    break;
2492  case BinaryOperator::MulAssign:
2493  case BinaryOperator::DivAssign:
2494    CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc, true);
2495    if (!CompTy.isNull())
2496      ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2497    break;
2498  case BinaryOperator::RemAssign:
2499    CompTy = CheckRemainderOperands(lhs, rhs, TokLoc, true);
2500    if (!CompTy.isNull())
2501      ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2502    break;
2503  case BinaryOperator::AddAssign:
2504    CompTy = CheckAdditionOperands(lhs, rhs, TokLoc, true);
2505    if (!CompTy.isNull())
2506      ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2507    break;
2508  case BinaryOperator::SubAssign:
2509    CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc, true);
2510    if (!CompTy.isNull())
2511      ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2512    break;
2513  case BinaryOperator::ShlAssign:
2514  case BinaryOperator::ShrAssign:
2515    CompTy = CheckShiftOperands(lhs, rhs, TokLoc, true);
2516    if (!CompTy.isNull())
2517      ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2518    break;
2519  case BinaryOperator::AndAssign:
2520  case BinaryOperator::XorAssign:
2521  case BinaryOperator::OrAssign:
2522    CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc, true);
2523    if (!CompTy.isNull())
2524      ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2525    break;
2526  case BinaryOperator::Comma:
2527    ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
2528    break;
2529  }
2530  if (ResultTy.isNull())
2531    return true;
2532  if (CompTy.isNull())
2533    return new BinaryOperator(lhs, rhs, Opc, ResultTy, TokLoc);
2534  else
2535    return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, TokLoc);
2536}
2537
2538// Unary Operators.  'Tok' is the token for the operator.
2539Action::ExprResult Sema::ActOnUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
2540                                      ExprTy *input) {
2541  Expr *Input = (Expr*)input;
2542  UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
2543  QualType resultType;
2544  switch (Opc) {
2545  default:
2546    assert(0 && "Unimplemented unary expr!");
2547  case UnaryOperator::PreInc:
2548  case UnaryOperator::PreDec:
2549    resultType = CheckIncrementDecrementOperand(Input, OpLoc);
2550    break;
2551  case UnaryOperator::AddrOf:
2552    resultType = CheckAddressOfOperand(Input, OpLoc);
2553    break;
2554  case UnaryOperator::Deref:
2555    DefaultFunctionArrayConversion(Input);
2556    resultType = CheckIndirectionOperand(Input, OpLoc);
2557    break;
2558  case UnaryOperator::Plus:
2559  case UnaryOperator::Minus:
2560    UsualUnaryConversions(Input);
2561    resultType = Input->getType();
2562    if (!resultType->isArithmeticType())  // C99 6.5.3.3p1
2563      return Diag(OpLoc, diag::err_typecheck_unary_expr,
2564                  resultType.getAsString());
2565    break;
2566  case UnaryOperator::Not: // bitwise complement
2567    UsualUnaryConversions(Input);
2568    resultType = Input->getType();
2569    // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
2570    if (resultType->isComplexType() || resultType->isComplexIntegerType())
2571      // C99 does not support '~' for complex conjugation.
2572      Diag(OpLoc, diag::ext_integer_complement_complex,
2573           resultType.getAsString(), Input->getSourceRange());
2574    else if (!resultType->isIntegerType())
2575      return Diag(OpLoc, diag::err_typecheck_unary_expr,
2576                  resultType.getAsString(), Input->getSourceRange());
2577    break;
2578  case UnaryOperator::LNot: // logical negation
2579    // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
2580    DefaultFunctionArrayConversion(Input);
2581    resultType = Input->getType();
2582    if (!resultType->isScalarType()) // C99 6.5.3.3p1
2583      return Diag(OpLoc, diag::err_typecheck_unary_expr,
2584                  resultType.getAsString());
2585    // LNot always has type int. C99 6.5.3.3p5.
2586    resultType = Context.IntTy;
2587    break;
2588  case UnaryOperator::SizeOf:
2589    resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc,
2590                                           Input->getSourceRange(), true);
2591    break;
2592  case UnaryOperator::AlignOf:
2593    resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc,
2594                                           Input->getSourceRange(), false);
2595    break;
2596  case UnaryOperator::Real:
2597  case UnaryOperator::Imag:
2598    resultType = CheckRealImagOperand(Input, OpLoc);
2599    break;
2600  case UnaryOperator::Extension:
2601    resultType = Input->getType();
2602    break;
2603  }
2604  if (resultType.isNull())
2605    return true;
2606  return new UnaryOperator(Input, Opc, resultType, OpLoc);
2607}
2608
2609/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
2610Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
2611                                      SourceLocation LabLoc,
2612                                      IdentifierInfo *LabelII) {
2613  // Look up the record for this label identifier.
2614  LabelStmt *&LabelDecl = LabelMap[LabelII];
2615
2616  // If we haven't seen this label yet, create a forward reference. It
2617  // will be validated and/or cleaned up in ActOnFinishFunctionBody.
2618  if (LabelDecl == 0)
2619    LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
2620
2621  // Create the AST node.  The address of a label always has type 'void*'.
2622  return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
2623                           Context.getPointerType(Context.VoidTy));
2624}
2625
2626Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
2627                                     SourceLocation RPLoc) { // "({..})"
2628  Stmt *SubStmt = static_cast<Stmt*>(substmt);
2629  assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
2630  CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
2631
2632  // FIXME: there are a variety of strange constraints to enforce here, for
2633  // example, it is not possible to goto into a stmt expression apparently.
2634  // More semantic analysis is needed.
2635
2636  // FIXME: the last statement in the compount stmt has its value used.  We
2637  // should not warn about it being unused.
2638
2639  // If there are sub stmts in the compound stmt, take the type of the last one
2640  // as the type of the stmtexpr.
2641  QualType Ty = Context.VoidTy;
2642
2643  if (!Compound->body_empty()) {
2644    Stmt *LastStmt = Compound->body_back();
2645    // If LastStmt is a label, skip down through into the body.
2646    while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
2647      LastStmt = Label->getSubStmt();
2648
2649    if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
2650      Ty = LastExpr->getType();
2651  }
2652
2653  return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
2654}
2655
2656Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
2657                                            SourceLocation TypeLoc,
2658                                            TypeTy *argty,
2659                                            OffsetOfComponent *CompPtr,
2660                                            unsigned NumComponents,
2661                                            SourceLocation RPLoc) {
2662  QualType ArgTy = QualType::getFromOpaquePtr(argty);
2663  assert(!ArgTy.isNull() && "Missing type argument!");
2664
2665  // We must have at least one component that refers to the type, and the first
2666  // one is known to be a field designator.  Verify that the ArgTy represents
2667  // a struct/union/class.
2668  if (!ArgTy->isRecordType())
2669    return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString());
2670
2671  // Otherwise, create a compound literal expression as the base, and
2672  // iteratively process the offsetof designators.
2673  Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0, false);
2674
2675  // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
2676  // GCC extension, diagnose them.
2677  if (NumComponents != 1)
2678    Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator,
2679         SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd));
2680
2681  for (unsigned i = 0; i != NumComponents; ++i) {
2682    const OffsetOfComponent &OC = CompPtr[i];
2683    if (OC.isBrackets) {
2684      // Offset of an array sub-field.  TODO: Should we allow vector elements?
2685      const ArrayType *AT = Context.getAsArrayType(Res->getType());
2686      if (!AT) {
2687        delete Res;
2688        return Diag(OC.LocEnd, diag::err_offsetof_array_type,
2689                    Res->getType().getAsString());
2690      }
2691
2692      // FIXME: C++: Verify that operator[] isn't overloaded.
2693
2694      // C99 6.5.2.1p1
2695      Expr *Idx = static_cast<Expr*>(OC.U.E);
2696      if (!Idx->getType()->isIntegerType())
2697        return Diag(Idx->getLocStart(), diag::err_typecheck_subscript,
2698                    Idx->getSourceRange());
2699
2700      Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
2701      continue;
2702    }
2703
2704    const RecordType *RC = Res->getType()->getAsRecordType();
2705    if (!RC) {
2706      delete Res;
2707      return Diag(OC.LocEnd, diag::err_offsetof_record_type,
2708                  Res->getType().getAsString());
2709    }
2710
2711    // Get the decl corresponding to this.
2712    RecordDecl *RD = RC->getDecl();
2713    FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
2714    if (!MemberDecl)
2715      return Diag(BuiltinLoc, diag::err_typecheck_no_member,
2716                  OC.U.IdentInfo->getName(),
2717                  SourceRange(OC.LocStart, OC.LocEnd));
2718
2719    // FIXME: C++: Verify that MemberDecl isn't a static field.
2720    // FIXME: Verify that MemberDecl isn't a bitfield.
2721    // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
2722    // matter here.
2723    Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd, MemberDecl->getType());
2724  }
2725
2726  return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
2727                           BuiltinLoc);
2728}
2729
2730
2731Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
2732                                                TypeTy *arg1, TypeTy *arg2,
2733                                                SourceLocation RPLoc) {
2734  QualType argT1 = QualType::getFromOpaquePtr(arg1);
2735  QualType argT2 = QualType::getFromOpaquePtr(arg2);
2736
2737  assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
2738
2739  return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
2740}
2741
2742Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
2743                                       ExprTy *expr1, ExprTy *expr2,
2744                                       SourceLocation RPLoc) {
2745  Expr *CondExpr = static_cast<Expr*>(cond);
2746  Expr *LHSExpr = static_cast<Expr*>(expr1);
2747  Expr *RHSExpr = static_cast<Expr*>(expr2);
2748
2749  assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
2750
2751  // The conditional expression is required to be a constant expression.
2752  llvm::APSInt condEval(32);
2753  SourceLocation ExpLoc;
2754  if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
2755    return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
2756                 CondExpr->getSourceRange());
2757
2758  // If the condition is > zero, then the AST type is the same as the LSHExpr.
2759  QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
2760                                               RHSExpr->getType();
2761  return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
2762}
2763
2764//===----------------------------------------------------------------------===//
2765// Clang Extensions.
2766//===----------------------------------------------------------------------===//
2767
2768/// ActOnBlockStart - This callback is invoked when a block literal is started.
2769void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope,
2770                           Declarator &ParamInfo) {
2771  // Analyze block parameters.
2772  BlockSemaInfo *BSI = new BlockSemaInfo();
2773
2774  // Add BSI to CurBlock.
2775  BSI->PrevBlockInfo = CurBlock;
2776  CurBlock = BSI;
2777
2778  BSI->ReturnType = 0;
2779  BSI->TheScope = BlockScope;
2780
2781  // Analyze arguments to block.
2782  assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2783         "Not a function declarator!");
2784  DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
2785
2786  BSI->hasPrototype = FTI.hasPrototype;
2787  BSI->isVariadic = true;
2788
2789  // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
2790  // no arguments, not a function that takes a single void argument.
2791  if (FTI.hasPrototype &&
2792      FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2793      (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
2794        ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
2795    // empty arg list, don't push any params.
2796    BSI->isVariadic = false;
2797  } else if (FTI.hasPrototype) {
2798    for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
2799      BSI->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
2800    BSI->isVariadic = FTI.isVariadic;
2801  }
2802}
2803
2804/// ActOnBlockError - If there is an error parsing a block, this callback
2805/// is invoked to pop the information about the block from the action impl.
2806void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
2807  // Ensure that CurBlock is deleted.
2808  llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
2809
2810  // Pop off CurBlock, handle nested blocks.
2811  CurBlock = CurBlock->PrevBlockInfo;
2812
2813  // FIXME: Delete the ParmVarDecl objects as well???
2814
2815}
2816
2817/// ActOnBlockStmtExpr - This is called when the body of a block statement
2818/// literal was successfully completed.  ^(int x){...}
2819Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
2820                                          Scope *CurScope) {
2821  // Ensure that CurBlock is deleted.
2822  llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
2823  llvm::OwningPtr<CompoundStmt> Body(static_cast<CompoundStmt*>(body));
2824
2825  // Pop off CurBlock, handle nested blocks.
2826  CurBlock = CurBlock->PrevBlockInfo;
2827
2828  QualType RetTy = Context.VoidTy;
2829  if (BSI->ReturnType)
2830    RetTy = QualType(BSI->ReturnType, 0);
2831
2832  llvm::SmallVector<QualType, 8> ArgTypes;
2833  for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
2834    ArgTypes.push_back(BSI->Params[i]->getType());
2835
2836  QualType BlockTy;
2837  if (!BSI->hasPrototype)
2838    BlockTy = Context.getFunctionTypeNoProto(RetTy);
2839  else
2840    BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
2841                                      BSI->isVariadic);
2842
2843  BlockTy = Context.getBlockPointerType(BlockTy);
2844  return new BlockStmtExpr(CaretLoc, BlockTy,
2845                           &BSI->Params[0], BSI->Params.size(), Body.take());
2846}
2847
2848/// ActOnBlockExprExpr - This is called when the body of a block
2849/// expression literal was successfully completed.  ^(int x)[foo bar: x]
2850Sema::ExprResult Sema::ActOnBlockExprExpr(SourceLocation CaretLoc, ExprTy *body,
2851                                      Scope *CurScope) {
2852  // Ensure that CurBlock is deleted.
2853  llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
2854  llvm::OwningPtr<Expr> Body(static_cast<Expr*>(body));
2855
2856  // Pop off CurBlock, handle nested blocks.
2857  CurBlock = CurBlock->PrevBlockInfo;
2858
2859  if (BSI->ReturnType) {
2860    Diag(CaretLoc, diag::err_return_in_block_expression);
2861    return true;
2862  }
2863
2864  QualType RetTy = Body->getType();
2865
2866  llvm::SmallVector<QualType, 8> ArgTypes;
2867  for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
2868    ArgTypes.push_back(BSI->Params[i]->getType());
2869
2870  QualType BlockTy;
2871  if (!BSI->hasPrototype)
2872    BlockTy = Context.getFunctionTypeNoProto(RetTy);
2873  else
2874    BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
2875                                      BSI->isVariadic);
2876
2877  BlockTy = Context.getBlockPointerType(BlockTy);
2878  return new BlockExprExpr(CaretLoc, BlockTy,
2879                           &BSI->Params[0], BSI->Params.size(), Body.take());
2880}
2881
2882/// ExprsMatchFnType - return true if the Exprs in array Args have
2883/// QualTypes that match the QualTypes of the arguments of the FnType.
2884/// The number of arguments has already been validated to match the number of
2885/// arguments in FnType.
2886static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
2887                             ASTContext &Context) {
2888  unsigned NumParams = FnType->getNumArgs();
2889  for (unsigned i = 0; i != NumParams; ++i) {
2890    QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
2891    QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
2892
2893    if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
2894      return false;
2895  }
2896  return true;
2897}
2898
2899Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
2900                                         SourceLocation *CommaLocs,
2901                                         SourceLocation BuiltinLoc,
2902                                         SourceLocation RParenLoc) {
2903  // __builtin_overload requires at least 2 arguments
2904  if (NumArgs < 2)
2905    return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
2906                SourceRange(BuiltinLoc, RParenLoc));
2907
2908  // The first argument is required to be a constant expression.  It tells us
2909  // the number of arguments to pass to each of the functions to be overloaded.
2910  Expr **Args = reinterpret_cast<Expr**>(args);
2911  Expr *NParamsExpr = Args[0];
2912  llvm::APSInt constEval(32);
2913  SourceLocation ExpLoc;
2914  if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
2915    return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
2916                NParamsExpr->getSourceRange());
2917
2918  // Verify that the number of parameters is > 0
2919  unsigned NumParams = constEval.getZExtValue();
2920  if (NumParams == 0)
2921    return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
2922                NParamsExpr->getSourceRange());
2923  // Verify that we have at least 1 + NumParams arguments to the builtin.
2924  if ((NumParams + 1) > NumArgs)
2925    return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
2926                SourceRange(BuiltinLoc, RParenLoc));
2927
2928  // Figure out the return type, by matching the args to one of the functions
2929  // listed after the parameters.
2930  OverloadExpr *OE = 0;
2931  for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
2932    // UsualUnaryConversions will convert the function DeclRefExpr into a
2933    // pointer to function.
2934    Expr *Fn = UsualUnaryConversions(Args[i]);
2935    const FunctionTypeProto *FnType = 0;
2936    if (const PointerType *PT = Fn->getType()->getAsPointerType())
2937      FnType = PT->getPointeeType()->getAsFunctionTypeProto();
2938
2939    // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
2940    // parameters, and the number of parameters must match the value passed to
2941    // the builtin.
2942    if (!FnType || (FnType->getNumArgs() != NumParams))
2943      return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype,
2944                  Fn->getSourceRange());
2945
2946    // Scan the parameter list for the FunctionType, checking the QualType of
2947    // each parameter against the QualTypes of the arguments to the builtin.
2948    // If they match, return a new OverloadExpr.
2949    if (ExprsMatchFnType(Args+1, FnType, Context)) {
2950      if (OE)
2951        return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match,
2952                    OE->getFn()->getSourceRange());
2953      // Remember our match, and continue processing the remaining arguments
2954      // to catch any errors.
2955      OE = new OverloadExpr(Args, NumArgs, i, FnType->getResultType(),
2956                            BuiltinLoc, RParenLoc);
2957    }
2958  }
2959  // Return the newly created OverloadExpr node, if we succeded in matching
2960  // exactly one of the candidate functions.
2961  if (OE)
2962    return OE;
2963
2964  // If we didn't find a matching function Expr in the __builtin_overload list
2965  // the return an error.
2966  std::string typeNames;
2967  for (unsigned i = 0; i != NumParams; ++i) {
2968    if (i != 0) typeNames += ", ";
2969    typeNames += Args[i+1]->getType().getAsString();
2970  }
2971
2972  return Diag(BuiltinLoc, diag::err_overload_no_match, typeNames,
2973              SourceRange(BuiltinLoc, RParenLoc));
2974}
2975
2976Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
2977                                  ExprTy *expr, TypeTy *type,
2978                                  SourceLocation RPLoc) {
2979  Expr *E = static_cast<Expr*>(expr);
2980  QualType T = QualType::getFromOpaquePtr(type);
2981
2982  InitBuiltinVaListType();
2983
2984  // Get the va_list type
2985  QualType VaListType = Context.getBuiltinVaListType();
2986  // Deal with implicit array decay; for example, on x86-64,
2987  // va_list is an array, but it's supposed to decay to
2988  // a pointer for va_arg.
2989  if (VaListType->isArrayType())
2990    VaListType = Context.getArrayDecayedType(VaListType);
2991  // Make sure the input expression also decays appropriately.
2992  UsualUnaryConversions(E);
2993
2994  if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
2995    return Diag(E->getLocStart(),
2996                diag::err_first_argument_to_va_arg_not_of_type_va_list,
2997                E->getType().getAsString(),
2998                E->getSourceRange());
2999
3000  // FIXME: Warn if a non-POD type is passed in.
3001
3002  return new VAArgExpr(BuiltinLoc, E, T, RPLoc);
3003}
3004
3005bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
3006                                    SourceLocation Loc,
3007                                    QualType DstType, QualType SrcType,
3008                                    Expr *SrcExpr, const char *Flavor) {
3009  // Decode the result (notice that AST's are still created for extensions).
3010  bool isInvalid = false;
3011  unsigned DiagKind;
3012  switch (ConvTy) {
3013  default: assert(0 && "Unknown conversion type");
3014  case Compatible: return false;
3015  case PointerToInt:
3016    DiagKind = diag::ext_typecheck_convert_pointer_int;
3017    break;
3018  case IntToPointer:
3019    DiagKind = diag::ext_typecheck_convert_int_pointer;
3020    break;
3021  case IncompatiblePointer:
3022    DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
3023    break;
3024  case FunctionVoidPointer:
3025    DiagKind = diag::ext_typecheck_convert_pointer_void_func;
3026    break;
3027  case CompatiblePointerDiscardsQualifiers:
3028    DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
3029    break;
3030  case IntToBlockPointer:
3031    DiagKind = diag::err_int_to_block_pointer;
3032    break;
3033  case IncompatibleBlockPointer:
3034    DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
3035    break;
3036  case BlockVoidPointer:
3037    DiagKind = diag::ext_typecheck_convert_pointer_void_block;
3038    break;
3039  case Incompatible:
3040    DiagKind = diag::err_typecheck_convert_incompatible;
3041    isInvalid = true;
3042    break;
3043  }
3044
3045  Diag(Loc, DiagKind, DstType.getAsString(), SrcType.getAsString(), Flavor,
3046       SrcExpr->getSourceRange());
3047  return isInvalid;
3048}
3049