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