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