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