SemaExpr.cpp revision 3454b6cd8d58c98e2a867fb1104af11e1c183f68
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      && rExpr->isNullPointerConstant(Context)) {
1583    ImpCastExprToType(rExpr, lhsType);
1584    return Compatible;
1585  }
1586
1587  // We don't allow conversion of non-null-pointer constants to integers.
1588  if (lhsType->isBlockPointerType() && rExpr->getType()->isIntegerType())
1589    return IntToBlockPointer;
1590
1591  // This check seems unnatural, however it is necessary to ensure the proper
1592  // conversion of functions/arrays. If the conversion were done for all
1593  // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
1594  // expressions that surpress this implicit conversion (&, sizeof).
1595  //
1596  // Suppress this for references: C99 8.5.3p5.  FIXME: revisit when references
1597  // are better understood.
1598  if (!lhsType->isReferenceType())
1599    DefaultFunctionArrayConversion(rExpr);
1600
1601  Sema::AssignConvertType result =
1602    CheckAssignmentConstraints(lhsType, rExpr->getType());
1603
1604  // C99 6.5.16.1p2: The value of the right operand is converted to the
1605  // type of the assignment expression.
1606  if (rExpr->getType() != lhsType)
1607    ImpCastExprToType(rExpr, lhsType);
1608  return result;
1609}
1610
1611Sema::AssignConvertType
1612Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1613  return CheckAssignmentConstraints(lhsType, rhsType);
1614}
1615
1616QualType Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
1617  Diag(loc, diag::err_typecheck_invalid_operands,
1618       lex->getType().getAsString(), rex->getType().getAsString(),
1619       lex->getSourceRange(), rex->getSourceRange());
1620  return QualType();
1621}
1622
1623inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
1624                                                              Expr *&rex) {
1625  // For conversion purposes, we ignore any qualifiers.
1626  // For example, "const float" and "float" are equivalent.
1627  QualType lhsType =
1628    Context.getCanonicalType(lex->getType()).getUnqualifiedType();
1629  QualType rhsType =
1630    Context.getCanonicalType(rex->getType()).getUnqualifiedType();
1631
1632  // If the vector types are identical, return.
1633  if (lhsType == rhsType)
1634    return lhsType;
1635
1636  // Handle the case of a vector & extvector type of the same size and element
1637  // type.  It would be nice if we only had one vector type someday.
1638  if (getLangOptions().LaxVectorConversions)
1639    if (const VectorType *LV = lhsType->getAsVectorType())
1640      if (const VectorType *RV = rhsType->getAsVectorType())
1641        if (LV->getElementType() == RV->getElementType() &&
1642            LV->getNumElements() == RV->getNumElements())
1643          return lhsType->isExtVectorType() ? lhsType : rhsType;
1644
1645  // If the lhs is an extended vector and the rhs is a scalar of the same type
1646  // or a literal, promote the rhs to the vector type.
1647  if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
1648    QualType eltType = V->getElementType();
1649
1650    if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
1651        (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
1652        (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
1653      ImpCastExprToType(rex, lhsType);
1654      return lhsType;
1655    }
1656  }
1657
1658  // If the rhs is an extended vector and the lhs is a scalar of the same type,
1659  // promote the lhs to the vector type.
1660  if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
1661    QualType eltType = V->getElementType();
1662
1663    if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
1664        (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
1665        (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
1666      ImpCastExprToType(lex, rhsType);
1667      return rhsType;
1668    }
1669  }
1670
1671  // You cannot convert between vector values of different size.
1672  Diag(loc, diag::err_typecheck_vector_not_convertable,
1673       lex->getType().getAsString(), rex->getType().getAsString(),
1674       lex->getSourceRange(), rex->getSourceRange());
1675  return QualType();
1676}
1677
1678inline QualType Sema::CheckMultiplyDivideOperands(
1679  Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
1680{
1681  QualType lhsType = lex->getType(), rhsType = rex->getType();
1682
1683  if (lhsType->isVectorType() || rhsType->isVectorType())
1684    return CheckVectorOperands(loc, lex, rex);
1685
1686  QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
1687
1688  if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1689    return compType;
1690  return InvalidOperands(loc, lex, rex);
1691}
1692
1693inline QualType Sema::CheckRemainderOperands(
1694  Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
1695{
1696  QualType lhsType = lex->getType(), rhsType = rex->getType();
1697
1698  QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
1699
1700  if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
1701    return compType;
1702  return InvalidOperands(loc, lex, rex);
1703}
1704
1705inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
1706  Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
1707{
1708  if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1709    return CheckVectorOperands(loc, lex, rex);
1710
1711  QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
1712
1713  // handle the common case first (both operands are arithmetic).
1714  if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1715    return compType;
1716
1717  // Put any potential pointer into PExp
1718  Expr* PExp = lex, *IExp = rex;
1719  if (IExp->getType()->isPointerType())
1720    std::swap(PExp, IExp);
1721
1722  if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
1723    if (IExp->getType()->isIntegerType()) {
1724      // Check for arithmetic on pointers to incomplete types
1725      if (!PTy->getPointeeType()->isObjectType()) {
1726        if (PTy->getPointeeType()->isVoidType()) {
1727          Diag(loc, diag::ext_gnu_void_ptr,
1728               lex->getSourceRange(), rex->getSourceRange());
1729        } else {
1730          Diag(loc, diag::err_typecheck_arithmetic_incomplete_type,
1731               lex->getType().getAsString(), lex->getSourceRange());
1732          return QualType();
1733        }
1734      }
1735      return PExp->getType();
1736    }
1737  }
1738
1739  return InvalidOperands(loc, lex, rex);
1740}
1741
1742// C99 6.5.6
1743QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
1744                                        SourceLocation loc, bool isCompAssign) {
1745  if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1746    return CheckVectorOperands(loc, lex, rex);
1747
1748  QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
1749
1750  // Enforce type constraints: C99 6.5.6p3.
1751
1752  // Handle the common case first (both operands are arithmetic).
1753  if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1754    return compType;
1755
1756  // Either ptr - int   or   ptr - ptr.
1757  if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
1758    QualType lpointee = LHSPTy->getPointeeType();
1759
1760    // The LHS must be an object type, not incomplete, function, etc.
1761    if (!lpointee->isObjectType()) {
1762      // Handle the GNU void* extension.
1763      if (lpointee->isVoidType()) {
1764        Diag(loc, diag::ext_gnu_void_ptr,
1765             lex->getSourceRange(), rex->getSourceRange());
1766      } else {
1767        Diag(loc, diag::err_typecheck_sub_ptr_object,
1768             lex->getType().getAsString(), lex->getSourceRange());
1769        return QualType();
1770      }
1771    }
1772
1773    // The result type of a pointer-int computation is the pointer type.
1774    if (rex->getType()->isIntegerType())
1775      return lex->getType();
1776
1777    // Handle pointer-pointer subtractions.
1778    if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
1779      QualType rpointee = RHSPTy->getPointeeType();
1780
1781      // RHS must be an object type, unless void (GNU).
1782      if (!rpointee->isObjectType()) {
1783        // Handle the GNU void* extension.
1784        if (rpointee->isVoidType()) {
1785          if (!lpointee->isVoidType())
1786            Diag(loc, diag::ext_gnu_void_ptr,
1787                 lex->getSourceRange(), rex->getSourceRange());
1788        } else {
1789          Diag(loc, diag::err_typecheck_sub_ptr_object,
1790               rex->getType().getAsString(), rex->getSourceRange());
1791          return QualType();
1792        }
1793      }
1794
1795      // Pointee types must be compatible.
1796      if (!Context.typesAreCompatible(
1797              Context.getCanonicalType(lpointee).getUnqualifiedType(),
1798              Context.getCanonicalType(rpointee).getUnqualifiedType())) {
1799        Diag(loc, diag::err_typecheck_sub_ptr_compatible,
1800             lex->getType().getAsString(), rex->getType().getAsString(),
1801             lex->getSourceRange(), rex->getSourceRange());
1802        return QualType();
1803      }
1804
1805      return Context.getPointerDiffType();
1806    }
1807  }
1808
1809  return InvalidOperands(loc, lex, rex);
1810}
1811
1812// C99 6.5.7
1813QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
1814                                  bool isCompAssign) {
1815  // C99 6.5.7p2: Each of the operands shall have integer type.
1816  if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
1817    return InvalidOperands(loc, lex, rex);
1818
1819  // Shifts don't perform usual arithmetic conversions, they just do integer
1820  // promotions on each operand. C99 6.5.7p3
1821  if (!isCompAssign)
1822    UsualUnaryConversions(lex);
1823  UsualUnaryConversions(rex);
1824
1825  // "The type of the result is that of the promoted left operand."
1826  return lex->getType();
1827}
1828
1829static bool areComparableObjCInterfaces(QualType LHS, QualType RHS,
1830                                        ASTContext& Context) {
1831  const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
1832  const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
1833  // ID acts sort of like void* for ObjC interfaces
1834  if (LHSIface && Context.isObjCIdType(RHS))
1835    return true;
1836  if (RHSIface && Context.isObjCIdType(LHS))
1837    return true;
1838  if (!LHSIface || !RHSIface)
1839    return false;
1840  return Context.canAssignObjCInterfaces(LHSIface, RHSIface) ||
1841         Context.canAssignObjCInterfaces(RHSIface, LHSIface);
1842}
1843
1844// C99 6.5.8
1845QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
1846                                    bool isRelational) {
1847  if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1848    return CheckVectorCompareOperands(lex, rex, loc, isRelational);
1849
1850  // C99 6.5.8p3 / C99 6.5.9p4
1851  if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1852    UsualArithmeticConversions(lex, rex);
1853  else {
1854    UsualUnaryConversions(lex);
1855    UsualUnaryConversions(rex);
1856  }
1857  QualType lType = lex->getType();
1858  QualType rType = rex->getType();
1859
1860  // For non-floating point types, check for self-comparisons of the form
1861  // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
1862  // often indicate logic errors in the program.
1863  if (!lType->isFloatingType()) {
1864    if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
1865      if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
1866        if (DRL->getDecl() == DRR->getDecl())
1867          Diag(loc, diag::warn_selfcomparison);
1868  }
1869
1870  if (isRelational) {
1871    if (lType->isRealType() && rType->isRealType())
1872      return Context.IntTy;
1873  } else {
1874    // Check for comparisons of floating point operands using != and ==.
1875    if (lType->isFloatingType()) {
1876      assert (rType->isFloatingType());
1877      CheckFloatComparison(loc,lex,rex);
1878    }
1879
1880    if (lType->isArithmeticType() && rType->isArithmeticType())
1881      return Context.IntTy;
1882  }
1883
1884  bool LHSIsNull = lex->isNullPointerConstant(Context);
1885  bool RHSIsNull = rex->isNullPointerConstant(Context);
1886
1887  // All of the following pointer related warnings are GCC extensions, except
1888  // when handling null pointer constants. One day, we can consider making them
1889  // errors (when -pedantic-errors is enabled).
1890  if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
1891    QualType LCanPointeeTy =
1892      Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
1893    QualType RCanPointeeTy =
1894      Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
1895
1896    if (!LHSIsNull && !RHSIsNull &&                       // C99 6.5.9p2
1897        !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
1898        !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
1899                                    RCanPointeeTy.getUnqualifiedType()) &&
1900        !areComparableObjCInterfaces(LCanPointeeTy, RCanPointeeTy, Context)) {
1901      Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
1902           lType.getAsString(), rType.getAsString(),
1903           lex->getSourceRange(), rex->getSourceRange());
1904    }
1905    ImpCastExprToType(rex, lType); // promote the pointer to pointer
1906    return Context.IntTy;
1907  }
1908  // Handle block pointer types.
1909  if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
1910    QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
1911    QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
1912
1913    if (!LHSIsNull && !RHSIsNull &&
1914        !Context.typesAreBlockCompatible(lpointee, rpointee)) {
1915      Diag(loc, diag::err_typecheck_comparison_of_distinct_blocks,
1916           lType.getAsString(), rType.getAsString(),
1917           lex->getSourceRange(), rex->getSourceRange());
1918    }
1919    ImpCastExprToType(rex, lType); // promote the pointer to pointer
1920    return Context.IntTy;
1921  }
1922
1923  if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
1924    if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
1925      ImpCastExprToType(rex, lType);
1926      return Context.IntTy;
1927    }
1928  }
1929  if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
1930       rType->isIntegerType()) {
1931    if (!RHSIsNull)
1932      Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1933           lType.getAsString(), rType.getAsString(),
1934           lex->getSourceRange(), rex->getSourceRange());
1935    ImpCastExprToType(rex, lType); // promote the integer to pointer
1936    return Context.IntTy;
1937  }
1938  if (lType->isIntegerType() &&
1939      (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
1940    if (!LHSIsNull)
1941      Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1942           lType.getAsString(), rType.getAsString(),
1943           lex->getSourceRange(), rex->getSourceRange());
1944    ImpCastExprToType(lex, rType); // promote the integer to pointer
1945    return Context.IntTy;
1946  }
1947  return InvalidOperands(loc, lex, rex);
1948}
1949
1950/// CheckVectorCompareOperands - vector comparisons are a clang extension that
1951/// operates on extended vector types.  Instead of producing an IntTy result,
1952/// like a scalar comparison, a vector comparison produces a vector of integer
1953/// types.
1954QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
1955                                          SourceLocation loc,
1956                                          bool isRelational) {
1957  // Check to make sure we're operating on vectors of the same type and width,
1958  // Allowing one side to be a scalar of element type.
1959  QualType vType = CheckVectorOperands(loc, lex, rex);
1960  if (vType.isNull())
1961    return vType;
1962
1963  QualType lType = lex->getType();
1964  QualType rType = rex->getType();
1965
1966  // For non-floating point types, check for self-comparisons of the form
1967  // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
1968  // often indicate logic errors in the program.
1969  if (!lType->isFloatingType()) {
1970    if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
1971      if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
1972        if (DRL->getDecl() == DRR->getDecl())
1973          Diag(loc, diag::warn_selfcomparison);
1974  }
1975
1976  // Check for comparisons of floating point operands using != and ==.
1977  if (!isRelational && lType->isFloatingType()) {
1978    assert (rType->isFloatingType());
1979    CheckFloatComparison(loc,lex,rex);
1980  }
1981
1982  // Return the type for the comparison, which is the same as vector type for
1983  // integer vectors, or an integer type of identical size and number of
1984  // elements for floating point vectors.
1985  if (lType->isIntegerType())
1986    return lType;
1987
1988  const VectorType *VTy = lType->getAsVectorType();
1989
1990  // FIXME: need to deal with non-32b int / non-64b long long
1991  unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
1992  if (TypeSize == 32) {
1993    return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
1994  }
1995  assert(TypeSize == 64 && "Unhandled vector element size in vector compare");
1996  return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
1997}
1998
1999inline QualType Sema::CheckBitwiseOperands(
2000  Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
2001{
2002  if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
2003    return CheckVectorOperands(loc, lex, rex);
2004
2005  QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
2006
2007  if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
2008    return compType;
2009  return InvalidOperands(loc, lex, rex);
2010}
2011
2012inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
2013  Expr *&lex, Expr *&rex, SourceLocation loc)
2014{
2015  UsualUnaryConversions(lex);
2016  UsualUnaryConversions(rex);
2017
2018  if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
2019    return Context.IntTy;
2020  return InvalidOperands(loc, lex, rex);
2021}
2022
2023inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
2024  Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType)
2025{
2026  QualType lhsType = lex->getType();
2027  QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
2028  Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue(Context);
2029
2030  switch (mlval) { // C99 6.5.16p2
2031  case Expr::MLV_Valid:
2032    break;
2033  case Expr::MLV_ConstQualified:
2034    Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
2035    return QualType();
2036  case Expr::MLV_ArrayType:
2037    Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
2038         lhsType.getAsString(), lex->getSourceRange());
2039    return QualType();
2040  case Expr::MLV_NotObjectType:
2041    Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
2042         lhsType.getAsString(), lex->getSourceRange());
2043    return QualType();
2044  case Expr::MLV_InvalidExpression:
2045    Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
2046         lex->getSourceRange());
2047    return QualType();
2048  case Expr::MLV_IncompleteType:
2049  case Expr::MLV_IncompleteVoidType:
2050    Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
2051         lhsType.getAsString(), lex->getSourceRange());
2052    return QualType();
2053  case Expr::MLV_DuplicateVectorComponents:
2054    Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
2055         lex->getSourceRange());
2056    return QualType();
2057  }
2058
2059  AssignConvertType ConvTy;
2060  if (compoundType.isNull()) {
2061    // Simple assignment "x = y".
2062    ConvTy = CheckSingleAssignmentConstraints(lhsType, rex);
2063
2064    // If the RHS is a unary plus or minus, check to see if they = and + are
2065    // right next to each other.  If so, the user may have typo'd "x =+ 4"
2066    // instead of "x += 4".
2067    Expr *RHSCheck = rex;
2068    if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
2069      RHSCheck = ICE->getSubExpr();
2070    if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
2071      if ((UO->getOpcode() == UnaryOperator::Plus ||
2072           UO->getOpcode() == UnaryOperator::Minus) &&
2073          loc.isFileID() && UO->getOperatorLoc().isFileID() &&
2074          // Only if the two operators are exactly adjacent.
2075          loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
2076        Diag(loc, diag::warn_not_compound_assign,
2077             UO->getOpcode() == UnaryOperator::Plus ? "+" : "-",
2078             SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()));
2079    }
2080  } else {
2081    // Compound assignment "x += y"
2082    ConvTy = CheckCompoundAssignmentConstraints(lhsType, rhsType);
2083  }
2084
2085  if (DiagnoseAssignmentResult(ConvTy, loc, lhsType, rhsType,
2086                               rex, "assigning"))
2087    return QualType();
2088
2089  // C99 6.5.16p3: The type of an assignment expression is the type of the
2090  // left operand unless the left operand has qualified type, in which case
2091  // it is the unqualified version of the type of the left operand.
2092  // C99 6.5.16.1p2: In simple assignment, the value of the right operand
2093  // is converted to the type of the assignment expression (above).
2094  // C++ 5.17p1: the type of the assignment expression is that of its left
2095  // oprdu.
2096  return lhsType.getUnqualifiedType();
2097}
2098
2099inline QualType Sema::CheckCommaOperands( // C99 6.5.17
2100  Expr *&lex, Expr *&rex, SourceLocation loc) {
2101
2102  // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
2103  DefaultFunctionArrayConversion(rex);
2104  return rex->getType();
2105}
2106
2107/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
2108/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
2109QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
2110  QualType resType = op->getType();
2111  assert(!resType.isNull() && "no type for increment/decrement expression");
2112
2113  // C99 6.5.2.4p1: We allow complex as a GCC extension.
2114  if (const PointerType *pt = resType->getAsPointerType()) {
2115    if (pt->getPointeeType()->isVoidType()) {
2116      Diag(OpLoc, diag::ext_gnu_void_ptr, op->getSourceRange());
2117    } else if (!pt->getPointeeType()->isObjectType()) {
2118      // C99 6.5.2.4p2, 6.5.6p2
2119      Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
2120           resType.getAsString(), op->getSourceRange());
2121      return QualType();
2122    }
2123  } else if (!resType->isRealType()) {
2124    if (resType->isComplexType())
2125      // C99 does not support ++/-- on complex types.
2126      Diag(OpLoc, diag::ext_integer_increment_complex,
2127           resType.getAsString(), op->getSourceRange());
2128    else {
2129      Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
2130           resType.getAsString(), op->getSourceRange());
2131      return QualType();
2132    }
2133  }
2134  // At this point, we know we have a real, complex or pointer type.
2135  // Now make sure the operand is a modifiable lvalue.
2136  Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue(Context);
2137  if (mlval != Expr::MLV_Valid) {
2138    // FIXME: emit a more precise diagnostic...
2139    Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
2140         op->getSourceRange());
2141    return QualType();
2142  }
2143  return resType;
2144}
2145
2146/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
2147/// This routine allows us to typecheck complex/recursive expressions
2148/// where the declaration is needed for type checking. We only need to
2149/// handle cases when the expression references a function designator
2150/// or is an lvalue. Here are some examples:
2151///  - &(x) => x
2152///  - &*****f => f for f a function designator.
2153///  - &s.xx => s
2154///  - &s.zz[1].yy -> s, if zz is an array
2155///  - *(x + 1) -> x, if x is an array
2156///  - &"123"[2] -> 0
2157///  - & __real__ x -> x
2158static ValueDecl *getPrimaryDecl(Expr *E) {
2159  switch (E->getStmtClass()) {
2160  case Stmt::DeclRefExprClass:
2161    return cast<DeclRefExpr>(E)->getDecl();
2162  case Stmt::MemberExprClass:
2163    // Fields cannot be declared with a 'register' storage class.
2164    // &X->f is always ok, even if X is declared register.
2165    if (cast<MemberExpr>(E)->isArrow())
2166      return 0;
2167    return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
2168  case Stmt::ArraySubscriptExprClass: {
2169    // &X[4] and &4[X] refers to X if X is not a pointer.
2170
2171    ValueDecl *VD = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
2172    if (!VD || VD->getType()->isPointerType())
2173      return 0;
2174    else
2175      return VD;
2176  }
2177  case Stmt::UnaryOperatorClass: {
2178    UnaryOperator *UO = cast<UnaryOperator>(E);
2179
2180    switch(UO->getOpcode()) {
2181    case UnaryOperator::Deref: {
2182      // *(X + 1) refers to X if X is not a pointer.
2183      ValueDecl *VD = getPrimaryDecl(UO->getSubExpr());
2184      if (!VD || VD->getType()->isPointerType())
2185        return 0;
2186      return VD;
2187    }
2188    case UnaryOperator::Real:
2189    case UnaryOperator::Imag:
2190    case UnaryOperator::Extension:
2191      return getPrimaryDecl(UO->getSubExpr());
2192    default:
2193      return 0;
2194    }
2195  }
2196  case Stmt::BinaryOperatorClass: {
2197    BinaryOperator *BO = cast<BinaryOperator>(E);
2198
2199    // Handle cases involving pointer arithmetic. The result of an
2200    // Assign or AddAssign is not an lvalue so they can be ignored.
2201
2202    // (x + n) or (n + x) => x
2203    if (BO->getOpcode() == BinaryOperator::Add) {
2204      if (BO->getLHS()->getType()->isPointerType()) {
2205        return getPrimaryDecl(BO->getLHS());
2206      } else if (BO->getRHS()->getType()->isPointerType()) {
2207        return getPrimaryDecl(BO->getRHS());
2208      }
2209    }
2210
2211    return 0;
2212  }
2213  case Stmt::ParenExprClass:
2214    return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
2215  case Stmt::ImplicitCastExprClass:
2216    // &X[4] when X is an array, has an implicit cast from array to pointer.
2217    return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
2218  default:
2219    return 0;
2220  }
2221}
2222
2223/// CheckAddressOfOperand - The operand of & must be either a function
2224/// designator or an lvalue designating an object. If it is an lvalue, the
2225/// object cannot be declared with storage class register or be a bit field.
2226/// Note: The usual conversions are *not* applied to the operand of the &
2227/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
2228QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
2229  if (getLangOptions().C99) {
2230    // Implement C99-only parts of addressof rules.
2231    if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
2232      if (uOp->getOpcode() == UnaryOperator::Deref)
2233        // Per C99 6.5.3.2, the address of a deref always returns a valid result
2234        // (assuming the deref expression is valid).
2235        return uOp->getSubExpr()->getType();
2236    }
2237    // Technically, there should be a check for array subscript
2238    // expressions here, but the result of one is always an lvalue anyway.
2239  }
2240  ValueDecl *dcl = getPrimaryDecl(op);
2241  Expr::isLvalueResult lval = op->isLvalue(Context);
2242
2243  if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
2244    if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
2245      // FIXME: emit more specific diag...
2246      Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
2247           op->getSourceRange());
2248      return QualType();
2249    }
2250  } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
2251    if (MemExpr->getMemberDecl()->isBitField()) {
2252      Diag(OpLoc, diag::err_typecheck_address_of,
2253           std::string("bit-field"), op->getSourceRange());
2254      return QualType();
2255    }
2256  // Check for Apple extension for accessing vector components.
2257  } else if (isa<ArraySubscriptExpr>(op) &&
2258           cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
2259    Diag(OpLoc, diag::err_typecheck_address_of,
2260         std::string("vector"), op->getSourceRange());
2261    return QualType();
2262  } else if (dcl) { // C99 6.5.3.2p1
2263    // We have an lvalue with a decl. Make sure the decl is not declared
2264    // with the register storage-class specifier.
2265    if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
2266      if (vd->getStorageClass() == VarDecl::Register) {
2267        Diag(OpLoc, diag::err_typecheck_address_of,
2268             std::string("register variable"), op->getSourceRange());
2269        return QualType();
2270      }
2271    } else
2272      assert(0 && "Unknown/unexpected decl type");
2273  }
2274
2275  // If the operand has type "type", the result has type "pointer to type".
2276  return Context.getPointerType(op->getType());
2277}
2278
2279QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
2280  UsualUnaryConversions(op);
2281  QualType qType = op->getType();
2282
2283  if (const PointerType *PT = qType->getAsPointerType()) {
2284    // Note that per both C89 and C99, this is always legal, even
2285    // if ptype is an incomplete type or void.
2286    // It would be possible to warn about dereferencing a
2287    // void pointer, but it's completely well-defined,
2288    // and such a warning is unlikely to catch any mistakes.
2289    return PT->getPointeeType();
2290  }
2291  Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
2292       qType.getAsString(), op->getSourceRange());
2293  return QualType();
2294}
2295
2296static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
2297  tok::TokenKind Kind) {
2298  BinaryOperator::Opcode Opc;
2299  switch (Kind) {
2300  default: assert(0 && "Unknown binop!");
2301  case tok::star:                 Opc = BinaryOperator::Mul; break;
2302  case tok::slash:                Opc = BinaryOperator::Div; break;
2303  case tok::percent:              Opc = BinaryOperator::Rem; break;
2304  case tok::plus:                 Opc = BinaryOperator::Add; break;
2305  case tok::minus:                Opc = BinaryOperator::Sub; break;
2306  case tok::lessless:             Opc = BinaryOperator::Shl; break;
2307  case tok::greatergreater:       Opc = BinaryOperator::Shr; break;
2308  case tok::lessequal:            Opc = BinaryOperator::LE; break;
2309  case tok::less:                 Opc = BinaryOperator::LT; break;
2310  case tok::greaterequal:         Opc = BinaryOperator::GE; break;
2311  case tok::greater:              Opc = BinaryOperator::GT; break;
2312  case tok::exclaimequal:         Opc = BinaryOperator::NE; break;
2313  case tok::equalequal:           Opc = BinaryOperator::EQ; break;
2314  case tok::amp:                  Opc = BinaryOperator::And; break;
2315  case tok::caret:                Opc = BinaryOperator::Xor; break;
2316  case tok::pipe:                 Opc = BinaryOperator::Or; break;
2317  case tok::ampamp:               Opc = BinaryOperator::LAnd; break;
2318  case tok::pipepipe:             Opc = BinaryOperator::LOr; break;
2319  case tok::equal:                Opc = BinaryOperator::Assign; break;
2320  case tok::starequal:            Opc = BinaryOperator::MulAssign; break;
2321  case tok::slashequal:           Opc = BinaryOperator::DivAssign; break;
2322  case tok::percentequal:         Opc = BinaryOperator::RemAssign; break;
2323  case tok::plusequal:            Opc = BinaryOperator::AddAssign; break;
2324  case tok::minusequal:           Opc = BinaryOperator::SubAssign; break;
2325  case tok::lesslessequal:        Opc = BinaryOperator::ShlAssign; break;
2326  case tok::greatergreaterequal:  Opc = BinaryOperator::ShrAssign; break;
2327  case tok::ampequal:             Opc = BinaryOperator::AndAssign; break;
2328  case tok::caretequal:           Opc = BinaryOperator::XorAssign; break;
2329  case tok::pipeequal:            Opc = BinaryOperator::OrAssign; break;
2330  case tok::comma:                Opc = BinaryOperator::Comma; break;
2331  }
2332  return Opc;
2333}
2334
2335static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
2336  tok::TokenKind Kind) {
2337  UnaryOperator::Opcode Opc;
2338  switch (Kind) {
2339  default: assert(0 && "Unknown unary op!");
2340  case tok::plusplus:     Opc = UnaryOperator::PreInc; break;
2341  case tok::minusminus:   Opc = UnaryOperator::PreDec; break;
2342  case tok::amp:          Opc = UnaryOperator::AddrOf; break;
2343  case tok::star:         Opc = UnaryOperator::Deref; break;
2344  case tok::plus:         Opc = UnaryOperator::Plus; break;
2345  case tok::minus:        Opc = UnaryOperator::Minus; break;
2346  case tok::tilde:        Opc = UnaryOperator::Not; break;
2347  case tok::exclaim:      Opc = UnaryOperator::LNot; break;
2348  case tok::kw_sizeof:    Opc = UnaryOperator::SizeOf; break;
2349  case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
2350  case tok::kw___real:    Opc = UnaryOperator::Real; break;
2351  case tok::kw___imag:    Opc = UnaryOperator::Imag; break;
2352  case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
2353  }
2354  return Opc;
2355}
2356
2357// Binary Operators.  'Tok' is the token for the operator.
2358Action::ExprResult Sema::ActOnBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
2359                                    ExprTy *LHS, ExprTy *RHS) {
2360  BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
2361  Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
2362
2363  assert((lhs != 0) && "ActOnBinOp(): missing left expression");
2364  assert((rhs != 0) && "ActOnBinOp(): missing right expression");
2365
2366  QualType ResultTy;  // Result type of the binary operator.
2367  QualType CompTy;    // Computation type for compound assignments (e.g. '+=')
2368
2369  switch (Opc) {
2370  default:
2371    assert(0 && "Unknown binary expr!");
2372  case BinaryOperator::Assign:
2373    ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
2374    break;
2375  case BinaryOperator::Mul:
2376  case BinaryOperator::Div:
2377    ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
2378    break;
2379  case BinaryOperator::Rem:
2380    ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
2381    break;
2382  case BinaryOperator::Add:
2383    ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
2384    break;
2385  case BinaryOperator::Sub:
2386    ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
2387    break;
2388  case BinaryOperator::Shl:
2389  case BinaryOperator::Shr:
2390    ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
2391    break;
2392  case BinaryOperator::LE:
2393  case BinaryOperator::LT:
2394  case BinaryOperator::GE:
2395  case BinaryOperator::GT:
2396    ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, true);
2397    break;
2398  case BinaryOperator::EQ:
2399  case BinaryOperator::NE:
2400    ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, false);
2401    break;
2402  case BinaryOperator::And:
2403  case BinaryOperator::Xor:
2404  case BinaryOperator::Or:
2405    ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
2406    break;
2407  case BinaryOperator::LAnd:
2408  case BinaryOperator::LOr:
2409    ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
2410    break;
2411  case BinaryOperator::MulAssign:
2412  case BinaryOperator::DivAssign:
2413    CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc, true);
2414    if (!CompTy.isNull())
2415      ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2416    break;
2417  case BinaryOperator::RemAssign:
2418    CompTy = CheckRemainderOperands(lhs, rhs, TokLoc, true);
2419    if (!CompTy.isNull())
2420      ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2421    break;
2422  case BinaryOperator::AddAssign:
2423    CompTy = CheckAdditionOperands(lhs, rhs, TokLoc, true);
2424    if (!CompTy.isNull())
2425      ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2426    break;
2427  case BinaryOperator::SubAssign:
2428    CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc, true);
2429    if (!CompTy.isNull())
2430      ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2431    break;
2432  case BinaryOperator::ShlAssign:
2433  case BinaryOperator::ShrAssign:
2434    CompTy = CheckShiftOperands(lhs, rhs, TokLoc, true);
2435    if (!CompTy.isNull())
2436      ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2437    break;
2438  case BinaryOperator::AndAssign:
2439  case BinaryOperator::XorAssign:
2440  case BinaryOperator::OrAssign:
2441    CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc, true);
2442    if (!CompTy.isNull())
2443      ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2444    break;
2445  case BinaryOperator::Comma:
2446    ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
2447    break;
2448  }
2449  if (ResultTy.isNull())
2450    return true;
2451  if (CompTy.isNull())
2452    return new BinaryOperator(lhs, rhs, Opc, ResultTy, TokLoc);
2453  else
2454    return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, TokLoc);
2455}
2456
2457// Unary Operators.  'Tok' is the token for the operator.
2458Action::ExprResult Sema::ActOnUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
2459                                      ExprTy *input) {
2460  Expr *Input = (Expr*)input;
2461  UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
2462  QualType resultType;
2463  switch (Opc) {
2464  default:
2465    assert(0 && "Unimplemented unary expr!");
2466  case UnaryOperator::PreInc:
2467  case UnaryOperator::PreDec:
2468    resultType = CheckIncrementDecrementOperand(Input, OpLoc);
2469    break;
2470  case UnaryOperator::AddrOf:
2471    resultType = CheckAddressOfOperand(Input, OpLoc);
2472    break;
2473  case UnaryOperator::Deref:
2474    DefaultFunctionArrayConversion(Input);
2475    resultType = CheckIndirectionOperand(Input, OpLoc);
2476    break;
2477  case UnaryOperator::Plus:
2478  case UnaryOperator::Minus:
2479    UsualUnaryConversions(Input);
2480    resultType = Input->getType();
2481    if (!resultType->isArithmeticType())  // C99 6.5.3.3p1
2482      return Diag(OpLoc, diag::err_typecheck_unary_expr,
2483                  resultType.getAsString());
2484    break;
2485  case UnaryOperator::Not: // bitwise complement
2486    UsualUnaryConversions(Input);
2487    resultType = Input->getType();
2488    // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
2489    if (resultType->isComplexType() || resultType->isComplexIntegerType())
2490      // C99 does not support '~' for complex conjugation.
2491      Diag(OpLoc, diag::ext_integer_complement_complex,
2492           resultType.getAsString(), Input->getSourceRange());
2493    else if (!resultType->isIntegerType())
2494      return Diag(OpLoc, diag::err_typecheck_unary_expr,
2495                  resultType.getAsString(), Input->getSourceRange());
2496    break;
2497  case UnaryOperator::LNot: // logical negation
2498    // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
2499    DefaultFunctionArrayConversion(Input);
2500    resultType = Input->getType();
2501    if (!resultType->isScalarType()) // C99 6.5.3.3p1
2502      return Diag(OpLoc, diag::err_typecheck_unary_expr,
2503                  resultType.getAsString());
2504    // LNot always has type int. C99 6.5.3.3p5.
2505    resultType = Context.IntTy;
2506    break;
2507  case UnaryOperator::SizeOf:
2508    resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc,
2509                                           Input->getSourceRange(), true);
2510    break;
2511  case UnaryOperator::AlignOf:
2512    resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc,
2513                                           Input->getSourceRange(), false);
2514    break;
2515  case UnaryOperator::Real:
2516  case UnaryOperator::Imag:
2517    resultType = CheckRealImagOperand(Input, OpLoc);
2518    break;
2519  case UnaryOperator::Extension:
2520    resultType = Input->getType();
2521    break;
2522  }
2523  if (resultType.isNull())
2524    return true;
2525  return new UnaryOperator(Input, Opc, resultType, OpLoc);
2526}
2527
2528/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
2529Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
2530                                      SourceLocation LabLoc,
2531                                      IdentifierInfo *LabelII) {
2532  // Look up the record for this label identifier.
2533  LabelStmt *&LabelDecl = LabelMap[LabelII];
2534
2535  // If we haven't seen this label yet, create a forward reference. It
2536  // will be validated and/or cleaned up in ActOnFinishFunctionBody.
2537  if (LabelDecl == 0)
2538    LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
2539
2540  // Create the AST node.  The address of a label always has type 'void*'.
2541  return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
2542                           Context.getPointerType(Context.VoidTy));
2543}
2544
2545Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
2546                                     SourceLocation RPLoc) { // "({..})"
2547  Stmt *SubStmt = static_cast<Stmt*>(substmt);
2548  assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
2549  CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
2550
2551  // FIXME: there are a variety of strange constraints to enforce here, for
2552  // example, it is not possible to goto into a stmt expression apparently.
2553  // More semantic analysis is needed.
2554
2555  // FIXME: the last statement in the compount stmt has its value used.  We
2556  // should not warn about it being unused.
2557
2558  // If there are sub stmts in the compound stmt, take the type of the last one
2559  // as the type of the stmtexpr.
2560  QualType Ty = Context.VoidTy;
2561
2562  if (!Compound->body_empty()) {
2563    Stmt *LastStmt = Compound->body_back();
2564    // If LastStmt is a label, skip down through into the body.
2565    while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
2566      LastStmt = Label->getSubStmt();
2567
2568    if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
2569      Ty = LastExpr->getType();
2570  }
2571
2572  return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
2573}
2574
2575Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
2576                                            SourceLocation TypeLoc,
2577                                            TypeTy *argty,
2578                                            OffsetOfComponent *CompPtr,
2579                                            unsigned NumComponents,
2580                                            SourceLocation RPLoc) {
2581  QualType ArgTy = QualType::getFromOpaquePtr(argty);
2582  assert(!ArgTy.isNull() && "Missing type argument!");
2583
2584  // We must have at least one component that refers to the type, and the first
2585  // one is known to be a field designator.  Verify that the ArgTy represents
2586  // a struct/union/class.
2587  if (!ArgTy->isRecordType())
2588    return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString());
2589
2590  // Otherwise, create a compound literal expression as the base, and
2591  // iteratively process the offsetof designators.
2592  Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0, false);
2593
2594  // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
2595  // GCC extension, diagnose them.
2596  if (NumComponents != 1)
2597    Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator,
2598         SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd));
2599
2600  for (unsigned i = 0; i != NumComponents; ++i) {
2601    const OffsetOfComponent &OC = CompPtr[i];
2602    if (OC.isBrackets) {
2603      // Offset of an array sub-field.  TODO: Should we allow vector elements?
2604      const ArrayType *AT = Context.getAsArrayType(Res->getType());
2605      if (!AT) {
2606        delete Res;
2607        return Diag(OC.LocEnd, diag::err_offsetof_array_type,
2608                    Res->getType().getAsString());
2609      }
2610
2611      // FIXME: C++: Verify that operator[] isn't overloaded.
2612
2613      // C99 6.5.2.1p1
2614      Expr *Idx = static_cast<Expr*>(OC.U.E);
2615      if (!Idx->getType()->isIntegerType())
2616        return Diag(Idx->getLocStart(), diag::err_typecheck_subscript,
2617                    Idx->getSourceRange());
2618
2619      Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
2620      continue;
2621    }
2622
2623    const RecordType *RC = Res->getType()->getAsRecordType();
2624    if (!RC) {
2625      delete Res;
2626      return Diag(OC.LocEnd, diag::err_offsetof_record_type,
2627                  Res->getType().getAsString());
2628    }
2629
2630    // Get the decl corresponding to this.
2631    RecordDecl *RD = RC->getDecl();
2632    FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
2633    if (!MemberDecl)
2634      return Diag(BuiltinLoc, diag::err_typecheck_no_member,
2635                  OC.U.IdentInfo->getName(),
2636                  SourceRange(OC.LocStart, OC.LocEnd));
2637
2638    // FIXME: C++: Verify that MemberDecl isn't a static field.
2639    // FIXME: Verify that MemberDecl isn't a bitfield.
2640    // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
2641    // matter here.
2642    Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd, MemberDecl->getType());
2643  }
2644
2645  return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
2646                           BuiltinLoc);
2647}
2648
2649
2650Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
2651                                                TypeTy *arg1, TypeTy *arg2,
2652                                                SourceLocation RPLoc) {
2653  QualType argT1 = QualType::getFromOpaquePtr(arg1);
2654  QualType argT2 = QualType::getFromOpaquePtr(arg2);
2655
2656  assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
2657
2658  return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
2659}
2660
2661Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
2662                                       ExprTy *expr1, ExprTy *expr2,
2663                                       SourceLocation RPLoc) {
2664  Expr *CondExpr = static_cast<Expr*>(cond);
2665  Expr *LHSExpr = static_cast<Expr*>(expr1);
2666  Expr *RHSExpr = static_cast<Expr*>(expr2);
2667
2668  assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
2669
2670  // The conditional expression is required to be a constant expression.
2671  llvm::APSInt condEval(32);
2672  SourceLocation ExpLoc;
2673  if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
2674    return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
2675                 CondExpr->getSourceRange());
2676
2677  // If the condition is > zero, then the AST type is the same as the LSHExpr.
2678  QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
2679                                               RHSExpr->getType();
2680  return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
2681}
2682
2683//===----------------------------------------------------------------------===//
2684// Clang Extensions.
2685//===----------------------------------------------------------------------===//
2686
2687/// ActOnBlockStart - This callback is invoked when a block literal is started.
2688void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope,
2689                           Declarator &ParamInfo) {
2690  // Analyze block parameters.
2691  BlockSemaInfo *BSI = new BlockSemaInfo();
2692
2693  // Add BSI to CurBlock.
2694  BSI->PrevBlockInfo = CurBlock;
2695  CurBlock = BSI;
2696
2697  BSI->ReturnType = 0;
2698  BSI->TheScope = BlockScope;
2699
2700  // Analyze arguments to block.
2701  assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2702         "Not a function declarator!");
2703  DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
2704
2705  BSI->hasPrototype = FTI.hasPrototype;
2706  BSI->isVariadic = true;
2707
2708  // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
2709  // no arguments, not a function that takes a single void argument.
2710  if (FTI.hasPrototype &&
2711      FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2712      (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
2713        ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
2714    // empty arg list, don't push any params.
2715    BSI->isVariadic = false;
2716  } else if (FTI.hasPrototype) {
2717    for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
2718      BSI->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
2719    BSI->isVariadic = FTI.isVariadic;
2720  }
2721}
2722
2723/// ActOnBlockError - If there is an error parsing a block, this callback
2724/// is invoked to pop the information about the block from the action impl.
2725void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
2726  // Ensure that CurBlock is deleted.
2727  llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
2728
2729  // Pop off CurBlock, handle nested blocks.
2730  CurBlock = CurBlock->PrevBlockInfo;
2731
2732  // FIXME: Delete the ParmVarDecl objects as well???
2733
2734}
2735
2736/// ActOnBlockStmtExpr - This is called when the body of a block statement
2737/// literal was successfully completed.  ^(int x){...}
2738Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
2739                                          Scope *CurScope) {
2740  // Ensure that CurBlock is deleted.
2741  llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
2742  llvm::OwningPtr<CompoundStmt> Body(static_cast<CompoundStmt*>(body));
2743
2744  // Pop off CurBlock, handle nested blocks.
2745  CurBlock = CurBlock->PrevBlockInfo;
2746
2747  QualType RetTy = Context.VoidTy;
2748  if (BSI->ReturnType)
2749    RetTy = QualType(BSI->ReturnType, 0);
2750
2751  llvm::SmallVector<QualType, 8> ArgTypes;
2752  for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
2753    ArgTypes.push_back(BSI->Params[i]->getType());
2754
2755  QualType BlockTy;
2756  if (!BSI->hasPrototype)
2757    BlockTy = Context.getFunctionTypeNoProto(RetTy);
2758  else
2759    BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
2760                                      BSI->isVariadic);
2761
2762  BlockTy = Context.getBlockPointerType(BlockTy);
2763  return new BlockStmtExpr(CaretLoc, BlockTy,
2764                           &BSI->Params[0], BSI->Params.size(), Body.take());
2765}
2766
2767/// ActOnBlockExprExpr - This is called when the body of a block
2768/// expression literal was successfully completed.  ^(int x)[foo bar: x]
2769Sema::ExprResult Sema::ActOnBlockExprExpr(SourceLocation CaretLoc, ExprTy *body,
2770                                      Scope *CurScope) {
2771  // Ensure that CurBlock is deleted.
2772  llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
2773  llvm::OwningPtr<Expr> Body(static_cast<Expr*>(body));
2774
2775  // Pop off CurBlock, handle nested blocks.
2776  CurBlock = CurBlock->PrevBlockInfo;
2777
2778  if (BSI->ReturnType) {
2779    Diag(CaretLoc, diag::err_return_in_block_expression);
2780    return true;
2781  }
2782
2783  QualType RetTy = Body->getType();
2784
2785  llvm::SmallVector<QualType, 8> ArgTypes;
2786  for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
2787    ArgTypes.push_back(BSI->Params[i]->getType());
2788
2789  QualType BlockTy;
2790  if (!BSI->hasPrototype)
2791    BlockTy = Context.getFunctionTypeNoProto(RetTy);
2792  else
2793    BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
2794                                      BSI->isVariadic);
2795
2796  BlockTy = Context.getBlockPointerType(BlockTy);
2797  return new BlockExprExpr(CaretLoc, BlockTy,
2798                           &BSI->Params[0], BSI->Params.size(), Body.take());
2799}
2800
2801/// ExprsMatchFnType - return true if the Exprs in array Args have
2802/// QualTypes that match the QualTypes of the arguments of the FnType.
2803/// The number of arguments has already been validated to match the number of
2804/// arguments in FnType.
2805static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
2806                             ASTContext &Context) {
2807  unsigned NumParams = FnType->getNumArgs();
2808  for (unsigned i = 0; i != NumParams; ++i) {
2809    QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
2810    QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
2811
2812    if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
2813      return false;
2814  }
2815  return true;
2816}
2817
2818Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
2819                                         SourceLocation *CommaLocs,
2820                                         SourceLocation BuiltinLoc,
2821                                         SourceLocation RParenLoc) {
2822  // __builtin_overload requires at least 2 arguments
2823  if (NumArgs < 2)
2824    return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
2825                SourceRange(BuiltinLoc, RParenLoc));
2826
2827  // The first argument is required to be a constant expression.  It tells us
2828  // the number of arguments to pass to each of the functions to be overloaded.
2829  Expr **Args = reinterpret_cast<Expr**>(args);
2830  Expr *NParamsExpr = Args[0];
2831  llvm::APSInt constEval(32);
2832  SourceLocation ExpLoc;
2833  if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
2834    return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
2835                NParamsExpr->getSourceRange());
2836
2837  // Verify that the number of parameters is > 0
2838  unsigned NumParams = constEval.getZExtValue();
2839  if (NumParams == 0)
2840    return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
2841                NParamsExpr->getSourceRange());
2842  // Verify that we have at least 1 + NumParams arguments to the builtin.
2843  if ((NumParams + 1) > NumArgs)
2844    return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
2845                SourceRange(BuiltinLoc, RParenLoc));
2846
2847  // Figure out the return type, by matching the args to one of the functions
2848  // listed after the parameters.
2849  OverloadExpr *OE = 0;
2850  for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
2851    // UsualUnaryConversions will convert the function DeclRefExpr into a
2852    // pointer to function.
2853    Expr *Fn = UsualUnaryConversions(Args[i]);
2854    const FunctionTypeProto *FnType = 0;
2855    if (const PointerType *PT = Fn->getType()->getAsPointerType())
2856      FnType = PT->getPointeeType()->getAsFunctionTypeProto();
2857
2858    // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
2859    // parameters, and the number of parameters must match the value passed to
2860    // the builtin.
2861    if (!FnType || (FnType->getNumArgs() != NumParams))
2862      return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype,
2863                  Fn->getSourceRange());
2864
2865    // Scan the parameter list for the FunctionType, checking the QualType of
2866    // each parameter against the QualTypes of the arguments to the builtin.
2867    // If they match, return a new OverloadExpr.
2868    if (ExprsMatchFnType(Args+1, FnType, Context)) {
2869      if (OE)
2870        return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match,
2871                    OE->getFn()->getSourceRange());
2872      // Remember our match, and continue processing the remaining arguments
2873      // to catch any errors.
2874      OE = new OverloadExpr(Args, NumArgs, i, FnType->getResultType(),
2875                            BuiltinLoc, RParenLoc);
2876    }
2877  }
2878  // Return the newly created OverloadExpr node, if we succeded in matching
2879  // exactly one of the candidate functions.
2880  if (OE)
2881    return OE;
2882
2883  // If we didn't find a matching function Expr in the __builtin_overload list
2884  // the return an error.
2885  std::string typeNames;
2886  for (unsigned i = 0; i != NumParams; ++i) {
2887    if (i != 0) typeNames += ", ";
2888    typeNames += Args[i+1]->getType().getAsString();
2889  }
2890
2891  return Diag(BuiltinLoc, diag::err_overload_no_match, typeNames,
2892              SourceRange(BuiltinLoc, RParenLoc));
2893}
2894
2895Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
2896                                  ExprTy *expr, TypeTy *type,
2897                                  SourceLocation RPLoc) {
2898  Expr *E = static_cast<Expr*>(expr);
2899  QualType T = QualType::getFromOpaquePtr(type);
2900
2901  InitBuiltinVaListType();
2902
2903  // Get the va_list type
2904  QualType VaListType = Context.getBuiltinVaListType();
2905  // Deal with implicit array decay; for example, on x86-64,
2906  // va_list is an array, but it's supposed to decay to
2907  // a pointer for va_arg.
2908  if (VaListType->isArrayType())
2909    VaListType = Context.getArrayDecayedType(VaListType);
2910  // Make sure the input expression also decays appropriately.
2911  UsualUnaryConversions(E);
2912
2913  if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
2914    return Diag(E->getLocStart(),
2915                diag::err_first_argument_to_va_arg_not_of_type_va_list,
2916                E->getType().getAsString(),
2917                E->getSourceRange());
2918
2919  // FIXME: Warn if a non-POD type is passed in.
2920
2921  return new VAArgExpr(BuiltinLoc, E, T, RPLoc);
2922}
2923
2924bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
2925                                    SourceLocation Loc,
2926                                    QualType DstType, QualType SrcType,
2927                                    Expr *SrcExpr, const char *Flavor) {
2928  // Decode the result (notice that AST's are still created for extensions).
2929  bool isInvalid = false;
2930  unsigned DiagKind;
2931  switch (ConvTy) {
2932  default: assert(0 && "Unknown conversion type");
2933  case Compatible: return false;
2934  case PointerToInt:
2935    DiagKind = diag::ext_typecheck_convert_pointer_int;
2936    break;
2937  case IntToPointer:
2938    DiagKind = diag::ext_typecheck_convert_int_pointer;
2939    break;
2940  case IncompatiblePointer:
2941    DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
2942    break;
2943  case FunctionVoidPointer:
2944    DiagKind = diag::ext_typecheck_convert_pointer_void_func;
2945    break;
2946  case CompatiblePointerDiscardsQualifiers:
2947    DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
2948    break;
2949  case IntToBlockPointer:
2950    DiagKind = diag::err_int_to_block_pointer;
2951    break;
2952  case IncompatibleBlockPointer:
2953    DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
2954    break;
2955  case BlockVoidPointer:
2956    DiagKind = diag::ext_typecheck_convert_pointer_void_block;
2957    break;
2958  case Incompatible:
2959    DiagKind = diag::err_typecheck_convert_incompatible;
2960    isInvalid = true;
2961    break;
2962  }
2963
2964  Diag(Loc, DiagKind, DstType.getAsString(), SrcType.getAsString(), Flavor,
2965       SrcExpr->getSourceRange());
2966  return isInvalid;
2967}
2968