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