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