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