SemaExprCXX.cpp revision 7755c88dcbfa1d4273fd97bdd3415c5c2aa19039
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 "Sema.h"
15#include "Lookup.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/CXXInheritance.h"
18#include "clang/AST/ExprCXX.h"
19#include "clang/Basic/PartialDiagnostic.h"
20#include "clang/Basic/TargetInfo.h"
21#include "clang/Lex/Preprocessor.h"
22#include "clang/Parse/DeclSpec.h"
23#include "llvm/ADT/STLExtras.h"
24using namespace clang;
25
26/// ActOnCXXTypeidOfType - Parse typeid( type-id ).
27Action::OwningExprResult
28Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
29                     bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
30  if (!StdNamespace)
31    return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
32
33  if (isType)
34    // FIXME: Preserve type source info.
35    TyOrExpr = GetTypeFromParser(TyOrExpr).getAsOpaquePtr();
36
37  IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
38  LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
39  LookupQualifiedName(R, StdNamespace);
40  RecordDecl *TypeInfoRecordDecl = R.getAsSingle<RecordDecl>();
41  if (!TypeInfoRecordDecl)
42    return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
43
44  QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
45
46  if (!isType) {
47    // C++0x [expr.typeid]p3:
48    //   When typeid is applied to an expression other than an lvalue of a
49    //   polymorphic class type [...] [the] expression is an unevaluated
50    //   operand.
51
52    // FIXME: if the type of the expression is a class type, the class
53    // shall be completely defined.
54    bool isUnevaluatedOperand = true;
55    Expr *E = static_cast<Expr *>(TyOrExpr);
56    if (E && !E->isTypeDependent() && E->isLvalue(Context) == Expr::LV_Valid) {
57      QualType T = E->getType();
58      if (const RecordType *RecordT = T->getAs<RecordType>()) {
59        CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
60        if (RecordD->isPolymorphic())
61          isUnevaluatedOperand = false;
62      }
63    }
64
65    // If this is an unevaluated operand, clear out the set of
66    // declaration references we have been computing and eliminate any
67    // temporaries introduced in its computation.
68    if (isUnevaluatedOperand)
69      ExprEvalContexts.back().Context = Unevaluated;
70  }
71
72  return Owned(new (Context) CXXTypeidExpr(isType, TyOrExpr,
73                                           TypeInfoType.withConst(),
74                                           SourceRange(OpLoc, RParenLoc)));
75}
76
77/// ActOnCXXBoolLiteral - Parse {true,false} literals.
78Action::OwningExprResult
79Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
80  assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
81         "Unknown C++ Boolean value!");
82  return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
83                                                Context.BoolTy, OpLoc));
84}
85
86/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
87Action::OwningExprResult
88Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
89  return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
90}
91
92/// ActOnCXXThrow - Parse throw expressions.
93Action::OwningExprResult
94Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) {
95  Expr *Ex = E.takeAs<Expr>();
96  if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
97    return ExprError();
98  return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
99}
100
101/// CheckCXXThrowOperand - Validate the operand of a throw.
102bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
103  // C++ [except.throw]p3:
104  //   [...] adjusting the type from "array of T" or "function returning T"
105  //   to "pointer to T" or "pointer to function returning T", [...]
106  DefaultFunctionArrayConversion(E);
107
108  //   If the type of the exception would be an incomplete type or a pointer
109  //   to an incomplete type other than (cv) void the program is ill-formed.
110  QualType Ty = E->getType();
111  int isPointer = 0;
112  if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
113    Ty = Ptr->getPointeeType();
114    isPointer = 1;
115  }
116  if (!isPointer || !Ty->isVoidType()) {
117    if (RequireCompleteType(ThrowLoc, Ty,
118                            PDiag(isPointer ? diag::err_throw_incomplete_ptr
119                                            : diag::err_throw_incomplete)
120                              << E->getSourceRange()))
121      return true;
122  }
123
124  // FIXME: Construct a temporary here.
125  return false;
126}
127
128Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
129  /// C++ 9.3.2: In the body of a non-static member function, the keyword this
130  /// is a non-lvalue expression whose value is the address of the object for
131  /// which the function is called.
132
133  if (!isa<FunctionDecl>(CurContext))
134    return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
135
136  if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
137    if (MD->isInstance())
138      return Owned(new (Context) CXXThisExpr(ThisLoc,
139                                             MD->getThisType(Context)));
140
141  return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
142}
143
144/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
145/// Can be interpreted either as function-style casting ("int(x)")
146/// or class type construction ("ClassType(x,y,z)")
147/// or creation of a value-initialized type ("int()").
148Action::OwningExprResult
149Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
150                                SourceLocation LParenLoc,
151                                MultiExprArg exprs,
152                                SourceLocation *CommaLocs,
153                                SourceLocation RParenLoc) {
154  assert(TypeRep && "Missing type!");
155  // FIXME: Preserve type source info.
156  QualType Ty = GetTypeFromParser(TypeRep);
157  unsigned NumExprs = exprs.size();
158  Expr **Exprs = (Expr**)exprs.get();
159  SourceLocation TyBeginLoc = TypeRange.getBegin();
160  SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
161
162  if (Ty->isDependentType() ||
163      CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
164    exprs.release();
165
166    return Owned(CXXUnresolvedConstructExpr::Create(Context,
167                                                    TypeRange.getBegin(), Ty,
168                                                    LParenLoc,
169                                                    Exprs, NumExprs,
170                                                    RParenLoc));
171  }
172
173  if (Ty->isArrayType())
174    return ExprError(Diag(TyBeginLoc,
175                          diag::err_value_init_for_array_type) << FullRange);
176  if (!Ty->isVoidType() &&
177      RequireCompleteType(TyBeginLoc, Ty,
178                          PDiag(diag::err_invalid_incomplete_type_use)
179                            << FullRange))
180    return ExprError();
181
182  if (RequireNonAbstractType(TyBeginLoc, Ty,
183                             diag::err_allocation_of_abstract_type))
184    return ExprError();
185
186
187  // C++ [expr.type.conv]p1:
188  // If the expression list is a single expression, the type conversion
189  // expression is equivalent (in definedness, and if defined in meaning) to the
190  // corresponding cast expression.
191  //
192  if (NumExprs == 1) {
193    CastExpr::CastKind Kind = CastExpr::CK_Unknown;
194    CXXMethodDecl *Method = 0;
195    if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, Method,
196                       /*FunctionalStyle=*/true))
197      return ExprError();
198
199    exprs.release();
200    if (Method) {
201      OwningExprResult CastArg
202        = BuildCXXCastArgument(TypeRange.getBegin(), Ty.getNonReferenceType(),
203                               Kind, Method, Owned(Exprs[0]));
204      if (CastArg.isInvalid())
205        return ExprError();
206
207      Exprs[0] = CastArg.takeAs<Expr>();
208    }
209
210    return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
211                                                     Ty, TyBeginLoc, Kind,
212                                                     Exprs[0], RParenLoc));
213  }
214
215  if (const RecordType *RT = Ty->getAs<RecordType>()) {
216    CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
217
218    if (NumExprs > 1 || !Record->hasTrivialConstructor() ||
219        !Record->hasTrivialDestructor()) {
220      ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
221
222      CXXConstructorDecl *Constructor
223        = PerformInitializationByConstructor(Ty, move(exprs),
224                                             TypeRange.getBegin(),
225                                             SourceRange(TypeRange.getBegin(),
226                                                         RParenLoc),
227                                             DeclarationName(),
228                                             IK_Direct,
229                                             ConstructorArgs);
230
231      if (!Constructor)
232        return ExprError();
233
234      OwningExprResult Result =
235        BuildCXXTemporaryObjectExpr(Constructor, Ty, TyBeginLoc,
236                                    move_arg(ConstructorArgs), RParenLoc);
237      if (Result.isInvalid())
238        return ExprError();
239
240      return MaybeBindToTemporary(Result.takeAs<Expr>());
241    }
242
243    // Fall through to value-initialize an object of class type that
244    // doesn't have a user-declared default constructor.
245  }
246
247  // C++ [expr.type.conv]p1:
248  // If the expression list specifies more than a single value, the type shall
249  // be a class with a suitably declared constructor.
250  //
251  if (NumExprs > 1)
252    return ExprError(Diag(CommaLocs[0],
253                          diag::err_builtin_func_cast_more_than_one_arg)
254      << FullRange);
255
256  assert(NumExprs == 0 && "Expected 0 expressions");
257  // C++ [expr.type.conv]p2:
258  // The expression T(), where T is a simple-type-specifier for a non-array
259  // complete object type or the (possibly cv-qualified) void type, creates an
260  // rvalue of the specified type, which is value-initialized.
261  //
262  exprs.release();
263  return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
264}
265
266
267/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
268/// @code new (memory) int[size][4] @endcode
269/// or
270/// @code ::new Foo(23, "hello") @endcode
271/// For the interpretation of this heap of arguments, consult the base version.
272Action::OwningExprResult
273Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
274                  SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
275                  SourceLocation PlacementRParen, bool ParenTypeId,
276                  Declarator &D, SourceLocation ConstructorLParen,
277                  MultiExprArg ConstructorArgs,
278                  SourceLocation ConstructorRParen) {
279  Expr *ArraySize = 0;
280  // If the specified type is an array, unwrap it and save the expression.
281  if (D.getNumTypeObjects() > 0 &&
282      D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
283    DeclaratorChunk &Chunk = D.getTypeObject(0);
284    if (Chunk.Arr.hasStatic)
285      return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
286        << D.getSourceRange());
287    if (!Chunk.Arr.NumElts)
288      return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
289        << D.getSourceRange());
290
291    if (ParenTypeId) {
292      // Can't have dynamic array size when the type-id is in parentheses.
293      Expr *NumElts = (Expr *)Chunk.Arr.NumElts;
294      if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
295          !NumElts->isIntegerConstantExpr(Context)) {
296        Diag(D.getTypeObject(0).Loc, diag::err_new_paren_array_nonconst)
297          << NumElts->getSourceRange();
298        return ExprError();
299      }
300    }
301
302    ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
303    D.DropFirstTypeObject();
304  }
305
306  // Every dimension shall be of constant size.
307  if (ArraySize) {
308    for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
309      if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
310        break;
311
312      DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
313      if (Expr *NumElts = (Expr *)Array.NumElts) {
314        if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
315            !NumElts->isIntegerConstantExpr(Context)) {
316          Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
317            << NumElts->getSourceRange();
318          return ExprError();
319        }
320      }
321    }
322  }
323
324  //FIXME: Store TypeSourceInfo in CXXNew expression.
325  TypeSourceInfo *TInfo = 0;
326  QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, &TInfo);
327  if (D.isInvalidType())
328    return ExprError();
329
330  return BuildCXXNew(StartLoc, UseGlobal,
331                     PlacementLParen,
332                     move(PlacementArgs),
333                     PlacementRParen,
334                     ParenTypeId,
335                     AllocType,
336                     D.getSourceRange().getBegin(),
337                     D.getSourceRange(),
338                     Owned(ArraySize),
339                     ConstructorLParen,
340                     move(ConstructorArgs),
341                     ConstructorRParen);
342}
343
344Sema::OwningExprResult
345Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
346                  SourceLocation PlacementLParen,
347                  MultiExprArg PlacementArgs,
348                  SourceLocation PlacementRParen,
349                  bool ParenTypeId,
350                  QualType AllocType,
351                  SourceLocation TypeLoc,
352                  SourceRange TypeRange,
353                  ExprArg ArraySizeE,
354                  SourceLocation ConstructorLParen,
355                  MultiExprArg ConstructorArgs,
356                  SourceLocation ConstructorRParen) {
357  if (CheckAllocatedType(AllocType, TypeLoc, TypeRange))
358    return ExprError();
359
360  QualType ResultType = Context.getPointerType(AllocType);
361
362  // That every array dimension except the first is constant was already
363  // checked by the type check above.
364
365  // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
366  //   or enumeration type with a non-negative value."
367  Expr *ArraySize = (Expr *)ArraySizeE.get();
368  if (ArraySize && !ArraySize->isTypeDependent()) {
369    QualType SizeType = ArraySize->getType();
370    if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
371      return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
372                            diag::err_array_size_not_integral)
373        << SizeType << ArraySize->getSourceRange());
374    // Let's see if this is a constant < 0. If so, we reject it out of hand.
375    // We don't care about special rules, so we tell the machinery it's not
376    // evaluated - it gives us a result in more cases.
377    if (!ArraySize->isValueDependent()) {
378      llvm::APSInt Value;
379      if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
380        if (Value < llvm::APSInt(
381                        llvm::APInt::getNullValue(Value.getBitWidth()),
382                                 Value.isUnsigned()))
383          return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
384                           diag::err_typecheck_negative_array_size)
385            << ArraySize->getSourceRange());
386      }
387    }
388
389    ImpCastExprToType(ArraySize, Context.getSizeType(),
390                      CastExpr::CK_IntegralCast);
391  }
392
393  FunctionDecl *OperatorNew = 0;
394  FunctionDecl *OperatorDelete = 0;
395  Expr **PlaceArgs = (Expr**)PlacementArgs.get();
396  unsigned NumPlaceArgs = PlacementArgs.size();
397
398  if (!AllocType->isDependentType() &&
399      !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
400      FindAllocationFunctions(StartLoc,
401                              SourceRange(PlacementLParen, PlacementRParen),
402                              UseGlobal, AllocType, ArraySize, PlaceArgs,
403                              NumPlaceArgs, OperatorNew, OperatorDelete))
404    return ExprError();
405  llvm::SmallVector<Expr *, 8> AllPlaceArgs;
406  if (OperatorNew) {
407    // Add default arguments, if any.
408    const FunctionProtoType *Proto =
409      OperatorNew->getType()->getAs<FunctionProtoType>();
410    VariadicCallType CallType =
411      Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
412    bool Invalid = GatherArgumentsForCall(PlacementLParen, OperatorNew,
413                                          Proto, 1, PlaceArgs, NumPlaceArgs,
414                                          AllPlaceArgs, CallType);
415    if (Invalid)
416      return ExprError();
417
418    NumPlaceArgs = AllPlaceArgs.size();
419    if (NumPlaceArgs > 0)
420      PlaceArgs = &AllPlaceArgs[0];
421  }
422
423  bool Init = ConstructorLParen.isValid();
424  // --- Choosing a constructor ---
425  // C++ 5.3.4p15
426  // 1) If T is a POD and there's no initializer (ConstructorLParen is invalid)
427  //   the object is not initialized. If the object, or any part of it, is
428  //   const-qualified, it's an error.
429  // 2) If T is a POD and there's an empty initializer, the object is value-
430  //   initialized.
431  // 3) If T is a POD and there's one initializer argument, the object is copy-
432  //   constructed.
433  // 4) If T is a POD and there's more initializer arguments, it's an error.
434  // 5) If T is not a POD, the initializer arguments are used as constructor
435  //   arguments.
436  //
437  // Or by the C++0x formulation:
438  // 1) If there's no initializer, the object is default-initialized according
439  //    to C++0x rules.
440  // 2) Otherwise, the object is direct-initialized.
441  CXXConstructorDecl *Constructor = 0;
442  Expr **ConsArgs = (Expr**)ConstructorArgs.get();
443  const RecordType *RT;
444  unsigned NumConsArgs = ConstructorArgs.size();
445  ASTOwningVector<&ActionBase::DeleteExpr> ConvertedConstructorArgs(*this);
446
447  if (AllocType->isDependentType() ||
448      Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
449    // Skip all the checks.
450  } else if ((RT = AllocType->getAs<RecordType>()) &&
451             !AllocType->isAggregateType()) {
452    Constructor = PerformInitializationByConstructor(
453                      AllocType, move(ConstructorArgs),
454                      TypeLoc,
455                      SourceRange(TypeLoc, ConstructorRParen),
456                      RT->getDecl()->getDeclName(),
457                      NumConsArgs != 0 ? IK_Direct : IK_Default,
458                      ConvertedConstructorArgs);
459    if (!Constructor)
460      return ExprError();
461
462    // Take the converted constructor arguments and use them for the new
463    // expression.
464    NumConsArgs = ConvertedConstructorArgs.size();
465    ConsArgs = (Expr **)ConvertedConstructorArgs.take();
466  } else {
467    if (!Init) {
468      // FIXME: Check that no subpart is const.
469      if (AllocType.isConstQualified())
470        return ExprError(Diag(StartLoc, diag::err_new_uninitialized_const)
471                           << TypeRange);
472    } else if (NumConsArgs == 0) {
473      // Object is value-initialized. Do nothing.
474    } else if (NumConsArgs == 1) {
475      // Object is direct-initialized.
476      // FIXME: What DeclarationName do we pass in here?
477      if (CheckInitializerTypes(ConsArgs[0], AllocType, StartLoc,
478                                DeclarationName() /*AllocType.getAsString()*/,
479                                /*DirectInit=*/true))
480        return ExprError();
481    } else {
482      return ExprError(Diag(StartLoc,
483                            diag::err_builtin_direct_init_more_than_one_arg)
484        << SourceRange(ConstructorLParen, ConstructorRParen));
485    }
486  }
487
488  // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
489
490  PlacementArgs.release();
491  ConstructorArgs.release();
492  ArraySizeE.release();
493  return Owned(new (Context) CXXNewExpr(UseGlobal, OperatorNew, PlaceArgs,
494                        NumPlaceArgs, ParenTypeId, ArraySize, Constructor, Init,
495                        ConsArgs, NumConsArgs, OperatorDelete, ResultType,
496                        StartLoc, Init ? ConstructorRParen : SourceLocation()));
497}
498
499/// CheckAllocatedType - Checks that a type is suitable as the allocated type
500/// in a new-expression.
501/// dimension off and stores the size expression in ArraySize.
502bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
503                              SourceRange R) {
504  // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
505  //   abstract class type or array thereof.
506  if (AllocType->isFunctionType())
507    return Diag(Loc, diag::err_bad_new_type)
508      << AllocType << 0 << R;
509  else if (AllocType->isReferenceType())
510    return Diag(Loc, diag::err_bad_new_type)
511      << AllocType << 1 << R;
512  else if (!AllocType->isDependentType() &&
513           RequireCompleteType(Loc, AllocType,
514                               PDiag(diag::err_new_incomplete_type)
515                                 << R))
516    return true;
517  else if (RequireNonAbstractType(Loc, AllocType,
518                                  diag::err_allocation_of_abstract_type))
519    return true;
520
521  return false;
522}
523
524/// FindAllocationFunctions - Finds the overloads of operator new and delete
525/// that are appropriate for the allocation.
526bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
527                                   bool UseGlobal, QualType AllocType,
528                                   bool IsArray, Expr **PlaceArgs,
529                                   unsigned NumPlaceArgs,
530                                   FunctionDecl *&OperatorNew,
531                                   FunctionDecl *&OperatorDelete) {
532  // --- Choosing an allocation function ---
533  // C++ 5.3.4p8 - 14 & 18
534  // 1) If UseGlobal is true, only look in the global scope. Else, also look
535  //   in the scope of the allocated class.
536  // 2) If an array size is given, look for operator new[], else look for
537  //   operator new.
538  // 3) The first argument is always size_t. Append the arguments from the
539  //   placement form.
540  // FIXME: Also find the appropriate delete operator.
541
542  llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
543  // We don't care about the actual value of this argument.
544  // FIXME: Should the Sema create the expression and embed it in the syntax
545  // tree? Or should the consumer just recalculate the value?
546  IntegerLiteral Size(llvm::APInt::getNullValue(
547                      Context.Target.getPointerWidth(0)),
548                      Context.getSizeType(),
549                      SourceLocation());
550  AllocArgs[0] = &Size;
551  std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
552
553  DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
554                                        IsArray ? OO_Array_New : OO_New);
555  if (AllocType->isRecordType() && !UseGlobal) {
556    CXXRecordDecl *Record
557      = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
558    // FIXME: We fail to find inherited overloads.
559    if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
560                          AllocArgs.size(), Record, /*AllowMissing=*/true,
561                          OperatorNew))
562      return true;
563  }
564  if (!OperatorNew) {
565    // Didn't find a member overload. Look for a global one.
566    DeclareGlobalNewDelete();
567    DeclContext *TUDecl = Context.getTranslationUnitDecl();
568    if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
569                          AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
570                          OperatorNew))
571      return true;
572  }
573
574  // FindAllocationOverload can change the passed in arguments, so we need to
575  // copy them back.
576  if (NumPlaceArgs > 0)
577    std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
578
579  return false;
580}
581
582/// FindAllocationOverload - Find an fitting overload for the allocation
583/// function in the specified scope.
584bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
585                                  DeclarationName Name, Expr** Args,
586                                  unsigned NumArgs, DeclContext *Ctx,
587                                  bool AllowMissing, FunctionDecl *&Operator) {
588  LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
589  LookupQualifiedName(R, Ctx);
590  if (R.empty()) {
591    if (AllowMissing)
592      return false;
593    return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
594      << Name << Range;
595  }
596
597  // FIXME: handle ambiguity
598
599  OverloadCandidateSet Candidates;
600  for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
601       Alloc != AllocEnd; ++Alloc) {
602    // Even member operator new/delete are implicitly treated as
603    // static, so don't use AddMemberCandidate.
604    if (FunctionDecl *Fn = dyn_cast<FunctionDecl>(*Alloc)) {
605      AddOverloadCandidate(Fn, Args, NumArgs, Candidates,
606                           /*SuppressUserConversions=*/false);
607      continue;
608    }
609
610    // FIXME: Handle function templates
611  }
612
613  // Do the resolution.
614  OverloadCandidateSet::iterator Best;
615  switch(BestViableFunction(Candidates, StartLoc, Best)) {
616  case OR_Success: {
617    // Got one!
618    FunctionDecl *FnDecl = Best->Function;
619    // The first argument is size_t, and the first parameter must be size_t,
620    // too. This is checked on declaration and can be assumed. (It can't be
621    // asserted on, though, since invalid decls are left in there.)
622    // Whatch out for variadic allocator function.
623    unsigned NumArgsInFnDecl = FnDecl->getNumParams();
624    for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
625      // FIXME: Passing word to diagnostic.
626      if (PerformCopyInitialization(Args[i],
627                                    FnDecl->getParamDecl(i)->getType(),
628                                    "passing"))
629        return true;
630    }
631    Operator = FnDecl;
632    return false;
633  }
634
635  case OR_No_Viable_Function:
636    Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
637      << Name << Range;
638    PrintOverloadCandidates(Candidates, /*OnlyViable=*/false);
639    return true;
640
641  case OR_Ambiguous:
642    Diag(StartLoc, diag::err_ovl_ambiguous_call)
643      << Name << Range;
644    PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
645    return true;
646
647  case OR_Deleted:
648    Diag(StartLoc, diag::err_ovl_deleted_call)
649      << Best->Function->isDeleted()
650      << Name << Range;
651    PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
652    return true;
653  }
654  assert(false && "Unreachable, bad result from BestViableFunction");
655  return true;
656}
657
658
659/// DeclareGlobalNewDelete - Declare the global forms of operator new and
660/// delete. These are:
661/// @code
662///   void* operator new(std::size_t) throw(std::bad_alloc);
663///   void* operator new[](std::size_t) throw(std::bad_alloc);
664///   void operator delete(void *) throw();
665///   void operator delete[](void *) throw();
666/// @endcode
667/// Note that the placement and nothrow forms of new are *not* implicitly
668/// declared. Their use requires including \<new\>.
669void Sema::DeclareGlobalNewDelete() {
670  if (GlobalNewDeleteDeclared)
671    return;
672
673  // C++ [basic.std.dynamic]p2:
674  //   [...] The following allocation and deallocation functions (18.4) are
675  //   implicitly declared in global scope in each translation unit of a
676  //   program
677  //
678  //     void* operator new(std::size_t) throw(std::bad_alloc);
679  //     void* operator new[](std::size_t) throw(std::bad_alloc);
680  //     void  operator delete(void*) throw();
681  //     void  operator delete[](void*) throw();
682  //
683  //   These implicit declarations introduce only the function names operator
684  //   new, operator new[], operator delete, operator delete[].
685  //
686  // Here, we need to refer to std::bad_alloc, so we will implicitly declare
687  // "std" or "bad_alloc" as necessary to form the exception specification.
688  // However, we do not make these implicit declarations visible to name
689  // lookup.
690  if (!StdNamespace) {
691    // The "std" namespace has not yet been defined, so build one implicitly.
692    StdNamespace = NamespaceDecl::Create(Context,
693                                         Context.getTranslationUnitDecl(),
694                                         SourceLocation(),
695                                         &PP.getIdentifierTable().get("std"));
696    StdNamespace->setImplicit(true);
697  }
698
699  if (!StdBadAlloc) {
700    // The "std::bad_alloc" class has not yet been declared, so build it
701    // implicitly.
702    StdBadAlloc = CXXRecordDecl::Create(Context, TagDecl::TK_class,
703                                        StdNamespace,
704                                        SourceLocation(),
705                                      &PP.getIdentifierTable().get("bad_alloc"),
706                                        SourceLocation(), 0);
707    StdBadAlloc->setImplicit(true);
708  }
709
710  GlobalNewDeleteDeclared = true;
711
712  QualType VoidPtr = Context.getPointerType(Context.VoidTy);
713  QualType SizeT = Context.getSizeType();
714
715  DeclareGlobalAllocationFunction(
716      Context.DeclarationNames.getCXXOperatorName(OO_New),
717      VoidPtr, SizeT);
718  DeclareGlobalAllocationFunction(
719      Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
720      VoidPtr, SizeT);
721  DeclareGlobalAllocationFunction(
722      Context.DeclarationNames.getCXXOperatorName(OO_Delete),
723      Context.VoidTy, VoidPtr);
724  DeclareGlobalAllocationFunction(
725      Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
726      Context.VoidTy, VoidPtr);
727}
728
729/// DeclareGlobalAllocationFunction - Declares a single implicit global
730/// allocation function if it doesn't already exist.
731void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
732                                           QualType Return, QualType Argument) {
733  DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
734
735  // Check if this function is already declared.
736  {
737    DeclContext::lookup_iterator Alloc, AllocEnd;
738    for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
739         Alloc != AllocEnd; ++Alloc) {
740      // FIXME: Do we need to check for default arguments here?
741      FunctionDecl *Func = cast<FunctionDecl>(*Alloc);
742      if (Func->getNumParams() == 1 &&
743          Context.getCanonicalType(Func->getParamDecl(0)->getType())==Argument)
744        return;
745    }
746  }
747
748  QualType BadAllocType;
749  bool HasBadAllocExceptionSpec
750    = (Name.getCXXOverloadedOperator() == OO_New ||
751       Name.getCXXOverloadedOperator() == OO_Array_New);
752  if (HasBadAllocExceptionSpec) {
753    assert(StdBadAlloc && "Must have std::bad_alloc declared");
754    BadAllocType = Context.getTypeDeclType(StdBadAlloc);
755  }
756
757  QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0,
758                                            true, false,
759                                            HasBadAllocExceptionSpec? 1 : 0,
760                                            &BadAllocType);
761  FunctionDecl *Alloc =
762    FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
763                         FnType, /*TInfo=*/0, FunctionDecl::None, false, true);
764  Alloc->setImplicit();
765  ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
766                                           0, Argument, /*TInfo=*/0,
767                                           VarDecl::None, 0);
768  Alloc->setParams(Context, &Param, 1);
769
770  // FIXME: Also add this declaration to the IdentifierResolver, but
771  // make sure it is at the end of the chain to coincide with the
772  // global scope.
773  ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
774}
775
776bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
777                                    DeclarationName Name,
778                                    FunctionDecl* &Operator) {
779  LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
780  // Try to find operator delete/operator delete[] in class scope.
781  LookupQualifiedName(Found, RD);
782
783  if (Found.isAmbiguous())
784    return true;
785
786  for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
787       F != FEnd; ++F) {
788    if (CXXMethodDecl *Delete = dyn_cast<CXXMethodDecl>(*F))
789      if (Delete->isUsualDeallocationFunction()) {
790        Operator = Delete;
791        return false;
792      }
793  }
794
795  // We did find operator delete/operator delete[] declarations, but
796  // none of them were suitable.
797  if (!Found.empty()) {
798    Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
799      << Name << RD;
800
801    for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
802         F != FEnd; ++F) {
803      Diag((*F)->getLocation(),
804           diag::note_delete_member_function_declared_here)
805        << Name;
806    }
807
808    return true;
809  }
810
811  // Look for a global declaration.
812  DeclareGlobalNewDelete();
813  DeclContext *TUDecl = Context.getTranslationUnitDecl();
814
815  CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
816  Expr* DeallocArgs[1];
817  DeallocArgs[0] = &Null;
818  if (FindAllocationOverload(StartLoc, SourceRange(), Name,
819                             DeallocArgs, 1, TUDecl, /*AllowMissing=*/false,
820                             Operator))
821    return true;
822
823  assert(Operator && "Did not find a deallocation function!");
824  return false;
825}
826
827/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
828/// @code ::delete ptr; @endcode
829/// or
830/// @code delete [] ptr; @endcode
831Action::OwningExprResult
832Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
833                     bool ArrayForm, ExprArg Operand) {
834  // C++ [expr.delete]p1:
835  //   The operand shall have a pointer type, or a class type having a single
836  //   conversion function to a pointer type. The result has type void.
837  //
838  // DR599 amends "pointer type" to "pointer to object type" in both cases.
839
840  FunctionDecl *OperatorDelete = 0;
841
842  Expr *Ex = (Expr *)Operand.get();
843  if (!Ex->isTypeDependent()) {
844    QualType Type = Ex->getType();
845
846    if (const RecordType *Record = Type->getAs<RecordType>()) {
847      llvm::SmallVector<CXXConversionDecl *, 4> ObjectPtrConversions;
848      CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
849      const UnresolvedSet *Conversions = RD->getVisibleConversionFunctions();
850
851      for (UnresolvedSet::iterator I = Conversions->begin(),
852             E = Conversions->end(); I != E; ++I) {
853        // Skip over templated conversion functions; they aren't considered.
854        if (isa<FunctionTemplateDecl>(*I))
855          continue;
856
857        CXXConversionDecl *Conv = cast<CXXConversionDecl>(*I);
858
859        QualType ConvType = Conv->getConversionType().getNonReferenceType();
860        if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
861          if (ConvPtrType->getPointeeType()->isObjectType())
862            ObjectPtrConversions.push_back(Conv);
863      }
864      if (ObjectPtrConversions.size() == 1) {
865        // We have a single conversion to a pointer-to-object type. Perform
866        // that conversion.
867        Operand.release();
868        if (!PerformImplicitConversion(Ex,
869                            ObjectPtrConversions.front()->getConversionType(),
870                                      "converting")) {
871          Operand = Owned(Ex);
872          Type = Ex->getType();
873        }
874      }
875      else if (ObjectPtrConversions.size() > 1) {
876        Diag(StartLoc, diag::err_ambiguous_delete_operand)
877              << Type << Ex->getSourceRange();
878        for (unsigned i= 0; i < ObjectPtrConversions.size(); i++) {
879          CXXConversionDecl *Conv = ObjectPtrConversions[i];
880          Diag(Conv->getLocation(), diag::err_ovl_candidate);
881        }
882        return ExprError();
883      }
884    }
885
886    if (!Type->isPointerType())
887      return ExprError(Diag(StartLoc, diag::err_delete_operand)
888        << Type << Ex->getSourceRange());
889
890    QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
891    if (Pointee->isFunctionType() || Pointee->isVoidType())
892      return ExprError(Diag(StartLoc, diag::err_delete_operand)
893        << Type << Ex->getSourceRange());
894    else if (!Pointee->isDependentType() &&
895             RequireCompleteType(StartLoc, Pointee,
896                                 PDiag(diag::warn_delete_incomplete)
897                                   << Ex->getSourceRange()))
898      return ExprError();
899
900    // C++ [expr.delete]p2:
901    //   [Note: a pointer to a const type can be the operand of a
902    //   delete-expression; it is not necessary to cast away the constness
903    //   (5.2.11) of the pointer expression before it is used as the operand
904    //   of the delete-expression. ]
905    ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy),
906                      CastExpr::CK_NoOp);
907
908    // Update the operand.
909    Operand.take();
910    Operand = ExprArg(*this, Ex);
911
912    DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
913                                      ArrayForm ? OO_Array_Delete : OO_Delete);
914
915    if (const RecordType *RT = Pointee->getAs<RecordType>()) {
916      CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
917
918      if (!UseGlobal &&
919          FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
920        return ExprError();
921
922      if (!RD->hasTrivialDestructor())
923        if (const CXXDestructorDecl *Dtor = RD->getDestructor(Context))
924          MarkDeclarationReferenced(StartLoc,
925                                    const_cast<CXXDestructorDecl*>(Dtor));
926    }
927
928    if (!OperatorDelete) {
929      // Look for a global declaration.
930      DeclareGlobalNewDelete();
931      DeclContext *TUDecl = Context.getTranslationUnitDecl();
932      if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
933                                 &Ex, 1, TUDecl, /*AllowMissing=*/false,
934                                 OperatorDelete))
935        return ExprError();
936    }
937
938    // FIXME: Check access and ambiguity of operator delete and destructor.
939  }
940
941  Operand.release();
942  return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
943                                           OperatorDelete, Ex, StartLoc));
944}
945
946/// \brief Check the use of the given variable as a C++ condition in an if,
947/// while, do-while, or switch statement.
948Action::OwningExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar) {
949  QualType T = ConditionVar->getType();
950
951  // C++ [stmt.select]p2:
952  //   The declarator shall not specify a function or an array.
953  if (T->isFunctionType())
954    return ExprError(Diag(ConditionVar->getLocation(),
955                          diag::err_invalid_use_of_function_type)
956                       << ConditionVar->getSourceRange());
957  else if (T->isArrayType())
958    return ExprError(Diag(ConditionVar->getLocation(),
959                          diag::err_invalid_use_of_array_type)
960                     << ConditionVar->getSourceRange());
961
962  return Owned(DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar,
963                                   ConditionVar->getLocation(),
964                                ConditionVar->getType().getNonReferenceType()));
965}
966
967/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
968bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
969  // C++ 6.4p4:
970  // The value of a condition that is an initialized declaration in a statement
971  // other than a switch statement is the value of the declared variable
972  // implicitly converted to type bool. If that conversion is ill-formed, the
973  // program is ill-formed.
974  // The value of a condition that is an expression is the value of the
975  // expression, implicitly converted to bool.
976  //
977  return PerformContextuallyConvertToBool(CondExpr);
978}
979
980/// Helper function to determine whether this is the (deprecated) C++
981/// conversion from a string literal to a pointer to non-const char or
982/// non-const wchar_t (for narrow and wide string literals,
983/// respectively).
984bool
985Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
986  // Look inside the implicit cast, if it exists.
987  if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
988    From = Cast->getSubExpr();
989
990  // A string literal (2.13.4) that is not a wide string literal can
991  // be converted to an rvalue of type "pointer to char"; a wide
992  // string literal can be converted to an rvalue of type "pointer
993  // to wchar_t" (C++ 4.2p2).
994  if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
995    if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
996      if (const BuiltinType *ToPointeeType
997          = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
998        // This conversion is considered only when there is an
999        // explicit appropriate pointer target type (C++ 4.2p2).
1000        if (!ToPtrType->getPointeeType().hasQualifiers() &&
1001            ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1002             (!StrLit->isWide() &&
1003              (ToPointeeType->getKind() == BuiltinType::Char_U ||
1004               ToPointeeType->getKind() == BuiltinType::Char_S))))
1005          return true;
1006      }
1007
1008  return false;
1009}
1010
1011/// PerformImplicitConversion - Perform an implicit conversion of the
1012/// expression From to the type ToType. Returns true if there was an
1013/// error, false otherwise. The expression From is replaced with the
1014/// converted expression. Flavor is the kind of conversion we're
1015/// performing, used in the error message. If @p AllowExplicit,
1016/// explicit user-defined conversions are permitted. @p Elidable should be true
1017/// when called for copies which may be elided (C++ 12.8p15). C++0x overload
1018/// resolution works differently in that case.
1019bool
1020Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1021                                const char *Flavor, bool AllowExplicit,
1022                                bool Elidable) {
1023  ImplicitConversionSequence ICS;
1024  return PerformImplicitConversion(From, ToType, Flavor, AllowExplicit,
1025                                   Elidable, ICS);
1026}
1027
1028bool
1029Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1030                                const char *Flavor, bool AllowExplicit,
1031                                bool Elidable,
1032                                ImplicitConversionSequence& ICS) {
1033  ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1034  if (Elidable && getLangOptions().CPlusPlus0x) {
1035    ICS = TryImplicitConversion(From, ToType,
1036                                /*SuppressUserConversions=*/false,
1037                                AllowExplicit,
1038                                /*ForceRValue=*/true,
1039                                /*InOverloadResolution=*/false);
1040  }
1041  if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) {
1042    ICS = TryImplicitConversion(From, ToType,
1043                                /*SuppressUserConversions=*/false,
1044                                AllowExplicit,
1045                                /*ForceRValue=*/false,
1046                                /*InOverloadResolution=*/false);
1047  }
1048  return PerformImplicitConversion(From, ToType, ICS, Flavor);
1049}
1050
1051/// BuildCXXDerivedToBaseExpr - This routine generates the suitable AST
1052/// for the derived to base conversion of the expression 'From'. All
1053/// necessary information is passed in ICS.
1054bool
1055Sema::BuildCXXDerivedToBaseExpr(Expr *&From, CastExpr::CastKind CastKind,
1056                                     const ImplicitConversionSequence& ICS,
1057                                     const char *Flavor) {
1058  QualType  BaseType =
1059    QualType::getFromOpaquePtr(ICS.UserDefined.After.ToTypePtr);
1060  // Must do additional defined to base conversion.
1061  QualType  DerivedType =
1062    QualType::getFromOpaquePtr(ICS.UserDefined.After.FromTypePtr);
1063
1064  From = new (Context) ImplicitCastExpr(
1065                                        DerivedType.getNonReferenceType(),
1066                                        CastKind,
1067                                        From,
1068                                        DerivedType->isLValueReferenceType());
1069  From = new (Context) ImplicitCastExpr(BaseType.getNonReferenceType(),
1070                                        CastExpr::CK_DerivedToBase, From,
1071                                        BaseType->isLValueReferenceType());
1072  ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1073  OwningExprResult FromResult =
1074  BuildCXXConstructExpr(
1075                        ICS.UserDefined.After.CopyConstructor->getLocation(),
1076                        BaseType,
1077                        ICS.UserDefined.After.CopyConstructor,
1078                        MultiExprArg(*this, (void **)&From, 1));
1079  if (FromResult.isInvalid())
1080    return true;
1081  From = FromResult.takeAs<Expr>();
1082  return false;
1083}
1084
1085/// PerformImplicitConversion - Perform an implicit conversion of the
1086/// expression From to the type ToType using the pre-computed implicit
1087/// conversion sequence ICS. Returns true if there was an error, false
1088/// otherwise. The expression From is replaced with the converted
1089/// expression. Flavor is the kind of conversion we're performing,
1090/// used in the error message.
1091bool
1092Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1093                                const ImplicitConversionSequence &ICS,
1094                                const char* Flavor, bool IgnoreBaseAccess) {
1095  switch (ICS.ConversionKind) {
1096  case ImplicitConversionSequence::StandardConversion:
1097    if (PerformImplicitConversion(From, ToType, ICS.Standard, Flavor,
1098                                  IgnoreBaseAccess))
1099      return true;
1100    break;
1101
1102  case ImplicitConversionSequence::UserDefinedConversion: {
1103
1104      FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
1105      CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
1106      QualType BeforeToType;
1107      if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
1108        CastKind = CastExpr::CK_UserDefinedConversion;
1109
1110        // If the user-defined conversion is specified by a conversion function,
1111        // the initial standard conversion sequence converts the source type to
1112        // the implicit object parameter of the conversion function.
1113        BeforeToType = Context.getTagDeclType(Conv->getParent());
1114      } else if (const CXXConstructorDecl *Ctor =
1115                  dyn_cast<CXXConstructorDecl>(FD)) {
1116        CastKind = CastExpr::CK_ConstructorConversion;
1117        // Do no conversion if dealing with ... for the first conversion.
1118        if (!ICS.UserDefined.EllipsisConversion) {
1119          // If the user-defined conversion is specified by a constructor, the
1120          // initial standard conversion sequence converts the source type to the
1121          // type required by the argument of the constructor
1122          BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
1123        }
1124      }
1125      else
1126        assert(0 && "Unknown conversion function kind!");
1127      // Whatch out for elipsis conversion.
1128      if (!ICS.UserDefined.EllipsisConversion) {
1129        if (PerformImplicitConversion(From, BeforeToType,
1130                                      ICS.UserDefined.Before, "converting",
1131                                      IgnoreBaseAccess))
1132          return true;
1133      }
1134
1135      OwningExprResult CastArg
1136        = BuildCXXCastArgument(From->getLocStart(),
1137                               ToType.getNonReferenceType(),
1138                               CastKind, cast<CXXMethodDecl>(FD),
1139                               Owned(From));
1140
1141      if (CastArg.isInvalid())
1142        return true;
1143
1144      From = CastArg.takeAs<Expr>();
1145
1146      // FIXME: This and the following if statement shouldn't be necessary, but
1147      // there's some nasty stuff involving MaybeBindToTemporary going on here.
1148      if (ICS.UserDefined.After.Second == ICK_Derived_To_Base &&
1149          ICS.UserDefined.After.CopyConstructor) {
1150        return BuildCXXDerivedToBaseExpr(From, CastKind, ICS, Flavor);
1151      }
1152
1153      if (ICS.UserDefined.After.CopyConstructor) {
1154        From = new (Context) ImplicitCastExpr(ToType.getNonReferenceType(),
1155                                              CastKind, From,
1156                                              ToType->isLValueReferenceType());
1157        return false;
1158      }
1159
1160      return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
1161                                       "converting", IgnoreBaseAccess);
1162  }
1163
1164  case ImplicitConversionSequence::EllipsisConversion:
1165    assert(false && "Cannot perform an ellipsis conversion");
1166    return false;
1167
1168  case ImplicitConversionSequence::BadConversion:
1169    return true;
1170  }
1171
1172  // Everything went well.
1173  return false;
1174}
1175
1176/// PerformImplicitConversion - Perform an implicit conversion of the
1177/// expression From to the type ToType by following the standard
1178/// conversion sequence SCS. Returns true if there was an error, false
1179/// otherwise. The expression From is replaced with the converted
1180/// expression. Flavor is the context in which we're performing this
1181/// conversion, for use in error messages.
1182bool
1183Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1184                                const StandardConversionSequence& SCS,
1185                                const char *Flavor, bool IgnoreBaseAccess) {
1186  // Overall FIXME: we are recomputing too many types here and doing far too
1187  // much extra work. What this means is that we need to keep track of more
1188  // information that is computed when we try the implicit conversion initially,
1189  // so that we don't need to recompute anything here.
1190  QualType FromType = From->getType();
1191
1192  if (SCS.CopyConstructor) {
1193    // FIXME: When can ToType be a reference type?
1194    assert(!ToType->isReferenceType());
1195    if (SCS.Second == ICK_Derived_To_Base) {
1196      ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1197      if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
1198                                  MultiExprArg(*this, (void **)&From, 1),
1199                                  /*FIXME:ConstructLoc*/SourceLocation(),
1200                                  ConstructorArgs))
1201        return true;
1202      OwningExprResult FromResult =
1203        BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1204                              ToType, SCS.CopyConstructor,
1205                              move_arg(ConstructorArgs));
1206      if (FromResult.isInvalid())
1207        return true;
1208      From = FromResult.takeAs<Expr>();
1209      return false;
1210    }
1211    OwningExprResult FromResult =
1212      BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1213                            ToType, SCS.CopyConstructor,
1214                            MultiExprArg(*this, (void**)&From, 1));
1215
1216    if (FromResult.isInvalid())
1217      return true;
1218
1219    From = FromResult.takeAs<Expr>();
1220    return false;
1221  }
1222
1223  // Perform the first implicit conversion.
1224  switch (SCS.First) {
1225  case ICK_Identity:
1226  case ICK_Lvalue_To_Rvalue:
1227    // Nothing to do.
1228    break;
1229
1230  case ICK_Array_To_Pointer:
1231    FromType = Context.getArrayDecayedType(FromType);
1232    ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay);
1233    break;
1234
1235  case ICK_Function_To_Pointer:
1236    if (Context.getCanonicalType(FromType) == Context.OverloadTy) {
1237      FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
1238      if (!Fn)
1239        return true;
1240
1241      if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1242        return true;
1243
1244      From = FixOverloadedFunctionReference(From, Fn);
1245      FromType = From->getType();
1246
1247      // If there's already an address-of operator in the expression, we have
1248      // the right type already, and the code below would just introduce an
1249      // invalid additional pointer level.
1250      if (FromType->isPointerType() || FromType->isMemberFunctionPointerType())
1251        break;
1252    }
1253    FromType = Context.getPointerType(FromType);
1254    ImpCastExprToType(From, FromType, CastExpr::CK_FunctionToPointerDecay);
1255    break;
1256
1257  default:
1258    assert(false && "Improper first standard conversion");
1259    break;
1260  }
1261
1262  // Perform the second implicit conversion
1263  switch (SCS.Second) {
1264  case ICK_Identity:
1265    // If both sides are functions (or pointers/references to them), there could
1266    // be incompatible exception declarations.
1267    if (CheckExceptionSpecCompatibility(From, ToType))
1268      return true;
1269    // Nothing else to do.
1270    break;
1271
1272  case ICK_Integral_Promotion:
1273  case ICK_Integral_Conversion:
1274    ImpCastExprToType(From, ToType, CastExpr::CK_IntegralCast);
1275    break;
1276
1277  case ICK_Floating_Promotion:
1278  case ICK_Floating_Conversion:
1279    ImpCastExprToType(From, ToType, CastExpr::CK_FloatingCast);
1280    break;
1281
1282  case ICK_Complex_Promotion:
1283  case ICK_Complex_Conversion:
1284    ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1285    break;
1286
1287  case ICK_Floating_Integral:
1288    if (ToType->isFloatingType())
1289      ImpCastExprToType(From, ToType, CastExpr::CK_IntegralToFloating);
1290    else
1291      ImpCastExprToType(From, ToType, CastExpr::CK_FloatingToIntegral);
1292    break;
1293
1294  case ICK_Complex_Real:
1295    ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1296    break;
1297
1298  case ICK_Compatible_Conversion:
1299    ImpCastExprToType(From, ToType, CastExpr::CK_NoOp);
1300    break;
1301
1302  case ICK_Pointer_Conversion: {
1303    if (SCS.IncompatibleObjC) {
1304      // Diagnose incompatible Objective-C conversions
1305      Diag(From->getSourceRange().getBegin(),
1306           diag::ext_typecheck_convert_incompatible_pointer)
1307        << From->getType() << ToType << Flavor
1308        << From->getSourceRange();
1309    }
1310
1311
1312    CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1313    if (CheckPointerConversion(From, ToType, Kind, IgnoreBaseAccess))
1314      return true;
1315    ImpCastExprToType(From, ToType, Kind);
1316    break;
1317  }
1318
1319  case ICK_Pointer_Member: {
1320    CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1321    if (CheckMemberPointerConversion(From, ToType, Kind, IgnoreBaseAccess))
1322      return true;
1323    if (CheckExceptionSpecCompatibility(From, ToType))
1324      return true;
1325    ImpCastExprToType(From, ToType, Kind);
1326    break;
1327  }
1328  case ICK_Boolean_Conversion: {
1329    CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1330    if (FromType->isMemberPointerType())
1331      Kind = CastExpr::CK_MemberPointerToBoolean;
1332
1333    ImpCastExprToType(From, Context.BoolTy, Kind);
1334    break;
1335  }
1336
1337  case ICK_Derived_To_Base:
1338    if (CheckDerivedToBaseConversion(From->getType(),
1339                                     ToType.getNonReferenceType(),
1340                                     From->getLocStart(),
1341                                     From->getSourceRange(),
1342                                     IgnoreBaseAccess))
1343      return true;
1344    ImpCastExprToType(From, ToType.getNonReferenceType(),
1345                      CastExpr::CK_DerivedToBase);
1346    break;
1347
1348  default:
1349    assert(false && "Improper second standard conversion");
1350    break;
1351  }
1352
1353  switch (SCS.Third) {
1354  case ICK_Identity:
1355    // Nothing to do.
1356    break;
1357
1358  case ICK_Qualification:
1359    // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
1360    // references.
1361    ImpCastExprToType(From, ToType.getNonReferenceType(),
1362                      CastExpr::CK_NoOp,
1363                      ToType->isLValueReferenceType());
1364    break;
1365
1366  default:
1367    assert(false && "Improper second standard conversion");
1368    break;
1369  }
1370
1371  return false;
1372}
1373
1374Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
1375                                                 SourceLocation KWLoc,
1376                                                 SourceLocation LParen,
1377                                                 TypeTy *Ty,
1378                                                 SourceLocation RParen) {
1379  QualType T = GetTypeFromParser(Ty);
1380
1381  // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
1382  // all traits except __is_class, __is_enum and __is_union require a the type
1383  // to be complete.
1384  if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
1385    if (RequireCompleteType(KWLoc, T,
1386                            diag::err_incomplete_type_used_in_type_trait_expr))
1387      return ExprError();
1388  }
1389
1390  // There is no point in eagerly computing the value. The traits are designed
1391  // to be used from type trait templates, so Ty will be a template parameter
1392  // 99% of the time.
1393  return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
1394                                                RParen, Context.BoolTy));
1395}
1396
1397QualType Sema::CheckPointerToMemberOperands(
1398  Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) {
1399  const char *OpSpelling = isIndirect ? "->*" : ".*";
1400  // C++ 5.5p2
1401  //   The binary operator .* [p3: ->*] binds its second operand, which shall
1402  //   be of type "pointer to member of T" (where T is a completely-defined
1403  //   class type) [...]
1404  QualType RType = rex->getType();
1405  const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
1406  if (!MemPtr) {
1407    Diag(Loc, diag::err_bad_memptr_rhs)
1408      << OpSpelling << RType << rex->getSourceRange();
1409    return QualType();
1410  }
1411
1412  QualType Class(MemPtr->getClass(), 0);
1413
1414  // C++ 5.5p2
1415  //   [...] to its first operand, which shall be of class T or of a class of
1416  //   which T is an unambiguous and accessible base class. [p3: a pointer to
1417  //   such a class]
1418  QualType LType = lex->getType();
1419  if (isIndirect) {
1420    if (const PointerType *Ptr = LType->getAs<PointerType>())
1421      LType = Ptr->getPointeeType().getNonReferenceType();
1422    else {
1423      Diag(Loc, diag::err_bad_memptr_lhs)
1424        << OpSpelling << 1 << LType
1425        << CodeModificationHint::CreateReplacement(SourceRange(Loc), ".*");
1426      return QualType();
1427    }
1428  }
1429
1430  if (!Context.hasSameUnqualifiedType(Class, LType)) {
1431    CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1432                       /*DetectVirtual=*/false);
1433    // FIXME: Would it be useful to print full ambiguity paths, or is that
1434    // overkill?
1435    if (!IsDerivedFrom(LType, Class, Paths) ||
1436        Paths.isAmbiguous(Context.getCanonicalType(Class))) {
1437      const char *ReplaceStr = isIndirect ? ".*" : "->*";
1438      Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
1439        << (int)isIndirect << lex->getType() <<
1440          CodeModificationHint::CreateReplacement(SourceRange(Loc), ReplaceStr);
1441      return QualType();
1442    }
1443  }
1444
1445  if (isa<CXXZeroInitValueExpr>(rex->IgnoreParens())) {
1446    // Diagnose use of pointer-to-member type which when used as
1447    // the functional cast in a pointer-to-member expression.
1448    Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
1449     return QualType();
1450  }
1451  // C++ 5.5p2
1452  //   The result is an object or a function of the type specified by the
1453  //   second operand.
1454  // The cv qualifiers are the union of those in the pointer and the left side,
1455  // in accordance with 5.5p5 and 5.2.5.
1456  // FIXME: This returns a dereferenced member function pointer as a normal
1457  // function type. However, the only operation valid on such functions is
1458  // calling them. There's also a GCC extension to get a function pointer to the
1459  // thing, which is another complication, because this type - unlike the type
1460  // that is the result of this expression - takes the class as the first
1461  // argument.
1462  // We probably need a "MemberFunctionClosureType" or something like that.
1463  QualType Result = MemPtr->getPointeeType();
1464  Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
1465  return Result;
1466}
1467
1468/// \brief Get the target type of a standard or user-defined conversion.
1469static QualType TargetType(const ImplicitConversionSequence &ICS) {
1470  assert((ICS.ConversionKind ==
1471              ImplicitConversionSequence::StandardConversion ||
1472          ICS.ConversionKind ==
1473              ImplicitConversionSequence::UserDefinedConversion) &&
1474         "function only valid for standard or user-defined conversions");
1475  if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion)
1476    return QualType::getFromOpaquePtr(ICS.Standard.ToTypePtr);
1477  return QualType::getFromOpaquePtr(ICS.UserDefined.After.ToTypePtr);
1478}
1479
1480/// \brief Try to convert a type to another according to C++0x 5.16p3.
1481///
1482/// This is part of the parameter validation for the ? operator. If either
1483/// value operand is a class type, the two operands are attempted to be
1484/// converted to each other. This function does the conversion in one direction.
1485/// It emits a diagnostic and returns true only if it finds an ambiguous
1486/// conversion.
1487static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
1488                                SourceLocation QuestionLoc,
1489                                ImplicitConversionSequence &ICS) {
1490  // C++0x 5.16p3
1491  //   The process for determining whether an operand expression E1 of type T1
1492  //   can be converted to match an operand expression E2 of type T2 is defined
1493  //   as follows:
1494  //   -- If E2 is an lvalue:
1495  if (To->isLvalue(Self.Context) == Expr::LV_Valid) {
1496    //   E1 can be converted to match E2 if E1 can be implicitly converted to
1497    //   type "lvalue reference to T2", subject to the constraint that in the
1498    //   conversion the reference must bind directly to E1.
1499    if (!Self.CheckReferenceInit(From,
1500                            Self.Context.getLValueReferenceType(To->getType()),
1501                                 To->getLocStart(),
1502                                 /*SuppressUserConversions=*/false,
1503                                 /*AllowExplicit=*/false,
1504                                 /*ForceRValue=*/false,
1505                                 &ICS))
1506    {
1507      assert((ICS.ConversionKind ==
1508                  ImplicitConversionSequence::StandardConversion ||
1509              ICS.ConversionKind ==
1510                  ImplicitConversionSequence::UserDefinedConversion) &&
1511             "expected a definite conversion");
1512      bool DirectBinding =
1513        ICS.ConversionKind == ImplicitConversionSequence::StandardConversion ?
1514        ICS.Standard.DirectBinding : ICS.UserDefined.After.DirectBinding;
1515      if (DirectBinding)
1516        return false;
1517    }
1518  }
1519  ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1520  //   -- If E2 is an rvalue, or if the conversion above cannot be done:
1521  //      -- if E1 and E2 have class type, and the underlying class types are
1522  //         the same or one is a base class of the other:
1523  QualType FTy = From->getType();
1524  QualType TTy = To->getType();
1525  const RecordType *FRec = FTy->getAs<RecordType>();
1526  const RecordType *TRec = TTy->getAs<RecordType>();
1527  bool FDerivedFromT = FRec && TRec && Self.IsDerivedFrom(FTy, TTy);
1528  if (FRec && TRec && (FRec == TRec ||
1529        FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
1530    //         E1 can be converted to match E2 if the class of T2 is the
1531    //         same type as, or a base class of, the class of T1, and
1532    //         [cv2 > cv1].
1533    if ((FRec == TRec || FDerivedFromT) && TTy.isAtLeastAsQualifiedAs(FTy)) {
1534      // Could still fail if there's no copy constructor.
1535      // FIXME: Is this a hard error then, or just a conversion failure? The
1536      // standard doesn't say.
1537      ICS = Self.TryCopyInitialization(From, TTy,
1538                                       /*SuppressUserConversions=*/false,
1539                                       /*ForceRValue=*/false,
1540                                       /*InOverloadResolution=*/false);
1541    }
1542  } else {
1543    //     -- Otherwise: E1 can be converted to match E2 if E1 can be
1544    //        implicitly converted to the type that expression E2 would have
1545    //        if E2 were converted to an rvalue.
1546    // First find the decayed type.
1547    if (TTy->isFunctionType())
1548      TTy = Self.Context.getPointerType(TTy);
1549    else if (TTy->isArrayType())
1550      TTy = Self.Context.getArrayDecayedType(TTy);
1551
1552    // Now try the implicit conversion.
1553    // FIXME: This doesn't detect ambiguities.
1554    ICS = Self.TryImplicitConversion(From, TTy,
1555                                     /*SuppressUserConversions=*/false,
1556                                     /*AllowExplicit=*/false,
1557                                     /*ForceRValue=*/false,
1558                                     /*InOverloadResolution=*/false);
1559  }
1560  return false;
1561}
1562
1563/// \brief Try to find a common type for two according to C++0x 5.16p5.
1564///
1565/// This is part of the parameter validation for the ? operator. If either
1566/// value operand is a class type, overload resolution is used to find a
1567/// conversion to a common type.
1568static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
1569                                    SourceLocation Loc) {
1570  Expr *Args[2] = { LHS, RHS };
1571  OverloadCandidateSet CandidateSet;
1572  Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet);
1573
1574  OverloadCandidateSet::iterator Best;
1575  switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
1576    case Sema::OR_Success:
1577      // We found a match. Perform the conversions on the arguments and move on.
1578      if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
1579                                         Best->Conversions[0], "converting") ||
1580          Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
1581                                         Best->Conversions[1], "converting"))
1582        break;
1583      return false;
1584
1585    case Sema::OR_No_Viable_Function:
1586      Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
1587        << LHS->getType() << RHS->getType()
1588        << LHS->getSourceRange() << RHS->getSourceRange();
1589      return true;
1590
1591    case Sema::OR_Ambiguous:
1592      Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
1593        << LHS->getType() << RHS->getType()
1594        << LHS->getSourceRange() << RHS->getSourceRange();
1595      // FIXME: Print the possible common types by printing the return types of
1596      // the viable candidates.
1597      break;
1598
1599    case Sema::OR_Deleted:
1600      assert(false && "Conditional operator has only built-in overloads");
1601      break;
1602  }
1603  return true;
1604}
1605
1606/// \brief Perform an "extended" implicit conversion as returned by
1607/// TryClassUnification.
1608///
1609/// TryClassUnification generates ICSs that include reference bindings.
1610/// PerformImplicitConversion is not suitable for this; it chokes if the
1611/// second part of a standard conversion is ICK_DerivedToBase. This function
1612/// handles the reference binding specially.
1613static bool ConvertForConditional(Sema &Self, Expr *&E,
1614                                  const ImplicitConversionSequence &ICS) {
1615  if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion &&
1616      ICS.Standard.ReferenceBinding) {
1617    assert(ICS.Standard.DirectBinding &&
1618           "TryClassUnification should never generate indirect ref bindings");
1619    // FIXME: CheckReferenceInit should be able to reuse the ICS instead of
1620    // redoing all the work.
1621    return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
1622                                        TargetType(ICS)),
1623                                   /*FIXME:*/E->getLocStart(),
1624                                   /*SuppressUserConversions=*/false,
1625                                   /*AllowExplicit=*/false,
1626                                   /*ForceRValue=*/false);
1627  }
1628  if (ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion &&
1629      ICS.UserDefined.After.ReferenceBinding) {
1630    assert(ICS.UserDefined.After.DirectBinding &&
1631           "TryClassUnification should never generate indirect ref bindings");
1632    return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
1633                                        TargetType(ICS)),
1634                                   /*FIXME:*/E->getLocStart(),
1635                                   /*SuppressUserConversions=*/false,
1636                                   /*AllowExplicit=*/false,
1637                                   /*ForceRValue=*/false);
1638  }
1639  if (Self.PerformImplicitConversion(E, TargetType(ICS), ICS, "converting"))
1640    return true;
1641  return false;
1642}
1643
1644/// \brief Check the operands of ?: under C++ semantics.
1645///
1646/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
1647/// extension. In this case, LHS == Cond. (But they're not aliases.)
1648QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
1649                                           SourceLocation QuestionLoc) {
1650  // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
1651  // interface pointers.
1652
1653  // C++0x 5.16p1
1654  //   The first expression is contextually converted to bool.
1655  if (!Cond->isTypeDependent()) {
1656    if (CheckCXXBooleanCondition(Cond))
1657      return QualType();
1658  }
1659
1660  // Either of the arguments dependent?
1661  if (LHS->isTypeDependent() || RHS->isTypeDependent())
1662    return Context.DependentTy;
1663
1664  CheckSignCompare(LHS, RHS, QuestionLoc, diag::warn_mixed_sign_conditional);
1665
1666  // C++0x 5.16p2
1667  //   If either the second or the third operand has type (cv) void, ...
1668  QualType LTy = LHS->getType();
1669  QualType RTy = RHS->getType();
1670  bool LVoid = LTy->isVoidType();
1671  bool RVoid = RTy->isVoidType();
1672  if (LVoid || RVoid) {
1673    //   ... then the [l2r] conversions are performed on the second and third
1674    //   operands ...
1675    DefaultFunctionArrayConversion(LHS);
1676    DefaultFunctionArrayConversion(RHS);
1677    LTy = LHS->getType();
1678    RTy = RHS->getType();
1679
1680    //   ... and one of the following shall hold:
1681    //   -- The second or the third operand (but not both) is a throw-
1682    //      expression; the result is of the type of the other and is an rvalue.
1683    bool LThrow = isa<CXXThrowExpr>(LHS);
1684    bool RThrow = isa<CXXThrowExpr>(RHS);
1685    if (LThrow && !RThrow)
1686      return RTy;
1687    if (RThrow && !LThrow)
1688      return LTy;
1689
1690    //   -- Both the second and third operands have type void; the result is of
1691    //      type void and is an rvalue.
1692    if (LVoid && RVoid)
1693      return Context.VoidTy;
1694
1695    // Neither holds, error.
1696    Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
1697      << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
1698      << LHS->getSourceRange() << RHS->getSourceRange();
1699    return QualType();
1700  }
1701
1702  // Neither is void.
1703
1704  // C++0x 5.16p3
1705  //   Otherwise, if the second and third operand have different types, and
1706  //   either has (cv) class type, and attempt is made to convert each of those
1707  //   operands to the other.
1708  if (Context.getCanonicalType(LTy) != Context.getCanonicalType(RTy) &&
1709      (LTy->isRecordType() || RTy->isRecordType())) {
1710    ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
1711    // These return true if a single direction is already ambiguous.
1712    if (TryClassUnification(*this, LHS, RHS, QuestionLoc, ICSLeftToRight))
1713      return QualType();
1714    if (TryClassUnification(*this, RHS, LHS, QuestionLoc, ICSRightToLeft))
1715      return QualType();
1716
1717    bool HaveL2R = ICSLeftToRight.ConversionKind !=
1718      ImplicitConversionSequence::BadConversion;
1719    bool HaveR2L = ICSRightToLeft.ConversionKind !=
1720      ImplicitConversionSequence::BadConversion;
1721    //   If both can be converted, [...] the program is ill-formed.
1722    if (HaveL2R && HaveR2L) {
1723      Diag(QuestionLoc, diag::err_conditional_ambiguous)
1724        << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
1725      return QualType();
1726    }
1727
1728    //   If exactly one conversion is possible, that conversion is applied to
1729    //   the chosen operand and the converted operands are used in place of the
1730    //   original operands for the remainder of this section.
1731    if (HaveL2R) {
1732      if (ConvertForConditional(*this, LHS, ICSLeftToRight))
1733        return QualType();
1734      LTy = LHS->getType();
1735    } else if (HaveR2L) {
1736      if (ConvertForConditional(*this, RHS, ICSRightToLeft))
1737        return QualType();
1738      RTy = RHS->getType();
1739    }
1740  }
1741
1742  // C++0x 5.16p4
1743  //   If the second and third operands are lvalues and have the same type,
1744  //   the result is of that type [...]
1745  bool Same = Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy);
1746  if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
1747      RHS->isLvalue(Context) == Expr::LV_Valid)
1748    return LTy;
1749
1750  // C++0x 5.16p5
1751  //   Otherwise, the result is an rvalue. If the second and third operands
1752  //   do not have the same type, and either has (cv) class type, ...
1753  if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
1754    //   ... overload resolution is used to determine the conversions (if any)
1755    //   to be applied to the operands. If the overload resolution fails, the
1756    //   program is ill-formed.
1757    if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
1758      return QualType();
1759  }
1760
1761  // C++0x 5.16p6
1762  //   LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
1763  //   conversions are performed on the second and third operands.
1764  DefaultFunctionArrayConversion(LHS);
1765  DefaultFunctionArrayConversion(RHS);
1766  LTy = LHS->getType();
1767  RTy = RHS->getType();
1768
1769  //   After those conversions, one of the following shall hold:
1770  //   -- The second and third operands have the same type; the result
1771  //      is of that type.
1772  if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy))
1773    return LTy;
1774
1775  //   -- The second and third operands have arithmetic or enumeration type;
1776  //      the usual arithmetic conversions are performed to bring them to a
1777  //      common type, and the result is of that type.
1778  if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
1779    UsualArithmeticConversions(LHS, RHS);
1780    return LHS->getType();
1781  }
1782
1783  //   -- The second and third operands have pointer type, or one has pointer
1784  //      type and the other is a null pointer constant; pointer conversions
1785  //      and qualification conversions are performed to bring them to their
1786  //      composite pointer type. The result is of the composite pointer type.
1787  QualType Composite = FindCompositePointerType(LHS, RHS);
1788  if (!Composite.isNull())
1789    return Composite;
1790
1791  // Fourth bullet is same for pointers-to-member. However, the possible
1792  // conversions are far more limited: we have null-to-pointer, upcast of
1793  // containing class, and second-level cv-ness.
1794  // cv-ness is not a union, but must match one of the two operands. (Which,
1795  // frankly, is stupid.)
1796  const MemberPointerType *LMemPtr = LTy->getAs<MemberPointerType>();
1797  const MemberPointerType *RMemPtr = RTy->getAs<MemberPointerType>();
1798  if (LMemPtr &&
1799      RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
1800    ImpCastExprToType(RHS, LTy, CastExpr::CK_NullToMemberPointer);
1801    return LTy;
1802  }
1803  if (RMemPtr &&
1804      LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
1805    ImpCastExprToType(LHS, RTy, CastExpr::CK_NullToMemberPointer);
1806    return RTy;
1807  }
1808  if (LMemPtr && RMemPtr) {
1809    QualType LPointee = LMemPtr->getPointeeType();
1810    QualType RPointee = RMemPtr->getPointeeType();
1811
1812    QualifierCollector LPQuals, RPQuals;
1813    const Type *LPCan = LPQuals.strip(Context.getCanonicalType(LPointee));
1814    const Type *RPCan = RPQuals.strip(Context.getCanonicalType(RPointee));
1815
1816    // First, we check that the unqualified pointee type is the same. If it's
1817    // not, there's no conversion that will unify the two pointers.
1818    if (LPCan == RPCan) {
1819
1820      // Second, we take the greater of the two qualifications. If neither
1821      // is greater than the other, the conversion is not possible.
1822
1823      Qualifiers MergedQuals = LPQuals + RPQuals;
1824
1825      bool CompatibleQuals = true;
1826      if (MergedQuals.getCVRQualifiers() != LPQuals.getCVRQualifiers() &&
1827          MergedQuals.getCVRQualifiers() != RPQuals.getCVRQualifiers())
1828        CompatibleQuals = false;
1829      else if (LPQuals.getAddressSpace() != RPQuals.getAddressSpace())
1830        // FIXME:
1831        // C99 6.5.15 as modified by TR 18037:
1832        //   If the second and third operands are pointers into different
1833        //   address spaces, the address spaces must overlap.
1834        CompatibleQuals = false;
1835      // FIXME: GC qualifiers?
1836
1837      if (CompatibleQuals) {
1838        // Third, we check if either of the container classes is derived from
1839        // the other.
1840        QualType LContainer(LMemPtr->getClass(), 0);
1841        QualType RContainer(RMemPtr->getClass(), 0);
1842        QualType MoreDerived;
1843        if (Context.getCanonicalType(LContainer) ==
1844            Context.getCanonicalType(RContainer))
1845          MoreDerived = LContainer;
1846        else if (IsDerivedFrom(LContainer, RContainer))
1847          MoreDerived = LContainer;
1848        else if (IsDerivedFrom(RContainer, LContainer))
1849          MoreDerived = RContainer;
1850
1851        if (!MoreDerived.isNull()) {
1852          // The type 'Q Pointee (MoreDerived::*)' is the common type.
1853          // We don't use ImpCastExprToType here because this could still fail
1854          // for ambiguous or inaccessible conversions.
1855          LPointee = Context.getQualifiedType(LPointee, MergedQuals);
1856          QualType Common
1857            = Context.getMemberPointerType(LPointee, MoreDerived.getTypePtr());
1858          if (PerformImplicitConversion(LHS, Common, "converting"))
1859            return QualType();
1860          if (PerformImplicitConversion(RHS, Common, "converting"))
1861            return QualType();
1862          return Common;
1863        }
1864      }
1865    }
1866  }
1867
1868  Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
1869    << LHS->getType() << RHS->getType()
1870    << LHS->getSourceRange() << RHS->getSourceRange();
1871  return QualType();
1872}
1873
1874/// \brief Find a merged pointer type and convert the two expressions to it.
1875///
1876/// This finds the composite pointer type (or member pointer type) for @p E1
1877/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
1878/// type and returns it.
1879/// It does not emit diagnostics.
1880QualType Sema::FindCompositePointerType(Expr *&E1, Expr *&E2) {
1881  assert(getLangOptions().CPlusPlus && "This function assumes C++");
1882  QualType T1 = E1->getType(), T2 = E2->getType();
1883
1884  if (!T1->isPointerType() && !T1->isMemberPointerType() &&
1885      !T2->isPointerType() && !T2->isMemberPointerType())
1886   return QualType();
1887
1888  // C++0x 5.9p2
1889  //   Pointer conversions and qualification conversions are performed on
1890  //   pointer operands to bring them to their composite pointer type. If
1891  //   one operand is a null pointer constant, the composite pointer type is
1892  //   the type of the other operand.
1893  if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
1894    if (T2->isMemberPointerType())
1895      ImpCastExprToType(E1, T2, CastExpr::CK_NullToMemberPointer);
1896    else
1897      ImpCastExprToType(E1, T2, CastExpr::CK_IntegralToPointer);
1898    return T2;
1899  }
1900  if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
1901    if (T1->isMemberPointerType())
1902      ImpCastExprToType(E2, T1, CastExpr::CK_NullToMemberPointer);
1903    else
1904      ImpCastExprToType(E2, T1, CastExpr::CK_IntegralToPointer);
1905    return T1;
1906  }
1907
1908  // Now both have to be pointers or member pointers.
1909  if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
1910      (!T2->isPointerType() && !T2->isMemberPointerType()))
1911    return QualType();
1912
1913  //   Otherwise, of one of the operands has type "pointer to cv1 void," then
1914  //   the other has type "pointer to cv2 T" and the composite pointer type is
1915  //   "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
1916  //   Otherwise, the composite pointer type is a pointer type similar to the
1917  //   type of one of the operands, with a cv-qualification signature that is
1918  //   the union of the cv-qualification signatures of the operand types.
1919  // In practice, the first part here is redundant; it's subsumed by the second.
1920  // What we do here is, we build the two possible composite types, and try the
1921  // conversions in both directions. If only one works, or if the two composite
1922  // types are the same, we have succeeded.
1923  // FIXME: extended qualifiers?
1924  typedef llvm::SmallVector<unsigned, 4> QualifierVector;
1925  QualifierVector QualifierUnion;
1926  typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
1927      ContainingClassVector;
1928  ContainingClassVector MemberOfClass;
1929  QualType Composite1 = Context.getCanonicalType(T1),
1930           Composite2 = Context.getCanonicalType(T2);
1931  do {
1932    const PointerType *Ptr1, *Ptr2;
1933    if ((Ptr1 = Composite1->getAs<PointerType>()) &&
1934        (Ptr2 = Composite2->getAs<PointerType>())) {
1935      Composite1 = Ptr1->getPointeeType();
1936      Composite2 = Ptr2->getPointeeType();
1937      QualifierUnion.push_back(
1938                 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1939      MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
1940      continue;
1941    }
1942
1943    const MemberPointerType *MemPtr1, *MemPtr2;
1944    if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
1945        (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
1946      Composite1 = MemPtr1->getPointeeType();
1947      Composite2 = MemPtr2->getPointeeType();
1948      QualifierUnion.push_back(
1949                 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1950      MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
1951                                             MemPtr2->getClass()));
1952      continue;
1953    }
1954
1955    // FIXME: block pointer types?
1956
1957    // Cannot unwrap any more types.
1958    break;
1959  } while (true);
1960
1961  // Rewrap the composites as pointers or member pointers with the union CVRs.
1962  ContainingClassVector::reverse_iterator MOC
1963    = MemberOfClass.rbegin();
1964  for (QualifierVector::reverse_iterator
1965         I = QualifierUnion.rbegin(),
1966         E = QualifierUnion.rend();
1967       I != E; (void)++I, ++MOC) {
1968    Qualifiers Quals = Qualifiers::fromCVRMask(*I);
1969    if (MOC->first && MOC->second) {
1970      // Rebuild member pointer type
1971      Composite1 = Context.getMemberPointerType(
1972                                    Context.getQualifiedType(Composite1, Quals),
1973                                    MOC->first);
1974      Composite2 = Context.getMemberPointerType(
1975                                    Context.getQualifiedType(Composite2, Quals),
1976                                    MOC->second);
1977    } else {
1978      // Rebuild pointer type
1979      Composite1
1980        = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
1981      Composite2
1982        = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
1983    }
1984  }
1985
1986  ImplicitConversionSequence E1ToC1 =
1987    TryImplicitConversion(E1, Composite1,
1988                          /*SuppressUserConversions=*/false,
1989                          /*AllowExplicit=*/false,
1990                          /*ForceRValue=*/false,
1991                          /*InOverloadResolution=*/false);
1992  ImplicitConversionSequence E2ToC1 =
1993    TryImplicitConversion(E2, Composite1,
1994                          /*SuppressUserConversions=*/false,
1995                          /*AllowExplicit=*/false,
1996                          /*ForceRValue=*/false,
1997                          /*InOverloadResolution=*/false);
1998
1999  ImplicitConversionSequence E1ToC2, E2ToC2;
2000  E1ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
2001  E2ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
2002  if (Context.getCanonicalType(Composite1) !=
2003      Context.getCanonicalType(Composite2)) {
2004    E1ToC2 = TryImplicitConversion(E1, Composite2,
2005                                   /*SuppressUserConversions=*/false,
2006                                   /*AllowExplicit=*/false,
2007                                   /*ForceRValue=*/false,
2008                                   /*InOverloadResolution=*/false);
2009    E2ToC2 = TryImplicitConversion(E2, Composite2,
2010                                   /*SuppressUserConversions=*/false,
2011                                   /*AllowExplicit=*/false,
2012                                   /*ForceRValue=*/false,
2013                                   /*InOverloadResolution=*/false);
2014  }
2015
2016  bool ToC1Viable = E1ToC1.ConversionKind !=
2017                      ImplicitConversionSequence::BadConversion
2018                 && E2ToC1.ConversionKind !=
2019                      ImplicitConversionSequence::BadConversion;
2020  bool ToC2Viable = E1ToC2.ConversionKind !=
2021                      ImplicitConversionSequence::BadConversion
2022                 && E2ToC2.ConversionKind !=
2023                      ImplicitConversionSequence::BadConversion;
2024  if (ToC1Viable && !ToC2Viable) {
2025    if (!PerformImplicitConversion(E1, Composite1, E1ToC1, "converting") &&
2026        !PerformImplicitConversion(E2, Composite1, E2ToC1, "converting"))
2027      return Composite1;
2028  }
2029  if (ToC2Viable && !ToC1Viable) {
2030    if (!PerformImplicitConversion(E1, Composite2, E1ToC2, "converting") &&
2031        !PerformImplicitConversion(E2, Composite2, E2ToC2, "converting"))
2032      return Composite2;
2033  }
2034  return QualType();
2035}
2036
2037Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
2038  if (!Context.getLangOptions().CPlusPlus)
2039    return Owned(E);
2040
2041  const RecordType *RT = E->getType()->getAs<RecordType>();
2042  if (!RT)
2043    return Owned(E);
2044
2045  CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2046  if (RD->hasTrivialDestructor())
2047    return Owned(E);
2048
2049  if (CallExpr *CE = dyn_cast<CallExpr>(E)) {
2050    QualType Ty = CE->getCallee()->getType();
2051    if (const PointerType *PT = Ty->getAs<PointerType>())
2052      Ty = PT->getPointeeType();
2053
2054    const FunctionType *FTy = Ty->getAs<FunctionType>();
2055    if (FTy->getResultType()->isReferenceType())
2056      return Owned(E);
2057  }
2058  CXXTemporary *Temp = CXXTemporary::Create(Context,
2059                                            RD->getDestructor(Context));
2060  ExprTemporaries.push_back(Temp);
2061  if (CXXDestructorDecl *Destructor =
2062        const_cast<CXXDestructorDecl*>(RD->getDestructor(Context)))
2063    MarkDeclarationReferenced(E->getExprLoc(), Destructor);
2064  // FIXME: Add the temporary to the temporaries vector.
2065  return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
2066}
2067
2068Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr,
2069                                              bool ShouldDestroyTemps) {
2070  assert(SubExpr && "sub expression can't be null!");
2071
2072  unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2073  assert(ExprTemporaries.size() >= FirstTemporary);
2074  if (ExprTemporaries.size() == FirstTemporary)
2075    return SubExpr;
2076
2077  Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
2078                                           &ExprTemporaries[FirstTemporary],
2079                                    ExprTemporaries.size() - FirstTemporary,
2080                                           ShouldDestroyTemps);
2081  ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2082                        ExprTemporaries.end());
2083
2084  return E;
2085}
2086
2087Sema::OwningExprResult
2088Sema::ActOnStartCXXMemberReference(Scope *S, ExprArg Base, SourceLocation OpLoc,
2089                                   tok::TokenKind OpKind, TypeTy *&ObjectType) {
2090  // Since this might be a postfix expression, get rid of ParenListExprs.
2091  Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
2092
2093  Expr *BaseExpr = (Expr*)Base.get();
2094  assert(BaseExpr && "no record expansion");
2095
2096  QualType BaseType = BaseExpr->getType();
2097  if (BaseType->isDependentType()) {
2098    // If we have a pointer to a dependent type and are using the -> operator,
2099    // the object type is the type that the pointer points to. We might still
2100    // have enough information about that type to do something useful.
2101    if (OpKind == tok::arrow)
2102      if (const PointerType *Ptr = BaseType->getAs<PointerType>())
2103        BaseType = Ptr->getPointeeType();
2104
2105    ObjectType = BaseType.getAsOpaquePtr();
2106    return move(Base);
2107  }
2108
2109  // C++ [over.match.oper]p8:
2110  //   [...] When operator->returns, the operator-> is applied  to the value
2111  //   returned, with the original second operand.
2112  if (OpKind == tok::arrow) {
2113    // The set of types we've considered so far.
2114    llvm::SmallPtrSet<CanQualType,8> CTypes;
2115    llvm::SmallVector<SourceLocation, 8> Locations;
2116    CTypes.insert(Context.getCanonicalType(BaseType));
2117
2118    while (BaseType->isRecordType()) {
2119      Base = BuildOverloadedArrowExpr(S, move(Base), OpLoc);
2120      BaseExpr = (Expr*)Base.get();
2121      if (BaseExpr == NULL)
2122        return ExprError();
2123      if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(BaseExpr))
2124        Locations.push_back(OpCall->getDirectCallee()->getLocation());
2125      BaseType = BaseExpr->getType();
2126      CanQualType CBaseType = Context.getCanonicalType(BaseType);
2127      if (!CTypes.insert(CBaseType)) {
2128        Diag(OpLoc, diag::err_operator_arrow_circular);
2129        for (unsigned i = 0; i < Locations.size(); i++)
2130          Diag(Locations[i], diag::note_declared_at);
2131        return ExprError();
2132      }
2133    }
2134
2135    if (BaseType->isPointerType())
2136      BaseType = BaseType->getPointeeType();
2137  }
2138
2139  // We could end up with various non-record types here, such as extended
2140  // vector types or Objective-C interfaces. Just return early and let
2141  // ActOnMemberReferenceExpr do the work.
2142  if (!BaseType->isRecordType()) {
2143    // C++ [basic.lookup.classref]p2:
2144    //   [...] If the type of the object expression is of pointer to scalar
2145    //   type, the unqualified-id is looked up in the context of the complete
2146    //   postfix-expression.
2147    ObjectType = 0;
2148    return move(Base);
2149  }
2150
2151  // The object type must be complete (or dependent).
2152  if (!BaseType->isDependentType() &&
2153      RequireCompleteType(OpLoc, BaseType,
2154                          PDiag(diag::err_incomplete_member_access)))
2155    return ExprError();
2156
2157  // C++ [basic.lookup.classref]p2:
2158  //   If the id-expression in a class member access (5.2.5) is an
2159  //   unqualified-id, and the type of the object expression is of a class
2160  //   type C (or of pointer to a class type C), the unqualified-id is looked
2161  //   up in the scope of class C. [...]
2162  ObjectType = BaseType.getAsOpaquePtr();
2163
2164  return move(Base);
2165}
2166
2167CXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp,
2168                                                CXXMethodDecl *Method) {
2169  MemberExpr *ME =
2170      new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
2171                               SourceLocation(), Method->getType());
2172  QualType ResultType;
2173  if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(Method))
2174    ResultType = Conv->getConversionType().getNonReferenceType();
2175  else
2176    ResultType = Method->getResultType().getNonReferenceType();
2177
2178  MarkDeclarationReferenced(Exp->getLocStart(), Method);
2179  CXXMemberCallExpr *CE =
2180    new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType,
2181                                    Exp->getLocEnd());
2182  return CE;
2183}
2184
2185Sema::OwningExprResult Sema::BuildCXXCastArgument(SourceLocation CastLoc,
2186                                                  QualType Ty,
2187                                                  CastExpr::CastKind Kind,
2188                                                  CXXMethodDecl *Method,
2189                                                  ExprArg Arg) {
2190  Expr *From = Arg.takeAs<Expr>();
2191
2192  switch (Kind) {
2193  default: assert(0 && "Unhandled cast kind!");
2194  case CastExpr::CK_ConstructorConversion: {
2195    ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
2196
2197    if (CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
2198                                MultiExprArg(*this, (void **)&From, 1),
2199                                CastLoc, ConstructorArgs))
2200      return ExprError();
2201
2202    OwningExprResult Result =
2203      BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
2204                            move_arg(ConstructorArgs));
2205    if (Result.isInvalid())
2206      return ExprError();
2207
2208    return MaybeBindToTemporary(Result.takeAs<Expr>());
2209  }
2210
2211  case CastExpr::CK_UserDefinedConversion: {
2212    assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
2213
2214    // Cast to base if needed.
2215    if (PerformObjectArgumentInitialization(From, Method))
2216      return ExprError();
2217
2218    // Create an implicit call expr that calls it.
2219    CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(From, Method);
2220    return MaybeBindToTemporary(CE);
2221  }
2222  }
2223}
2224
2225Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
2226  Expr *FullExpr = Arg.takeAs<Expr>();
2227  if (FullExpr)
2228    FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr,
2229                                                 /*ShouldDestroyTemps=*/true);
2230
2231
2232  return Owned(FullExpr);
2233}
2234
2235/// \brief Determine whether a reference to the given declaration in the
2236/// current context is an implicit member access
2237/// (C++ [class.mfct.non-static]p2).
2238///
2239/// FIXME: Should Objective-C also use this approach?
2240///
2241/// \param D the declaration being referenced from the current scope.
2242///
2243/// \param NameLoc the location of the name in the source.
2244///
2245/// \param ThisType if the reference to this declaration is an implicit member
2246/// access, will be set to the type of the "this" pointer to be used when
2247/// building that implicit member access.
2248///
2249/// \returns true if this is an implicit member reference (in which case
2250/// \p ThisType and \p MemberType will be set), or false if it is not an
2251/// implicit member reference.
2252bool Sema::isImplicitMemberReference(const LookupResult &R,
2253                                     QualType &ThisType) {
2254  // If this isn't a C++ method, then it isn't an implicit member reference.
2255  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext);
2256  if (!MD || MD->isStatic())
2257    return false;
2258
2259  // C++ [class.mfct.nonstatic]p2:
2260  //   [...] if name lookup (3.4.1) resolves the name in the
2261  //   id-expression to a nonstatic nontype member of class X or of
2262  //   a base class of X, the id-expression is transformed into a
2263  //   class member access expression (5.2.5) using (*this) (9.3.2)
2264  //   as the postfix-expression to the left of the '.' operator.
2265  DeclContext *Ctx = 0;
2266  if (R.isUnresolvableResult()) {
2267    // FIXME: this is just picking one at random
2268    Ctx = R.getRepresentativeDecl()->getDeclContext();
2269  } else if (FieldDecl *FD = R.getAsSingle<FieldDecl>()) {
2270    Ctx = FD->getDeclContext();
2271  } else {
2272    for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2273      CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*I);
2274      FunctionTemplateDecl *FunTmpl = 0;
2275      if (!Method && (FunTmpl = dyn_cast<FunctionTemplateDecl>(*I)))
2276        Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
2277
2278      // FIXME: Do we have to know if there are explicit template arguments?
2279      if (Method && !Method->isStatic()) {
2280        Ctx = Method->getParent();
2281        break;
2282      }
2283    }
2284  }
2285
2286  if (!Ctx || !Ctx->isRecord())
2287    return false;
2288
2289  // Determine whether the declaration(s) we found are actually in a base
2290  // class. If not, this isn't an implicit member reference.
2291  ThisType = MD->getThisType(Context);
2292
2293  // FIXME: this doesn't really work for overloaded lookups.
2294
2295  QualType CtxType = Context.getTypeDeclType(cast<CXXRecordDecl>(Ctx));
2296  QualType ClassType
2297    = Context.getTypeDeclType(cast<CXXRecordDecl>(MD->getParent()));
2298  return Context.hasSameType(CtxType, ClassType) ||
2299         IsDerivedFrom(ClassType, CtxType);
2300}
2301
2302