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