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