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