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