SemaExprCXX.cpp revision 45f01f8db034ded74a9a414ea24239fffbd730d9
1//===--- SemaExprCXX.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 C++ expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "SemaInherit.h"
15#include "Sema.h"
16#include "clang/AST/ExprCXX.h"
17#include "clang/AST/ASTContext.h"
18#include "clang/Parse/DeclSpec.h"
19#include "clang/Lex/Preprocessor.h"
20#include "clang/Basic/TargetInfo.h"
21#include "llvm/ADT/STLExtras.h"
22using namespace clang;
23
24/// ActOnCXXConversionFunctionExpr - Parse a C++ conversion function
25/// name (e.g., operator void const *) as an expression. This is
26/// very similar to ActOnIdentifierExpr, except that instead of
27/// providing an identifier the parser provides the type of the
28/// conversion function.
29Sema::OwningExprResult
30Sema::ActOnCXXConversionFunctionExpr(Scope *S, SourceLocation OperatorLoc,
31                                     TypeTy *Ty, bool HasTrailingLParen,
32                                     const CXXScopeSpec &SS,
33                                     bool isAddressOfOperand) {
34  QualType ConvType = QualType::getFromOpaquePtr(Ty);
35  QualType ConvTypeCanon = Context.getCanonicalType(ConvType);
36  DeclarationName ConvName
37    = Context.DeclarationNames.getCXXConversionFunctionName(ConvTypeCanon);
38  return ActOnDeclarationNameExpr(S, OperatorLoc, ConvName, HasTrailingLParen,
39                                  &SS, isAddressOfOperand);
40}
41
42/// ActOnCXXOperatorFunctionIdExpr - Parse a C++ overloaded operator
43/// name (e.g., @c operator+ ) as an expression. This is very
44/// similar to ActOnIdentifierExpr, except that instead of providing
45/// an identifier the parser provides the kind of overloaded
46/// operator that was parsed.
47Sema::OwningExprResult
48Sema::ActOnCXXOperatorFunctionIdExpr(Scope *S, SourceLocation OperatorLoc,
49                                     OverloadedOperatorKind Op,
50                                     bool HasTrailingLParen,
51                                     const CXXScopeSpec &SS,
52                                     bool isAddressOfOperand) {
53  DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(Op);
54  return ActOnDeclarationNameExpr(S, OperatorLoc, Name, HasTrailingLParen, &SS,
55                                  isAddressOfOperand);
56}
57
58/// ActOnCXXTypeidOfType - Parse typeid( type-id ).
59Action::OwningExprResult
60Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
61                     bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
62  NamespaceDecl *StdNs = GetStdNamespace();
63  if (!StdNs)
64    return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
65
66  IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
67  Decl *TypeInfoDecl = LookupQualifiedName(StdNs, TypeInfoII, LookupTagName);
68  RecordDecl *TypeInfoRecordDecl = dyn_cast_or_null<RecordDecl>(TypeInfoDecl);
69  if (!TypeInfoRecordDecl)
70    return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
71
72  QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
73
74  return Owned(new (Context) CXXTypeidExpr(isType, TyOrExpr,
75                                           TypeInfoType.withConst(),
76                                           SourceRange(OpLoc, RParenLoc)));
77}
78
79/// ActOnCXXBoolLiteral - Parse {true,false} literals.
80Action::OwningExprResult
81Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
82  assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
83         "Unknown C++ Boolean value!");
84  return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
85                                                Context.BoolTy, OpLoc));
86}
87
88/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
89Action::OwningExprResult
90Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
91  return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
92}
93
94/// ActOnCXXThrow - Parse throw expressions.
95Action::OwningExprResult
96Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) {
97  Expr *Ex = E.takeAs<Expr>();
98  if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
99    return ExprError();
100  return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
101}
102
103/// CheckCXXThrowOperand - Validate the operand of a throw.
104bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
105  // C++ [except.throw]p3:
106  //   [...] adjusting the type from "array of T" or "function returning T"
107  //   to "pointer to T" or "pointer to function returning T", [...]
108  DefaultFunctionArrayConversion(E);
109
110  //   If the type of the exception would be an incomplete type or a pointer
111  //   to an incomplete type other than (cv) void the program is ill-formed.
112  QualType Ty = E->getType();
113  int isPointer = 0;
114  if (const PointerType* Ptr = Ty->getAsPointerType()) {
115    Ty = Ptr->getPointeeType();
116    isPointer = 1;
117  }
118  if (!isPointer || !Ty->isVoidType()) {
119    if (RequireCompleteType(ThrowLoc, Ty,
120                            isPointer ? diag::err_throw_incomplete_ptr
121                                      : diag::err_throw_incomplete,
122                            E->getSourceRange(), SourceRange(), QualType()))
123      return true;
124  }
125
126  // FIXME: Construct a temporary here.
127  return false;
128}
129
130Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
131  /// C++ 9.3.2: In the body of a non-static member function, the keyword this
132  /// is a non-lvalue expression whose value is the address of the object for
133  /// which the function is called.
134
135  if (!isa<FunctionDecl>(CurContext))
136    return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
137
138  if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
139    if (MD->isInstance())
140      return Owned(new (Context) CXXThisExpr(ThisLoc,
141                                             MD->getThisType(Context)));
142
143  return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
144}
145
146/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
147/// Can be interpreted either as function-style casting ("int(x)")
148/// or class type construction ("ClassType(x,y,z)")
149/// or creation of a value-initialized type ("int()").
150Action::OwningExprResult
151Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
152                                SourceLocation LParenLoc,
153                                MultiExprArg exprs,
154                                SourceLocation *CommaLocs,
155                                SourceLocation RParenLoc) {
156  assert(TypeRep && "Missing type!");
157  QualType Ty = QualType::getFromOpaquePtr(TypeRep);
158  unsigned NumExprs = exprs.size();
159  Expr **Exprs = (Expr**)exprs.get();
160  SourceLocation TyBeginLoc = TypeRange.getBegin();
161  SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
162
163  if (Ty->isDependentType() ||
164      CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
165    exprs.release();
166
167    // FIXME: Is this correct?
168    CXXTempVarDecl *Temp = CXXTempVarDecl::Create(Context, CurContext, Ty);
169    return Owned(new (Context) CXXTemporaryObjectExpr(Context, Temp, 0, Ty,
170                                                      TyBeginLoc,
171                                                      Exprs, NumExprs,
172                                                      RParenLoc));
173  }
174
175
176  // C++ [expr.type.conv]p1:
177  // If the expression list is a single expression, the type conversion
178  // expression is equivalent (in definedness, and if defined in meaning) to the
179  // corresponding cast expression.
180  //
181  if (NumExprs == 1) {
182    if (CheckCastTypes(TypeRange, Ty, Exprs[0]))
183      return ExprError();
184    exprs.release();
185    return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
186                                                     Ty, TyBeginLoc, Exprs[0],
187                                                     RParenLoc));
188  }
189
190  if (const RecordType *RT = Ty->getAsRecordType()) {
191    CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
192
193    if (NumExprs > 1 || Record->hasUserDeclaredConstructor()) {
194      CXXConstructorDecl *Constructor
195        = PerformInitializationByConstructor(Ty, Exprs, NumExprs,
196                                             TypeRange.getBegin(),
197                                             SourceRange(TypeRange.getBegin(),
198                                                         RParenLoc),
199                                             DeclarationName(),
200                                             IK_Direct);
201
202      if (!Constructor)
203        return ExprError();
204
205      CXXTempVarDecl *Temp = CXXTempVarDecl::Create(Context, CurContext, Ty);
206
207      exprs.release();
208      return Owned(new (Context) CXXTemporaryObjectExpr(Context, Temp,
209                                                        Constructor, Ty,
210                                                        TyBeginLoc,  Exprs,
211                                                        NumExprs, RParenLoc));
212    }
213
214    // Fall through to value-initialize an object of class type that
215    // doesn't have a user-declared default constructor.
216  }
217
218  // C++ [expr.type.conv]p1:
219  // If the expression list specifies more than a single value, the type shall
220  // be a class with a suitably declared constructor.
221  //
222  if (NumExprs > 1)
223    return ExprError(Diag(CommaLocs[0],
224                          diag::err_builtin_func_cast_more_than_one_arg)
225      << FullRange);
226
227  assert(NumExprs == 0 && "Expected 0 expressions");
228
229  // C++ [expr.type.conv]p2:
230  // The expression T(), where T is a simple-type-specifier for a non-array
231  // complete object type or the (possibly cv-qualified) void type, creates an
232  // rvalue of the specified type, which is value-initialized.
233  //
234  if (Ty->isArrayType())
235    return ExprError(Diag(TyBeginLoc,
236                          diag::err_value_init_for_array_type) << FullRange);
237  if (!Ty->isDependentType() && !Ty->isVoidType() &&
238      RequireCompleteType(TyBeginLoc, Ty,
239                          diag::err_invalid_incomplete_type_use, FullRange))
240    return ExprError();
241
242  if (RequireNonAbstractType(TyBeginLoc, Ty,
243                             diag::err_allocation_of_abstract_type))
244    return ExprError();
245
246  exprs.release();
247  return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
248}
249
250
251/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
252/// @code new (memory) int[size][4] @endcode
253/// or
254/// @code ::new Foo(23, "hello") @endcode
255/// For the interpretation of this heap of arguments, consult the base version.
256Action::OwningExprResult
257Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
258                  SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
259                  SourceLocation PlacementRParen, bool ParenTypeId,
260                  Declarator &D, SourceLocation ConstructorLParen,
261                  MultiExprArg ConstructorArgs,
262                  SourceLocation ConstructorRParen)
263{
264  Expr *ArraySize = 0;
265  unsigned Skip = 0;
266  // If the specified type is an array, unwrap it and save the expression.
267  if (D.getNumTypeObjects() > 0 &&
268      D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
269    DeclaratorChunk &Chunk = D.getTypeObject(0);
270    if (Chunk.Arr.hasStatic)
271      return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
272        << D.getSourceRange());
273    if (!Chunk.Arr.NumElts)
274      return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
275        << D.getSourceRange());
276    ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
277    Skip = 1;
278  }
279
280  QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, Skip);
281  if (D.isInvalidType())
282    return ExprError();
283
284  if (CheckAllocatedType(AllocType, D))
285    return ExprError();
286
287  QualType ResultType = AllocType->isDependentType()
288                          ? Context.DependentTy
289                          : Context.getPointerType(AllocType);
290
291  // That every array dimension except the first is constant was already
292  // checked by the type check above.
293
294  // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
295  //   or enumeration type with a non-negative value."
296  if (ArraySize && !ArraySize->isTypeDependent()) {
297    QualType SizeType = ArraySize->getType();
298    if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
299      return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
300                            diag::err_array_size_not_integral)
301        << SizeType << ArraySize->getSourceRange());
302    // Let's see if this is a constant < 0. If so, we reject it out of hand.
303    // We don't care about special rules, so we tell the machinery it's not
304    // evaluated - it gives us a result in more cases.
305    if (!ArraySize->isValueDependent()) {
306      llvm::APSInt Value;
307      if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
308        if (Value < llvm::APSInt(
309                        llvm::APInt::getNullValue(Value.getBitWidth()), false))
310          return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
311                           diag::err_typecheck_negative_array_size)
312            << ArraySize->getSourceRange());
313      }
314    }
315  }
316
317  FunctionDecl *OperatorNew = 0;
318  FunctionDecl *OperatorDelete = 0;
319  Expr **PlaceArgs = (Expr**)PlacementArgs.get();
320  unsigned NumPlaceArgs = PlacementArgs.size();
321  if (!AllocType->isDependentType() &&
322      !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
323      FindAllocationFunctions(StartLoc,
324                              SourceRange(PlacementLParen, PlacementRParen),
325                              UseGlobal, AllocType, ArraySize, PlaceArgs,
326                              NumPlaceArgs, OperatorNew, OperatorDelete))
327    return ExprError();
328
329  bool Init = ConstructorLParen.isValid();
330  // --- Choosing a constructor ---
331  // C++ 5.3.4p15
332  // 1) If T is a POD and there's no initializer (ConstructorLParen is invalid)
333  //   the object is not initialized. If the object, or any part of it, is
334  //   const-qualified, it's an error.
335  // 2) If T is a POD and there's an empty initializer, the object is value-
336  //   initialized.
337  // 3) If T is a POD and there's one initializer argument, the object is copy-
338  //   constructed.
339  // 4) If T is a POD and there's more initializer arguments, it's an error.
340  // 5) If T is not a POD, the initializer arguments are used as constructor
341  //   arguments.
342  //
343  // Or by the C++0x formulation:
344  // 1) If there's no initializer, the object is default-initialized according
345  //    to C++0x rules.
346  // 2) Otherwise, the object is direct-initialized.
347  CXXConstructorDecl *Constructor = 0;
348  Expr **ConsArgs = (Expr**)ConstructorArgs.get();
349  const RecordType *RT;
350  unsigned NumConsArgs = ConstructorArgs.size();
351  if (AllocType->isDependentType()) {
352    // Skip all the checks.
353  }
354  else if ((RT = AllocType->getAsRecordType()) &&
355            !AllocType->isAggregateType()) {
356    Constructor = PerformInitializationByConstructor(
357                      AllocType, ConsArgs, NumConsArgs,
358                      D.getSourceRange().getBegin(),
359                      SourceRange(D.getSourceRange().getBegin(),
360                                  ConstructorRParen),
361                      RT->getDecl()->getDeclName(),
362                      NumConsArgs != 0 ? IK_Direct : IK_Default);
363    if (!Constructor)
364      return ExprError();
365  } else {
366    if (!Init) {
367      // FIXME: Check that no subpart is const.
368      if (AllocType.isConstQualified())
369        return ExprError(Diag(StartLoc, diag::err_new_uninitialized_const)
370          << D.getSourceRange());
371    } else if (NumConsArgs == 0) {
372      // Object is value-initialized. Do nothing.
373    } else if (NumConsArgs == 1) {
374      // Object is direct-initialized.
375      // FIXME: What DeclarationName do we pass in here?
376      if (CheckInitializerTypes(ConsArgs[0], AllocType, StartLoc,
377                                DeclarationName() /*AllocType.getAsString()*/,
378                                /*DirectInit=*/true))
379        return ExprError();
380    } else {
381      return ExprError(Diag(StartLoc,
382                            diag::err_builtin_direct_init_more_than_one_arg)
383        << SourceRange(ConstructorLParen, ConstructorRParen));
384    }
385  }
386
387  // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
388
389  PlacementArgs.release();
390  ConstructorArgs.release();
391  return Owned(new (Context) CXXNewExpr(UseGlobal, OperatorNew, PlaceArgs,
392                        NumPlaceArgs, ParenTypeId, ArraySize, Constructor, Init,
393                        ConsArgs, NumConsArgs, OperatorDelete, ResultType,
394                        StartLoc, Init ? ConstructorRParen : SourceLocation()));
395}
396
397/// CheckAllocatedType - Checks that a type is suitable as the allocated type
398/// in a new-expression.
399/// dimension off and stores the size expression in ArraySize.
400bool Sema::CheckAllocatedType(QualType AllocType, const Declarator &D)
401{
402  // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
403  //   abstract class type or array thereof.
404  if (AllocType->isFunctionType())
405    return Diag(D.getSourceRange().getBegin(), diag::err_bad_new_type)
406      << AllocType << 0 << D.getSourceRange();
407  else if (AllocType->isReferenceType())
408    return Diag(D.getSourceRange().getBegin(), diag::err_bad_new_type)
409      << AllocType << 1 << D.getSourceRange();
410  else if (!AllocType->isDependentType() &&
411           RequireCompleteType(D.getSourceRange().getBegin(), AllocType,
412                               diag::err_new_incomplete_type,
413                               D.getSourceRange()))
414    return true;
415  else if (RequireNonAbstractType(D.getSourceRange().getBegin(), AllocType,
416                                  diag::err_allocation_of_abstract_type))
417    return true;
418
419  // Every dimension shall be of constant size.
420  unsigned i = 1;
421  while (const ArrayType *Array = Context.getAsArrayType(AllocType)) {
422    if (!Array->isConstantArrayType()) {
423      Diag(D.getTypeObject(i).Loc, diag::err_new_array_nonconst)
424        << static_cast<Expr*>(D.getTypeObject(i).Arr.NumElts)->getSourceRange();
425      return true;
426    }
427    AllocType = Array->getElementType();
428    ++i;
429  }
430
431  return false;
432}
433
434/// FindAllocationFunctions - Finds the overloads of operator new and delete
435/// that are appropriate for the allocation.
436bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
437                                   bool UseGlobal, QualType AllocType,
438                                   bool IsArray, Expr **PlaceArgs,
439                                   unsigned NumPlaceArgs,
440                                   FunctionDecl *&OperatorNew,
441                                   FunctionDecl *&OperatorDelete)
442{
443  // --- Choosing an allocation function ---
444  // C++ 5.3.4p8 - 14 & 18
445  // 1) If UseGlobal is true, only look in the global scope. Else, also look
446  //   in the scope of the allocated class.
447  // 2) If an array size is given, look for operator new[], else look for
448  //   operator new.
449  // 3) The first argument is always size_t. Append the arguments from the
450  //   placement form.
451  // FIXME: Also find the appropriate delete operator.
452
453  llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
454  // We don't care about the actual value of this argument.
455  // FIXME: Should the Sema create the expression and embed it in the syntax
456  // tree? Or should the consumer just recalculate the value?
457  AllocArgs[0] = new (Context) IntegerLiteral(llvm::APInt::getNullValue(
458                                        Context.Target.getPointerWidth(0)),
459                                    Context.getSizeType(),
460                                    SourceLocation());
461  std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
462
463  DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
464                                        IsArray ? OO_Array_New : OO_New);
465  if (AllocType->isRecordType() && !UseGlobal) {
466    CXXRecordDecl *Record
467      = cast<CXXRecordDecl>(AllocType->getAsRecordType()->getDecl());
468    // FIXME: We fail to find inherited overloads.
469    if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
470                          AllocArgs.size(), Record, /*AllowMissing=*/true,
471                          OperatorNew))
472      return true;
473  }
474  if (!OperatorNew) {
475    // Didn't find a member overload. Look for a global one.
476    DeclareGlobalNewDelete();
477    DeclContext *TUDecl = Context.getTranslationUnitDecl();
478    if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
479                          AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
480                          OperatorNew))
481      return true;
482  }
483
484  // FIXME: This is leaked on error. But so much is currently in Sema that it's
485  // easier to clean it in one go.
486  AllocArgs[0]->Destroy(Context);
487  return false;
488}
489
490/// FindAllocationOverload - Find an fitting overload for the allocation
491/// function in the specified scope.
492bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
493                                  DeclarationName Name, Expr** Args,
494                                  unsigned NumArgs, DeclContext *Ctx,
495                                  bool AllowMissing, FunctionDecl *&Operator)
496{
497  DeclContext::lookup_iterator Alloc, AllocEnd;
498  llvm::tie(Alloc, AllocEnd) = Ctx->lookup(Context, Name);
499  if (Alloc == AllocEnd) {
500    if (AllowMissing)
501      return false;
502    return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
503      << Name << Range;
504  }
505
506  OverloadCandidateSet Candidates;
507  for (; Alloc != AllocEnd; ++Alloc) {
508    // Even member operator new/delete are implicitly treated as
509    // static, so don't use AddMemberCandidate.
510    if (FunctionDecl *Fn = dyn_cast<FunctionDecl>(*Alloc))
511      AddOverloadCandidate(Fn, Args, NumArgs, Candidates,
512                           /*SuppressUserConversions=*/false);
513  }
514
515  // Do the resolution.
516  OverloadCandidateSet::iterator Best;
517  switch(BestViableFunction(Candidates, Best)) {
518  case OR_Success: {
519    // Got one!
520    FunctionDecl *FnDecl = Best->Function;
521    // The first argument is size_t, and the first parameter must be size_t,
522    // too. This is checked on declaration and can be assumed. (It can't be
523    // asserted on, though, since invalid decls are left in there.)
524    for (unsigned i = 1; i < NumArgs; ++i) {
525      // FIXME: Passing word to diagnostic.
526      if (PerformCopyInitialization(Args[i-1],
527                                    FnDecl->getParamDecl(i)->getType(),
528                                    "passing"))
529        return true;
530    }
531    Operator = FnDecl;
532    return false;
533  }
534
535  case OR_No_Viable_Function:
536    Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
537      << Name << Range;
538    PrintOverloadCandidates(Candidates, /*OnlyViable=*/false);
539    return true;
540
541  case OR_Ambiguous:
542    Diag(StartLoc, diag::err_ovl_ambiguous_call)
543      << Name << Range;
544    PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
545    return true;
546
547  case OR_Deleted:
548    Diag(StartLoc, diag::err_ovl_deleted_call)
549      << Best->Function->isDeleted()
550      << Name << Range;
551    PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
552    return true;
553  }
554  assert(false && "Unreachable, bad result from BestViableFunction");
555  return true;
556}
557
558
559/// DeclareGlobalNewDelete - Declare the global forms of operator new and
560/// delete. These are:
561/// @code
562///   void* operator new(std::size_t) throw(std::bad_alloc);
563///   void* operator new[](std::size_t) throw(std::bad_alloc);
564///   void operator delete(void *) throw();
565///   void operator delete[](void *) throw();
566/// @endcode
567/// Note that the placement and nothrow forms of new are *not* implicitly
568/// declared. Their use requires including \<new\>.
569void Sema::DeclareGlobalNewDelete()
570{
571  if (GlobalNewDeleteDeclared)
572    return;
573  GlobalNewDeleteDeclared = true;
574
575  QualType VoidPtr = Context.getPointerType(Context.VoidTy);
576  QualType SizeT = Context.getSizeType();
577
578  // FIXME: Exception specifications are not added.
579  DeclareGlobalAllocationFunction(
580      Context.DeclarationNames.getCXXOperatorName(OO_New),
581      VoidPtr, SizeT);
582  DeclareGlobalAllocationFunction(
583      Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
584      VoidPtr, SizeT);
585  DeclareGlobalAllocationFunction(
586      Context.DeclarationNames.getCXXOperatorName(OO_Delete),
587      Context.VoidTy, VoidPtr);
588  DeclareGlobalAllocationFunction(
589      Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
590      Context.VoidTy, VoidPtr);
591}
592
593/// DeclareGlobalAllocationFunction - Declares a single implicit global
594/// allocation function if it doesn't already exist.
595void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
596                                           QualType Return, QualType Argument)
597{
598  DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
599
600  // Check if this function is already declared.
601  {
602    DeclContext::lookup_iterator Alloc, AllocEnd;
603    for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Context, Name);
604         Alloc != AllocEnd; ++Alloc) {
605      // FIXME: Do we need to check for default arguments here?
606      FunctionDecl *Func = cast<FunctionDecl>(*Alloc);
607      if (Func->getNumParams() == 1 &&
608          Context.getCanonicalType(Func->getParamDecl(0)->getType())==Argument)
609        return;
610    }
611  }
612
613  QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0);
614  FunctionDecl *Alloc =
615    FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
616                         FnType, FunctionDecl::None, false, true,
617                         SourceLocation());
618  Alloc->setImplicit();
619  ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
620                                           0, Argument, VarDecl::None, 0);
621  Alloc->setParams(Context, &Param, 1);
622
623  // FIXME: Also add this declaration to the IdentifierResolver, but
624  // make sure it is at the end of the chain to coincide with the
625  // global scope.
626  ((DeclContext *)TUScope->getEntity())->addDecl(Context, Alloc);
627}
628
629/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
630/// @code ::delete ptr; @endcode
631/// or
632/// @code delete [] ptr; @endcode
633Action::OwningExprResult
634Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
635                     bool ArrayForm, ExprArg Operand)
636{
637  // C++ 5.3.5p1: "The operand shall have a pointer type, or a class type
638  //   having a single conversion function to a pointer type. The result has
639  //   type void."
640  // DR599 amends "pointer type" to "pointer to object type" in both cases.
641
642  Expr *Ex = (Expr *)Operand.get();
643  if (!Ex->isTypeDependent()) {
644    QualType Type = Ex->getType();
645
646    if (Type->isRecordType()) {
647      // FIXME: Find that one conversion function and amend the type.
648    }
649
650    if (!Type->isPointerType())
651      return ExprError(Diag(StartLoc, diag::err_delete_operand)
652        << Type << Ex->getSourceRange());
653
654    QualType Pointee = Type->getAsPointerType()->getPointeeType();
655    if (Pointee->isFunctionType() || Pointee->isVoidType())
656      return ExprError(Diag(StartLoc, diag::err_delete_operand)
657        << Type << Ex->getSourceRange());
658    else if (!Pointee->isDependentType() &&
659             RequireCompleteType(StartLoc, Pointee,
660                                 diag::warn_delete_incomplete,
661                                 Ex->getSourceRange()))
662      return ExprError();
663
664    // FIXME: Look up the correct operator delete overload and pass a pointer
665    // along.
666    // FIXME: Check access and ambiguity of operator delete and destructor.
667  }
668
669  Operand.release();
670  return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
671                                           0, Ex, StartLoc));
672}
673
674
675/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
676/// C++ if/switch/while/for statement.
677/// e.g: "if (int x = f()) {...}"
678Action::OwningExprResult
679Sema::ActOnCXXConditionDeclarationExpr(Scope *S, SourceLocation StartLoc,
680                                       Declarator &D,
681                                       SourceLocation EqualLoc,
682                                       ExprArg AssignExprVal) {
683  assert(AssignExprVal.get() && "Null assignment expression");
684
685  // C++ 6.4p2:
686  // The declarator shall not specify a function or an array.
687  // The type-specifier-seq shall not contain typedef and shall not declare a
688  // new class or enumeration.
689
690  assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
691         "Parser allowed 'typedef' as storage class of condition decl.");
692
693  QualType Ty = GetTypeForDeclarator(D, S);
694
695  if (Ty->isFunctionType()) { // The declarator shall not specify a function...
696    // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
697    // would be created and CXXConditionDeclExpr wants a VarDecl.
698    return ExprError(Diag(StartLoc, diag::err_invalid_use_of_function_type)
699      << SourceRange(StartLoc, EqualLoc));
700  } else if (Ty->isArrayType()) { // ...or an array.
701    Diag(StartLoc, diag::err_invalid_use_of_array_type)
702      << SourceRange(StartLoc, EqualLoc);
703  } else if (const RecordType *RT = Ty->getAsRecordType()) {
704    RecordDecl *RD = RT->getDecl();
705    // The type-specifier-seq shall not declare a new class...
706    if (RD->isDefinition() &&
707        (RD->getIdentifier() == 0 || S->isDeclScope(DeclPtrTy::make(RD))))
708      Diag(RD->getLocation(), diag::err_type_defined_in_condition);
709  } else if (const EnumType *ET = Ty->getAsEnumType()) {
710    EnumDecl *ED = ET->getDecl();
711    // ...or enumeration.
712    if (ED->isDefinition() &&
713        (ED->getIdentifier() == 0 || S->isDeclScope(DeclPtrTy::make(ED))))
714      Diag(ED->getLocation(), diag::err_type_defined_in_condition);
715  }
716
717  DeclPtrTy Dcl = ActOnDeclarator(S, D, DeclPtrTy());
718  if (!Dcl)
719    return ExprError();
720  AddInitializerToDecl(Dcl, move(AssignExprVal));
721
722  // Mark this variable as one that is declared within a conditional.
723  // We know that the decl had to be a VarDecl because that is the only type of
724  // decl that can be assigned and the grammar requires an '='.
725  VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
726  VD->setDeclaredInCondition(true);
727  return Owned(new (Context) CXXConditionDeclExpr(StartLoc, EqualLoc, VD));
728}
729
730/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
731bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
732  // C++ 6.4p4:
733  // The value of a condition that is an initialized declaration in a statement
734  // other than a switch statement is the value of the declared variable
735  // implicitly converted to type bool. If that conversion is ill-formed, the
736  // program is ill-formed.
737  // The value of a condition that is an expression is the value of the
738  // expression, implicitly converted to bool.
739  //
740  return PerformContextuallyConvertToBool(CondExpr);
741}
742
743/// Helper function to determine whether this is the (deprecated) C++
744/// conversion from a string literal to a pointer to non-const char or
745/// non-const wchar_t (for narrow and wide string literals,
746/// respectively).
747bool
748Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
749  // Look inside the implicit cast, if it exists.
750  if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
751    From = Cast->getSubExpr();
752
753  // A string literal (2.13.4) that is not a wide string literal can
754  // be converted to an rvalue of type "pointer to char"; a wide
755  // string literal can be converted to an rvalue of type "pointer
756  // to wchar_t" (C++ 4.2p2).
757  if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
758    if (const PointerType *ToPtrType = ToType->getAsPointerType())
759      if (const BuiltinType *ToPointeeType
760          = ToPtrType->getPointeeType()->getAsBuiltinType()) {
761        // This conversion is considered only when there is an
762        // explicit appropriate pointer target type (C++ 4.2p2).
763        if (ToPtrType->getPointeeType().getCVRQualifiers() == 0 &&
764            ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
765             (!StrLit->isWide() &&
766              (ToPointeeType->getKind() == BuiltinType::Char_U ||
767               ToPointeeType->getKind() == BuiltinType::Char_S))))
768          return true;
769      }
770
771  return false;
772}
773
774/// PerformImplicitConversion - Perform an implicit conversion of the
775/// expression From to the type ToType. Returns true if there was an
776/// error, false otherwise. The expression From is replaced with the
777/// converted expression. Flavor is the kind of conversion we're
778/// performing, used in the error message. If @p AllowExplicit,
779/// explicit user-defined conversions are permitted. @p Elidable should be true
780/// when called for copies which may be elided (C++ 12.8p15). C++0x overload
781/// resolution works differently in that case.
782bool
783Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
784                                const char *Flavor, bool AllowExplicit,
785                                bool Elidable)
786{
787  ImplicitConversionSequence ICS;
788  ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
789  if (Elidable && getLangOptions().CPlusPlus0x) {
790    ICS = TryImplicitConversion(From, ToType, /*SuppressUserConversions*/false,
791                                AllowExplicit, /*ForceRValue*/true);
792  }
793  if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) {
794    ICS = TryImplicitConversion(From, ToType, false, AllowExplicit);
795  }
796  return PerformImplicitConversion(From, ToType, ICS, Flavor);
797}
798
799/// PerformImplicitConversion - Perform an implicit conversion of the
800/// expression From to the type ToType using the pre-computed implicit
801/// conversion sequence ICS. Returns true if there was an error, false
802/// otherwise. The expression From is replaced with the converted
803/// expression. Flavor is the kind of conversion we're performing,
804/// used in the error message.
805bool
806Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
807                                const ImplicitConversionSequence &ICS,
808                                const char* Flavor) {
809  switch (ICS.ConversionKind) {
810  case ImplicitConversionSequence::StandardConversion:
811    if (PerformImplicitConversion(From, ToType, ICS.Standard, Flavor))
812      return true;
813    break;
814
815  case ImplicitConversionSequence::UserDefinedConversion:
816    // FIXME: This is, of course, wrong. We'll need to actually call
817    // the constructor or conversion operator, and then cope with the
818    // standard conversions.
819    ImpCastExprToType(From, ToType.getNonReferenceType(),
820                      ToType->isLValueReferenceType());
821    return false;
822
823  case ImplicitConversionSequence::EllipsisConversion:
824    assert(false && "Cannot perform an ellipsis conversion");
825    return false;
826
827  case ImplicitConversionSequence::BadConversion:
828    return true;
829  }
830
831  // Everything went well.
832  return false;
833}
834
835/// PerformImplicitConversion - Perform an implicit conversion of the
836/// expression From to the type ToType by following the standard
837/// conversion sequence SCS. Returns true if there was an error, false
838/// otherwise. The expression From is replaced with the converted
839/// expression. Flavor is the context in which we're performing this
840/// conversion, for use in error messages.
841bool
842Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
843                                const StandardConversionSequence& SCS,
844                                const char *Flavor) {
845  // Overall FIXME: we are recomputing too many types here and doing
846  // far too much extra work. What this means is that we need to keep
847  // track of more information that is computed when we try the
848  // implicit conversion initially, so that we don't need to recompute
849  // anything here.
850  QualType FromType = From->getType();
851
852  if (SCS.CopyConstructor) {
853    // FIXME: Create a temporary object by calling the copy
854    // constructor.
855    ImpCastExprToType(From, ToType.getNonReferenceType(),
856                      ToType->isLValueReferenceType());
857    return false;
858  }
859
860  // Perform the first implicit conversion.
861  switch (SCS.First) {
862  case ICK_Identity:
863  case ICK_Lvalue_To_Rvalue:
864    // Nothing to do.
865    break;
866
867  case ICK_Array_To_Pointer:
868    FromType = Context.getArrayDecayedType(FromType);
869    ImpCastExprToType(From, FromType);
870    break;
871
872  case ICK_Function_To_Pointer:
873    if (Context.getCanonicalType(FromType) == Context.OverloadTy) {
874      FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
875      if (!Fn)
876        return true;
877
878      if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
879        return true;
880
881      FixOverloadedFunctionReference(From, Fn);
882      FromType = From->getType();
883    }
884    FromType = Context.getPointerType(FromType);
885    ImpCastExprToType(From, FromType);
886    break;
887
888  default:
889    assert(false && "Improper first standard conversion");
890    break;
891  }
892
893  // Perform the second implicit conversion
894  switch (SCS.Second) {
895  case ICK_Identity:
896    // Nothing to do.
897    break;
898
899  case ICK_Integral_Promotion:
900  case ICK_Floating_Promotion:
901  case ICK_Complex_Promotion:
902  case ICK_Integral_Conversion:
903  case ICK_Floating_Conversion:
904  case ICK_Complex_Conversion:
905  case ICK_Floating_Integral:
906  case ICK_Complex_Real:
907  case ICK_Compatible_Conversion:
908      // FIXME: Go deeper to get the unqualified type!
909    FromType = ToType.getUnqualifiedType();
910    ImpCastExprToType(From, FromType);
911    break;
912
913  case ICK_Pointer_Conversion:
914    if (SCS.IncompatibleObjC) {
915      // Diagnose incompatible Objective-C conversions
916      Diag(From->getSourceRange().getBegin(),
917           diag::ext_typecheck_convert_incompatible_pointer)
918        << From->getType() << ToType << Flavor
919        << From->getSourceRange();
920    }
921
922    if (CheckPointerConversion(From, ToType))
923      return true;
924    ImpCastExprToType(From, ToType);
925    break;
926
927  case ICK_Pointer_Member:
928    if (CheckMemberPointerConversion(From, ToType))
929      return true;
930    ImpCastExprToType(From, ToType);
931    break;
932
933  case ICK_Boolean_Conversion:
934    FromType = Context.BoolTy;
935    ImpCastExprToType(From, FromType);
936    break;
937
938  default:
939    assert(false && "Improper second standard conversion");
940    break;
941  }
942
943  switch (SCS.Third) {
944  case ICK_Identity:
945    // Nothing to do.
946    break;
947
948  case ICK_Qualification:
949    // FIXME: Not sure about lvalue vs rvalue here in the presence of
950    // rvalue references.
951    ImpCastExprToType(From, ToType.getNonReferenceType(),
952                      ToType->isLValueReferenceType());
953    break;
954
955  default:
956    assert(false && "Improper second standard conversion");
957    break;
958  }
959
960  return false;
961}
962
963Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
964                                                 SourceLocation KWLoc,
965                                                 SourceLocation LParen,
966                                                 TypeTy *Ty,
967                                                 SourceLocation RParen) {
968  // FIXME: Some of the type traits have requirements. Interestingly, only the
969  // __is_base_of requirement is explicitly stated to be diagnosed. Indeed,
970  // G++ accepts __is_pod(Incomplete) without complaints, and claims that the
971  // type is indeed a POD.
972
973  // There is no point in eagerly computing the value. The traits are designed
974  // to be used from type trait templates, so Ty will be a template parameter
975  // 99% of the time.
976  return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT,
977                                      QualType::getFromOpaquePtr(Ty),
978                                      RParen, Context.BoolTy));
979}
980
981QualType Sema::CheckPointerToMemberOperands(
982  Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect)
983{
984  const char *OpSpelling = isIndirect ? "->*" : ".*";
985  // C++ 5.5p2
986  //   The binary operator .* [p3: ->*] binds its second operand, which shall
987  //   be of type "pointer to member of T" (where T is a completely-defined
988  //   class type) [...]
989  QualType RType = rex->getType();
990  const MemberPointerType *MemPtr = RType->getAsMemberPointerType();
991  if (!MemPtr) {
992    Diag(Loc, diag::err_bad_memptr_rhs)
993      << OpSpelling << RType << rex->getSourceRange();
994    return QualType();
995  }
996
997  QualType Class(MemPtr->getClass(), 0);
998
999  // C++ 5.5p2
1000  //   [...] to its first operand, which shall be of class T or of a class of
1001  //   which T is an unambiguous and accessible base class. [p3: a pointer to
1002  //   such a class]
1003  QualType LType = lex->getType();
1004  if (isIndirect) {
1005    if (const PointerType *Ptr = LType->getAsPointerType())
1006      LType = Ptr->getPointeeType().getNonReferenceType();
1007    else {
1008      Diag(Loc, diag::err_bad_memptr_lhs)
1009        << OpSpelling << 1 << LType << lex->getSourceRange();
1010      return QualType();
1011    }
1012  }
1013
1014  if (Context.getCanonicalType(Class).getUnqualifiedType() !=
1015      Context.getCanonicalType(LType).getUnqualifiedType()) {
1016    BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1017                    /*DetectVirtual=*/false);
1018    // FIXME: Would it be useful to print full ambiguity paths,
1019    // or is that overkill?
1020    if (!IsDerivedFrom(LType, Class, Paths) ||
1021        Paths.isAmbiguous(Context.getCanonicalType(Class))) {
1022      Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
1023        << (int)isIndirect << lex->getType() << lex->getSourceRange();
1024      return QualType();
1025    }
1026  }
1027
1028  // C++ 5.5p2
1029  //   The result is an object or a function of the type specified by the
1030  //   second operand.
1031  // The cv qualifiers are the union of those in the pointer and the left side,
1032  // in accordance with 5.5p5 and 5.2.5.
1033  // FIXME: This returns a dereferenced member function pointer as a normal
1034  // function type. However, the only operation valid on such functions is
1035  // calling them. There's also a GCC extension to get a function pointer to
1036  // the thing, which is another complication, because this type - unlike the
1037  // type that is the result of this expression - takes the class as the first
1038  // argument.
1039  // We probably need a "MemberFunctionClosureType" or something like that.
1040  QualType Result = MemPtr->getPointeeType();
1041  if (LType.isConstQualified())
1042    Result.addConst();
1043  if (LType.isVolatileQualified())
1044    Result.addVolatile();
1045  return Result;
1046}
1047
1048/// \brief Get the target type of a standard or user-defined conversion.
1049static QualType TargetType(const ImplicitConversionSequence &ICS) {
1050  assert((ICS.ConversionKind ==
1051              ImplicitConversionSequence::StandardConversion ||
1052          ICS.ConversionKind ==
1053              ImplicitConversionSequence::UserDefinedConversion) &&
1054         "function only valid for standard or user-defined conversions");
1055  if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion)
1056    return QualType::getFromOpaquePtr(ICS.Standard.ToTypePtr);
1057  return QualType::getFromOpaquePtr(ICS.UserDefined.After.ToTypePtr);
1058}
1059
1060/// \brief Try to convert a type to another according to C++0x 5.16p3.
1061///
1062/// This is part of the parameter validation for the ? operator. If either
1063/// value operand is a class type, the two operands are attempted to be
1064/// converted to each other. This function does the conversion in one direction.
1065/// It emits a diagnostic and returns true only if it finds an ambiguous
1066/// conversion.
1067static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
1068                                SourceLocation QuestionLoc,
1069                                ImplicitConversionSequence &ICS)
1070{
1071  // C++0x 5.16p3
1072  //   The process for determining whether an operand expression E1 of type T1
1073  //   can be converted to match an operand expression E2 of type T2 is defined
1074  //   as follows:
1075  //   -- If E2 is an lvalue:
1076  if (To->isLvalue(Self.Context) == Expr::LV_Valid) {
1077    //   E1 can be converted to match E2 if E1 can be implicitly converted to
1078    //   type "lvalue reference to T2", subject to the constraint that in the
1079    //   conversion the reference must bind directly to E1.
1080    if (!Self.CheckReferenceInit(From,
1081                            Self.Context.getLValueReferenceType(To->getType()),
1082                            &ICS))
1083    {
1084      assert((ICS.ConversionKind ==
1085                  ImplicitConversionSequence::StandardConversion ||
1086              ICS.ConversionKind ==
1087                  ImplicitConversionSequence::UserDefinedConversion) &&
1088             "expected a definite conversion");
1089      bool DirectBinding =
1090        ICS.ConversionKind == ImplicitConversionSequence::StandardConversion ?
1091        ICS.Standard.DirectBinding : ICS.UserDefined.After.DirectBinding;
1092      if (DirectBinding)
1093        return false;
1094    }
1095  }
1096  ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1097  //   -- If E2 is an rvalue, or if the conversion above cannot be done:
1098  //      -- if E1 and E2 have class type, and the underlying class types are
1099  //         the same or one is a base class of the other:
1100  QualType FTy = From->getType();
1101  QualType TTy = To->getType();
1102  const RecordType *FRec = FTy->getAsRecordType();
1103  const RecordType *TRec = TTy->getAsRecordType();
1104  bool FDerivedFromT = FRec && TRec && Self.IsDerivedFrom(FTy, TTy);
1105  if (FRec && TRec && (FRec == TRec ||
1106        FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
1107    //         E1 can be converted to match E2 if the class of T2 is the
1108    //         same type as, or a base class of, the class of T1, and
1109    //         [cv2 > cv1].
1110    if ((FRec == TRec || FDerivedFromT) && TTy.isAtLeastAsQualifiedAs(FTy)) {
1111      // Could still fail if there's no copy constructor.
1112      // FIXME: Is this a hard error then, or just a conversion failure? The
1113      // standard doesn't say.
1114      ICS = Self.TryCopyInitialization(From, TTy);
1115    }
1116  } else {
1117    //     -- Otherwise: E1 can be converted to match E2 if E1 can be
1118    //        implicitly converted to the type that expression E2 would have
1119    //        if E2 were converted to an rvalue.
1120    // First find the decayed type.
1121    if (TTy->isFunctionType())
1122      TTy = Self.Context.getPointerType(TTy);
1123    else if(TTy->isArrayType())
1124      TTy = Self.Context.getArrayDecayedType(TTy);
1125
1126    // Now try the implicit conversion.
1127    // FIXME: This doesn't detect ambiguities.
1128    ICS = Self.TryImplicitConversion(From, TTy);
1129  }
1130  return false;
1131}
1132
1133/// \brief Try to find a common type for two according to C++0x 5.16p5.
1134///
1135/// This is part of the parameter validation for the ? operator. If either
1136/// value operand is a class type, overload resolution is used to find a
1137/// conversion to a common type.
1138static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
1139                                    SourceLocation Loc) {
1140  Expr *Args[2] = { LHS, RHS };
1141  OverloadCandidateSet CandidateSet;
1142  Self.AddBuiltinOperatorCandidates(OO_Conditional, Args, 2, CandidateSet);
1143
1144  OverloadCandidateSet::iterator Best;
1145  switch (Self.BestViableFunction(CandidateSet, Best)) {
1146    case Sema::OR_Success:
1147      // We found a match. Perform the conversions on the arguments and move on.
1148      if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
1149                                         Best->Conversions[0], "converting") ||
1150          Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
1151                                         Best->Conversions[1], "converting"))
1152        break;
1153      return false;
1154
1155    case Sema::OR_No_Viable_Function:
1156      Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
1157        << LHS->getType() << RHS->getType()
1158        << LHS->getSourceRange() << RHS->getSourceRange();
1159      return true;
1160
1161    case Sema::OR_Ambiguous:
1162      Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
1163        << LHS->getType() << RHS->getType()
1164        << LHS->getSourceRange() << RHS->getSourceRange();
1165      // FIXME: Print the possible common types by printing the return types
1166      // of the viable candidates.
1167      break;
1168
1169    case Sema::OR_Deleted:
1170      assert(false && "Conditional operator has only built-in overloads");
1171      break;
1172  }
1173  return true;
1174}
1175
1176/// \brief Perform an "extended" implicit conversion as returned by
1177/// TryClassUnification.
1178///
1179/// TryClassUnification generates ICSs that include reference bindings.
1180/// PerformImplicitConversion is not suitable for this; it chokes if the
1181/// second part of a standard conversion is ICK_DerivedToBase. This function
1182/// handles the reference binding specially.
1183static bool ConvertForConditional(Sema &Self, Expr *&E,
1184                                  const ImplicitConversionSequence &ICS)
1185{
1186  if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion &&
1187      ICS.Standard.ReferenceBinding) {
1188    assert(ICS.Standard.DirectBinding &&
1189           "TryClassUnification should never generate indirect ref bindings");
1190    // FIXME: CheckReferenceInit should be able to reuse the ICS instead of
1191    // redoing all the work.
1192    return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
1193                                        TargetType(ICS)));
1194  }
1195  if (ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion &&
1196      ICS.UserDefined.After.ReferenceBinding) {
1197    assert(ICS.UserDefined.After.DirectBinding &&
1198           "TryClassUnification should never generate indirect ref bindings");
1199    return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
1200                                        TargetType(ICS)));
1201  }
1202  if (Self.PerformImplicitConversion(E, TargetType(ICS), ICS, "converting"))
1203    return true;
1204  return false;
1205}
1206
1207/// \brief Check the operands of ?: under C++ semantics.
1208///
1209/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
1210/// extension. In this case, LHS == Cond. (But they're not aliases.)
1211QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
1212                                           SourceLocation QuestionLoc) {
1213  // FIXME: Handle C99's complex types, vector types, block pointers and
1214  // Obj-C++ interface pointers.
1215
1216  // C++0x 5.16p1
1217  //   The first expression is contextually converted to bool.
1218  if (!Cond->isTypeDependent()) {
1219    if (CheckCXXBooleanCondition(Cond))
1220      return QualType();
1221  }
1222
1223  // Either of the arguments dependent?
1224  if (LHS->isTypeDependent() || RHS->isTypeDependent())
1225    return Context.DependentTy;
1226
1227  // C++0x 5.16p2
1228  //   If either the second or the third operand has type (cv) void, ...
1229  QualType LTy = LHS->getType();
1230  QualType RTy = RHS->getType();
1231  bool LVoid = LTy->isVoidType();
1232  bool RVoid = RTy->isVoidType();
1233  if (LVoid || RVoid) {
1234    //   ... then the [l2r] conversions are performed on the second and third
1235    //   operands ...
1236    DefaultFunctionArrayConversion(LHS);
1237    DefaultFunctionArrayConversion(RHS);
1238    LTy = LHS->getType();
1239    RTy = RHS->getType();
1240
1241    //   ... and one of the following shall hold:
1242    //   -- The second or the third operand (but not both) is a throw-
1243    //      expression; the result is of the type of the other and is an rvalue.
1244    bool LThrow = isa<CXXThrowExpr>(LHS);
1245    bool RThrow = isa<CXXThrowExpr>(RHS);
1246    if (LThrow && !RThrow)
1247      return RTy;
1248    if (RThrow && !LThrow)
1249      return LTy;
1250
1251    //   -- Both the second and third operands have type void; the result is of
1252    //      type void and is an rvalue.
1253    if (LVoid && RVoid)
1254      return Context.VoidTy;
1255
1256    // Neither holds, error.
1257    Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
1258      << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
1259      << LHS->getSourceRange() << RHS->getSourceRange();
1260    return QualType();
1261  }
1262
1263  // Neither is void.
1264
1265  // C++0x 5.16p3
1266  //   Otherwise, if the second and third operand have different types, and
1267  //   either has (cv) class type, and attempt is made to convert each of those
1268  //   operands to the other.
1269  if (Context.getCanonicalType(LTy) != Context.getCanonicalType(RTy) &&
1270      (LTy->isRecordType() || RTy->isRecordType())) {
1271    ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
1272    // These return true if a single direction is already ambiguous.
1273    if (TryClassUnification(*this, LHS, RHS, QuestionLoc, ICSLeftToRight))
1274      return QualType();
1275    if (TryClassUnification(*this, RHS, LHS, QuestionLoc, ICSRightToLeft))
1276      return QualType();
1277
1278    bool HaveL2R = ICSLeftToRight.ConversionKind !=
1279      ImplicitConversionSequence::BadConversion;
1280    bool HaveR2L = ICSRightToLeft.ConversionKind !=
1281      ImplicitConversionSequence::BadConversion;
1282    //   If both can be converted, [...] the program is ill-formed.
1283    if (HaveL2R && HaveR2L) {
1284      Diag(QuestionLoc, diag::err_conditional_ambiguous)
1285        << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
1286      return QualType();
1287    }
1288
1289    //   If exactly one conversion is possible, that conversion is applied to
1290    //   the chosen operand and the converted operands are used in place of the
1291    //   original operands for the remainder of this section.
1292    if (HaveL2R) {
1293      if (ConvertForConditional(*this, LHS, ICSLeftToRight))
1294        return QualType();
1295      LTy = LHS->getType();
1296    } else if (HaveR2L) {
1297      if (ConvertForConditional(*this, RHS, ICSRightToLeft))
1298        return QualType();
1299      RTy = RHS->getType();
1300    }
1301  }
1302
1303  // C++0x 5.16p4
1304  //   If the second and third operands are lvalues and have the same type,
1305  //   the result is of that type [...]
1306  bool Same = Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy);
1307  if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
1308      RHS->isLvalue(Context) == Expr::LV_Valid)
1309    return LTy;
1310
1311  // C++0x 5.16p5
1312  //   Otherwise, the result is an rvalue. If the second and third operands
1313  //   do not have the same type, and either has (cv) class type, ...
1314  if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
1315    //   ... overload resolution is used to determine the conversions (if any)
1316    //   to be applied to the operands. If the overload resolution fails, the
1317    //   program is ill-formed.
1318    if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
1319      return QualType();
1320  }
1321
1322  // C++0x 5.16p6
1323  //   LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
1324  //   conversions are performed on the second and third operands.
1325  DefaultFunctionArrayConversion(LHS);
1326  DefaultFunctionArrayConversion(RHS);
1327  LTy = LHS->getType();
1328  RTy = RHS->getType();
1329
1330  //   After those conversions, one of the following shall hold:
1331  //   -- The second and third operands have the same type; the result
1332  //      is of that type.
1333  if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy))
1334    return LTy;
1335
1336  //   -- The second and third operands have arithmetic or enumeration type;
1337  //      the usual arithmetic conversions are performed to bring them to a
1338  //      common type, and the result is of that type.
1339  if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
1340    UsualArithmeticConversions(LHS, RHS);
1341    return LHS->getType();
1342  }
1343
1344  //   -- The second and third operands have pointer type, or one has pointer
1345  //      type and the other is a null pointer constant; pointer conversions
1346  //      and qualification conversions are performed to bring them to their
1347  //      composite pointer type. The result is of the composite pointer type.
1348  QualType Composite = FindCompositePointerType(LHS, RHS);
1349  if (!Composite.isNull())
1350    return Composite;
1351
1352  // Fourth bullet is same for pointers-to-member. However, the possible
1353  // conversions are far more limited: we have null-to-pointer, upcast of
1354  // containing class, and second-level cv-ness.
1355  // cv-ness is not a union, but must match one of the two operands. (Which,
1356  // frankly, is stupid.)
1357  const MemberPointerType *LMemPtr = LTy->getAsMemberPointerType();
1358  const MemberPointerType *RMemPtr = RTy->getAsMemberPointerType();
1359  if (LMemPtr && RHS->isNullPointerConstant(Context)) {
1360    ImpCastExprToType(RHS, LTy);
1361    return LTy;
1362  }
1363  if (RMemPtr && LHS->isNullPointerConstant(Context)) {
1364    ImpCastExprToType(LHS, RTy);
1365    return RTy;
1366  }
1367  if (LMemPtr && RMemPtr) {
1368    QualType LPointee = LMemPtr->getPointeeType();
1369    QualType RPointee = RMemPtr->getPointeeType();
1370    // First, we check that the unqualified pointee type is the same. If it's
1371    // not, there's no conversion that will unify the two pointers.
1372    if (Context.getCanonicalType(LPointee).getUnqualifiedType() ==
1373        Context.getCanonicalType(RPointee).getUnqualifiedType()) {
1374      // Second, we take the greater of the two cv qualifications. If neither
1375      // is greater than the other, the conversion is not possible.
1376      unsigned Q = LPointee.getCVRQualifiers() | RPointee.getCVRQualifiers();
1377      if (Q == LPointee.getCVRQualifiers() || Q == RPointee.getCVRQualifiers()){
1378        // Third, we check if either of the container classes is derived from
1379        // the other.
1380        QualType LContainer(LMemPtr->getClass(), 0);
1381        QualType RContainer(RMemPtr->getClass(), 0);
1382        QualType MoreDerived;
1383        if (Context.getCanonicalType(LContainer) ==
1384            Context.getCanonicalType(RContainer))
1385          MoreDerived = LContainer;
1386        else if (IsDerivedFrom(LContainer, RContainer))
1387          MoreDerived = LContainer;
1388        else if (IsDerivedFrom(RContainer, LContainer))
1389          MoreDerived = RContainer;
1390
1391        if (!MoreDerived.isNull()) {
1392          // The type 'Q Pointee (MoreDerived::*)' is the common type.
1393          // We don't use ImpCastExprToType here because this could still fail
1394          // for ambiguous or inaccessible conversions.
1395          QualType Common = Context.getMemberPointerType(
1396            LPointee.getQualifiedType(Q), MoreDerived.getTypePtr());
1397          if (PerformImplicitConversion(LHS, Common, "converting"))
1398            return QualType();
1399          if (PerformImplicitConversion(RHS, Common, "converting"))
1400            return QualType();
1401          return Common;
1402        }
1403      }
1404    }
1405  }
1406
1407  Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
1408    << LHS->getType() << RHS->getType()
1409    << LHS->getSourceRange() << RHS->getSourceRange();
1410  return QualType();
1411}
1412
1413/// \brief Find a merged pointer type and convert the two expressions to it.
1414///
1415/// This finds the composite pointer type for @p E1 and @p E2 according to
1416/// C++0x 5.9p2. It converts both expressions to this type and returns it.
1417/// It does not emit diagnostics.
1418QualType Sema::FindCompositePointerType(Expr *&E1, Expr *&E2) {
1419  assert(getLangOptions().CPlusPlus && "This function assumes C++");
1420  QualType T1 = E1->getType(), T2 = E2->getType();
1421  if(!T1->isPointerType() && !T2->isPointerType())
1422    return QualType();
1423
1424  // C++0x 5.9p2
1425  //   Pointer conversions and qualification conversions are performed on
1426  //   pointer operands to bring them to their composite pointer type. If
1427  //   one operand is a null pointer constant, the composite pointer type is
1428  //   the type of the other operand.
1429  if (E1->isNullPointerConstant(Context)) {
1430    ImpCastExprToType(E1, T2);
1431    return T2;
1432  }
1433  if (E2->isNullPointerConstant(Context)) {
1434    ImpCastExprToType(E2, T1);
1435    return T1;
1436  }
1437  // Now both have to be pointers.
1438  if(!T1->isPointerType() || !T2->isPointerType())
1439    return QualType();
1440
1441  //   Otherwise, of one of the operands has type "pointer to cv1 void," then
1442  //   the other has type "pointer to cv2 T" and the composite pointer type is
1443  //   "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
1444  //   Otherwise, the composite pointer type is a pointer type similar to the
1445  //   type of one of the operands, with a cv-qualification signature that is
1446  //   the union of the cv-qualification signatures of the operand types.
1447  // In practice, the first part here is redundant; it's subsumed by the second.
1448  // What we do here is, we build the two possible composite types, and try the
1449  // conversions in both directions. If only one works, or if the two composite
1450  // types are the same, we have succeeded.
1451  llvm::SmallVector<unsigned, 4> QualifierUnion;
1452  QualType Composite1 = T1, Composite2 = T2;
1453  const PointerType *Ptr1, *Ptr2;
1454  while ((Ptr1 = Composite1->getAsPointerType()) &&
1455         (Ptr2 = Composite2->getAsPointerType())) {
1456    Composite1 = Ptr1->getPointeeType();
1457    Composite2 = Ptr2->getPointeeType();
1458    QualifierUnion.push_back(
1459      Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1460  }
1461  // Rewrap the composites as pointers with the union CVRs.
1462  for (llvm::SmallVector<unsigned, 4>::iterator I = QualifierUnion.begin(),
1463       E = QualifierUnion.end(); I != E; ++I) {
1464    Composite1 = Context.getPointerType(Composite1.getQualifiedType(*I));
1465    Composite2 = Context.getPointerType(Composite2.getQualifiedType(*I));
1466  }
1467
1468  ImplicitConversionSequence E1ToC1 = TryImplicitConversion(E1, Composite1);
1469  ImplicitConversionSequence E2ToC1 = TryImplicitConversion(E2, Composite1);
1470  ImplicitConversionSequence E1ToC2, E2ToC2;
1471  E1ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
1472  E2ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
1473  if (Context.getCanonicalType(Composite1) !=
1474      Context.getCanonicalType(Composite2)) {
1475    E1ToC2 = TryImplicitConversion(E1, Composite2);
1476    E2ToC2 = TryImplicitConversion(E2, Composite2);
1477  }
1478
1479  bool ToC1Viable = E1ToC1.ConversionKind !=
1480                      ImplicitConversionSequence::BadConversion
1481                 && E2ToC1.ConversionKind !=
1482                      ImplicitConversionSequence::BadConversion;
1483  bool ToC2Viable = E1ToC2.ConversionKind !=
1484                      ImplicitConversionSequence::BadConversion
1485                 && E2ToC2.ConversionKind !=
1486                      ImplicitConversionSequence::BadConversion;
1487  if (ToC1Viable && !ToC2Viable) {
1488    if (!PerformImplicitConversion(E1, Composite1, E1ToC1, "converting") &&
1489        !PerformImplicitConversion(E2, Composite1, E2ToC1, "converting"))
1490      return Composite1;
1491  }
1492  if (ToC2Viable && !ToC1Viable) {
1493    if (!PerformImplicitConversion(E1, Composite2, E1ToC2, "converting") &&
1494        !PerformImplicitConversion(E2, Composite2, E2ToC2, "converting"))
1495      return Composite2;
1496  }
1497  return QualType();
1498}
1499