SemaExprCXX.cpp revision 7a9f49296a6454b7a6f0edce89dc99d413a7e14e
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 "clang/Sema/SemaInternal.h"
15#include "clang/Sema/DeclSpec.h"
16#include "clang/Sema/Initialization.h"
17#include "clang/Sema/Lookup.h"
18#include "clang/Sema/ParsedTemplate.h"
19#include "clang/Sema/ScopeInfo.h"
20#include "clang/Sema/Scope.h"
21#include "clang/Sema/TemplateDeduction.h"
22#include "clang/AST/ASTContext.h"
23#include "clang/AST/CharUnits.h"
24#include "clang/AST/CXXInheritance.h"
25#include "clang/AST/DeclObjC.h"
26#include "clang/AST/ExprCXX.h"
27#include "clang/AST/ExprObjC.h"
28#include "clang/AST/TypeLoc.h"
29#include "clang/Basic/PartialDiagnostic.h"
30#include "clang/Basic/TargetInfo.h"
31#include "clang/Lex/Preprocessor.h"
32#include "TypeLocBuilder.h"
33#include "llvm/ADT/APInt.h"
34#include "llvm/ADT/STLExtras.h"
35#include "llvm/Support/ErrorHandling.h"
36using namespace clang;
37using namespace sema;
38
39ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
40                                   IdentifierInfo &II,
41                                   SourceLocation NameLoc,
42                                   Scope *S, CXXScopeSpec &SS,
43                                   ParsedType ObjectTypePtr,
44                                   bool EnteringContext) {
45  // Determine where to perform name lookup.
46
47  // FIXME: This area of the standard is very messy, and the current
48  // wording is rather unclear about which scopes we search for the
49  // destructor name; see core issues 399 and 555. Issue 399 in
50  // particular shows where the current description of destructor name
51  // lookup is completely out of line with existing practice, e.g.,
52  // this appears to be ill-formed:
53  //
54  //   namespace N {
55  //     template <typename T> struct S {
56  //       ~S();
57  //     };
58  //   }
59  //
60  //   void f(N::S<int>* s) {
61  //     s->N::S<int>::~S();
62  //   }
63  //
64  // See also PR6358 and PR6359.
65  // For this reason, we're currently only doing the C++03 version of this
66  // code; the C++0x version has to wait until we get a proper spec.
67  QualType SearchType;
68  DeclContext *LookupCtx = 0;
69  bool isDependent = false;
70  bool LookInScope = false;
71
72  // If we have an object type, it's because we are in a
73  // pseudo-destructor-expression or a member access expression, and
74  // we know what type we're looking for.
75  if (ObjectTypePtr)
76    SearchType = GetTypeFromParser(ObjectTypePtr);
77
78  if (SS.isSet()) {
79    NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
80
81    bool AlreadySearched = false;
82    bool LookAtPrefix = true;
83    // C++ [basic.lookup.qual]p6:
84    //   If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
85    //   the type-names are looked up as types in the scope designated by the
86    //   nested-name-specifier. In a qualified-id of the form:
87    //
88    //     ::[opt] nested-name-specifier  ~ class-name
89    //
90    //   where the nested-name-specifier designates a namespace scope, and in
91    //   a qualified-id of the form:
92    //
93    //     ::opt nested-name-specifier class-name ::  ~ class-name
94    //
95    //   the class-names are looked up as types in the scope designated by
96    //   the nested-name-specifier.
97    //
98    // Here, we check the first case (completely) and determine whether the
99    // code below is permitted to look at the prefix of the
100    // nested-name-specifier.
101    DeclContext *DC = computeDeclContext(SS, EnteringContext);
102    if (DC && DC->isFileContext()) {
103      AlreadySearched = true;
104      LookupCtx = DC;
105      isDependent = false;
106    } else if (DC && isa<CXXRecordDecl>(DC))
107      LookAtPrefix = false;
108
109    // The second case from the C++03 rules quoted further above.
110    NestedNameSpecifier *Prefix = 0;
111    if (AlreadySearched) {
112      // Nothing left to do.
113    } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
114      CXXScopeSpec PrefixSS;
115      PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
116      LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
117      isDependent = isDependentScopeSpecifier(PrefixSS);
118    } else if (ObjectTypePtr) {
119      LookupCtx = computeDeclContext(SearchType);
120      isDependent = SearchType->isDependentType();
121    } else {
122      LookupCtx = computeDeclContext(SS, EnteringContext);
123      isDependent = LookupCtx && LookupCtx->isDependentContext();
124    }
125
126    LookInScope = false;
127  } else if (ObjectTypePtr) {
128    // C++ [basic.lookup.classref]p3:
129    //   If the unqualified-id is ~type-name, the type-name is looked up
130    //   in the context of the entire postfix-expression. If the type T
131    //   of the object expression is of a class type C, the type-name is
132    //   also looked up in the scope of class C. At least one of the
133    //   lookups shall find a name that refers to (possibly
134    //   cv-qualified) T.
135    LookupCtx = computeDeclContext(SearchType);
136    isDependent = SearchType->isDependentType();
137    assert((isDependent || !SearchType->isIncompleteType()) &&
138           "Caller should have completed object type");
139
140    LookInScope = true;
141  } else {
142    // Perform lookup into the current scope (only).
143    LookInScope = true;
144  }
145
146  TypeDecl *NonMatchingTypeDecl = 0;
147  LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
148  for (unsigned Step = 0; Step != 2; ++Step) {
149    // Look for the name first in the computed lookup context (if we
150    // have one) and, if that fails to find a match, in the scope (if
151    // we're allowed to look there).
152    Found.clear();
153    if (Step == 0 && LookupCtx)
154      LookupQualifiedName(Found, LookupCtx);
155    else if (Step == 1 && LookInScope && S)
156      LookupName(Found, S);
157    else
158      continue;
159
160    // FIXME: Should we be suppressing ambiguities here?
161    if (Found.isAmbiguous())
162      return ParsedType();
163
164    if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
165      QualType T = Context.getTypeDeclType(Type);
166
167      if (SearchType.isNull() || SearchType->isDependentType() ||
168          Context.hasSameUnqualifiedType(T, SearchType)) {
169        // We found our type!
170
171        return ParsedType::make(T);
172      }
173
174      if (!SearchType.isNull())
175        NonMatchingTypeDecl = Type;
176    }
177
178    // If the name that we found is a class template name, and it is
179    // the same name as the template name in the last part of the
180    // nested-name-specifier (if present) or the object type, then
181    // this is the destructor for that class.
182    // FIXME: This is a workaround until we get real drafting for core
183    // issue 399, for which there isn't even an obvious direction.
184    if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
185      QualType MemberOfType;
186      if (SS.isSet()) {
187        if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
188          // Figure out the type of the context, if it has one.
189          if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
190            MemberOfType = Context.getTypeDeclType(Record);
191        }
192      }
193      if (MemberOfType.isNull())
194        MemberOfType = SearchType;
195
196      if (MemberOfType.isNull())
197        continue;
198
199      // We're referring into a class template specialization. If the
200      // class template we found is the same as the template being
201      // specialized, we found what we are looking for.
202      if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
203        if (ClassTemplateSpecializationDecl *Spec
204              = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
205          if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
206                Template->getCanonicalDecl())
207            return ParsedType::make(MemberOfType);
208        }
209
210        continue;
211      }
212
213      // We're referring to an unresolved class template
214      // specialization. Determine whether we class template we found
215      // is the same as the template being specialized or, if we don't
216      // know which template is being specialized, that it at least
217      // has the same name.
218      if (const TemplateSpecializationType *SpecType
219            = MemberOfType->getAs<TemplateSpecializationType>()) {
220        TemplateName SpecName = SpecType->getTemplateName();
221
222        // The class template we found is the same template being
223        // specialized.
224        if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
225          if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
226            return ParsedType::make(MemberOfType);
227
228          continue;
229        }
230
231        // The class template we found has the same name as the
232        // (dependent) template name being specialized.
233        if (DependentTemplateName *DepTemplate
234                                    = SpecName.getAsDependentTemplateName()) {
235          if (DepTemplate->isIdentifier() &&
236              DepTemplate->getIdentifier() == Template->getIdentifier())
237            return ParsedType::make(MemberOfType);
238
239          continue;
240        }
241      }
242    }
243  }
244
245  if (isDependent) {
246    // We didn't find our type, but that's okay: it's dependent
247    // anyway.
248
249    // FIXME: What if we have no nested-name-specifier?
250    QualType T = CheckTypenameType(ETK_None, SourceLocation(),
251                                   SS.getWithLocInContext(Context),
252                                   II, NameLoc);
253    return ParsedType::make(T);
254  }
255
256  if (NonMatchingTypeDecl) {
257    QualType T = Context.getTypeDeclType(NonMatchingTypeDecl);
258    Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
259      << T << SearchType;
260    Diag(NonMatchingTypeDecl->getLocation(), diag::note_destructor_type_here)
261      << T;
262  } else if (ObjectTypePtr)
263    Diag(NameLoc, diag::err_ident_in_dtor_not_a_type)
264      << &II;
265  else
266    Diag(NameLoc, diag::err_destructor_class_name);
267
268  return ParsedType();
269}
270
271ParsedType Sema::getDestructorType(const DeclSpec& DS, ParsedType ObjectType) {
272    if (DS.getTypeSpecType() == DeclSpec::TST_error || !ObjectType)
273      return ParsedType();
274    assert(DS.getTypeSpecType() == DeclSpec::TST_decltype
275           && "only get destructor types from declspecs");
276    QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
277    QualType SearchType = GetTypeFromParser(ObjectType);
278    if (SearchType->isDependentType() || Context.hasSameUnqualifiedType(SearchType, T)) {
279      return ParsedType::make(T);
280    }
281
282    Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)
283      << T << SearchType;
284    return ParsedType();
285}
286
287/// \brief Build a C++ typeid expression with a type operand.
288ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
289                                SourceLocation TypeidLoc,
290                                TypeSourceInfo *Operand,
291                                SourceLocation RParenLoc) {
292  // C++ [expr.typeid]p4:
293  //   The top-level cv-qualifiers of the lvalue expression or the type-id
294  //   that is the operand of typeid are always ignored.
295  //   If the type of the type-id is a class type or a reference to a class
296  //   type, the class shall be completely-defined.
297  Qualifiers Quals;
298  QualType T
299    = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
300                                      Quals);
301  if (T->getAs<RecordType>() &&
302      RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
303    return ExprError();
304
305  return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
306                                           Operand,
307                                           SourceRange(TypeidLoc, RParenLoc)));
308}
309
310/// \brief Build a C++ typeid expression with an expression operand.
311ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
312                                SourceLocation TypeidLoc,
313                                Expr *E,
314                                SourceLocation RParenLoc) {
315  if (E && !E->isTypeDependent()) {
316    if (E->getType()->isPlaceholderType()) {
317      ExprResult result = CheckPlaceholderExpr(E);
318      if (result.isInvalid()) return ExprError();
319      E = result.take();
320    }
321
322    QualType T = E->getType();
323    if (const RecordType *RecordT = T->getAs<RecordType>()) {
324      CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
325      // C++ [expr.typeid]p3:
326      //   [...] If the type of the expression is a class type, the class
327      //   shall be completely-defined.
328      if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
329        return ExprError();
330
331      // C++ [expr.typeid]p3:
332      //   When typeid is applied to an expression other than an glvalue of a
333      //   polymorphic class type [...] [the] expression is an unevaluated
334      //   operand. [...]
335      if (RecordD->isPolymorphic() && E->Classify(Context).isGLValue()) {
336        // The subexpression is potentially evaluated; switch the context
337        // and recheck the subexpression.
338        ExprResult Result = TranformToPotentiallyEvaluated(E);
339        if (Result.isInvalid()) return ExprError();
340        E = Result.take();
341
342        // We require a vtable to query the type at run time.
343        MarkVTableUsed(TypeidLoc, RecordD);
344      }
345    }
346
347    // C++ [expr.typeid]p4:
348    //   [...] If the type of the type-id is a reference to a possibly
349    //   cv-qualified type, the result of the typeid expression refers to a
350    //   std::type_info object representing the cv-unqualified referenced
351    //   type.
352    Qualifiers Quals;
353    QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
354    if (!Context.hasSameType(T, UnqualT)) {
355      T = UnqualT;
356      E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).take();
357    }
358  }
359
360  return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
361                                           E,
362                                           SourceRange(TypeidLoc, RParenLoc)));
363}
364
365/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
366ExprResult
367Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
368                     bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
369  // Find the std::type_info type.
370  if (!getStdNamespace())
371    return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
372
373  if (!CXXTypeInfoDecl) {
374    IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
375    LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
376    LookupQualifiedName(R, getStdNamespace());
377    CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
378    if (!CXXTypeInfoDecl)
379      return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
380  }
381
382  QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
383
384  if (isType) {
385    // The operand is a type; handle it as such.
386    TypeSourceInfo *TInfo = 0;
387    QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
388                                   &TInfo);
389    if (T.isNull())
390      return ExprError();
391
392    if (!TInfo)
393      TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
394
395    return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
396  }
397
398  // The operand is an expression.
399  return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
400}
401
402/// Retrieve the UuidAttr associated with QT.
403static UuidAttr *GetUuidAttrOfType(QualType QT) {
404  // Optionally remove one level of pointer, reference or array indirection.
405  const Type *Ty = QT.getTypePtr();;
406  if (QT->isPointerType() || QT->isReferenceType())
407    Ty = QT->getPointeeType().getTypePtr();
408  else if (QT->isArrayType())
409    Ty = cast<ArrayType>(QT)->getElementType().getTypePtr();
410
411  // Loop all record redeclaration looking for an uuid attribute.
412  CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
413  for (CXXRecordDecl::redecl_iterator I = RD->redecls_begin(),
414       E = RD->redecls_end(); I != E; ++I) {
415    if (UuidAttr *Uuid = I->getAttr<UuidAttr>())
416      return Uuid;
417  }
418
419  return 0;
420}
421
422/// \brief Build a Microsoft __uuidof expression with a type operand.
423ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
424                                SourceLocation TypeidLoc,
425                                TypeSourceInfo *Operand,
426                                SourceLocation RParenLoc) {
427  if (!Operand->getType()->isDependentType()) {
428    if (!GetUuidAttrOfType(Operand->getType()))
429      return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
430  }
431
432  // FIXME: add __uuidof semantic analysis for type operand.
433  return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
434                                           Operand,
435                                           SourceRange(TypeidLoc, RParenLoc)));
436}
437
438/// \brief Build a Microsoft __uuidof expression with an expression operand.
439ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
440                                SourceLocation TypeidLoc,
441                                Expr *E,
442                                SourceLocation RParenLoc) {
443  if (!E->getType()->isDependentType()) {
444    if (!GetUuidAttrOfType(E->getType()) &&
445        !E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
446      return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
447  }
448  // FIXME: add __uuidof semantic analysis for type operand.
449  return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
450                                           E,
451                                           SourceRange(TypeidLoc, RParenLoc)));
452}
453
454/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
455ExprResult
456Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
457                     bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
458  // If MSVCGuidDecl has not been cached, do the lookup.
459  if (!MSVCGuidDecl) {
460    IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
461    LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
462    LookupQualifiedName(R, Context.getTranslationUnitDecl());
463    MSVCGuidDecl = R.getAsSingle<RecordDecl>();
464    if (!MSVCGuidDecl)
465      return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
466  }
467
468  QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
469
470  if (isType) {
471    // The operand is a type; handle it as such.
472    TypeSourceInfo *TInfo = 0;
473    QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
474                                   &TInfo);
475    if (T.isNull())
476      return ExprError();
477
478    if (!TInfo)
479      TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
480
481    return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
482  }
483
484  // The operand is an expression.
485  return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
486}
487
488/// ActOnCXXBoolLiteral - Parse {true,false} literals.
489ExprResult
490Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
491  assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
492         "Unknown C++ Boolean value!");
493  return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
494                                                Context.BoolTy, OpLoc));
495}
496
497/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
498ExprResult
499Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
500  return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
501}
502
503/// ActOnCXXThrow - Parse throw expressions.
504ExprResult
505Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) {
506  bool IsThrownVarInScope = false;
507  if (Ex) {
508    // C++0x [class.copymove]p31:
509    //   When certain criteria are met, an implementation is allowed to omit the
510    //   copy/move construction of a class object [...]
511    //
512    //     - in a throw-expression, when the operand is the name of a
513    //       non-volatile automatic object (other than a function or catch-
514    //       clause parameter) whose scope does not extend beyond the end of the
515    //       innermost enclosing try-block (if there is one), the copy/move
516    //       operation from the operand to the exception object (15.1) can be
517    //       omitted by constructing the automatic object directly into the
518    //       exception object
519    if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
520      if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
521        if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) {
522          for( ; S; S = S->getParent()) {
523            if (S->isDeclScope(Var)) {
524              IsThrownVarInScope = true;
525              break;
526            }
527
528            if (S->getFlags() &
529                (Scope::FnScope | Scope::ClassScope | Scope::BlockScope |
530                 Scope::FunctionPrototypeScope | Scope::ObjCMethodScope |
531                 Scope::TryScope))
532              break;
533          }
534        }
535      }
536  }
537
538  return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
539}
540
541ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
542                               bool IsThrownVarInScope) {
543  // Don't report an error if 'throw' is used in system headers.
544  if (!getLangOptions().CXXExceptions &&
545      !getSourceManager().isInSystemHeader(OpLoc))
546    Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
547
548  if (Ex && !Ex->isTypeDependent()) {
549    ExprResult ExRes = CheckCXXThrowOperand(OpLoc, Ex, IsThrownVarInScope);
550    if (ExRes.isInvalid())
551      return ExprError();
552    Ex = ExRes.take();
553  }
554
555  return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc,
556                                          IsThrownVarInScope));
557}
558
559/// CheckCXXThrowOperand - Validate the operand of a throw.
560ExprResult Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *E,
561                                      bool IsThrownVarInScope) {
562  // C++ [except.throw]p3:
563  //   A throw-expression initializes a temporary object, called the exception
564  //   object, the type of which is determined by removing any top-level
565  //   cv-qualifiers from the static type of the operand of throw and adjusting
566  //   the type from "array of T" or "function returning T" to "pointer to T"
567  //   or "pointer to function returning T", [...]
568  if (E->getType().hasQualifiers())
569    E = ImpCastExprToType(E, E->getType().getUnqualifiedType(), CK_NoOp,
570                          E->getValueKind()).take();
571
572  ExprResult Res = DefaultFunctionArrayConversion(E);
573  if (Res.isInvalid())
574    return ExprError();
575  E = Res.take();
576
577  //   If the type of the exception would be an incomplete type or a pointer
578  //   to an incomplete type other than (cv) void the program is ill-formed.
579  QualType Ty = E->getType();
580  bool isPointer = false;
581  if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
582    Ty = Ptr->getPointeeType();
583    isPointer = true;
584  }
585  if (!isPointer || !Ty->isVoidType()) {
586    if (RequireCompleteType(ThrowLoc, Ty,
587                            PDiag(isPointer ? diag::err_throw_incomplete_ptr
588                                            : diag::err_throw_incomplete)
589                              << E->getSourceRange()))
590      return ExprError();
591
592    if (RequireNonAbstractType(ThrowLoc, E->getType(),
593                               PDiag(diag::err_throw_abstract_type)
594                                 << E->getSourceRange()))
595      return ExprError();
596  }
597
598  // Initialize the exception result.  This implicitly weeds out
599  // abstract types or types with inaccessible copy constructors.
600
601  // C++0x [class.copymove]p31:
602  //   When certain criteria are met, an implementation is allowed to omit the
603  //   copy/move construction of a class object [...]
604  //
605  //     - in a throw-expression, when the operand is the name of a
606  //       non-volatile automatic object (other than a function or catch-clause
607  //       parameter) whose scope does not extend beyond the end of the
608  //       innermost enclosing try-block (if there is one), the copy/move
609  //       operation from the operand to the exception object (15.1) can be
610  //       omitted by constructing the automatic object directly into the
611  //       exception object
612  const VarDecl *NRVOVariable = 0;
613  if (IsThrownVarInScope)
614    NRVOVariable = getCopyElisionCandidate(QualType(), E, false);
615
616  InitializedEntity Entity =
617      InitializedEntity::InitializeException(ThrowLoc, E->getType(),
618                                             /*NRVO=*/NRVOVariable != 0);
619  Res = PerformMoveOrCopyInitialization(Entity, NRVOVariable,
620                                        QualType(), E,
621                                        IsThrownVarInScope);
622  if (Res.isInvalid())
623    return ExprError();
624  E = Res.take();
625
626  // If the exception has class type, we need additional handling.
627  const RecordType *RecordTy = Ty->getAs<RecordType>();
628  if (!RecordTy)
629    return Owned(E);
630  CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
631
632  // If we are throwing a polymorphic class type or pointer thereof,
633  // exception handling will make use of the vtable.
634  MarkVTableUsed(ThrowLoc, RD);
635
636  // If a pointer is thrown, the referenced object will not be destroyed.
637  if (isPointer)
638    return Owned(E);
639
640  // If the class has a destructor, we must be able to call it.
641  if (RD->hasIrrelevantDestructor())
642    return Owned(E);
643
644  CXXDestructorDecl *Destructor
645    = const_cast<CXXDestructorDecl*>(LookupDestructor(RD));
646  if (!Destructor)
647    return Owned(E);
648
649  MarkFunctionReferenced(E->getExprLoc(), Destructor);
650  CheckDestructorAccess(E->getExprLoc(), Destructor,
651                        PDiag(diag::err_access_dtor_exception) << Ty);
652  DiagnoseUseOfDecl(Destructor, E->getExprLoc());
653  return Owned(E);
654}
655
656QualType Sema::getCurrentThisType() {
657  DeclContext *DC = getFunctionLevelDeclContext();
658  QualType ThisTy;
659  if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
660    if (method && method->isInstance())
661      ThisTy = method->getThisType(Context);
662  } else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
663    // C++0x [expr.prim]p4:
664    //   Otherwise, if a member-declarator declares a non-static data member
665    // of a class X, the expression this is a prvalue of type "pointer to X"
666    // within the optional brace-or-equal-initializer.
667    Scope *S = getScopeForContext(DC);
668    if (!S || S->getFlags() & Scope::ThisScope)
669      ThisTy = Context.getPointerType(Context.getRecordType(RD));
670  }
671
672  return ThisTy;
673}
674
675void Sema::CheckCXXThisCapture(SourceLocation Loc, bool Explicit) {
676  // We don't need to capture this in an unevaluated context.
677  if (ExprEvalContexts.back().Context == Unevaluated && !Explicit)
678    return;
679
680  // Otherwise, check that we can capture 'this'.
681  unsigned NumClosures = 0;
682  for (unsigned idx = FunctionScopes.size() - 1; idx != 0; idx--) {
683    if (CapturingScopeInfo *CSI =
684            dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
685      if (CSI->CXXThisCaptureIndex != 0) {
686        // 'this' is already being captured; there isn't anything more to do.
687        break;
688      }
689
690      if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
691          CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
692          CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
693          Explicit) {
694        // This closure can capture 'this'; continue looking upwards.
695        NumClosures++;
696        Explicit = false;
697        continue;
698      }
699      // This context can't implicitly capture 'this'; fail out.
700      Diag(Loc, diag::err_this_capture) << Explicit;
701      return;
702    }
703    break;
704  }
705
706  // Mark that we're implicitly capturing 'this' in all the scopes we skipped.
707  // FIXME: We need to delay this marking in PotentiallyPotentiallyEvaluated
708  // contexts.
709  for (unsigned idx = FunctionScopes.size() - 1;
710       NumClosures; --idx, --NumClosures) {
711    CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
712    Expr *ThisExpr = 0;
713    QualType ThisTy = getCurrentThisType();
714    if (LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
715      // For lambda expressions, build a field and an initializing expression.
716      CXXRecordDecl *Lambda = LSI->Lambda;
717      FieldDecl *Field
718        = FieldDecl::Create(Context, Lambda, Loc, Loc, 0, ThisTy,
719                            Context.getTrivialTypeSourceInfo(ThisTy, Loc),
720                            0, false, false);
721      Field->setImplicit(true);
722      Field->setAccess(AS_private);
723      Lambda->addDecl(Field);
724      ThisExpr = new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/true);
725    }
726    bool isNested = NumClosures > 1;
727    CSI->addThisCapture(isNested, Loc, ThisTy, ThisExpr);
728  }
729}
730
731ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
732  /// C++ 9.3.2: In the body of a non-static member function, the keyword this
733  /// is a non-lvalue expression whose value is the address of the object for
734  /// which the function is called.
735
736  QualType ThisTy = getCurrentThisType();
737  if (ThisTy.isNull()) return Diag(Loc, diag::err_invalid_this_use);
738
739  CheckCXXThisCapture(Loc);
740  return Owned(new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/false));
741}
742
743ExprResult
744Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
745                                SourceLocation LParenLoc,
746                                MultiExprArg exprs,
747                                SourceLocation RParenLoc) {
748  if (!TypeRep)
749    return ExprError();
750
751  TypeSourceInfo *TInfo;
752  QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
753  if (!TInfo)
754    TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
755
756  return BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc);
757}
758
759/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
760/// Can be interpreted either as function-style casting ("int(x)")
761/// or class type construction ("ClassType(x,y,z)")
762/// or creation of a value-initialized type ("int()").
763ExprResult
764Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
765                                SourceLocation LParenLoc,
766                                MultiExprArg exprs,
767                                SourceLocation RParenLoc) {
768  QualType Ty = TInfo->getType();
769  unsigned NumExprs = exprs.size();
770  Expr **Exprs = (Expr**)exprs.get();
771  SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
772
773  if (Ty->isDependentType() ||
774      CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
775    exprs.release();
776
777    return Owned(CXXUnresolvedConstructExpr::Create(Context, TInfo,
778                                                    LParenLoc,
779                                                    Exprs, NumExprs,
780                                                    RParenLoc));
781  }
782
783  bool ListInitialization = LParenLoc.isInvalid();
784  assert((!ListInitialization || (NumExprs == 1 && isa<InitListExpr>(Exprs[0])))
785         && "List initialization must have initializer list as expression.");
786  SourceRange FullRange = SourceRange(TyBeginLoc,
787      ListInitialization ? Exprs[0]->getSourceRange().getEnd() : RParenLoc);
788
789  if (Ty->isArrayType())
790    return ExprError(Diag(TyBeginLoc,
791                          diag::err_value_init_for_array_type) << FullRange);
792  if (!Ty->isVoidType() &&
793      RequireCompleteType(TyBeginLoc, Ty,
794                          PDiag(diag::err_invalid_incomplete_type_use)
795                            << FullRange))
796    return ExprError();
797
798  if (RequireNonAbstractType(TyBeginLoc, Ty,
799                             diag::err_allocation_of_abstract_type))
800    return ExprError();
801
802
803  // C++ [expr.type.conv]p1:
804  // If the expression list is a single expression, the type conversion
805  // expression is equivalent (in definedness, and if defined in meaning) to the
806  // corresponding cast expression.
807  if (NumExprs == 1 && !ListInitialization) {
808    Expr *Arg = Exprs[0];
809    exprs.release();
810    return BuildCXXFunctionalCastExpr(TInfo, LParenLoc, Arg, RParenLoc);
811  }
812
813  InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
814  InitializationKind Kind
815    = NumExprs ? ListInitialization
816                    ? InitializationKind::CreateDirectList(TyBeginLoc)
817                    : InitializationKind::CreateDirect(TyBeginLoc,
818                                                       LParenLoc, RParenLoc)
819               : InitializationKind::CreateValue(TyBeginLoc,
820                                                 LParenLoc, RParenLoc);
821  InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
822  ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(exprs));
823
824  if (!Result.isInvalid() && ListInitialization &&
825      isa<InitListExpr>(Result.get())) {
826    // If the list-initialization doesn't involve a constructor call, we'll get
827    // the initializer-list (with corrected type) back, but that's not what we
828    // want, since it will be treated as an initializer list in further
829    // processing. Explicitly insert a cast here.
830    InitListExpr *List = cast<InitListExpr>(Result.take());
831    Result = Owned(CXXFunctionalCastExpr::Create(Context, List->getType(),
832                                    Expr::getValueKindForType(TInfo->getType()),
833                                                 TInfo, TyBeginLoc, CK_NoOp,
834                                                 List, /*Path=*/0, RParenLoc));
835  }
836
837  // FIXME: Improve AST representation?
838  return move(Result);
839}
840
841/// doesUsualArrayDeleteWantSize - Answers whether the usual
842/// operator delete[] for the given type has a size_t parameter.
843static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
844                                         QualType allocType) {
845  const RecordType *record =
846    allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
847  if (!record) return false;
848
849  // Try to find an operator delete[] in class scope.
850
851  DeclarationName deleteName =
852    S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
853  LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
854  S.LookupQualifiedName(ops, record->getDecl());
855
856  // We're just doing this for information.
857  ops.suppressDiagnostics();
858
859  // Very likely: there's no operator delete[].
860  if (ops.empty()) return false;
861
862  // If it's ambiguous, it should be illegal to call operator delete[]
863  // on this thing, so it doesn't matter if we allocate extra space or not.
864  if (ops.isAmbiguous()) return false;
865
866  LookupResult::Filter filter = ops.makeFilter();
867  while (filter.hasNext()) {
868    NamedDecl *del = filter.next()->getUnderlyingDecl();
869
870    // C++0x [basic.stc.dynamic.deallocation]p2:
871    //   A template instance is never a usual deallocation function,
872    //   regardless of its signature.
873    if (isa<FunctionTemplateDecl>(del)) {
874      filter.erase();
875      continue;
876    }
877
878    // C++0x [basic.stc.dynamic.deallocation]p2:
879    //   If class T does not declare [an operator delete[] with one
880    //   parameter] but does declare a member deallocation function
881    //   named operator delete[] with exactly two parameters, the
882    //   second of which has type std::size_t, then this function
883    //   is a usual deallocation function.
884    if (!cast<CXXMethodDecl>(del)->isUsualDeallocationFunction()) {
885      filter.erase();
886      continue;
887    }
888  }
889  filter.done();
890
891  if (!ops.isSingleResult()) return false;
892
893  const FunctionDecl *del = cast<FunctionDecl>(ops.getFoundDecl());
894  return (del->getNumParams() == 2);
895}
896
897/// \brief Parsed a C++ 'new' expression (C++ 5.3.4).
898
899/// E.g.:
900/// @code new (memory) int[size][4] @endcode
901/// or
902/// @code ::new Foo(23, "hello") @endcode
903///
904/// \param StartLoc The first location of the expression.
905/// \param UseGlobal True if 'new' was prefixed with '::'.
906/// \param PlacementLParen Opening paren of the placement arguments.
907/// \param PlacementArgs Placement new arguments.
908/// \param PlacementRParen Closing paren of the placement arguments.
909/// \param TypeIdParens If the type is in parens, the source range.
910/// \param D The type to be allocated, as well as array dimensions.
911/// \param ConstructorLParen Opening paren of the constructor args, empty if
912///                          initializer-list syntax is used.
913/// \param ConstructorArgs Constructor/initialization arguments.
914/// \param ConstructorRParen Closing paren of the constructor args.
915ExprResult
916Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
917                  SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
918                  SourceLocation PlacementRParen, SourceRange TypeIdParens,
919                  Declarator &D, Expr *Initializer) {
920  bool TypeContainsAuto = D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto;
921
922  Expr *ArraySize = 0;
923  // If the specified type is an array, unwrap it and save the expression.
924  if (D.getNumTypeObjects() > 0 &&
925      D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
926    DeclaratorChunk &Chunk = D.getTypeObject(0);
927    if (TypeContainsAuto)
928      return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
929        << D.getSourceRange());
930    if (Chunk.Arr.hasStatic)
931      return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
932        << D.getSourceRange());
933    if (!Chunk.Arr.NumElts)
934      return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
935        << D.getSourceRange());
936
937    ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
938    D.DropFirstTypeObject();
939  }
940
941  // Every dimension shall be of constant size.
942  if (ArraySize) {
943    for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
944      if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
945        break;
946
947      DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
948      if (Expr *NumElts = (Expr *)Array.NumElts) {
949        if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
950          Array.NumElts = VerifyIntegerConstantExpression(NumElts, 0,
951            PDiag(diag::err_new_array_nonconst)).take();
952          if (!Array.NumElts)
953            return ExprError();
954        }
955      }
956    }
957  }
958
959  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/0);
960  QualType AllocType = TInfo->getType();
961  if (D.isInvalidType())
962    return ExprError();
963
964  SourceRange DirectInitRange;
965  if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer))
966    DirectInitRange = List->getSourceRange();
967
968  return BuildCXXNew(StartLoc, UseGlobal,
969                     PlacementLParen,
970                     move(PlacementArgs),
971                     PlacementRParen,
972                     TypeIdParens,
973                     AllocType,
974                     TInfo,
975                     ArraySize,
976                     DirectInitRange,
977                     Initializer,
978                     TypeContainsAuto);
979}
980
981static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style,
982                                       Expr *Init) {
983  if (!Init)
984    return true;
985  if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
986    return PLE->getNumExprs() == 0;
987  if (isa<ImplicitValueInitExpr>(Init))
988    return true;
989  else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
990    return !CCE->isListInitialization() &&
991           CCE->getConstructor()->isDefaultConstructor();
992  else if (Style == CXXNewExpr::ListInit) {
993    assert(isa<InitListExpr>(Init) &&
994           "Shouldn't create list CXXConstructExprs for arrays.");
995    return true;
996  }
997  return false;
998}
999
1000ExprResult
1001Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
1002                  SourceLocation PlacementLParen,
1003                  MultiExprArg PlacementArgs,
1004                  SourceLocation PlacementRParen,
1005                  SourceRange TypeIdParens,
1006                  QualType AllocType,
1007                  TypeSourceInfo *AllocTypeInfo,
1008                  Expr *ArraySize,
1009                  SourceRange DirectInitRange,
1010                  Expr *Initializer,
1011                  bool TypeMayContainAuto) {
1012  SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
1013
1014  CXXNewExpr::InitializationStyle initStyle;
1015  if (DirectInitRange.isValid()) {
1016    assert(Initializer && "Have parens but no initializer.");
1017    initStyle = CXXNewExpr::CallInit;
1018  } else if (Initializer && isa<InitListExpr>(Initializer))
1019    initStyle = CXXNewExpr::ListInit;
1020  else {
1021    // In template instantiation, the initializer could be a CXXDefaultArgExpr
1022    // unwrapped from a CXXConstructExpr that was implicitly built. There is no
1023    // particularly sane way we can handle this (especially since it can even
1024    // occur for array new), so we throw the initializer away and have it be
1025    // rebuilt.
1026    if (Initializer && isa<CXXDefaultArgExpr>(Initializer))
1027      Initializer = 0;
1028    assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||
1029            isa<CXXConstructExpr>(Initializer)) &&
1030           "Initializer expression that cannot have been implicitly created.");
1031    initStyle = CXXNewExpr::NoInit;
1032  }
1033
1034  Expr **Inits = &Initializer;
1035  unsigned NumInits = Initializer ? 1 : 0;
1036  if (initStyle == CXXNewExpr::CallInit) {
1037    if (ParenListExpr *List = dyn_cast<ParenListExpr>(Initializer)) {
1038      Inits = List->getExprs();
1039      NumInits = List->getNumExprs();
1040    } else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Initializer)){
1041      if (!isa<CXXTemporaryObjectExpr>(CCE)) {
1042        // Can happen in template instantiation. Since this is just an implicit
1043        // construction, we just take it apart and rebuild it.
1044        Inits = CCE->getArgs();
1045        NumInits = CCE->getNumArgs();
1046      }
1047    }
1048  }
1049
1050  // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
1051  if (TypeMayContainAuto && AllocType->getContainedAutoType()) {
1052    if (initStyle == CXXNewExpr::NoInit || NumInits == 0)
1053      return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
1054                       << AllocType << TypeRange);
1055    if (initStyle == CXXNewExpr::ListInit)
1056      return ExprError(Diag(Inits[0]->getSourceRange().getBegin(),
1057                            diag::err_auto_new_requires_parens)
1058                       << AllocType << TypeRange);
1059    if (NumInits > 1) {
1060      Expr *FirstBad = Inits[1];
1061      return ExprError(Diag(FirstBad->getSourceRange().getBegin(),
1062                            diag::err_auto_new_ctor_multiple_expressions)
1063                       << AllocType << TypeRange);
1064    }
1065    Expr *Deduce = Inits[0];
1066    TypeSourceInfo *DeducedType = 0;
1067    if (DeduceAutoType(AllocTypeInfo, Deduce, DeducedType) ==
1068            DAR_Failed)
1069      return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
1070                       << AllocType << Deduce->getType()
1071                       << TypeRange << Deduce->getSourceRange());
1072    if (!DeducedType)
1073      return ExprError();
1074
1075    AllocTypeInfo = DeducedType;
1076    AllocType = AllocTypeInfo->getType();
1077  }
1078
1079  // Per C++0x [expr.new]p5, the type being constructed may be a
1080  // typedef of an array type.
1081  if (!ArraySize) {
1082    if (const ConstantArrayType *Array
1083                              = Context.getAsConstantArrayType(AllocType)) {
1084      ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
1085                                         Context.getSizeType(),
1086                                         TypeRange.getEnd());
1087      AllocType = Array->getElementType();
1088    }
1089  }
1090
1091  if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
1092    return ExprError();
1093
1094  if (initStyle == CXXNewExpr::ListInit && isStdInitializerList(AllocType, 0)) {
1095    Diag(AllocTypeInfo->getTypeLoc().getBeginLoc(),
1096         diag::warn_dangling_std_initializer_list)
1097        << /*at end of FE*/0 << Inits[0]->getSourceRange();
1098  }
1099
1100  // In ARC, infer 'retaining' for the allocated
1101  if (getLangOptions().ObjCAutoRefCount &&
1102      AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1103      AllocType->isObjCLifetimeType()) {
1104    AllocType = Context.getLifetimeQualifiedType(AllocType,
1105                                    AllocType->getObjCARCImplicitLifetime());
1106  }
1107
1108  QualType ResultType = Context.getPointerType(AllocType);
1109
1110  // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
1111  //   integral or enumeration type with a non-negative value."
1112  // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
1113  //   enumeration type, or a class type for which a single non-explicit
1114  //   conversion function to integral or unscoped enumeration type exists.
1115  if (ArraySize && !ArraySize->isTypeDependent()) {
1116    ExprResult ConvertedSize = ConvertToIntegralOrEnumerationType(
1117      StartLoc, ArraySize,
1118      PDiag(diag::err_array_size_not_integral) << getLangOptions().CPlusPlus0x,
1119      PDiag(diag::err_array_size_incomplete_type)
1120        << ArraySize->getSourceRange(),
1121      PDiag(diag::err_array_size_explicit_conversion),
1122      PDiag(diag::note_array_size_conversion),
1123      PDiag(diag::err_array_size_ambiguous_conversion),
1124      PDiag(diag::note_array_size_conversion),
1125      PDiag(getLangOptions().CPlusPlus0x ?
1126              diag::warn_cxx98_compat_array_size_conversion :
1127              diag::ext_array_size_conversion),
1128      /*AllowScopedEnumerations*/ false);
1129    if (ConvertedSize.isInvalid())
1130      return ExprError();
1131
1132    ArraySize = ConvertedSize.take();
1133    QualType SizeType = ArraySize->getType();
1134    if (!SizeType->isIntegralOrUnscopedEnumerationType())
1135      return ExprError();
1136
1137    // C++98 [expr.new]p7:
1138    //   The expression in a direct-new-declarator shall have integral type
1139    //   with a non-negative value.
1140    //
1141    // Let's see if this is a constant < 0. If so, we reject it out of
1142    // hand. Otherwise, if it's not a constant, we must have an unparenthesized
1143    // array type.
1144    //
1145    // Note: such a construct has well-defined semantics in C++11: it throws
1146    // std::bad_array_new_length.
1147    if (!ArraySize->isValueDependent()) {
1148      llvm::APSInt Value;
1149      // We've already performed any required implicit conversion to integer or
1150      // unscoped enumeration type.
1151      if (ArraySize->isIntegerConstantExpr(Value, Context)) {
1152        if (Value < llvm::APSInt(
1153                        llvm::APInt::getNullValue(Value.getBitWidth()),
1154                                 Value.isUnsigned())) {
1155          if (getLangOptions().CPlusPlus0x)
1156            Diag(ArraySize->getSourceRange().getBegin(),
1157                 diag::warn_typecheck_negative_array_new_size)
1158              << ArraySize->getSourceRange();
1159          else
1160            return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
1161                                  diag::err_typecheck_negative_array_size)
1162                             << ArraySize->getSourceRange());
1163        } else if (!AllocType->isDependentType()) {
1164          unsigned ActiveSizeBits =
1165            ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
1166          if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
1167            if (getLangOptions().CPlusPlus0x)
1168              Diag(ArraySize->getSourceRange().getBegin(),
1169                   diag::warn_array_new_too_large)
1170                << Value.toString(10)
1171                << ArraySize->getSourceRange();
1172            else
1173              return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
1174                                    diag::err_array_too_large)
1175                               << Value.toString(10)
1176                               << ArraySize->getSourceRange());
1177          }
1178        }
1179      } else if (TypeIdParens.isValid()) {
1180        // Can't have dynamic array size when the type-id is in parentheses.
1181        Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
1182          << ArraySize->getSourceRange()
1183          << FixItHint::CreateRemoval(TypeIdParens.getBegin())
1184          << FixItHint::CreateRemoval(TypeIdParens.getEnd());
1185
1186        TypeIdParens = SourceRange();
1187      }
1188    }
1189
1190    // ARC: warn about ABI issues.
1191    if (getLangOptions().ObjCAutoRefCount) {
1192      QualType BaseAllocType = Context.getBaseElementType(AllocType);
1193      if (BaseAllocType.hasStrongOrWeakObjCLifetime())
1194        Diag(StartLoc, diag::warn_err_new_delete_object_array)
1195          << 0 << BaseAllocType;
1196    }
1197
1198    // Note that we do *not* convert the argument in any way.  It can
1199    // be signed, larger than size_t, whatever.
1200  }
1201
1202  FunctionDecl *OperatorNew = 0;
1203  FunctionDecl *OperatorDelete = 0;
1204  Expr **PlaceArgs = (Expr**)PlacementArgs.get();
1205  unsigned NumPlaceArgs = PlacementArgs.size();
1206
1207  if (!AllocType->isDependentType() &&
1208      !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
1209      FindAllocationFunctions(StartLoc,
1210                              SourceRange(PlacementLParen, PlacementRParen),
1211                              UseGlobal, AllocType, ArraySize, PlaceArgs,
1212                              NumPlaceArgs, OperatorNew, OperatorDelete))
1213    return ExprError();
1214
1215  // If this is an array allocation, compute whether the usual array
1216  // deallocation function for the type has a size_t parameter.
1217  bool UsualArrayDeleteWantsSize = false;
1218  if (ArraySize && !AllocType->isDependentType())
1219    UsualArrayDeleteWantsSize
1220      = doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
1221
1222  SmallVector<Expr *, 8> AllPlaceArgs;
1223  if (OperatorNew) {
1224    // Add default arguments, if any.
1225    const FunctionProtoType *Proto =
1226      OperatorNew->getType()->getAs<FunctionProtoType>();
1227    VariadicCallType CallType =
1228      Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
1229
1230    if (GatherArgumentsForCall(PlacementLParen, OperatorNew,
1231                               Proto, 1, PlaceArgs, NumPlaceArgs,
1232                               AllPlaceArgs, CallType))
1233      return ExprError();
1234
1235    NumPlaceArgs = AllPlaceArgs.size();
1236    if (NumPlaceArgs > 0)
1237      PlaceArgs = &AllPlaceArgs[0];
1238
1239    DiagnoseSentinelCalls(OperatorNew, PlacementLParen,
1240                          PlaceArgs, NumPlaceArgs);
1241
1242    // FIXME: Missing call to CheckFunctionCall or equivalent
1243  }
1244
1245  // Warn if the type is over-aligned and is being allocated by global operator
1246  // new.
1247  if (NumPlaceArgs == 0 && OperatorNew &&
1248      (OperatorNew->isImplicit() ||
1249       getSourceManager().isInSystemHeader(OperatorNew->getLocStart()))) {
1250    if (unsigned Align = Context.getPreferredTypeAlign(AllocType.getTypePtr())){
1251      unsigned SuitableAlign = Context.getTargetInfo().getSuitableAlign();
1252      if (Align > SuitableAlign)
1253        Diag(StartLoc, diag::warn_overaligned_type)
1254            << AllocType
1255            << unsigned(Align / Context.getCharWidth())
1256            << unsigned(SuitableAlign / Context.getCharWidth());
1257    }
1258  }
1259
1260  QualType InitType = AllocType;
1261  // Array 'new' can't have any initializers except empty parentheses.
1262  // Initializer lists are also allowed, in C++11. Rely on the parser for the
1263  // dialect distinction.
1264  if (ResultType->isArrayType() || ArraySize) {
1265    if (!isLegalArrayNewInitializer(initStyle, Initializer)) {
1266      SourceRange InitRange(Inits[0]->getLocStart(),
1267                            Inits[NumInits - 1]->getLocEnd());
1268      Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
1269      return ExprError();
1270    }
1271    if (InitListExpr *ILE = dyn_cast_or_null<InitListExpr>(Initializer)) {
1272      // We do the initialization typechecking against the array type
1273      // corresponding to the number of initializers + 1 (to also check
1274      // default-initialization).
1275      unsigned NumElements = ILE->getNumInits() + 1;
1276      InitType = Context.getConstantArrayType(AllocType,
1277          llvm::APInt(Context.getTypeSize(Context.getSizeType()), NumElements),
1278                                              ArrayType::Normal, 0);
1279    }
1280  }
1281
1282  if (!AllocType->isDependentType() &&
1283      !Expr::hasAnyTypeDependentArguments(Inits, NumInits)) {
1284    // C++11 [expr.new]p15:
1285    //   A new-expression that creates an object of type T initializes that
1286    //   object as follows:
1287    InitializationKind Kind
1288    //     - If the new-initializer is omitted, the object is default-
1289    //       initialized (8.5); if no initialization is performed,
1290    //       the object has indeterminate value
1291      = initStyle == CXXNewExpr::NoInit
1292          ? InitializationKind::CreateDefault(TypeRange.getBegin())
1293    //     - Otherwise, the new-initializer is interpreted according to the
1294    //       initialization rules of 8.5 for direct-initialization.
1295          : initStyle == CXXNewExpr::ListInit
1296              ? InitializationKind::CreateDirectList(TypeRange.getBegin())
1297              : InitializationKind::CreateDirect(TypeRange.getBegin(),
1298                                                 DirectInitRange.getBegin(),
1299                                                 DirectInitRange.getEnd());
1300
1301    InitializedEntity Entity
1302      = InitializedEntity::InitializeNew(StartLoc, InitType);
1303    InitializationSequence InitSeq(*this, Entity, Kind, Inits, NumInits);
1304    ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
1305                                          MultiExprArg(Inits, NumInits));
1306    if (FullInit.isInvalid())
1307      return ExprError();
1308
1309    // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
1310    // we don't want the initialized object to be destructed.
1311    if (CXXBindTemporaryExpr *Binder =
1312            dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
1313      FullInit = Owned(Binder->getSubExpr());
1314
1315    Initializer = FullInit.take();
1316  }
1317
1318  // Mark the new and delete operators as referenced.
1319  if (OperatorNew)
1320    MarkFunctionReferenced(StartLoc, OperatorNew);
1321  if (OperatorDelete)
1322    MarkFunctionReferenced(StartLoc, OperatorDelete);
1323
1324  // C++0x [expr.new]p17:
1325  //   If the new expression creates an array of objects of class type,
1326  //   access and ambiguity control are done for the destructor.
1327  if (ArraySize && AllocType->isRecordType() && !AllocType->isDependentType()) {
1328    if (CXXDestructorDecl *dtor = LookupDestructor(
1329            cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl()))) {
1330      MarkFunctionReferenced(StartLoc, dtor);
1331      CheckDestructorAccess(StartLoc, dtor,
1332                            PDiag(diag::err_access_dtor)
1333                              << Context.getBaseElementType(AllocType));
1334      DiagnoseUseOfDecl(dtor, StartLoc);
1335    }
1336  }
1337
1338  PlacementArgs.release();
1339
1340  return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
1341                                        OperatorDelete,
1342                                        UsualArrayDeleteWantsSize,
1343                                        PlaceArgs, NumPlaceArgs, TypeIdParens,
1344                                        ArraySize, initStyle, Initializer,
1345                                        ResultType, AllocTypeInfo,
1346                                        StartLoc, DirectInitRange));
1347}
1348
1349/// \brief Checks that a type is suitable as the allocated type
1350/// in a new-expression.
1351bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
1352                              SourceRange R) {
1353  // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
1354  //   abstract class type or array thereof.
1355  if (AllocType->isFunctionType())
1356    return Diag(Loc, diag::err_bad_new_type)
1357      << AllocType << 0 << R;
1358  else if (AllocType->isReferenceType())
1359    return Diag(Loc, diag::err_bad_new_type)
1360      << AllocType << 1 << R;
1361  else if (!AllocType->isDependentType() &&
1362           RequireCompleteType(Loc, AllocType,
1363                               PDiag(diag::err_new_incomplete_type)
1364                                 << R))
1365    return true;
1366  else if (RequireNonAbstractType(Loc, AllocType,
1367                                  diag::err_allocation_of_abstract_type))
1368    return true;
1369  else if (AllocType->isVariablyModifiedType())
1370    return Diag(Loc, diag::err_variably_modified_new_type)
1371             << AllocType;
1372  else if (unsigned AddressSpace = AllocType.getAddressSpace())
1373    return Diag(Loc, diag::err_address_space_qualified_new)
1374      << AllocType.getUnqualifiedType() << AddressSpace;
1375  else if (getLangOptions().ObjCAutoRefCount) {
1376    if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
1377      QualType BaseAllocType = Context.getBaseElementType(AT);
1378      if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1379          BaseAllocType->isObjCLifetimeType())
1380        return Diag(Loc, diag::err_arc_new_array_without_ownership)
1381          << BaseAllocType;
1382    }
1383  }
1384
1385  return false;
1386}
1387
1388/// \brief Determine whether the given function is a non-placement
1389/// deallocation function.
1390static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
1391  if (FD->isInvalidDecl())
1392    return false;
1393
1394  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1395    return Method->isUsualDeallocationFunction();
1396
1397  return ((FD->getOverloadedOperator() == OO_Delete ||
1398           FD->getOverloadedOperator() == OO_Array_Delete) &&
1399          FD->getNumParams() == 1);
1400}
1401
1402/// FindAllocationFunctions - Finds the overloads of operator new and delete
1403/// that are appropriate for the allocation.
1404bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
1405                                   bool UseGlobal, QualType AllocType,
1406                                   bool IsArray, Expr **PlaceArgs,
1407                                   unsigned NumPlaceArgs,
1408                                   FunctionDecl *&OperatorNew,
1409                                   FunctionDecl *&OperatorDelete) {
1410  // --- Choosing an allocation function ---
1411  // C++ 5.3.4p8 - 14 & 18
1412  // 1) If UseGlobal is true, only look in the global scope. Else, also look
1413  //   in the scope of the allocated class.
1414  // 2) If an array size is given, look for operator new[], else look for
1415  //   operator new.
1416  // 3) The first argument is always size_t. Append the arguments from the
1417  //   placement form.
1418
1419  SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
1420  // We don't care about the actual value of this argument.
1421  // FIXME: Should the Sema create the expression and embed it in the syntax
1422  // tree? Or should the consumer just recalculate the value?
1423  IntegerLiteral Size(Context, llvm::APInt::getNullValue(
1424                      Context.getTargetInfo().getPointerWidth(0)),
1425                      Context.getSizeType(),
1426                      SourceLocation());
1427  AllocArgs[0] = &Size;
1428  std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
1429
1430  // C++ [expr.new]p8:
1431  //   If the allocated type is a non-array type, the allocation
1432  //   function's name is operator new and the deallocation function's
1433  //   name is operator delete. If the allocated type is an array
1434  //   type, the allocation function's name is operator new[] and the
1435  //   deallocation function's name is operator delete[].
1436  DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
1437                                        IsArray ? OO_Array_New : OO_New);
1438  DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1439                                        IsArray ? OO_Array_Delete : OO_Delete);
1440
1441  QualType AllocElemType = Context.getBaseElementType(AllocType);
1442
1443  if (AllocElemType->isRecordType() && !UseGlobal) {
1444    CXXRecordDecl *Record
1445      = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
1446    if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
1447                          AllocArgs.size(), Record, /*AllowMissing=*/true,
1448                          OperatorNew))
1449      return true;
1450  }
1451  if (!OperatorNew) {
1452    // Didn't find a member overload. Look for a global one.
1453    DeclareGlobalNewDelete();
1454    DeclContext *TUDecl = Context.getTranslationUnitDecl();
1455    if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
1456                          AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
1457                          OperatorNew))
1458      return true;
1459  }
1460
1461  // We don't need an operator delete if we're running under
1462  // -fno-exceptions.
1463  if (!getLangOptions().Exceptions) {
1464    OperatorDelete = 0;
1465    return false;
1466  }
1467
1468  // FindAllocationOverload can change the passed in arguments, so we need to
1469  // copy them back.
1470  if (NumPlaceArgs > 0)
1471    std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
1472
1473  // C++ [expr.new]p19:
1474  //
1475  //   If the new-expression begins with a unary :: operator, the
1476  //   deallocation function's name is looked up in the global
1477  //   scope. Otherwise, if the allocated type is a class type T or an
1478  //   array thereof, the deallocation function's name is looked up in
1479  //   the scope of T. If this lookup fails to find the name, or if
1480  //   the allocated type is not a class type or array thereof, the
1481  //   deallocation function's name is looked up in the global scope.
1482  LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
1483  if (AllocElemType->isRecordType() && !UseGlobal) {
1484    CXXRecordDecl *RD
1485      = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
1486    LookupQualifiedName(FoundDelete, RD);
1487  }
1488  if (FoundDelete.isAmbiguous())
1489    return true; // FIXME: clean up expressions?
1490
1491  if (FoundDelete.empty()) {
1492    DeclareGlobalNewDelete();
1493    LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
1494  }
1495
1496  FoundDelete.suppressDiagnostics();
1497
1498  SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
1499
1500  // Whether we're looking for a placement operator delete is dictated
1501  // by whether we selected a placement operator new, not by whether
1502  // we had explicit placement arguments.  This matters for things like
1503  //   struct A { void *operator new(size_t, int = 0); ... };
1504  //   A *a = new A()
1505  bool isPlacementNew = (NumPlaceArgs > 0 || OperatorNew->param_size() != 1);
1506
1507  if (isPlacementNew) {
1508    // C++ [expr.new]p20:
1509    //   A declaration of a placement deallocation function matches the
1510    //   declaration of a placement allocation function if it has the
1511    //   same number of parameters and, after parameter transformations
1512    //   (8.3.5), all parameter types except the first are
1513    //   identical. [...]
1514    //
1515    // To perform this comparison, we compute the function type that
1516    // the deallocation function should have, and use that type both
1517    // for template argument deduction and for comparison purposes.
1518    //
1519    // FIXME: this comparison should ignore CC and the like.
1520    QualType ExpectedFunctionType;
1521    {
1522      const FunctionProtoType *Proto
1523        = OperatorNew->getType()->getAs<FunctionProtoType>();
1524
1525      SmallVector<QualType, 4> ArgTypes;
1526      ArgTypes.push_back(Context.VoidPtrTy);
1527      for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
1528        ArgTypes.push_back(Proto->getArgType(I));
1529
1530      FunctionProtoType::ExtProtoInfo EPI;
1531      EPI.Variadic = Proto->isVariadic();
1532
1533      ExpectedFunctionType
1534        = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
1535                                  ArgTypes.size(), EPI);
1536    }
1537
1538    for (LookupResult::iterator D = FoundDelete.begin(),
1539                             DEnd = FoundDelete.end();
1540         D != DEnd; ++D) {
1541      FunctionDecl *Fn = 0;
1542      if (FunctionTemplateDecl *FnTmpl
1543            = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
1544        // Perform template argument deduction to try to match the
1545        // expected function type.
1546        TemplateDeductionInfo Info(Context, StartLoc);
1547        if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
1548          continue;
1549      } else
1550        Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
1551
1552      if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
1553        Matches.push_back(std::make_pair(D.getPair(), Fn));
1554    }
1555  } else {
1556    // C++ [expr.new]p20:
1557    //   [...] Any non-placement deallocation function matches a
1558    //   non-placement allocation function. [...]
1559    for (LookupResult::iterator D = FoundDelete.begin(),
1560                             DEnd = FoundDelete.end();
1561         D != DEnd; ++D) {
1562      if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
1563        if (isNonPlacementDeallocationFunction(Fn))
1564          Matches.push_back(std::make_pair(D.getPair(), Fn));
1565    }
1566  }
1567
1568  // C++ [expr.new]p20:
1569  //   [...] If the lookup finds a single matching deallocation
1570  //   function, that function will be called; otherwise, no
1571  //   deallocation function will be called.
1572  if (Matches.size() == 1) {
1573    OperatorDelete = Matches[0].second;
1574
1575    // C++0x [expr.new]p20:
1576    //   If the lookup finds the two-parameter form of a usual
1577    //   deallocation function (3.7.4.2) and that function, considered
1578    //   as a placement deallocation function, would have been
1579    //   selected as a match for the allocation function, the program
1580    //   is ill-formed.
1581    if (NumPlaceArgs && getLangOptions().CPlusPlus0x &&
1582        isNonPlacementDeallocationFunction(OperatorDelete)) {
1583      Diag(StartLoc, diag::err_placement_new_non_placement_delete)
1584        << SourceRange(PlaceArgs[0]->getLocStart(),
1585                       PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1586      Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1587        << DeleteName;
1588    } else {
1589      CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
1590                            Matches[0].first);
1591    }
1592  }
1593
1594  return false;
1595}
1596
1597/// FindAllocationOverload - Find an fitting overload for the allocation
1598/// function in the specified scope.
1599bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1600                                  DeclarationName Name, Expr** Args,
1601                                  unsigned NumArgs, DeclContext *Ctx,
1602                                  bool AllowMissing, FunctionDecl *&Operator,
1603                                  bool Diagnose) {
1604  LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1605  LookupQualifiedName(R, Ctx);
1606  if (R.empty()) {
1607    if (AllowMissing || !Diagnose)
1608      return false;
1609    return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
1610      << Name << Range;
1611  }
1612
1613  if (R.isAmbiguous())
1614    return true;
1615
1616  R.suppressDiagnostics();
1617
1618  OverloadCandidateSet Candidates(StartLoc);
1619  for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
1620       Alloc != AllocEnd; ++Alloc) {
1621    // Even member operator new/delete are implicitly treated as
1622    // static, so don't use AddMemberCandidate.
1623    NamedDecl *D = (*Alloc)->getUnderlyingDecl();
1624
1625    if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1626      AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
1627                                   /*ExplicitTemplateArgs=*/0, Args, NumArgs,
1628                                   Candidates,
1629                                   /*SuppressUserConversions=*/false);
1630      continue;
1631    }
1632
1633    FunctionDecl *Fn = cast<FunctionDecl>(D);
1634    AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates,
1635                         /*SuppressUserConversions=*/false);
1636  }
1637
1638  // Do the resolution.
1639  OverloadCandidateSet::iterator Best;
1640  switch (Candidates.BestViableFunction(*this, StartLoc, Best)) {
1641  case OR_Success: {
1642    // Got one!
1643    FunctionDecl *FnDecl = Best->Function;
1644    MarkFunctionReferenced(StartLoc, FnDecl);
1645    // The first argument is size_t, and the first parameter must be size_t,
1646    // too. This is checked on declaration and can be assumed. (It can't be
1647    // asserted on, though, since invalid decls are left in there.)
1648    // Watch out for variadic allocator function.
1649    unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1650    for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
1651      InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1652                                                       FnDecl->getParamDecl(i));
1653
1654      if (!Diagnose && !CanPerformCopyInitialization(Entity, Owned(Args[i])))
1655        return true;
1656
1657      ExprResult Result
1658        = PerformCopyInitialization(Entity, SourceLocation(), Owned(Args[i]));
1659      if (Result.isInvalid())
1660        return true;
1661
1662      Args[i] = Result.takeAs<Expr>();
1663    }
1664    Operator = FnDecl;
1665    CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl,
1666                          Diagnose);
1667    return false;
1668  }
1669
1670  case OR_No_Viable_Function:
1671    if (Diagnose) {
1672      Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
1673        << Name << Range;
1674      Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
1675    }
1676    return true;
1677
1678  case OR_Ambiguous:
1679    if (Diagnose) {
1680      Diag(StartLoc, diag::err_ovl_ambiguous_call)
1681        << Name << Range;
1682      Candidates.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
1683    }
1684    return true;
1685
1686  case OR_Deleted: {
1687    if (Diagnose) {
1688      Diag(StartLoc, diag::err_ovl_deleted_call)
1689        << Best->Function->isDeleted()
1690        << Name
1691        << getDeletedOrUnavailableSuffix(Best->Function)
1692        << Range;
1693      Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
1694    }
1695    return true;
1696  }
1697  }
1698  llvm_unreachable("Unreachable, bad result from BestViableFunction");
1699}
1700
1701
1702/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1703/// delete. These are:
1704/// @code
1705///   // C++03:
1706///   void* operator new(std::size_t) throw(std::bad_alloc);
1707///   void* operator new[](std::size_t) throw(std::bad_alloc);
1708///   void operator delete(void *) throw();
1709///   void operator delete[](void *) throw();
1710///   // C++0x:
1711///   void* operator new(std::size_t);
1712///   void* operator new[](std::size_t);
1713///   void operator delete(void *);
1714///   void operator delete[](void *);
1715/// @endcode
1716/// C++0x operator delete is implicitly noexcept.
1717/// Note that the placement and nothrow forms of new are *not* implicitly
1718/// declared. Their use requires including \<new\>.
1719void Sema::DeclareGlobalNewDelete() {
1720  if (GlobalNewDeleteDeclared)
1721    return;
1722
1723  // C++ [basic.std.dynamic]p2:
1724  //   [...] The following allocation and deallocation functions (18.4) are
1725  //   implicitly declared in global scope in each translation unit of a
1726  //   program
1727  //
1728  //     C++03:
1729  //     void* operator new(std::size_t) throw(std::bad_alloc);
1730  //     void* operator new[](std::size_t) throw(std::bad_alloc);
1731  //     void  operator delete(void*) throw();
1732  //     void  operator delete[](void*) throw();
1733  //     C++0x:
1734  //     void* operator new(std::size_t);
1735  //     void* operator new[](std::size_t);
1736  //     void  operator delete(void*);
1737  //     void  operator delete[](void*);
1738  //
1739  //   These implicit declarations introduce only the function names operator
1740  //   new, operator new[], operator delete, operator delete[].
1741  //
1742  // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1743  // "std" or "bad_alloc" as necessary to form the exception specification.
1744  // However, we do not make these implicit declarations visible to name
1745  // lookup.
1746  // Note that the C++0x versions of operator delete are deallocation functions,
1747  // and thus are implicitly noexcept.
1748  if (!StdBadAlloc && !getLangOptions().CPlusPlus0x) {
1749    // The "std::bad_alloc" class has not yet been declared, so build it
1750    // implicitly.
1751    StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
1752                                        getOrCreateStdNamespace(),
1753                                        SourceLocation(), SourceLocation(),
1754                                      &PP.getIdentifierTable().get("bad_alloc"),
1755                                        0);
1756    getStdBadAlloc()->setImplicit(true);
1757  }
1758
1759  GlobalNewDeleteDeclared = true;
1760
1761  QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1762  QualType SizeT = Context.getSizeType();
1763  bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
1764
1765  DeclareGlobalAllocationFunction(
1766      Context.DeclarationNames.getCXXOperatorName(OO_New),
1767      VoidPtr, SizeT, AssumeSaneOperatorNew);
1768  DeclareGlobalAllocationFunction(
1769      Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
1770      VoidPtr, SizeT, AssumeSaneOperatorNew);
1771  DeclareGlobalAllocationFunction(
1772      Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1773      Context.VoidTy, VoidPtr);
1774  DeclareGlobalAllocationFunction(
1775      Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1776      Context.VoidTy, VoidPtr);
1777}
1778
1779/// DeclareGlobalAllocationFunction - Declares a single implicit global
1780/// allocation function if it doesn't already exist.
1781void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
1782                                           QualType Return, QualType Argument,
1783                                           bool AddMallocAttr) {
1784  DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1785
1786  // Check if this function is already declared.
1787  {
1788    DeclContext::lookup_iterator Alloc, AllocEnd;
1789    for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
1790         Alloc != AllocEnd; ++Alloc) {
1791      // Only look at non-template functions, as it is the predefined,
1792      // non-templated allocation function we are trying to declare here.
1793      if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1794        QualType InitialParamType =
1795          Context.getCanonicalType(
1796            Func->getParamDecl(0)->getType().getUnqualifiedType());
1797        // FIXME: Do we need to check for default arguments here?
1798        if (Func->getNumParams() == 1 && InitialParamType == Argument) {
1799          if(AddMallocAttr && !Func->hasAttr<MallocAttr>())
1800            Func->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
1801          return;
1802        }
1803      }
1804    }
1805  }
1806
1807  QualType BadAllocType;
1808  bool HasBadAllocExceptionSpec
1809    = (Name.getCXXOverloadedOperator() == OO_New ||
1810       Name.getCXXOverloadedOperator() == OO_Array_New);
1811  if (HasBadAllocExceptionSpec && !getLangOptions().CPlusPlus0x) {
1812    assert(StdBadAlloc && "Must have std::bad_alloc declared");
1813    BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
1814  }
1815
1816  FunctionProtoType::ExtProtoInfo EPI;
1817  if (HasBadAllocExceptionSpec) {
1818    if (!getLangOptions().CPlusPlus0x) {
1819      EPI.ExceptionSpecType = EST_Dynamic;
1820      EPI.NumExceptions = 1;
1821      EPI.Exceptions = &BadAllocType;
1822    }
1823  } else {
1824    EPI.ExceptionSpecType = getLangOptions().CPlusPlus0x ?
1825                                EST_BasicNoexcept : EST_DynamicNone;
1826  }
1827
1828  QualType FnType = Context.getFunctionType(Return, &Argument, 1, EPI);
1829  FunctionDecl *Alloc =
1830    FunctionDecl::Create(Context, GlobalCtx, SourceLocation(),
1831                         SourceLocation(), Name,
1832                         FnType, /*TInfo=*/0, SC_None,
1833                         SC_None, false, true);
1834  Alloc->setImplicit();
1835
1836  if (AddMallocAttr)
1837    Alloc->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
1838
1839  ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
1840                                           SourceLocation(), 0,
1841                                           Argument, /*TInfo=*/0,
1842                                           SC_None, SC_None, 0);
1843  Alloc->setParams(Param);
1844
1845  // FIXME: Also add this declaration to the IdentifierResolver, but
1846  // make sure it is at the end of the chain to coincide with the
1847  // global scope.
1848  Context.getTranslationUnitDecl()->addDecl(Alloc);
1849}
1850
1851bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1852                                    DeclarationName Name,
1853                                    FunctionDecl* &Operator, bool Diagnose) {
1854  LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
1855  // Try to find operator delete/operator delete[] in class scope.
1856  LookupQualifiedName(Found, RD);
1857
1858  if (Found.isAmbiguous())
1859    return true;
1860
1861  Found.suppressDiagnostics();
1862
1863  SmallVector<DeclAccessPair,4> Matches;
1864  for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1865       F != FEnd; ++F) {
1866    NamedDecl *ND = (*F)->getUnderlyingDecl();
1867
1868    // Ignore template operator delete members from the check for a usual
1869    // deallocation function.
1870    if (isa<FunctionTemplateDecl>(ND))
1871      continue;
1872
1873    if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction())
1874      Matches.push_back(F.getPair());
1875  }
1876
1877  // There's exactly one suitable operator;  pick it.
1878  if (Matches.size() == 1) {
1879    Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl());
1880
1881    if (Operator->isDeleted()) {
1882      if (Diagnose) {
1883        Diag(StartLoc, diag::err_deleted_function_use);
1884        Diag(Operator->getLocation(), diag::note_unavailable_here)
1885          << /*function*/ 1 << /*deleted*/ 1;
1886      }
1887      return true;
1888    }
1889
1890    CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
1891                          Matches[0], Diagnose);
1892    return false;
1893
1894  // We found multiple suitable operators;  complain about the ambiguity.
1895  } else if (!Matches.empty()) {
1896    if (Diagnose) {
1897      Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
1898        << Name << RD;
1899
1900      for (SmallVectorImpl<DeclAccessPair>::iterator
1901             F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F)
1902        Diag((*F)->getUnderlyingDecl()->getLocation(),
1903             diag::note_member_declared_here) << Name;
1904    }
1905    return true;
1906  }
1907
1908  // We did find operator delete/operator delete[] declarations, but
1909  // none of them were suitable.
1910  if (!Found.empty()) {
1911    if (Diagnose) {
1912      Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1913        << Name << RD;
1914
1915      for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1916           F != FEnd; ++F)
1917        Diag((*F)->getUnderlyingDecl()->getLocation(),
1918             diag::note_member_declared_here) << Name;
1919    }
1920    return true;
1921  }
1922
1923  // Look for a global declaration.
1924  DeclareGlobalNewDelete();
1925  DeclContext *TUDecl = Context.getTranslationUnitDecl();
1926
1927  CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1928  Expr* DeallocArgs[1];
1929  DeallocArgs[0] = &Null;
1930  if (FindAllocationOverload(StartLoc, SourceRange(), Name,
1931                             DeallocArgs, 1, TUDecl, !Diagnose,
1932                             Operator, Diagnose))
1933    return true;
1934
1935  assert(Operator && "Did not find a deallocation function!");
1936  return false;
1937}
1938
1939/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1940/// @code ::delete ptr; @endcode
1941/// or
1942/// @code delete [] ptr; @endcode
1943ExprResult
1944Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
1945                     bool ArrayForm, Expr *ExE) {
1946  // C++ [expr.delete]p1:
1947  //   The operand shall have a pointer type, or a class type having a single
1948  //   conversion function to a pointer type. The result has type void.
1949  //
1950  // DR599 amends "pointer type" to "pointer to object type" in both cases.
1951
1952  ExprResult Ex = Owned(ExE);
1953  FunctionDecl *OperatorDelete = 0;
1954  bool ArrayFormAsWritten = ArrayForm;
1955  bool UsualArrayDeleteWantsSize = false;
1956
1957  if (!Ex.get()->isTypeDependent()) {
1958    QualType Type = Ex.get()->getType();
1959
1960    if (const RecordType *Record = Type->getAs<RecordType>()) {
1961      if (RequireCompleteType(StartLoc, Type,
1962                              PDiag(diag::err_delete_incomplete_class_type)))
1963        return ExprError();
1964
1965      SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
1966
1967      CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1968      const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
1969      for (UnresolvedSetImpl::iterator I = Conversions->begin(),
1970             E = Conversions->end(); I != E; ++I) {
1971        NamedDecl *D = I.getDecl();
1972        if (isa<UsingShadowDecl>(D))
1973          D = cast<UsingShadowDecl>(D)->getTargetDecl();
1974
1975        // Skip over templated conversion functions; they aren't considered.
1976        if (isa<FunctionTemplateDecl>(D))
1977          continue;
1978
1979        CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
1980
1981        QualType ConvType = Conv->getConversionType().getNonReferenceType();
1982        if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
1983          if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
1984            ObjectPtrConversions.push_back(Conv);
1985      }
1986      if (ObjectPtrConversions.size() == 1) {
1987        // We have a single conversion to a pointer-to-object type. Perform
1988        // that conversion.
1989        // TODO: don't redo the conversion calculation.
1990        ExprResult Res =
1991          PerformImplicitConversion(Ex.get(),
1992                            ObjectPtrConversions.front()->getConversionType(),
1993                                    AA_Converting);
1994        if (Res.isUsable()) {
1995          Ex = move(Res);
1996          Type = Ex.get()->getType();
1997        }
1998      }
1999      else if (ObjectPtrConversions.size() > 1) {
2000        Diag(StartLoc, diag::err_ambiguous_delete_operand)
2001              << Type << Ex.get()->getSourceRange();
2002        for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
2003          NoteOverloadCandidate(ObjectPtrConversions[i]);
2004        return ExprError();
2005      }
2006    }
2007
2008    if (!Type->isPointerType())
2009      return ExprError(Diag(StartLoc, diag::err_delete_operand)
2010        << Type << Ex.get()->getSourceRange());
2011
2012    QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
2013    QualType PointeeElem = Context.getBaseElementType(Pointee);
2014
2015    if (unsigned AddressSpace = Pointee.getAddressSpace())
2016      return Diag(Ex.get()->getLocStart(),
2017                  diag::err_address_space_qualified_delete)
2018               << Pointee.getUnqualifiedType() << AddressSpace;
2019
2020    CXXRecordDecl *PointeeRD = 0;
2021    if (Pointee->isVoidType() && !isSFINAEContext()) {
2022      // The C++ standard bans deleting a pointer to a non-object type, which
2023      // effectively bans deletion of "void*". However, most compilers support
2024      // this, so we treat it as a warning unless we're in a SFINAE context.
2025      Diag(StartLoc, diag::ext_delete_void_ptr_operand)
2026        << Type << Ex.get()->getSourceRange();
2027    } else if (Pointee->isFunctionType() || Pointee->isVoidType()) {
2028      return ExprError(Diag(StartLoc, diag::err_delete_operand)
2029        << Type << Ex.get()->getSourceRange());
2030    } else if (!Pointee->isDependentType()) {
2031      if (!RequireCompleteType(StartLoc, Pointee,
2032                               PDiag(diag::warn_delete_incomplete)
2033                                 << Ex.get()->getSourceRange())) {
2034        if (const RecordType *RT = PointeeElem->getAs<RecordType>())
2035          PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
2036      }
2037    }
2038
2039    // Perform lvalue-to-rvalue cast, if needed.
2040    Ex = DefaultLvalueConversion(Ex.take());
2041
2042    // C++ [expr.delete]p2:
2043    //   [Note: a pointer to a const type can be the operand of a
2044    //   delete-expression; it is not necessary to cast away the constness
2045    //   (5.2.11) of the pointer expression before it is used as the operand
2046    //   of the delete-expression. ]
2047    if (!Context.hasSameType(Ex.get()->getType(), Context.VoidPtrTy))
2048      Ex = Owned(ImplicitCastExpr::Create(Context, Context.VoidPtrTy,
2049                                          CK_BitCast, Ex.take(), 0, VK_RValue));
2050
2051    if (Pointee->isArrayType() && !ArrayForm) {
2052      Diag(StartLoc, diag::warn_delete_array_type)
2053          << Type << Ex.get()->getSourceRange()
2054          << FixItHint::CreateInsertion(PP.getLocForEndOfToken(StartLoc), "[]");
2055      ArrayForm = true;
2056    }
2057
2058    DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
2059                                      ArrayForm ? OO_Array_Delete : OO_Delete);
2060
2061    if (PointeeRD) {
2062      if (!UseGlobal &&
2063          FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
2064                                   OperatorDelete))
2065        return ExprError();
2066
2067      // If we're allocating an array of records, check whether the
2068      // usual operator delete[] has a size_t parameter.
2069      if (ArrayForm) {
2070        // If the user specifically asked to use the global allocator,
2071        // we'll need to do the lookup into the class.
2072        if (UseGlobal)
2073          UsualArrayDeleteWantsSize =
2074            doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
2075
2076        // Otherwise, the usual operator delete[] should be the
2077        // function we just found.
2078        else if (isa<CXXMethodDecl>(OperatorDelete))
2079          UsualArrayDeleteWantsSize = (OperatorDelete->getNumParams() == 2);
2080      }
2081
2082      if (!PointeeRD->hasIrrelevantDestructor())
2083        if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
2084          MarkFunctionReferenced(StartLoc,
2085                                    const_cast<CXXDestructorDecl*>(Dtor));
2086          DiagnoseUseOfDecl(Dtor, StartLoc);
2087        }
2088
2089      // C++ [expr.delete]p3:
2090      //   In the first alternative (delete object), if the static type of the
2091      //   object to be deleted is different from its dynamic type, the static
2092      //   type shall be a base class of the dynamic type of the object to be
2093      //   deleted and the static type shall have a virtual destructor or the
2094      //   behavior is undefined.
2095      //
2096      // Note: a final class cannot be derived from, no issue there
2097      if (PointeeRD->isPolymorphic() && !PointeeRD->hasAttr<FinalAttr>()) {
2098        CXXDestructorDecl *dtor = PointeeRD->getDestructor();
2099        if (dtor && !dtor->isVirtual()) {
2100          if (PointeeRD->isAbstract()) {
2101            // If the class is abstract, we warn by default, because we're
2102            // sure the code has undefined behavior.
2103            Diag(StartLoc, diag::warn_delete_abstract_non_virtual_dtor)
2104                << PointeeElem;
2105          } else if (!ArrayForm) {
2106            // Otherwise, if this is not an array delete, it's a bit suspect,
2107            // but not necessarily wrong.
2108            Diag(StartLoc, diag::warn_delete_non_virtual_dtor) << PointeeElem;
2109          }
2110        }
2111      }
2112
2113    } else if (getLangOptions().ObjCAutoRefCount &&
2114               PointeeElem->isObjCLifetimeType() &&
2115               (PointeeElem.getObjCLifetime() == Qualifiers::OCL_Strong ||
2116                PointeeElem.getObjCLifetime() == Qualifiers::OCL_Weak) &&
2117               ArrayForm) {
2118      Diag(StartLoc, diag::warn_err_new_delete_object_array)
2119        << 1 << PointeeElem;
2120    }
2121
2122    if (!OperatorDelete) {
2123      // Look for a global declaration.
2124      DeclareGlobalNewDelete();
2125      DeclContext *TUDecl = Context.getTranslationUnitDecl();
2126      Expr *Arg = Ex.get();
2127      if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
2128                                 &Arg, 1, TUDecl, /*AllowMissing=*/false,
2129                                 OperatorDelete))
2130        return ExprError();
2131    }
2132
2133    MarkFunctionReferenced(StartLoc, OperatorDelete);
2134
2135    // Check access and ambiguity of operator delete and destructor.
2136    if (PointeeRD) {
2137      if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
2138          CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
2139                      PDiag(diag::err_access_dtor) << PointeeElem);
2140      }
2141    }
2142
2143  }
2144
2145  return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
2146                                           ArrayFormAsWritten,
2147                                           UsualArrayDeleteWantsSize,
2148                                           OperatorDelete, Ex.take(), StartLoc));
2149}
2150
2151/// \brief Check the use of the given variable as a C++ condition in an if,
2152/// while, do-while, or switch statement.
2153ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
2154                                        SourceLocation StmtLoc,
2155                                        bool ConvertToBoolean) {
2156  QualType T = ConditionVar->getType();
2157
2158  // C++ [stmt.select]p2:
2159  //   The declarator shall not specify a function or an array.
2160  if (T->isFunctionType())
2161    return ExprError(Diag(ConditionVar->getLocation(),
2162                          diag::err_invalid_use_of_function_type)
2163                       << ConditionVar->getSourceRange());
2164  else if (T->isArrayType())
2165    return ExprError(Diag(ConditionVar->getLocation(),
2166                          diag::err_invalid_use_of_array_type)
2167                     << ConditionVar->getSourceRange());
2168
2169  ExprResult Condition =
2170    Owned(DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
2171                              SourceLocation(),
2172                              ConditionVar,
2173                              ConditionVar->getLocation(),
2174                              ConditionVar->getType().getNonReferenceType(),
2175                              VK_LValue));
2176
2177  MarkDeclRefReferenced(cast<DeclRefExpr>(Condition.get()));
2178
2179  if (ConvertToBoolean) {
2180    Condition = CheckBooleanCondition(Condition.take(), StmtLoc);
2181    if (Condition.isInvalid())
2182      return ExprError();
2183  }
2184
2185  return move(Condition);
2186}
2187
2188/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
2189ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr) {
2190  // C++ 6.4p4:
2191  // The value of a condition that is an initialized declaration in a statement
2192  // other than a switch statement is the value of the declared variable
2193  // implicitly converted to type bool. If that conversion is ill-formed, the
2194  // program is ill-formed.
2195  // The value of a condition that is an expression is the value of the
2196  // expression, implicitly converted to bool.
2197  //
2198  return PerformContextuallyConvertToBool(CondExpr);
2199}
2200
2201/// Helper function to determine whether this is the (deprecated) C++
2202/// conversion from a string literal to a pointer to non-const char or
2203/// non-const wchar_t (for narrow and wide string literals,
2204/// respectively).
2205bool
2206Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
2207  // Look inside the implicit cast, if it exists.
2208  if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
2209    From = Cast->getSubExpr();
2210
2211  // A string literal (2.13.4) that is not a wide string literal can
2212  // be converted to an rvalue of type "pointer to char"; a wide
2213  // string literal can be converted to an rvalue of type "pointer
2214  // to wchar_t" (C++ 4.2p2).
2215  if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
2216    if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
2217      if (const BuiltinType *ToPointeeType
2218          = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
2219        // This conversion is considered only when there is an
2220        // explicit appropriate pointer target type (C++ 4.2p2).
2221        if (!ToPtrType->getPointeeType().hasQualifiers()) {
2222          switch (StrLit->getKind()) {
2223            case StringLiteral::UTF8:
2224            case StringLiteral::UTF16:
2225            case StringLiteral::UTF32:
2226              // We don't allow UTF literals to be implicitly converted
2227              break;
2228            case StringLiteral::Ascii:
2229              return (ToPointeeType->getKind() == BuiltinType::Char_U ||
2230                      ToPointeeType->getKind() == BuiltinType::Char_S);
2231            case StringLiteral::Wide:
2232              return ToPointeeType->isWideCharType();
2233          }
2234        }
2235      }
2236
2237  return false;
2238}
2239
2240static ExprResult BuildCXXCastArgument(Sema &S,
2241                                       SourceLocation CastLoc,
2242                                       QualType Ty,
2243                                       CastKind Kind,
2244                                       CXXMethodDecl *Method,
2245                                       DeclAccessPair FoundDecl,
2246                                       bool HadMultipleCandidates,
2247                                       Expr *From) {
2248  switch (Kind) {
2249  default: llvm_unreachable("Unhandled cast kind!");
2250  case CK_ConstructorConversion: {
2251    CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
2252    ASTOwningVector<Expr*> ConstructorArgs(S);
2253
2254    if (S.CompleteConstructorCall(Constructor,
2255                                  MultiExprArg(&From, 1),
2256                                  CastLoc, ConstructorArgs))
2257      return ExprError();
2258
2259    S.CheckConstructorAccess(CastLoc, Constructor, Constructor->getAccess(),
2260                             S.PDiag(diag::err_access_ctor));
2261
2262    ExprResult Result
2263      = S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
2264                                move_arg(ConstructorArgs),
2265                                HadMultipleCandidates, /*ZeroInit*/ false,
2266                                CXXConstructExpr::CK_Complete, SourceRange());
2267    if (Result.isInvalid())
2268      return ExprError();
2269
2270    return S.MaybeBindToTemporary(Result.takeAs<Expr>());
2271  }
2272
2273  case CK_UserDefinedConversion: {
2274    assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
2275
2276    // Create an implicit call expr that calls it.
2277    ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Method,
2278                                                 HadMultipleCandidates);
2279    if (Result.isInvalid())
2280      return ExprError();
2281    // Record usage of conversion in an implicit cast.
2282    Result = S.Owned(ImplicitCastExpr::Create(S.Context,
2283                                              Result.get()->getType(),
2284                                              CK_UserDefinedConversion,
2285                                              Result.get(), 0,
2286                                              Result.get()->getValueKind()));
2287
2288    S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ 0, FoundDecl);
2289
2290    return S.MaybeBindToTemporary(Result.get());
2291  }
2292  }
2293}
2294
2295/// PerformImplicitConversion - Perform an implicit conversion of the
2296/// expression From to the type ToType using the pre-computed implicit
2297/// conversion sequence ICS. Returns the converted
2298/// expression. Action is the kind of conversion we're performing,
2299/// used in the error message.
2300ExprResult
2301Sema::PerformImplicitConversion(Expr *From, QualType ToType,
2302                                const ImplicitConversionSequence &ICS,
2303                                AssignmentAction Action,
2304                                CheckedConversionKind CCK) {
2305  switch (ICS.getKind()) {
2306  case ImplicitConversionSequence::StandardConversion: {
2307    ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
2308                                               Action, CCK);
2309    if (Res.isInvalid())
2310      return ExprError();
2311    From = Res.take();
2312    break;
2313  }
2314
2315  case ImplicitConversionSequence::UserDefinedConversion: {
2316
2317      FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
2318      CastKind CastKind;
2319      QualType BeforeToType;
2320      assert(FD && "FIXME: aggregate initialization from init list");
2321      if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
2322        CastKind = CK_UserDefinedConversion;
2323
2324        // If the user-defined conversion is specified by a conversion function,
2325        // the initial standard conversion sequence converts the source type to
2326        // the implicit object parameter of the conversion function.
2327        BeforeToType = Context.getTagDeclType(Conv->getParent());
2328      } else {
2329        const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
2330        CastKind = CK_ConstructorConversion;
2331        // Do no conversion if dealing with ... for the first conversion.
2332        if (!ICS.UserDefined.EllipsisConversion) {
2333          // If the user-defined conversion is specified by a constructor, the
2334          // initial standard conversion sequence converts the source type to the
2335          // type required by the argument of the constructor
2336          BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
2337        }
2338      }
2339      // Watch out for elipsis conversion.
2340      if (!ICS.UserDefined.EllipsisConversion) {
2341        ExprResult Res =
2342          PerformImplicitConversion(From, BeforeToType,
2343                                    ICS.UserDefined.Before, AA_Converting,
2344                                    CCK);
2345        if (Res.isInvalid())
2346          return ExprError();
2347        From = Res.take();
2348      }
2349
2350      ExprResult CastArg
2351        = BuildCXXCastArgument(*this,
2352                               From->getLocStart(),
2353                               ToType.getNonReferenceType(),
2354                               CastKind, cast<CXXMethodDecl>(FD),
2355                               ICS.UserDefined.FoundConversionFunction,
2356                               ICS.UserDefined.HadMultipleCandidates,
2357                               From);
2358
2359      if (CastArg.isInvalid())
2360        return ExprError();
2361
2362      From = CastArg.take();
2363
2364      return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
2365                                       AA_Converting, CCK);
2366  }
2367
2368  case ImplicitConversionSequence::AmbiguousConversion:
2369    ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
2370                          PDiag(diag::err_typecheck_ambiguous_condition)
2371                            << From->getSourceRange());
2372     return ExprError();
2373
2374  case ImplicitConversionSequence::EllipsisConversion:
2375    llvm_unreachable("Cannot perform an ellipsis conversion");
2376
2377  case ImplicitConversionSequence::BadConversion:
2378    return ExprError();
2379  }
2380
2381  // Everything went well.
2382  return Owned(From);
2383}
2384
2385/// PerformImplicitConversion - Perform an implicit conversion of the
2386/// expression From to the type ToType by following the standard
2387/// conversion sequence SCS. Returns the converted
2388/// expression. Flavor is the context in which we're performing this
2389/// conversion, for use in error messages.
2390ExprResult
2391Sema::PerformImplicitConversion(Expr *From, QualType ToType,
2392                                const StandardConversionSequence& SCS,
2393                                AssignmentAction Action,
2394                                CheckedConversionKind CCK) {
2395  bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
2396
2397  // Overall FIXME: we are recomputing too many types here and doing far too
2398  // much extra work. What this means is that we need to keep track of more
2399  // information that is computed when we try the implicit conversion initially,
2400  // so that we don't need to recompute anything here.
2401  QualType FromType = From->getType();
2402
2403  if (SCS.CopyConstructor) {
2404    // FIXME: When can ToType be a reference type?
2405    assert(!ToType->isReferenceType());
2406    if (SCS.Second == ICK_Derived_To_Base) {
2407      ASTOwningVector<Expr*> ConstructorArgs(*this);
2408      if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
2409                                  MultiExprArg(*this, &From, 1),
2410                                  /*FIXME:ConstructLoc*/SourceLocation(),
2411                                  ConstructorArgs))
2412        return ExprError();
2413      return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2414                                   ToType, SCS.CopyConstructor,
2415                                   move_arg(ConstructorArgs),
2416                                   /*HadMultipleCandidates*/ false,
2417                                   /*ZeroInit*/ false,
2418                                   CXXConstructExpr::CK_Complete,
2419                                   SourceRange());
2420    }
2421    return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2422                                 ToType, SCS.CopyConstructor,
2423                                 MultiExprArg(*this, &From, 1),
2424                                 /*HadMultipleCandidates*/ false,
2425                                 /*ZeroInit*/ false,
2426                                 CXXConstructExpr::CK_Complete,
2427                                 SourceRange());
2428  }
2429
2430  // Resolve overloaded function references.
2431  if (Context.hasSameType(FromType, Context.OverloadTy)) {
2432    DeclAccessPair Found;
2433    FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
2434                                                          true, Found);
2435    if (!Fn)
2436      return ExprError();
2437
2438    if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
2439      return ExprError();
2440
2441    From = FixOverloadedFunctionReference(From, Found, Fn);
2442    FromType = From->getType();
2443  }
2444
2445  // Perform the first implicit conversion.
2446  switch (SCS.First) {
2447  case ICK_Identity:
2448    // Nothing to do.
2449    break;
2450
2451  case ICK_Lvalue_To_Rvalue: {
2452    assert(From->getObjectKind() != OK_ObjCProperty);
2453    FromType = FromType.getUnqualifiedType();
2454    ExprResult FromRes = DefaultLvalueConversion(From);
2455    assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!");
2456    From = FromRes.take();
2457    break;
2458  }
2459
2460  case ICK_Array_To_Pointer:
2461    FromType = Context.getArrayDecayedType(FromType);
2462    From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
2463                             VK_RValue, /*BasePath=*/0, CCK).take();
2464    break;
2465
2466  case ICK_Function_To_Pointer:
2467    FromType = Context.getPointerType(FromType);
2468    From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
2469                             VK_RValue, /*BasePath=*/0, CCK).take();
2470    break;
2471
2472  default:
2473    llvm_unreachable("Improper first standard conversion");
2474  }
2475
2476  // Perform the second implicit conversion
2477  switch (SCS.Second) {
2478  case ICK_Identity:
2479    // If both sides are functions (or pointers/references to them), there could
2480    // be incompatible exception declarations.
2481    if (CheckExceptionSpecCompatibility(From, ToType))
2482      return ExprError();
2483    // Nothing else to do.
2484    break;
2485
2486  case ICK_NoReturn_Adjustment:
2487    // If both sides are functions (or pointers/references to them), there could
2488    // be incompatible exception declarations.
2489    if (CheckExceptionSpecCompatibility(From, ToType))
2490      return ExprError();
2491
2492    From = ImpCastExprToType(From, ToType, CK_NoOp,
2493                             VK_RValue, /*BasePath=*/0, CCK).take();
2494    break;
2495
2496  case ICK_Integral_Promotion:
2497  case ICK_Integral_Conversion:
2498    From = ImpCastExprToType(From, ToType, CK_IntegralCast,
2499                             VK_RValue, /*BasePath=*/0, CCK).take();
2500    break;
2501
2502  case ICK_Floating_Promotion:
2503  case ICK_Floating_Conversion:
2504    From = ImpCastExprToType(From, ToType, CK_FloatingCast,
2505                             VK_RValue, /*BasePath=*/0, CCK).take();
2506    break;
2507
2508  case ICK_Complex_Promotion:
2509  case ICK_Complex_Conversion: {
2510    QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
2511    QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
2512    CastKind CK;
2513    if (FromEl->isRealFloatingType()) {
2514      if (ToEl->isRealFloatingType())
2515        CK = CK_FloatingComplexCast;
2516      else
2517        CK = CK_FloatingComplexToIntegralComplex;
2518    } else if (ToEl->isRealFloatingType()) {
2519      CK = CK_IntegralComplexToFloatingComplex;
2520    } else {
2521      CK = CK_IntegralComplexCast;
2522    }
2523    From = ImpCastExprToType(From, ToType, CK,
2524                             VK_RValue, /*BasePath=*/0, CCK).take();
2525    break;
2526  }
2527
2528  case ICK_Floating_Integral:
2529    if (ToType->isRealFloatingType())
2530      From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
2531                               VK_RValue, /*BasePath=*/0, CCK).take();
2532    else
2533      From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
2534                               VK_RValue, /*BasePath=*/0, CCK).take();
2535    break;
2536
2537  case ICK_Compatible_Conversion:
2538      From = ImpCastExprToType(From, ToType, CK_NoOp,
2539                               VK_RValue, /*BasePath=*/0, CCK).take();
2540    break;
2541
2542  case ICK_Writeback_Conversion:
2543  case ICK_Pointer_Conversion: {
2544    if (SCS.IncompatibleObjC && Action != AA_Casting) {
2545      // Diagnose incompatible Objective-C conversions
2546      if (Action == AA_Initializing || Action == AA_Assigning)
2547        Diag(From->getSourceRange().getBegin(),
2548             diag::ext_typecheck_convert_incompatible_pointer)
2549          << ToType << From->getType() << Action
2550          << From->getSourceRange() << 0;
2551      else
2552        Diag(From->getSourceRange().getBegin(),
2553             diag::ext_typecheck_convert_incompatible_pointer)
2554          << From->getType() << ToType << Action
2555          << From->getSourceRange() << 0;
2556
2557      if (From->getType()->isObjCObjectPointerType() &&
2558          ToType->isObjCObjectPointerType())
2559        EmitRelatedResultTypeNote(From);
2560    }
2561    else if (getLangOptions().ObjCAutoRefCount &&
2562             !CheckObjCARCUnavailableWeakConversion(ToType,
2563                                                    From->getType())) {
2564      if (Action == AA_Initializing)
2565        Diag(From->getSourceRange().getBegin(),
2566             diag::err_arc_weak_unavailable_assign);
2567      else
2568        Diag(From->getSourceRange().getBegin(),
2569             diag::err_arc_convesion_of_weak_unavailable)
2570          << (Action == AA_Casting) << From->getType() << ToType
2571          << From->getSourceRange();
2572    }
2573
2574    CastKind Kind = CK_Invalid;
2575    CXXCastPath BasePath;
2576    if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
2577      return ExprError();
2578
2579    // Make sure we extend blocks if necessary.
2580    // FIXME: doing this here is really ugly.
2581    if (Kind == CK_BlockPointerToObjCPointerCast) {
2582      ExprResult E = From;
2583      (void) PrepareCastToObjCObjectPointer(E);
2584      From = E.take();
2585    }
2586
2587    From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
2588             .take();
2589    break;
2590  }
2591
2592  case ICK_Pointer_Member: {
2593    CastKind Kind = CK_Invalid;
2594    CXXCastPath BasePath;
2595    if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
2596      return ExprError();
2597    if (CheckExceptionSpecCompatibility(From, ToType))
2598      return ExprError();
2599    From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
2600             .take();
2601    break;
2602  }
2603
2604  case ICK_Boolean_Conversion:
2605    // Perform half-to-boolean conversion via float.
2606    if (From->getType()->isHalfType()) {
2607      From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).take();
2608      FromType = Context.FloatTy;
2609    }
2610
2611    From = ImpCastExprToType(From, Context.BoolTy,
2612                             ScalarTypeToBooleanCastKind(FromType),
2613                             VK_RValue, /*BasePath=*/0, CCK).take();
2614    break;
2615
2616  case ICK_Derived_To_Base: {
2617    CXXCastPath BasePath;
2618    if (CheckDerivedToBaseConversion(From->getType(),
2619                                     ToType.getNonReferenceType(),
2620                                     From->getLocStart(),
2621                                     From->getSourceRange(),
2622                                     &BasePath,
2623                                     CStyle))
2624      return ExprError();
2625
2626    From = ImpCastExprToType(From, ToType.getNonReferenceType(),
2627                      CK_DerivedToBase, From->getValueKind(),
2628                      &BasePath, CCK).take();
2629    break;
2630  }
2631
2632  case ICK_Vector_Conversion:
2633    From = ImpCastExprToType(From, ToType, CK_BitCast,
2634                             VK_RValue, /*BasePath=*/0, CCK).take();
2635    break;
2636
2637  case ICK_Vector_Splat:
2638    From = ImpCastExprToType(From, ToType, CK_VectorSplat,
2639                             VK_RValue, /*BasePath=*/0, CCK).take();
2640    break;
2641
2642  case ICK_Complex_Real:
2643    // Case 1.  x -> _Complex y
2644    if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
2645      QualType ElType = ToComplex->getElementType();
2646      bool isFloatingComplex = ElType->isRealFloatingType();
2647
2648      // x -> y
2649      if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
2650        // do nothing
2651      } else if (From->getType()->isRealFloatingType()) {
2652        From = ImpCastExprToType(From, ElType,
2653                isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).take();
2654      } else {
2655        assert(From->getType()->isIntegerType());
2656        From = ImpCastExprToType(From, ElType,
2657                isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).take();
2658      }
2659      // y -> _Complex y
2660      From = ImpCastExprToType(From, ToType,
2661                   isFloatingComplex ? CK_FloatingRealToComplex
2662                                     : CK_IntegralRealToComplex).take();
2663
2664    // Case 2.  _Complex x -> y
2665    } else {
2666      const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
2667      assert(FromComplex);
2668
2669      QualType ElType = FromComplex->getElementType();
2670      bool isFloatingComplex = ElType->isRealFloatingType();
2671
2672      // _Complex x -> x
2673      From = ImpCastExprToType(From, ElType,
2674                   isFloatingComplex ? CK_FloatingComplexToReal
2675                                     : CK_IntegralComplexToReal,
2676                               VK_RValue, /*BasePath=*/0, CCK).take();
2677
2678      // x -> y
2679      if (Context.hasSameUnqualifiedType(ElType, ToType)) {
2680        // do nothing
2681      } else if (ToType->isRealFloatingType()) {
2682        From = ImpCastExprToType(From, ToType,
2683                   isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating,
2684                                 VK_RValue, /*BasePath=*/0, CCK).take();
2685      } else {
2686        assert(ToType->isIntegerType());
2687        From = ImpCastExprToType(From, ToType,
2688                   isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
2689                                 VK_RValue, /*BasePath=*/0, CCK).take();
2690      }
2691    }
2692    break;
2693
2694  case ICK_Block_Pointer_Conversion: {
2695    From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast,
2696                             VK_RValue, /*BasePath=*/0, CCK).take();
2697    break;
2698  }
2699
2700  case ICK_TransparentUnionConversion: {
2701    ExprResult FromRes = Owned(From);
2702    Sema::AssignConvertType ConvTy =
2703      CheckTransparentUnionArgumentConstraints(ToType, FromRes);
2704    if (FromRes.isInvalid())
2705      return ExprError();
2706    From = FromRes.take();
2707    assert ((ConvTy == Sema::Compatible) &&
2708            "Improper transparent union conversion");
2709    (void)ConvTy;
2710    break;
2711  }
2712
2713  case ICK_Lvalue_To_Rvalue:
2714  case ICK_Array_To_Pointer:
2715  case ICK_Function_To_Pointer:
2716  case ICK_Qualification:
2717  case ICK_Num_Conversion_Kinds:
2718    llvm_unreachable("Improper second standard conversion");
2719  }
2720
2721  switch (SCS.Third) {
2722  case ICK_Identity:
2723    // Nothing to do.
2724    break;
2725
2726  case ICK_Qualification: {
2727    // The qualification keeps the category of the inner expression, unless the
2728    // target type isn't a reference.
2729    ExprValueKind VK = ToType->isReferenceType() ?
2730                                  From->getValueKind() : VK_RValue;
2731    From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
2732                             CK_NoOp, VK, /*BasePath=*/0, CCK).take();
2733
2734    if (SCS.DeprecatedStringLiteralToCharPtr &&
2735        !getLangOptions().WritableStrings)
2736      Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
2737        << ToType.getNonReferenceType();
2738
2739    break;
2740    }
2741
2742  default:
2743    llvm_unreachable("Improper third standard conversion");
2744  }
2745
2746  return Owned(From);
2747}
2748
2749ExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait UTT,
2750                                     SourceLocation KWLoc,
2751                                     ParsedType Ty,
2752                                     SourceLocation RParen) {
2753  TypeSourceInfo *TSInfo;
2754  QualType T = GetTypeFromParser(Ty, &TSInfo);
2755
2756  if (!TSInfo)
2757    TSInfo = Context.getTrivialTypeSourceInfo(T);
2758  return BuildUnaryTypeTrait(UTT, KWLoc, TSInfo, RParen);
2759}
2760
2761/// \brief Check the completeness of a type in a unary type trait.
2762///
2763/// If the particular type trait requires a complete type, tries to complete
2764/// it. If completing the type fails, a diagnostic is emitted and false
2765/// returned. If completing the type succeeds or no completion was required,
2766/// returns true.
2767static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S,
2768                                                UnaryTypeTrait UTT,
2769                                                SourceLocation Loc,
2770                                                QualType ArgTy) {
2771  // C++0x [meta.unary.prop]p3:
2772  //   For all of the class templates X declared in this Clause, instantiating
2773  //   that template with a template argument that is a class template
2774  //   specialization may result in the implicit instantiation of the template
2775  //   argument if and only if the semantics of X require that the argument
2776  //   must be a complete type.
2777  // We apply this rule to all the type trait expressions used to implement
2778  // these class templates. We also try to follow any GCC documented behavior
2779  // in these expressions to ensure portability of standard libraries.
2780  switch (UTT) {
2781    // is_complete_type somewhat obviously cannot require a complete type.
2782  case UTT_IsCompleteType:
2783    // Fall-through
2784
2785    // These traits are modeled on the type predicates in C++0x
2786    // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
2787    // requiring a complete type, as whether or not they return true cannot be
2788    // impacted by the completeness of the type.
2789  case UTT_IsVoid:
2790  case UTT_IsIntegral:
2791  case UTT_IsFloatingPoint:
2792  case UTT_IsArray:
2793  case UTT_IsPointer:
2794  case UTT_IsLvalueReference:
2795  case UTT_IsRvalueReference:
2796  case UTT_IsMemberFunctionPointer:
2797  case UTT_IsMemberObjectPointer:
2798  case UTT_IsEnum:
2799  case UTT_IsUnion:
2800  case UTT_IsClass:
2801  case UTT_IsFunction:
2802  case UTT_IsReference:
2803  case UTT_IsArithmetic:
2804  case UTT_IsFundamental:
2805  case UTT_IsObject:
2806  case UTT_IsScalar:
2807  case UTT_IsCompound:
2808  case UTT_IsMemberPointer:
2809    // Fall-through
2810
2811    // These traits are modeled on type predicates in C++0x [meta.unary.prop]
2812    // which requires some of its traits to have the complete type. However,
2813    // the completeness of the type cannot impact these traits' semantics, and
2814    // so they don't require it. This matches the comments on these traits in
2815    // Table 49.
2816  case UTT_IsConst:
2817  case UTT_IsVolatile:
2818  case UTT_IsSigned:
2819  case UTT_IsUnsigned:
2820    return true;
2821
2822    // C++0x [meta.unary.prop] Table 49 requires the following traits to be
2823    // applied to a complete type.
2824  case UTT_IsTrivial:
2825  case UTT_IsTriviallyCopyable:
2826  case UTT_IsStandardLayout:
2827  case UTT_IsPOD:
2828  case UTT_IsLiteral:
2829  case UTT_IsEmpty:
2830  case UTT_IsPolymorphic:
2831  case UTT_IsAbstract:
2832    // Fall-through
2833
2834  // These traits require a complete type.
2835  case UTT_IsFinal:
2836
2837    // These trait expressions are designed to help implement predicates in
2838    // [meta.unary.prop] despite not being named the same. They are specified
2839    // by both GCC and the Embarcadero C++ compiler, and require the complete
2840    // type due to the overarching C++0x type predicates being implemented
2841    // requiring the complete type.
2842  case UTT_HasNothrowAssign:
2843  case UTT_HasNothrowConstructor:
2844  case UTT_HasNothrowCopy:
2845  case UTT_HasTrivialAssign:
2846  case UTT_HasTrivialDefaultConstructor:
2847  case UTT_HasTrivialCopy:
2848  case UTT_HasTrivialDestructor:
2849  case UTT_HasVirtualDestructor:
2850    // Arrays of unknown bound are expressly allowed.
2851    QualType ElTy = ArgTy;
2852    if (ArgTy->isIncompleteArrayType())
2853      ElTy = S.Context.getAsArrayType(ArgTy)->getElementType();
2854
2855    // The void type is expressly allowed.
2856    if (ElTy->isVoidType())
2857      return true;
2858
2859    return !S.RequireCompleteType(
2860      Loc, ElTy, diag::err_incomplete_type_used_in_type_trait_expr);
2861  }
2862  llvm_unreachable("Type trait not handled by switch");
2863}
2864
2865static bool EvaluateUnaryTypeTrait(Sema &Self, UnaryTypeTrait UTT,
2866                                   SourceLocation KeyLoc, QualType T) {
2867  assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
2868
2869  ASTContext &C = Self.Context;
2870  switch(UTT) {
2871    // Type trait expressions corresponding to the primary type category
2872    // predicates in C++0x [meta.unary.cat].
2873  case UTT_IsVoid:
2874    return T->isVoidType();
2875  case UTT_IsIntegral:
2876    return T->isIntegralType(C);
2877  case UTT_IsFloatingPoint:
2878    return T->isFloatingType();
2879  case UTT_IsArray:
2880    return T->isArrayType();
2881  case UTT_IsPointer:
2882    return T->isPointerType();
2883  case UTT_IsLvalueReference:
2884    return T->isLValueReferenceType();
2885  case UTT_IsRvalueReference:
2886    return T->isRValueReferenceType();
2887  case UTT_IsMemberFunctionPointer:
2888    return T->isMemberFunctionPointerType();
2889  case UTT_IsMemberObjectPointer:
2890    return T->isMemberDataPointerType();
2891  case UTT_IsEnum:
2892    return T->isEnumeralType();
2893  case UTT_IsUnion:
2894    return T->isUnionType();
2895  case UTT_IsClass:
2896    return T->isClassType() || T->isStructureType();
2897  case UTT_IsFunction:
2898    return T->isFunctionType();
2899
2900    // Type trait expressions which correspond to the convenient composition
2901    // predicates in C++0x [meta.unary.comp].
2902  case UTT_IsReference:
2903    return T->isReferenceType();
2904  case UTT_IsArithmetic:
2905    return T->isArithmeticType() && !T->isEnumeralType();
2906  case UTT_IsFundamental:
2907    return T->isFundamentalType();
2908  case UTT_IsObject:
2909    return T->isObjectType();
2910  case UTT_IsScalar:
2911    // Note: semantic analysis depends on Objective-C lifetime types to be
2912    // considered scalar types. However, such types do not actually behave
2913    // like scalar types at run time (since they may require retain/release
2914    // operations), so we report them as non-scalar.
2915    if (T->isObjCLifetimeType()) {
2916      switch (T.getObjCLifetime()) {
2917      case Qualifiers::OCL_None:
2918      case Qualifiers::OCL_ExplicitNone:
2919        return true;
2920
2921      case Qualifiers::OCL_Strong:
2922      case Qualifiers::OCL_Weak:
2923      case Qualifiers::OCL_Autoreleasing:
2924        return false;
2925      }
2926    }
2927
2928    return T->isScalarType();
2929  case UTT_IsCompound:
2930    return T->isCompoundType();
2931  case UTT_IsMemberPointer:
2932    return T->isMemberPointerType();
2933
2934    // Type trait expressions which correspond to the type property predicates
2935    // in C++0x [meta.unary.prop].
2936  case UTT_IsConst:
2937    return T.isConstQualified();
2938  case UTT_IsVolatile:
2939    return T.isVolatileQualified();
2940  case UTT_IsTrivial:
2941    return T.isTrivialType(Self.Context);
2942  case UTT_IsTriviallyCopyable:
2943    return T.isTriviallyCopyableType(Self.Context);
2944  case UTT_IsStandardLayout:
2945    return T->isStandardLayoutType();
2946  case UTT_IsPOD:
2947    return T.isPODType(Self.Context);
2948  case UTT_IsLiteral:
2949    return T->isLiteralType();
2950  case UTT_IsEmpty:
2951    if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2952      return !RD->isUnion() && RD->isEmpty();
2953    return false;
2954  case UTT_IsPolymorphic:
2955    if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2956      return RD->isPolymorphic();
2957    return false;
2958  case UTT_IsAbstract:
2959    if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2960      return RD->isAbstract();
2961    return false;
2962  case UTT_IsFinal:
2963    if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2964      return RD->hasAttr<FinalAttr>();
2965    return false;
2966  case UTT_IsSigned:
2967    return T->isSignedIntegerType();
2968  case UTT_IsUnsigned:
2969    return T->isUnsignedIntegerType();
2970
2971    // Type trait expressions which query classes regarding their construction,
2972    // destruction, and copying. Rather than being based directly on the
2973    // related type predicates in the standard, they are specified by both
2974    // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
2975    // specifications.
2976    //
2977    //   1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
2978    //   2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
2979  case UTT_HasTrivialDefaultConstructor:
2980    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2981    //   If __is_pod (type) is true then the trait is true, else if type is
2982    //   a cv class or union type (or array thereof) with a trivial default
2983    //   constructor ([class.ctor]) then the trait is true, else it is false.
2984    if (T.isPODType(Self.Context))
2985      return true;
2986    if (const RecordType *RT =
2987          C.getBaseElementType(T)->getAs<RecordType>())
2988      return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDefaultConstructor();
2989    return false;
2990  case UTT_HasTrivialCopy:
2991    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2992    //   If __is_pod (type) is true or type is a reference type then
2993    //   the trait is true, else if type is a cv class or union type
2994    //   with a trivial copy constructor ([class.copy]) then the trait
2995    //   is true, else it is false.
2996    if (T.isPODType(Self.Context) || T->isReferenceType())
2997      return true;
2998    if (const RecordType *RT = T->getAs<RecordType>())
2999      return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyConstructor();
3000    return false;
3001  case UTT_HasTrivialAssign:
3002    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3003    //   If type is const qualified or is a reference type then the
3004    //   trait is false. Otherwise if __is_pod (type) is true then the
3005    //   trait is true, else if type is a cv class or union type with
3006    //   a trivial copy assignment ([class.copy]) then the trait is
3007    //   true, else it is false.
3008    // Note: the const and reference restrictions are interesting,
3009    // given that const and reference members don't prevent a class
3010    // from having a trivial copy assignment operator (but do cause
3011    // errors if the copy assignment operator is actually used, q.v.
3012    // [class.copy]p12).
3013
3014    if (C.getBaseElementType(T).isConstQualified())
3015      return false;
3016    if (T.isPODType(Self.Context))
3017      return true;
3018    if (const RecordType *RT = T->getAs<RecordType>())
3019      return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyAssignment();
3020    return false;
3021  case UTT_HasTrivialDestructor:
3022    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3023    //   If __is_pod (type) is true or type is a reference type
3024    //   then the trait is true, else if type is a cv class or union
3025    //   type (or array thereof) with a trivial destructor
3026    //   ([class.dtor]) then the trait is true, else it is
3027    //   false.
3028    if (T.isPODType(Self.Context) || T->isReferenceType())
3029      return true;
3030
3031    // Objective-C++ ARC: autorelease types don't require destruction.
3032    if (T->isObjCLifetimeType() &&
3033        T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
3034      return true;
3035
3036    if (const RecordType *RT =
3037          C.getBaseElementType(T)->getAs<RecordType>())
3038      return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDestructor();
3039    return false;
3040  // TODO: Propagate nothrowness for implicitly declared special members.
3041  case UTT_HasNothrowAssign:
3042    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3043    //   If type is const qualified or is a reference type then the
3044    //   trait is false. Otherwise if __has_trivial_assign (type)
3045    //   is true then the trait is true, else if type is a cv class
3046    //   or union type with copy assignment operators that are known
3047    //   not to throw an exception then the trait is true, else it is
3048    //   false.
3049    if (C.getBaseElementType(T).isConstQualified())
3050      return false;
3051    if (T->isReferenceType())
3052      return false;
3053    if (T.isPODType(Self.Context) || T->isObjCLifetimeType())
3054      return true;
3055    if (const RecordType *RT = T->getAs<RecordType>()) {
3056      CXXRecordDecl* RD = cast<CXXRecordDecl>(RT->getDecl());
3057      if (RD->hasTrivialCopyAssignment())
3058        return true;
3059
3060      bool FoundAssign = false;
3061      DeclarationName Name = C.DeclarationNames.getCXXOperatorName(OO_Equal);
3062      LookupResult Res(Self, DeclarationNameInfo(Name, KeyLoc),
3063                       Sema::LookupOrdinaryName);
3064      if (Self.LookupQualifiedName(Res, RD)) {
3065        Res.suppressDiagnostics();
3066        for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
3067             Op != OpEnd; ++Op) {
3068          if (isa<FunctionTemplateDecl>(*Op))
3069            continue;
3070
3071          CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
3072          if (Operator->isCopyAssignmentOperator()) {
3073            FoundAssign = true;
3074            const FunctionProtoType *CPT
3075                = Operator->getType()->getAs<FunctionProtoType>();
3076            if (CPT->getExceptionSpecType() == EST_Delayed)
3077              return false;
3078            if (!CPT->isNothrow(Self.Context))
3079              return false;
3080          }
3081        }
3082      }
3083
3084      return FoundAssign;
3085    }
3086    return false;
3087  case UTT_HasNothrowCopy:
3088    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3089    //   If __has_trivial_copy (type) is true then the trait is true, else
3090    //   if type is a cv class or union type with copy constructors that are
3091    //   known not to throw an exception then the trait is true, else it is
3092    //   false.
3093    if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
3094      return true;
3095    if (const RecordType *RT = T->getAs<RecordType>()) {
3096      CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3097      if (RD->hasTrivialCopyConstructor())
3098        return true;
3099
3100      bool FoundConstructor = false;
3101      unsigned FoundTQs;
3102      DeclContext::lookup_const_iterator Con, ConEnd;
3103      for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
3104           Con != ConEnd; ++Con) {
3105        // A template constructor is never a copy constructor.
3106        // FIXME: However, it may actually be selected at the actual overload
3107        // resolution point.
3108        if (isa<FunctionTemplateDecl>(*Con))
3109          continue;
3110        CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
3111        if (Constructor->isCopyConstructor(FoundTQs)) {
3112          FoundConstructor = true;
3113          const FunctionProtoType *CPT
3114              = Constructor->getType()->getAs<FunctionProtoType>();
3115          if (CPT->getExceptionSpecType() == EST_Delayed)
3116            return false;
3117          // FIXME: check whether evaluating default arguments can throw.
3118          // For now, we'll be conservative and assume that they can throw.
3119          if (!CPT->isNothrow(Self.Context) || CPT->getNumArgs() > 1)
3120            return false;
3121        }
3122      }
3123
3124      return FoundConstructor;
3125    }
3126    return false;
3127  case UTT_HasNothrowConstructor:
3128    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3129    //   If __has_trivial_constructor (type) is true then the trait is
3130    //   true, else if type is a cv class or union type (or array
3131    //   thereof) with a default constructor that is known not to
3132    //   throw an exception then the trait is true, else it is false.
3133    if (T.isPODType(C) || T->isObjCLifetimeType())
3134      return true;
3135    if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>()) {
3136      CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3137      if (RD->hasTrivialDefaultConstructor())
3138        return true;
3139
3140      DeclContext::lookup_const_iterator Con, ConEnd;
3141      for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
3142           Con != ConEnd; ++Con) {
3143        // FIXME: In C++0x, a constructor template can be a default constructor.
3144        if (isa<FunctionTemplateDecl>(*Con))
3145          continue;
3146        CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
3147        if (Constructor->isDefaultConstructor()) {
3148          const FunctionProtoType *CPT
3149              = Constructor->getType()->getAs<FunctionProtoType>();
3150          if (CPT->getExceptionSpecType() == EST_Delayed)
3151            return false;
3152          // TODO: check whether evaluating default arguments can throw.
3153          // For now, we'll be conservative and assume that they can throw.
3154          return CPT->isNothrow(Self.Context) && CPT->getNumArgs() == 0;
3155        }
3156      }
3157    }
3158    return false;
3159  case UTT_HasVirtualDestructor:
3160    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3161    //   If type is a class type with a virtual destructor ([class.dtor])
3162    //   then the trait is true, else it is false.
3163    if (const RecordType *Record = T->getAs<RecordType>()) {
3164      CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
3165      if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
3166        return Destructor->isVirtual();
3167    }
3168    return false;
3169
3170    // These type trait expressions are modeled on the specifications for the
3171    // Embarcadero C++0x type trait functions:
3172    //   http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
3173  case UTT_IsCompleteType:
3174    // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
3175    //   Returns True if and only if T is a complete type at the point of the
3176    //   function call.
3177    return !T->isIncompleteType();
3178  }
3179  llvm_unreachable("Type trait not covered by switch");
3180}
3181
3182ExprResult Sema::BuildUnaryTypeTrait(UnaryTypeTrait UTT,
3183                                     SourceLocation KWLoc,
3184                                     TypeSourceInfo *TSInfo,
3185                                     SourceLocation RParen) {
3186  QualType T = TSInfo->getType();
3187  if (!CheckUnaryTypeTraitTypeCompleteness(*this, UTT, KWLoc, T))
3188    return ExprError();
3189
3190  bool Value = false;
3191  if (!T->isDependentType())
3192    Value = EvaluateUnaryTypeTrait(*this, UTT, KWLoc, T);
3193
3194  return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, UTT, TSInfo, Value,
3195                                                RParen, Context.BoolTy));
3196}
3197
3198ExprResult Sema::ActOnBinaryTypeTrait(BinaryTypeTrait BTT,
3199                                      SourceLocation KWLoc,
3200                                      ParsedType LhsTy,
3201                                      ParsedType RhsTy,
3202                                      SourceLocation RParen) {
3203  TypeSourceInfo *LhsTSInfo;
3204  QualType LhsT = GetTypeFromParser(LhsTy, &LhsTSInfo);
3205  if (!LhsTSInfo)
3206    LhsTSInfo = Context.getTrivialTypeSourceInfo(LhsT);
3207
3208  TypeSourceInfo *RhsTSInfo;
3209  QualType RhsT = GetTypeFromParser(RhsTy, &RhsTSInfo);
3210  if (!RhsTSInfo)
3211    RhsTSInfo = Context.getTrivialTypeSourceInfo(RhsT);
3212
3213  return BuildBinaryTypeTrait(BTT, KWLoc, LhsTSInfo, RhsTSInfo, RParen);
3214}
3215
3216static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc,
3217                              ArrayRef<TypeSourceInfo *> Args,
3218                              SourceLocation RParenLoc) {
3219  switch (Kind) {
3220  case clang::TT_IsTriviallyConstructible: {
3221    // C++11 [meta.unary.prop]:
3222    //   is_trivially_constructible is defined as:
3223    //
3224    //     is_constructible<T, Args...>::value is true and the variable
3225    //     definition for is_constructible, as defined below, is known to call no
3226    //     operation that is not trivial.
3227    //
3228    //   The predicate condition for a template specialization
3229    //   is_constructible<T, Args...> shall be satisfied if and only if the
3230    //   following variable definition would be well-formed for some invented
3231    //   variable t:
3232    //
3233    //     T t(create<Args>()...);
3234    if (Args.empty()) {
3235      S.Diag(KWLoc, diag::err_type_trait_arity)
3236        << 1 << 1 << 1 << (int)Args.size();
3237      return false;
3238    }
3239
3240    bool SawVoid = false;
3241    for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3242      if (Args[I]->getType()->isVoidType()) {
3243        SawVoid = true;
3244        continue;
3245      }
3246
3247      if (!Args[I]->getType()->isIncompleteType() &&
3248        S.RequireCompleteType(KWLoc, Args[I]->getType(),
3249          diag::err_incomplete_type_used_in_type_trait_expr))
3250        return false;
3251    }
3252
3253    // If any argument was 'void', of course it won't type-check.
3254    if (SawVoid)
3255      return false;
3256
3257    llvm::SmallVector<OpaqueValueExpr, 2> OpaqueArgExprs;
3258    llvm::SmallVector<Expr *, 2> ArgExprs;
3259    ArgExprs.reserve(Args.size() - 1);
3260    for (unsigned I = 1, N = Args.size(); I != N; ++I) {
3261      QualType T = Args[I]->getType();
3262      if (T->isObjectType() || T->isFunctionType())
3263        T = S.Context.getRValueReferenceType(T);
3264      OpaqueArgExprs.push_back(
3265        OpaqueValueExpr(Args[I]->getTypeLoc().getSourceRange().getBegin(),
3266                        T.getNonLValueExprType(S.Context),
3267                        Expr::getValueKindForType(T)));
3268      ArgExprs.push_back(&OpaqueArgExprs.back());
3269    }
3270
3271    // Perform the initialization in an unevaluated context within a SFINAE
3272    // trap at translation unit scope.
3273    EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
3274    Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
3275    Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
3276    InitializedEntity To(InitializedEntity::InitializeTemporary(Args[0]));
3277    InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc,
3278                                                                 RParenLoc));
3279    InitializationSequence Init(S, To, InitKind,
3280                                ArgExprs.begin(), ArgExprs.size());
3281    if (Init.Failed())
3282      return false;
3283
3284    ExprResult Result = Init.Perform(S, To, InitKind,
3285                                     MultiExprArg(ArgExprs.data(),
3286                                                  ArgExprs.size()));
3287    if (Result.isInvalid() || SFINAE.hasErrorOccurred())
3288      return false;
3289
3290    // The initialization succeeded; not make sure there are no non-trivial
3291    // calls.
3292    return !Result.get()->hasNonTrivialCall(S.Context);
3293  }
3294  }
3295
3296  return false;
3297}
3298
3299ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
3300                                ArrayRef<TypeSourceInfo *> Args,
3301                                SourceLocation RParenLoc) {
3302  bool Dependent = false;
3303  for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3304    if (Args[I]->getType()->isDependentType()) {
3305      Dependent = true;
3306      break;
3307    }
3308  }
3309
3310  bool Value = false;
3311  if (!Dependent)
3312    Value = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc);
3313
3314  return TypeTraitExpr::Create(Context, Context.BoolTy, KWLoc, Kind,
3315                               Args, RParenLoc, Value);
3316}
3317
3318ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
3319                                ArrayRef<ParsedType> Args,
3320                                SourceLocation RParenLoc) {
3321  llvm::SmallVector<TypeSourceInfo *, 4> ConvertedArgs;
3322  ConvertedArgs.reserve(Args.size());
3323
3324  for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3325    TypeSourceInfo *TInfo;
3326    QualType T = GetTypeFromParser(Args[I], &TInfo);
3327    if (!TInfo)
3328      TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);
3329
3330    ConvertedArgs.push_back(TInfo);
3331  }
3332
3333  return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
3334}
3335
3336static bool EvaluateBinaryTypeTrait(Sema &Self, BinaryTypeTrait BTT,
3337                                    QualType LhsT, QualType RhsT,
3338                                    SourceLocation KeyLoc) {
3339  assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
3340         "Cannot evaluate traits of dependent types");
3341
3342  switch(BTT) {
3343  case BTT_IsBaseOf: {
3344    // C++0x [meta.rel]p2
3345    // Base is a base class of Derived without regard to cv-qualifiers or
3346    // Base and Derived are not unions and name the same class type without
3347    // regard to cv-qualifiers.
3348
3349    const RecordType *lhsRecord = LhsT->getAs<RecordType>();
3350    if (!lhsRecord) return false;
3351
3352    const RecordType *rhsRecord = RhsT->getAs<RecordType>();
3353    if (!rhsRecord) return false;
3354
3355    assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
3356             == (lhsRecord == rhsRecord));
3357
3358    if (lhsRecord == rhsRecord)
3359      return !lhsRecord->getDecl()->isUnion();
3360
3361    // C++0x [meta.rel]p2:
3362    //   If Base and Derived are class types and are different types
3363    //   (ignoring possible cv-qualifiers) then Derived shall be a
3364    //   complete type.
3365    if (Self.RequireCompleteType(KeyLoc, RhsT,
3366                          diag::err_incomplete_type_used_in_type_trait_expr))
3367      return false;
3368
3369    return cast<CXXRecordDecl>(rhsRecord->getDecl())
3370      ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
3371  }
3372  case BTT_IsSame:
3373    return Self.Context.hasSameType(LhsT, RhsT);
3374  case BTT_TypeCompatible:
3375    return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(),
3376                                           RhsT.getUnqualifiedType());
3377  case BTT_IsConvertible:
3378  case BTT_IsConvertibleTo: {
3379    // C++0x [meta.rel]p4:
3380    //   Given the following function prototype:
3381    //
3382    //     template <class T>
3383    //       typename add_rvalue_reference<T>::type create();
3384    //
3385    //   the predicate condition for a template specialization
3386    //   is_convertible<From, To> shall be satisfied if and only if
3387    //   the return expression in the following code would be
3388    //   well-formed, including any implicit conversions to the return
3389    //   type of the function:
3390    //
3391    //     To test() {
3392    //       return create<From>();
3393    //     }
3394    //
3395    //   Access checking is performed as if in a context unrelated to To and
3396    //   From. Only the validity of the immediate context of the expression
3397    //   of the return-statement (including conversions to the return type)
3398    //   is considered.
3399    //
3400    // We model the initialization as a copy-initialization of a temporary
3401    // of the appropriate type, which for this expression is identical to the
3402    // return statement (since NRVO doesn't apply).
3403    if (LhsT->isObjectType() || LhsT->isFunctionType())
3404      LhsT = Self.Context.getRValueReferenceType(LhsT);
3405
3406    InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
3407    OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
3408                         Expr::getValueKindForType(LhsT));
3409    Expr *FromPtr = &From;
3410    InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
3411                                                           SourceLocation()));
3412
3413    // Perform the initialization in an unevaluated context within a SFINAE
3414    // trap at translation unit scope.
3415    EnterExpressionEvaluationContext Unevaluated(Self, Sema::Unevaluated);
3416    Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
3417    Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
3418    InitializationSequence Init(Self, To, Kind, &FromPtr, 1);
3419    if (Init.Failed())
3420      return false;
3421
3422    ExprResult Result = Init.Perform(Self, To, Kind, MultiExprArg(&FromPtr, 1));
3423    return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
3424  }
3425
3426  case BTT_IsTriviallyAssignable: {
3427    // C++11 [meta.unary.prop]p3:
3428    //   is_trivially_assignable is defined as:
3429    //     is_assignable<T, U>::value is true and the assignment, as defined by
3430    //     is_assignable, is known to call no operation that is not trivial
3431    //
3432    //   is_assignable is defined as:
3433    //     The expression declval<T>() = declval<U>() is well-formed when
3434    //     treated as an unevaluated operand (Clause 5).
3435    //
3436    //   For both, T and U shall be complete types, (possibly cv-qualified)
3437    //   void, or arrays of unknown bound.
3438    if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
3439        Self.RequireCompleteType(KeyLoc, LhsT,
3440          diag::err_incomplete_type_used_in_type_trait_expr))
3441      return false;
3442    if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
3443        Self.RequireCompleteType(KeyLoc, RhsT,
3444          diag::err_incomplete_type_used_in_type_trait_expr))
3445      return false;
3446
3447    // cv void is never assignable.
3448    if (LhsT->isVoidType() || RhsT->isVoidType())
3449      return false;
3450
3451    // Build expressions that emulate the effect of declval<T>() and
3452    // declval<U>().
3453    if (LhsT->isObjectType() || LhsT->isFunctionType())
3454      LhsT = Self.Context.getRValueReferenceType(LhsT);
3455    if (RhsT->isObjectType() || RhsT->isFunctionType())
3456      RhsT = Self.Context.getRValueReferenceType(RhsT);
3457    OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
3458                        Expr::getValueKindForType(LhsT));
3459    OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
3460                        Expr::getValueKindForType(RhsT));
3461
3462    // Attempt the assignment in an unevaluated context within a SFINAE
3463    // trap at translation unit scope.
3464    EnterExpressionEvaluationContext Unevaluated(Self, Sema::Unevaluated);
3465    Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
3466    Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
3467    ExprResult Result = Self.BuildBinOp(/*S=*/0, KeyLoc, BO_Assign, &Lhs, &Rhs);
3468    if (Result.isInvalid() || SFINAE.hasErrorOccurred())
3469      return false;
3470
3471    return !Result.get()->hasNonTrivialCall(Self.Context);
3472  }
3473  }
3474  llvm_unreachable("Unknown type trait or not implemented");
3475}
3476
3477ExprResult Sema::BuildBinaryTypeTrait(BinaryTypeTrait BTT,
3478                                      SourceLocation KWLoc,
3479                                      TypeSourceInfo *LhsTSInfo,
3480                                      TypeSourceInfo *RhsTSInfo,
3481                                      SourceLocation RParen) {
3482  QualType LhsT = LhsTSInfo->getType();
3483  QualType RhsT = RhsTSInfo->getType();
3484
3485  if (BTT == BTT_TypeCompatible) {
3486    if (getLangOptions().CPlusPlus) {
3487      Diag(KWLoc, diag::err_types_compatible_p_in_cplusplus)
3488        << SourceRange(KWLoc, RParen);
3489      return ExprError();
3490    }
3491  }
3492
3493  bool Value = false;
3494  if (!LhsT->isDependentType() && !RhsT->isDependentType())
3495    Value = EvaluateBinaryTypeTrait(*this, BTT, LhsT, RhsT, KWLoc);
3496
3497  // Select trait result type.
3498  QualType ResultType;
3499  switch (BTT) {
3500  case BTT_IsBaseOf:       ResultType = Context.BoolTy; break;
3501  case BTT_IsConvertible:  ResultType = Context.BoolTy; break;
3502  case BTT_IsSame:         ResultType = Context.BoolTy; break;
3503  case BTT_TypeCompatible: ResultType = Context.IntTy; break;
3504  case BTT_IsConvertibleTo: ResultType = Context.BoolTy; break;
3505  case BTT_IsTriviallyAssignable: ResultType = Context.BoolTy;
3506  }
3507
3508  return Owned(new (Context) BinaryTypeTraitExpr(KWLoc, BTT, LhsTSInfo,
3509                                                 RhsTSInfo, Value, RParen,
3510                                                 ResultType));
3511}
3512
3513ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
3514                                     SourceLocation KWLoc,
3515                                     ParsedType Ty,
3516                                     Expr* DimExpr,
3517                                     SourceLocation RParen) {
3518  TypeSourceInfo *TSInfo;
3519  QualType T = GetTypeFromParser(Ty, &TSInfo);
3520  if (!TSInfo)
3521    TSInfo = Context.getTrivialTypeSourceInfo(T);
3522
3523  return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
3524}
3525
3526static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
3527                                           QualType T, Expr *DimExpr,
3528                                           SourceLocation KeyLoc) {
3529  assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
3530
3531  switch(ATT) {
3532  case ATT_ArrayRank:
3533    if (T->isArrayType()) {
3534      unsigned Dim = 0;
3535      while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
3536        ++Dim;
3537        T = AT->getElementType();
3538      }
3539      return Dim;
3540    }
3541    return 0;
3542
3543  case ATT_ArrayExtent: {
3544    llvm::APSInt Value;
3545    uint64_t Dim;
3546    if (Self.VerifyIntegerConstantExpression(DimExpr, &Value,
3547          Self.PDiag(diag::err_dimension_expr_not_constant_integer),
3548          false).isInvalid())
3549      return 0;
3550    if (Value.isSigned() && Value.isNegative()) {
3551      Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer),
3552        DimExpr->getSourceRange();
3553      return 0;
3554    }
3555    Dim = Value.getLimitedValue();
3556
3557    if (T->isArrayType()) {
3558      unsigned D = 0;
3559      bool Matched = false;
3560      while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
3561        if (Dim == D) {
3562          Matched = true;
3563          break;
3564        }
3565        ++D;
3566        T = AT->getElementType();
3567      }
3568
3569      if (Matched && T->isArrayType()) {
3570        if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
3571          return CAT->getSize().getLimitedValue();
3572      }
3573    }
3574    return 0;
3575  }
3576  }
3577  llvm_unreachable("Unknown type trait or not implemented");
3578}
3579
3580ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
3581                                     SourceLocation KWLoc,
3582                                     TypeSourceInfo *TSInfo,
3583                                     Expr* DimExpr,
3584                                     SourceLocation RParen) {
3585  QualType T = TSInfo->getType();
3586
3587  // FIXME: This should likely be tracked as an APInt to remove any host
3588  // assumptions about the width of size_t on the target.
3589  uint64_t Value = 0;
3590  if (!T->isDependentType())
3591    Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
3592
3593  // While the specification for these traits from the Embarcadero C++
3594  // compiler's documentation says the return type is 'unsigned int', Clang
3595  // returns 'size_t'. On Windows, the primary platform for the Embarcadero
3596  // compiler, there is no difference. On several other platforms this is an
3597  // important distinction.
3598  return Owned(new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value,
3599                                                DimExpr, RParen,
3600                                                Context.getSizeType()));
3601}
3602
3603ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
3604                                      SourceLocation KWLoc,
3605                                      Expr *Queried,
3606                                      SourceLocation RParen) {
3607  // If error parsing the expression, ignore.
3608  if (!Queried)
3609    return ExprError();
3610
3611  ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
3612
3613  return move(Result);
3614}
3615
3616static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
3617  switch (ET) {
3618  case ET_IsLValueExpr: return E->isLValue();
3619  case ET_IsRValueExpr: return E->isRValue();
3620  }
3621  llvm_unreachable("Expression trait not covered by switch");
3622}
3623
3624ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
3625                                      SourceLocation KWLoc,
3626                                      Expr *Queried,
3627                                      SourceLocation RParen) {
3628  if (Queried->isTypeDependent()) {
3629    // Delay type-checking for type-dependent expressions.
3630  } else if (Queried->getType()->isPlaceholderType()) {
3631    ExprResult PE = CheckPlaceholderExpr(Queried);
3632    if (PE.isInvalid()) return ExprError();
3633    return BuildExpressionTrait(ET, KWLoc, PE.take(), RParen);
3634  }
3635
3636  bool Value = EvaluateExpressionTrait(ET, Queried);
3637
3638  return Owned(new (Context) ExpressionTraitExpr(KWLoc, ET, Queried, Value,
3639                                                 RParen, Context.BoolTy));
3640}
3641
3642QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
3643                                            ExprValueKind &VK,
3644                                            SourceLocation Loc,
3645                                            bool isIndirect) {
3646  assert(!LHS.get()->getType()->isPlaceholderType() &&
3647         !RHS.get()->getType()->isPlaceholderType() &&
3648         "placeholders should have been weeded out by now");
3649
3650  // The LHS undergoes lvalue conversions if this is ->*.
3651  if (isIndirect) {
3652    LHS = DefaultLvalueConversion(LHS.take());
3653    if (LHS.isInvalid()) return QualType();
3654  }
3655
3656  // The RHS always undergoes lvalue conversions.
3657  RHS = DefaultLvalueConversion(RHS.take());
3658  if (RHS.isInvalid()) return QualType();
3659
3660  const char *OpSpelling = isIndirect ? "->*" : ".*";
3661  // C++ 5.5p2
3662  //   The binary operator .* [p3: ->*] binds its second operand, which shall
3663  //   be of type "pointer to member of T" (where T is a completely-defined
3664  //   class type) [...]
3665  QualType RHSType = RHS.get()->getType();
3666  const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
3667  if (!MemPtr) {
3668    Diag(Loc, diag::err_bad_memptr_rhs)
3669      << OpSpelling << RHSType << RHS.get()->getSourceRange();
3670    return QualType();
3671  }
3672
3673  QualType Class(MemPtr->getClass(), 0);
3674
3675  // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
3676  // member pointer points must be completely-defined. However, there is no
3677  // reason for this semantic distinction, and the rule is not enforced by
3678  // other compilers. Therefore, we do not check this property, as it is
3679  // likely to be considered a defect.
3680
3681  // C++ 5.5p2
3682  //   [...] to its first operand, which shall be of class T or of a class of
3683  //   which T is an unambiguous and accessible base class. [p3: a pointer to
3684  //   such a class]
3685  QualType LHSType = LHS.get()->getType();
3686  if (isIndirect) {
3687    if (const PointerType *Ptr = LHSType->getAs<PointerType>())
3688      LHSType = Ptr->getPointeeType();
3689    else {
3690      Diag(Loc, diag::err_bad_memptr_lhs)
3691        << OpSpelling << 1 << LHSType
3692        << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
3693      return QualType();
3694    }
3695  }
3696
3697  if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
3698    // If we want to check the hierarchy, we need a complete type.
3699    if (RequireCompleteType(Loc, LHSType, PDiag(diag::err_bad_memptr_lhs)
3700        << OpSpelling << (int)isIndirect)) {
3701      return QualType();
3702    }
3703    CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3704                       /*DetectVirtual=*/false);
3705    // FIXME: Would it be useful to print full ambiguity paths, or is that
3706    // overkill?
3707    if (!IsDerivedFrom(LHSType, Class, Paths) ||
3708        Paths.isAmbiguous(Context.getCanonicalType(Class))) {
3709      Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
3710        << (int)isIndirect << LHS.get()->getType();
3711      return QualType();
3712    }
3713    // Cast LHS to type of use.
3714    QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
3715    ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind();
3716
3717    CXXCastPath BasePath;
3718    BuildBasePathArray(Paths, BasePath);
3719    LHS = ImpCastExprToType(LHS.take(), UseType, CK_DerivedToBase, VK,
3720                            &BasePath);
3721  }
3722
3723  if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
3724    // Diagnose use of pointer-to-member type which when used as
3725    // the functional cast in a pointer-to-member expression.
3726    Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
3727     return QualType();
3728  }
3729
3730  // C++ 5.5p2
3731  //   The result is an object or a function of the type specified by the
3732  //   second operand.
3733  // The cv qualifiers are the union of those in the pointer and the left side,
3734  // in accordance with 5.5p5 and 5.2.5.
3735  QualType Result = MemPtr->getPointeeType();
3736  Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
3737
3738  // C++0x [expr.mptr.oper]p6:
3739  //   In a .* expression whose object expression is an rvalue, the program is
3740  //   ill-formed if the second operand is a pointer to member function with
3741  //   ref-qualifier &. In a ->* expression or in a .* expression whose object
3742  //   expression is an lvalue, the program is ill-formed if the second operand
3743  //   is a pointer to member function with ref-qualifier &&.
3744  if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
3745    switch (Proto->getRefQualifier()) {
3746    case RQ_None:
3747      // Do nothing
3748      break;
3749
3750    case RQ_LValue:
3751      if (!isIndirect && !LHS.get()->Classify(Context).isLValue())
3752        Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
3753          << RHSType << 1 << LHS.get()->getSourceRange();
3754      break;
3755
3756    case RQ_RValue:
3757      if (isIndirect || !LHS.get()->Classify(Context).isRValue())
3758        Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
3759          << RHSType << 0 << LHS.get()->getSourceRange();
3760      break;
3761    }
3762  }
3763
3764  // C++ [expr.mptr.oper]p6:
3765  //   The result of a .* expression whose second operand is a pointer
3766  //   to a data member is of the same value category as its
3767  //   first operand. The result of a .* expression whose second
3768  //   operand is a pointer to a member function is a prvalue. The
3769  //   result of an ->* expression is an lvalue if its second operand
3770  //   is a pointer to data member and a prvalue otherwise.
3771  if (Result->isFunctionType()) {
3772    VK = VK_RValue;
3773    return Context.BoundMemberTy;
3774  } else if (isIndirect) {
3775    VK = VK_LValue;
3776  } else {
3777    VK = LHS.get()->getValueKind();
3778  }
3779
3780  return Result;
3781}
3782
3783/// \brief Try to convert a type to another according to C++0x 5.16p3.
3784///
3785/// This is part of the parameter validation for the ? operator. If either
3786/// value operand is a class type, the two operands are attempted to be
3787/// converted to each other. This function does the conversion in one direction.
3788/// It returns true if the program is ill-formed and has already been diagnosed
3789/// as such.
3790static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
3791                                SourceLocation QuestionLoc,
3792                                bool &HaveConversion,
3793                                QualType &ToType) {
3794  HaveConversion = false;
3795  ToType = To->getType();
3796
3797  InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
3798                                                           SourceLocation());
3799  // C++0x 5.16p3
3800  //   The process for determining whether an operand expression E1 of type T1
3801  //   can be converted to match an operand expression E2 of type T2 is defined
3802  //   as follows:
3803  //   -- If E2 is an lvalue:
3804  bool ToIsLvalue = To->isLValue();
3805  if (ToIsLvalue) {
3806    //   E1 can be converted to match E2 if E1 can be implicitly converted to
3807    //   type "lvalue reference to T2", subject to the constraint that in the
3808    //   conversion the reference must bind directly to E1.
3809    QualType T = Self.Context.getLValueReferenceType(ToType);
3810    InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
3811
3812    InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
3813    if (InitSeq.isDirectReferenceBinding()) {
3814      ToType = T;
3815      HaveConversion = true;
3816      return false;
3817    }
3818
3819    if (InitSeq.isAmbiguous())
3820      return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
3821  }
3822
3823  //   -- If E2 is an rvalue, or if the conversion above cannot be done:
3824  //      -- if E1 and E2 have class type, and the underlying class types are
3825  //         the same or one is a base class of the other:
3826  QualType FTy = From->getType();
3827  QualType TTy = To->getType();
3828  const RecordType *FRec = FTy->getAs<RecordType>();
3829  const RecordType *TRec = TTy->getAs<RecordType>();
3830  bool FDerivedFromT = FRec && TRec && FRec != TRec &&
3831                       Self.IsDerivedFrom(FTy, TTy);
3832  if (FRec && TRec &&
3833      (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
3834    //         E1 can be converted to match E2 if the class of T2 is the
3835    //         same type as, or a base class of, the class of T1, and
3836    //         [cv2 > cv1].
3837    if (FRec == TRec || FDerivedFromT) {
3838      if (TTy.isAtLeastAsQualifiedAs(FTy)) {
3839        InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
3840        InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
3841        if (InitSeq) {
3842          HaveConversion = true;
3843          return false;
3844        }
3845
3846        if (InitSeq.isAmbiguous())
3847          return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
3848      }
3849    }
3850
3851    return false;
3852  }
3853
3854  //     -- Otherwise: E1 can be converted to match E2 if E1 can be
3855  //        implicitly converted to the type that expression E2 would have
3856  //        if E2 were converted to an rvalue (or the type it has, if E2 is
3857  //        an rvalue).
3858  //
3859  // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
3860  // to the array-to-pointer or function-to-pointer conversions.
3861  if (!TTy->getAs<TagType>())
3862    TTy = TTy.getUnqualifiedType();
3863
3864  InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
3865  InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
3866  HaveConversion = !InitSeq.Failed();
3867  ToType = TTy;
3868  if (InitSeq.isAmbiguous())
3869    return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
3870
3871  return false;
3872}
3873
3874/// \brief Try to find a common type for two according to C++0x 5.16p5.
3875///
3876/// This is part of the parameter validation for the ? operator. If either
3877/// value operand is a class type, overload resolution is used to find a
3878/// conversion to a common type.
3879static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
3880                                    SourceLocation QuestionLoc) {
3881  Expr *Args[2] = { LHS.get(), RHS.get() };
3882  OverloadCandidateSet CandidateSet(QuestionLoc);
3883  Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args, 2,
3884                                    CandidateSet);
3885
3886  OverloadCandidateSet::iterator Best;
3887  switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
3888    case OR_Success: {
3889      // We found a match. Perform the conversions on the arguments and move on.
3890      ExprResult LHSRes =
3891        Self.PerformImplicitConversion(LHS.get(), Best->BuiltinTypes.ParamTypes[0],
3892                                       Best->Conversions[0], Sema::AA_Converting);
3893      if (LHSRes.isInvalid())
3894        break;
3895      LHS = move(LHSRes);
3896
3897      ExprResult RHSRes =
3898        Self.PerformImplicitConversion(RHS.get(), Best->BuiltinTypes.ParamTypes[1],
3899                                       Best->Conversions[1], Sema::AA_Converting);
3900      if (RHSRes.isInvalid())
3901        break;
3902      RHS = move(RHSRes);
3903      if (Best->Function)
3904        Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
3905      return false;
3906    }
3907
3908    case OR_No_Viable_Function:
3909
3910      // Emit a better diagnostic if one of the expressions is a null pointer
3911      // constant and the other is a pointer type. In this case, the user most
3912      // likely forgot to take the address of the other expression.
3913      if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
3914        return true;
3915
3916      Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3917        << LHS.get()->getType() << RHS.get()->getType()
3918        << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
3919      return true;
3920
3921    case OR_Ambiguous:
3922      Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
3923        << LHS.get()->getType() << RHS.get()->getType()
3924        << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
3925      // FIXME: Print the possible common types by printing the return types of
3926      // the viable candidates.
3927      break;
3928
3929    case OR_Deleted:
3930      llvm_unreachable("Conditional operator has only built-in overloads");
3931  }
3932  return true;
3933}
3934
3935/// \brief Perform an "extended" implicit conversion as returned by
3936/// TryClassUnification.
3937static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
3938  InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
3939  InitializationKind Kind = InitializationKind::CreateCopy(E.get()->getLocStart(),
3940                                                           SourceLocation());
3941  Expr *Arg = E.take();
3942  InitializationSequence InitSeq(Self, Entity, Kind, &Arg, 1);
3943  ExprResult Result = InitSeq.Perform(Self, Entity, Kind, MultiExprArg(&Arg, 1));
3944  if (Result.isInvalid())
3945    return true;
3946
3947  E = Result;
3948  return false;
3949}
3950
3951/// \brief Check the operands of ?: under C++ semantics.
3952///
3953/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
3954/// extension. In this case, LHS == Cond. (But they're not aliases.)
3955QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
3956                                           ExprValueKind &VK, ExprObjectKind &OK,
3957                                           SourceLocation QuestionLoc) {
3958  // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
3959  // interface pointers.
3960
3961  // C++0x 5.16p1
3962  //   The first expression is contextually converted to bool.
3963  if (!Cond.get()->isTypeDependent()) {
3964    ExprResult CondRes = CheckCXXBooleanCondition(Cond.take());
3965    if (CondRes.isInvalid())
3966      return QualType();
3967    Cond = move(CondRes);
3968  }
3969
3970  // Assume r-value.
3971  VK = VK_RValue;
3972  OK = OK_Ordinary;
3973
3974  // Either of the arguments dependent?
3975  if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
3976    return Context.DependentTy;
3977
3978  // C++0x 5.16p2
3979  //   If either the second or the third operand has type (cv) void, ...
3980  QualType LTy = LHS.get()->getType();
3981  QualType RTy = RHS.get()->getType();
3982  bool LVoid = LTy->isVoidType();
3983  bool RVoid = RTy->isVoidType();
3984  if (LVoid || RVoid) {
3985    //   ... then the [l2r] conversions are performed on the second and third
3986    //   operands ...
3987    LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
3988    RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
3989    if (LHS.isInvalid() || RHS.isInvalid())
3990      return QualType();
3991    LTy = LHS.get()->getType();
3992    RTy = RHS.get()->getType();
3993
3994    //   ... and one of the following shall hold:
3995    //   -- The second or the third operand (but not both) is a throw-
3996    //      expression; the result is of the type of the other and is an rvalue.
3997    bool LThrow = isa<CXXThrowExpr>(LHS.get());
3998    bool RThrow = isa<CXXThrowExpr>(RHS.get());
3999    if (LThrow && !RThrow)
4000      return RTy;
4001    if (RThrow && !LThrow)
4002      return LTy;
4003
4004    //   -- Both the second and third operands have type void; the result is of
4005    //      type void and is an rvalue.
4006    if (LVoid && RVoid)
4007      return Context.VoidTy;
4008
4009    // Neither holds, error.
4010    Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
4011      << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
4012      << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
4013    return QualType();
4014  }
4015
4016  // Neither is void.
4017
4018  // C++0x 5.16p3
4019  //   Otherwise, if the second and third operand have different types, and
4020  //   either has (cv) class type, and attempt is made to convert each of those
4021  //   operands to the other.
4022  if (!Context.hasSameType(LTy, RTy) &&
4023      (LTy->isRecordType() || RTy->isRecordType())) {
4024    ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
4025    // These return true if a single direction is already ambiguous.
4026    QualType L2RType, R2LType;
4027    bool HaveL2R, HaveR2L;
4028    if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
4029      return QualType();
4030    if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
4031      return QualType();
4032
4033    //   If both can be converted, [...] the program is ill-formed.
4034    if (HaveL2R && HaveR2L) {
4035      Diag(QuestionLoc, diag::err_conditional_ambiguous)
4036        << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
4037      return QualType();
4038    }
4039
4040    //   If exactly one conversion is possible, that conversion is applied to
4041    //   the chosen operand and the converted operands are used in place of the
4042    //   original operands for the remainder of this section.
4043    if (HaveL2R) {
4044      if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
4045        return QualType();
4046      LTy = LHS.get()->getType();
4047    } else if (HaveR2L) {
4048      if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
4049        return QualType();
4050      RTy = RHS.get()->getType();
4051    }
4052  }
4053
4054  // C++0x 5.16p4
4055  //   If the second and third operands are glvalues of the same value
4056  //   category and have the same type, the result is of that type and
4057  //   value category and it is a bit-field if the second or the third
4058  //   operand is a bit-field, or if both are bit-fields.
4059  // We only extend this to bitfields, not to the crazy other kinds of
4060  // l-values.
4061  bool Same = Context.hasSameType(LTy, RTy);
4062  if (Same &&
4063      LHS.get()->isGLValue() &&
4064      LHS.get()->getValueKind() == RHS.get()->getValueKind() &&
4065      LHS.get()->isOrdinaryOrBitFieldObject() &&
4066      RHS.get()->isOrdinaryOrBitFieldObject()) {
4067    VK = LHS.get()->getValueKind();
4068    if (LHS.get()->getObjectKind() == OK_BitField ||
4069        RHS.get()->getObjectKind() == OK_BitField)
4070      OK = OK_BitField;
4071    return LTy;
4072  }
4073
4074  // C++0x 5.16p5
4075  //   Otherwise, the result is an rvalue. If the second and third operands
4076  //   do not have the same type, and either has (cv) class type, ...
4077  if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
4078    //   ... overload resolution is used to determine the conversions (if any)
4079    //   to be applied to the operands. If the overload resolution fails, the
4080    //   program is ill-formed.
4081    if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
4082      return QualType();
4083  }
4084
4085  // C++0x 5.16p6
4086  //   LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
4087  //   conversions are performed on the second and third operands.
4088  LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
4089  RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
4090  if (LHS.isInvalid() || RHS.isInvalid())
4091    return QualType();
4092  LTy = LHS.get()->getType();
4093  RTy = RHS.get()->getType();
4094
4095  //   After those conversions, one of the following shall hold:
4096  //   -- The second and third operands have the same type; the result
4097  //      is of that type. If the operands have class type, the result
4098  //      is a prvalue temporary of the result type, which is
4099  //      copy-initialized from either the second operand or the third
4100  //      operand depending on the value of the first operand.
4101  if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
4102    if (LTy->isRecordType()) {
4103      // The operands have class type. Make a temporary copy.
4104      InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
4105      ExprResult LHSCopy = PerformCopyInitialization(Entity,
4106                                                     SourceLocation(),
4107                                                     LHS);
4108      if (LHSCopy.isInvalid())
4109        return QualType();
4110
4111      ExprResult RHSCopy = PerformCopyInitialization(Entity,
4112                                                     SourceLocation(),
4113                                                     RHS);
4114      if (RHSCopy.isInvalid())
4115        return QualType();
4116
4117      LHS = LHSCopy;
4118      RHS = RHSCopy;
4119    }
4120
4121    return LTy;
4122  }
4123
4124  // Extension: conditional operator involving vector types.
4125  if (LTy->isVectorType() || RTy->isVectorType())
4126    return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
4127
4128  //   -- The second and third operands have arithmetic or enumeration type;
4129  //      the usual arithmetic conversions are performed to bring them to a
4130  //      common type, and the result is of that type.
4131  if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
4132    UsualArithmeticConversions(LHS, RHS);
4133    if (LHS.isInvalid() || RHS.isInvalid())
4134      return QualType();
4135    return LHS.get()->getType();
4136  }
4137
4138  //   -- The second and third operands have pointer type, or one has pointer
4139  //      type and the other is a null pointer constant; pointer conversions
4140  //      and qualification conversions are performed to bring them to their
4141  //      composite pointer type. The result is of the composite pointer type.
4142  //   -- The second and third operands have pointer to member type, or one has
4143  //      pointer to member type and the other is a null pointer constant;
4144  //      pointer to member conversions and qualification conversions are
4145  //      performed to bring them to a common type, whose cv-qualification
4146  //      shall match the cv-qualification of either the second or the third
4147  //      operand. The result is of the common type.
4148  bool NonStandardCompositeType = false;
4149  QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
4150                              isSFINAEContext()? 0 : &NonStandardCompositeType);
4151  if (!Composite.isNull()) {
4152    if (NonStandardCompositeType)
4153      Diag(QuestionLoc,
4154           diag::ext_typecheck_cond_incompatible_operands_nonstandard)
4155        << LTy << RTy << Composite
4156        << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
4157
4158    return Composite;
4159  }
4160
4161  // Similarly, attempt to find composite type of two objective-c pointers.
4162  Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
4163  if (!Composite.isNull())
4164    return Composite;
4165
4166  // Check if we are using a null with a non-pointer type.
4167  if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
4168    return QualType();
4169
4170  Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
4171    << LHS.get()->getType() << RHS.get()->getType()
4172    << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
4173  return QualType();
4174}
4175
4176/// \brief Find a merged pointer type and convert the two expressions to it.
4177///
4178/// This finds the composite pointer type (or member pointer type) for @p E1
4179/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
4180/// type and returns it.
4181/// It does not emit diagnostics.
4182///
4183/// \param Loc The location of the operator requiring these two expressions to
4184/// be converted to the composite pointer type.
4185///
4186/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
4187/// a non-standard (but still sane) composite type to which both expressions
4188/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
4189/// will be set true.
4190QualType Sema::FindCompositePointerType(SourceLocation Loc,
4191                                        Expr *&E1, Expr *&E2,
4192                                        bool *NonStandardCompositeType) {
4193  if (NonStandardCompositeType)
4194    *NonStandardCompositeType = false;
4195
4196  assert(getLangOptions().CPlusPlus && "This function assumes C++");
4197  QualType T1 = E1->getType(), T2 = E2->getType();
4198
4199  if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
4200      !T2->isAnyPointerType() && !T2->isMemberPointerType())
4201   return QualType();
4202
4203  // C++0x 5.9p2
4204  //   Pointer conversions and qualification conversions are performed on
4205  //   pointer operands to bring them to their composite pointer type. If
4206  //   one operand is a null pointer constant, the composite pointer type is
4207  //   the type of the other operand.
4208  if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
4209    if (T2->isMemberPointerType())
4210      E1 = ImpCastExprToType(E1, T2, CK_NullToMemberPointer).take();
4211    else
4212      E1 = ImpCastExprToType(E1, T2, CK_NullToPointer).take();
4213    return T2;
4214  }
4215  if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
4216    if (T1->isMemberPointerType())
4217      E2 = ImpCastExprToType(E2, T1, CK_NullToMemberPointer).take();
4218    else
4219      E2 = ImpCastExprToType(E2, T1, CK_NullToPointer).take();
4220    return T1;
4221  }
4222
4223  // Now both have to be pointers or member pointers.
4224  if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
4225      (!T2->isPointerType() && !T2->isMemberPointerType()))
4226    return QualType();
4227
4228  //   Otherwise, of one of the operands has type "pointer to cv1 void," then
4229  //   the other has type "pointer to cv2 T" and the composite pointer type is
4230  //   "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
4231  //   Otherwise, the composite pointer type is a pointer type similar to the
4232  //   type of one of the operands, with a cv-qualification signature that is
4233  //   the union of the cv-qualification signatures of the operand types.
4234  // In practice, the first part here is redundant; it's subsumed by the second.
4235  // What we do here is, we build the two possible composite types, and try the
4236  // conversions in both directions. If only one works, or if the two composite
4237  // types are the same, we have succeeded.
4238  // FIXME: extended qualifiers?
4239  typedef SmallVector<unsigned, 4> QualifierVector;
4240  QualifierVector QualifierUnion;
4241  typedef SmallVector<std::pair<const Type *, const Type *>, 4>
4242      ContainingClassVector;
4243  ContainingClassVector MemberOfClass;
4244  QualType Composite1 = Context.getCanonicalType(T1),
4245           Composite2 = Context.getCanonicalType(T2);
4246  unsigned NeedConstBefore = 0;
4247  do {
4248    const PointerType *Ptr1, *Ptr2;
4249    if ((Ptr1 = Composite1->getAs<PointerType>()) &&
4250        (Ptr2 = Composite2->getAs<PointerType>())) {
4251      Composite1 = Ptr1->getPointeeType();
4252      Composite2 = Ptr2->getPointeeType();
4253
4254      // If we're allowed to create a non-standard composite type, keep track
4255      // of where we need to fill in additional 'const' qualifiers.
4256      if (NonStandardCompositeType &&
4257          Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
4258        NeedConstBefore = QualifierUnion.size();
4259
4260      QualifierUnion.push_back(
4261                 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
4262      MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
4263      continue;
4264    }
4265
4266    const MemberPointerType *MemPtr1, *MemPtr2;
4267    if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
4268        (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
4269      Composite1 = MemPtr1->getPointeeType();
4270      Composite2 = MemPtr2->getPointeeType();
4271
4272      // If we're allowed to create a non-standard composite type, keep track
4273      // of where we need to fill in additional 'const' qualifiers.
4274      if (NonStandardCompositeType &&
4275          Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
4276        NeedConstBefore = QualifierUnion.size();
4277
4278      QualifierUnion.push_back(
4279                 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
4280      MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
4281                                             MemPtr2->getClass()));
4282      continue;
4283    }
4284
4285    // FIXME: block pointer types?
4286
4287    // Cannot unwrap any more types.
4288    break;
4289  } while (true);
4290
4291  if (NeedConstBefore && NonStandardCompositeType) {
4292    // Extension: Add 'const' to qualifiers that come before the first qualifier
4293    // mismatch, so that our (non-standard!) composite type meets the
4294    // requirements of C++ [conv.qual]p4 bullet 3.
4295    for (unsigned I = 0; I != NeedConstBefore; ++I) {
4296      if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
4297        QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
4298        *NonStandardCompositeType = true;
4299      }
4300    }
4301  }
4302
4303  // Rewrap the composites as pointers or member pointers with the union CVRs.
4304  ContainingClassVector::reverse_iterator MOC
4305    = MemberOfClass.rbegin();
4306  for (QualifierVector::reverse_iterator
4307         I = QualifierUnion.rbegin(),
4308         E = QualifierUnion.rend();
4309       I != E; (void)++I, ++MOC) {
4310    Qualifiers Quals = Qualifiers::fromCVRMask(*I);
4311    if (MOC->first && MOC->second) {
4312      // Rebuild member pointer type
4313      Composite1 = Context.getMemberPointerType(
4314                                    Context.getQualifiedType(Composite1, Quals),
4315                                    MOC->first);
4316      Composite2 = Context.getMemberPointerType(
4317                                    Context.getQualifiedType(Composite2, Quals),
4318                                    MOC->second);
4319    } else {
4320      // Rebuild pointer type
4321      Composite1
4322        = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
4323      Composite2
4324        = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
4325    }
4326  }
4327
4328  // Try to convert to the first composite pointer type.
4329  InitializedEntity Entity1
4330    = InitializedEntity::InitializeTemporary(Composite1);
4331  InitializationKind Kind
4332    = InitializationKind::CreateCopy(Loc, SourceLocation());
4333  InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1);
4334  InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1);
4335
4336  if (E1ToC1 && E2ToC1) {
4337    // Conversion to Composite1 is viable.
4338    if (!Context.hasSameType(Composite1, Composite2)) {
4339      // Composite2 is a different type from Composite1. Check whether
4340      // Composite2 is also viable.
4341      InitializedEntity Entity2
4342        = InitializedEntity::InitializeTemporary(Composite2);
4343      InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
4344      InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
4345      if (E1ToC2 && E2ToC2) {
4346        // Both Composite1 and Composite2 are viable and are different;
4347        // this is an ambiguity.
4348        return QualType();
4349      }
4350    }
4351
4352    // Convert E1 to Composite1
4353    ExprResult E1Result
4354      = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E1,1));
4355    if (E1Result.isInvalid())
4356      return QualType();
4357    E1 = E1Result.takeAs<Expr>();
4358
4359    // Convert E2 to Composite1
4360    ExprResult E2Result
4361      = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E2,1));
4362    if (E2Result.isInvalid())
4363      return QualType();
4364    E2 = E2Result.takeAs<Expr>();
4365
4366    return Composite1;
4367  }
4368
4369  // Check whether Composite2 is viable.
4370  InitializedEntity Entity2
4371    = InitializedEntity::InitializeTemporary(Composite2);
4372  InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
4373  InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
4374  if (!E1ToC2 || !E2ToC2)
4375    return QualType();
4376
4377  // Convert E1 to Composite2
4378  ExprResult E1Result
4379    = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E1, 1));
4380  if (E1Result.isInvalid())
4381    return QualType();
4382  E1 = E1Result.takeAs<Expr>();
4383
4384  // Convert E2 to Composite2
4385  ExprResult E2Result
4386    = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E2, 1));
4387  if (E2Result.isInvalid())
4388    return QualType();
4389  E2 = E2Result.takeAs<Expr>();
4390
4391  return Composite2;
4392}
4393
4394ExprResult Sema::MaybeBindToTemporary(Expr *E) {
4395  if (!E)
4396    return ExprError();
4397
4398  assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
4399
4400  // If the result is a glvalue, we shouldn't bind it.
4401  if (!E->isRValue())
4402    return Owned(E);
4403
4404  // In ARC, calls that return a retainable type can return retained,
4405  // in which case we have to insert a consuming cast.
4406  if (getLangOptions().ObjCAutoRefCount &&
4407      E->getType()->isObjCRetainableType()) {
4408
4409    bool ReturnsRetained;
4410
4411    // For actual calls, we compute this by examining the type of the
4412    // called value.
4413    if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
4414      Expr *Callee = Call->getCallee()->IgnoreParens();
4415      QualType T = Callee->getType();
4416
4417      if (T == Context.BoundMemberTy) {
4418        // Handle pointer-to-members.
4419        if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
4420          T = BinOp->getRHS()->getType();
4421        else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
4422          T = Mem->getMemberDecl()->getType();
4423      }
4424
4425      if (const PointerType *Ptr = T->getAs<PointerType>())
4426        T = Ptr->getPointeeType();
4427      else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
4428        T = Ptr->getPointeeType();
4429      else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
4430        T = MemPtr->getPointeeType();
4431
4432      const FunctionType *FTy = T->getAs<FunctionType>();
4433      assert(FTy && "call to value not of function type?");
4434      ReturnsRetained = FTy->getExtInfo().getProducesResult();
4435
4436    // ActOnStmtExpr arranges things so that StmtExprs of retainable
4437    // type always produce a +1 object.
4438    } else if (isa<StmtExpr>(E)) {
4439      ReturnsRetained = true;
4440
4441    // For message sends and property references, we try to find an
4442    // actual method.  FIXME: we should infer retention by selector in
4443    // cases where we don't have an actual method.
4444    } else {
4445      ObjCMethodDecl *D = 0;
4446      if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
4447        D = Send->getMethodDecl();
4448      }
4449
4450      ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
4451
4452      // Don't do reclaims on performSelector calls; despite their
4453      // return type, the invoked method doesn't necessarily actually
4454      // return an object.
4455      if (!ReturnsRetained &&
4456          D && D->getMethodFamily() == OMF_performSelector)
4457        return Owned(E);
4458    }
4459
4460    // Don't reclaim an object of Class type.
4461    if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
4462      return Owned(E);
4463
4464    ExprNeedsCleanups = true;
4465
4466    CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
4467                                   : CK_ARCReclaimReturnedObject);
4468    return Owned(ImplicitCastExpr::Create(Context, E->getType(), ck, E, 0,
4469                                          VK_RValue));
4470  }
4471
4472  if (!getLangOptions().CPlusPlus)
4473    return Owned(E);
4474
4475  // Search for the base element type (cf. ASTContext::getBaseElementType) with
4476  // a fast path for the common case that the type is directly a RecordType.
4477  const Type *T = Context.getCanonicalType(E->getType().getTypePtr());
4478  const RecordType *RT = 0;
4479  while (!RT) {
4480    switch (T->getTypeClass()) {
4481    case Type::Record:
4482      RT = cast<RecordType>(T);
4483      break;
4484    case Type::ConstantArray:
4485    case Type::IncompleteArray:
4486    case Type::VariableArray:
4487    case Type::DependentSizedArray:
4488      T = cast<ArrayType>(T)->getElementType().getTypePtr();
4489      break;
4490    default:
4491      return Owned(E);
4492    }
4493  }
4494
4495  // That should be enough to guarantee that this type is complete, if we're
4496  // not processing a decltype expression.
4497  CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4498  if (RD->isInvalidDecl() || RD->isDependentContext())
4499    return Owned(E);
4500
4501  bool IsDecltype = ExprEvalContexts.back().IsDecltype;
4502  CXXDestructorDecl *Destructor = IsDecltype ? 0 : LookupDestructor(RD);
4503
4504  if (Destructor) {
4505    MarkFunctionReferenced(E->getExprLoc(), Destructor);
4506    CheckDestructorAccess(E->getExprLoc(), Destructor,
4507                          PDiag(diag::err_access_dtor_temp)
4508                            << E->getType());
4509    DiagnoseUseOfDecl(Destructor, E->getExprLoc());
4510
4511    // If destructor is trivial, we can avoid the extra copy.
4512    if (Destructor->isTrivial())
4513      return Owned(E);
4514
4515    // We need a cleanup, but we don't need to remember the temporary.
4516    ExprNeedsCleanups = true;
4517  }
4518
4519  CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
4520  CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E);
4521
4522  if (IsDecltype)
4523    ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind);
4524
4525  return Owned(Bind);
4526}
4527
4528ExprResult
4529Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
4530  if (SubExpr.isInvalid())
4531    return ExprError();
4532
4533  return Owned(MaybeCreateExprWithCleanups(SubExpr.take()));
4534}
4535
4536Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
4537  assert(SubExpr && "sub expression can't be null!");
4538
4539  CleanupVarDeclMarking();
4540
4541  unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
4542  assert(ExprCleanupObjects.size() >= FirstCleanup);
4543  assert(ExprNeedsCleanups || ExprCleanupObjects.size() == FirstCleanup);
4544  if (!ExprNeedsCleanups)
4545    return SubExpr;
4546
4547  ArrayRef<ExprWithCleanups::CleanupObject> Cleanups
4548    = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
4549                         ExprCleanupObjects.size() - FirstCleanup);
4550
4551  Expr *E = ExprWithCleanups::Create(Context, SubExpr, Cleanups);
4552  DiscardCleanupsInEvaluationContext();
4553
4554  return E;
4555}
4556
4557Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
4558  assert(SubStmt && "sub statement can't be null!");
4559
4560  CleanupVarDeclMarking();
4561
4562  if (!ExprNeedsCleanups)
4563    return SubStmt;
4564
4565  // FIXME: In order to attach the temporaries, wrap the statement into
4566  // a StmtExpr; currently this is only used for asm statements.
4567  // This is hacky, either create a new CXXStmtWithTemporaries statement or
4568  // a new AsmStmtWithTemporaries.
4569  CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, &SubStmt, 1,
4570                                                      SourceLocation(),
4571                                                      SourceLocation());
4572  Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
4573                                   SourceLocation());
4574  return MaybeCreateExprWithCleanups(E);
4575}
4576
4577/// Process the expression contained within a decltype. For such expressions,
4578/// certain semantic checks on temporaries are delayed until this point, and
4579/// are omitted for the 'topmost' call in the decltype expression. If the
4580/// topmost call bound a temporary, strip that temporary off the expression.
4581ExprResult Sema::ActOnDecltypeExpression(Expr *E) {
4582  ExpressionEvaluationContextRecord &Rec = ExprEvalContexts.back();
4583  assert(Rec.IsDecltype && "not in a decltype expression");
4584
4585  // C++11 [expr.call]p11:
4586  //   If a function call is a prvalue of object type,
4587  // -- if the function call is either
4588  //   -- the operand of a decltype-specifier, or
4589  //   -- the right operand of a comma operator that is the operand of a
4590  //      decltype-specifier,
4591  //   a temporary object is not introduced for the prvalue.
4592
4593  // Recursively rebuild ParenExprs and comma expressions to strip out the
4594  // outermost CXXBindTemporaryExpr, if any.
4595  if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
4596    ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr());
4597    if (SubExpr.isInvalid())
4598      return ExprError();
4599    if (SubExpr.get() == PE->getSubExpr())
4600      return Owned(E);
4601    return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.take());
4602  }
4603  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
4604    if (BO->getOpcode() == BO_Comma) {
4605      ExprResult RHS = ActOnDecltypeExpression(BO->getRHS());
4606      if (RHS.isInvalid())
4607        return ExprError();
4608      if (RHS.get() == BO->getRHS())
4609        return Owned(E);
4610      return Owned(new (Context) BinaryOperator(BO->getLHS(), RHS.take(),
4611                                                BO_Comma, BO->getType(),
4612                                                BO->getValueKind(),
4613                                                BO->getObjectKind(),
4614                                                BO->getOperatorLoc()));
4615    }
4616  }
4617
4618  CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E);
4619  if (TopBind)
4620    E = TopBind->getSubExpr();
4621
4622  // Disable the special decltype handling now.
4623  Rec.IsDecltype = false;
4624
4625  // Perform the semantic checks we delayed until this point.
4626  CallExpr *TopCall = dyn_cast<CallExpr>(E);
4627  for (unsigned I = 0, N = Rec.DelayedDecltypeCalls.size(); I != N; ++I) {
4628    CallExpr *Call = Rec.DelayedDecltypeCalls[I];
4629    if (Call == TopCall)
4630      continue;
4631
4632    if (CheckCallReturnType(Call->getCallReturnType(),
4633                            Call->getSourceRange().getBegin(),
4634                            Call, Call->getDirectCallee()))
4635      return ExprError();
4636  }
4637
4638  // Now all relevant types are complete, check the destructors are accessible
4639  // and non-deleted, and annotate them on the temporaries.
4640  for (unsigned I = 0, N = Rec.DelayedDecltypeBinds.size(); I != N; ++I) {
4641    CXXBindTemporaryExpr *Bind = Rec.DelayedDecltypeBinds[I];
4642    if (Bind == TopBind)
4643      continue;
4644
4645    CXXTemporary *Temp = Bind->getTemporary();
4646
4647    CXXRecordDecl *RD =
4648      Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
4649    CXXDestructorDecl *Destructor = LookupDestructor(RD);
4650    Temp->setDestructor(Destructor);
4651
4652    MarkFunctionReferenced(E->getExprLoc(), Destructor);
4653    CheckDestructorAccess(E->getExprLoc(), Destructor,
4654                          PDiag(diag::err_access_dtor_temp)
4655                            << E->getType());
4656    DiagnoseUseOfDecl(Destructor, E->getExprLoc());
4657
4658    // We need a cleanup, but we don't need to remember the temporary.
4659    ExprNeedsCleanups = true;
4660  }
4661
4662  // Possibly strip off the top CXXBindTemporaryExpr.
4663  return Owned(E);
4664}
4665
4666ExprResult
4667Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc,
4668                                   tok::TokenKind OpKind, ParsedType &ObjectType,
4669                                   bool &MayBePseudoDestructor) {
4670  // Since this might be a postfix expression, get rid of ParenListExprs.
4671  ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
4672  if (Result.isInvalid()) return ExprError();
4673  Base = Result.get();
4674
4675  Result = CheckPlaceholderExpr(Base);
4676  if (Result.isInvalid()) return ExprError();
4677  Base = Result.take();
4678
4679  QualType BaseType = Base->getType();
4680  MayBePseudoDestructor = false;
4681  if (BaseType->isDependentType()) {
4682    // If we have a pointer to a dependent type and are using the -> operator,
4683    // the object type is the type that the pointer points to. We might still
4684    // have enough information about that type to do something useful.
4685    if (OpKind == tok::arrow)
4686      if (const PointerType *Ptr = BaseType->getAs<PointerType>())
4687        BaseType = Ptr->getPointeeType();
4688
4689    ObjectType = ParsedType::make(BaseType);
4690    MayBePseudoDestructor = true;
4691    return Owned(Base);
4692  }
4693
4694  // C++ [over.match.oper]p8:
4695  //   [...] When operator->returns, the operator-> is applied  to the value
4696  //   returned, with the original second operand.
4697  if (OpKind == tok::arrow) {
4698    // The set of types we've considered so far.
4699    llvm::SmallPtrSet<CanQualType,8> CTypes;
4700    SmallVector<SourceLocation, 8> Locations;
4701    CTypes.insert(Context.getCanonicalType(BaseType));
4702
4703    while (BaseType->isRecordType()) {
4704      Result = BuildOverloadedArrowExpr(S, Base, OpLoc);
4705      if (Result.isInvalid())
4706        return ExprError();
4707      Base = Result.get();
4708      if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
4709        Locations.push_back(OpCall->getDirectCallee()->getLocation());
4710      BaseType = Base->getType();
4711      CanQualType CBaseType = Context.getCanonicalType(BaseType);
4712      if (!CTypes.insert(CBaseType)) {
4713        Diag(OpLoc, diag::err_operator_arrow_circular);
4714        for (unsigned i = 0; i < Locations.size(); i++)
4715          Diag(Locations[i], diag::note_declared_at);
4716        return ExprError();
4717      }
4718    }
4719
4720    if (BaseType->isPointerType() || BaseType->isObjCObjectPointerType())
4721      BaseType = BaseType->getPointeeType();
4722  }
4723
4724  // Objective-C properties allow "." access on Objective-C pointer types,
4725  // so adjust the base type to the object type itself.
4726  if (BaseType->isObjCObjectPointerType())
4727    BaseType = BaseType->getPointeeType();
4728
4729  // C++ [basic.lookup.classref]p2:
4730  //   [...] If the type of the object expression is of pointer to scalar
4731  //   type, the unqualified-id is looked up in the context of the complete
4732  //   postfix-expression.
4733  //
4734  // This also indicates that we could be parsing a pseudo-destructor-name.
4735  // Note that Objective-C class and object types can be pseudo-destructor
4736  // expressions or normal member (ivar or property) access expressions.
4737  if (BaseType->isObjCObjectOrInterfaceType()) {
4738    MayBePseudoDestructor = true;
4739  } else if (!BaseType->isRecordType()) {
4740    ObjectType = ParsedType();
4741    MayBePseudoDestructor = true;
4742    return Owned(Base);
4743  }
4744
4745  // The object type must be complete (or dependent).
4746  if (!BaseType->isDependentType() &&
4747      RequireCompleteType(OpLoc, BaseType,
4748                          PDiag(diag::err_incomplete_member_access)))
4749    return ExprError();
4750
4751  // C++ [basic.lookup.classref]p2:
4752  //   If the id-expression in a class member access (5.2.5) is an
4753  //   unqualified-id, and the type of the object expression is of a class
4754  //   type C (or of pointer to a class type C), the unqualified-id is looked
4755  //   up in the scope of class C. [...]
4756  ObjectType = ParsedType::make(BaseType);
4757  return move(Base);
4758}
4759
4760ExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
4761                                                   Expr *MemExpr) {
4762  SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
4763  Diag(MemExpr->getLocStart(), diag::err_dtor_expr_without_call)
4764    << isa<CXXPseudoDestructorExpr>(MemExpr)
4765    << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
4766
4767  return ActOnCallExpr(/*Scope*/ 0,
4768                       MemExpr,
4769                       /*LPLoc*/ ExpectedLParenLoc,
4770                       MultiExprArg(),
4771                       /*RPLoc*/ ExpectedLParenLoc);
4772}
4773
4774static bool CheckArrow(Sema& S, QualType& ObjectType, Expr *&Base,
4775                   tok::TokenKind& OpKind, SourceLocation OpLoc) {
4776  if (Base->hasPlaceholderType()) {
4777    ExprResult result = S.CheckPlaceholderExpr(Base);
4778    if (result.isInvalid()) return true;
4779    Base = result.take();
4780  }
4781  ObjectType = Base->getType();
4782
4783  // C++ [expr.pseudo]p2:
4784  //   The left-hand side of the dot operator shall be of scalar type. The
4785  //   left-hand side of the arrow operator shall be of pointer to scalar type.
4786  //   This scalar type is the object type.
4787  // Note that this is rather different from the normal handling for the
4788  // arrow operator.
4789  if (OpKind == tok::arrow) {
4790    if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
4791      ObjectType = Ptr->getPointeeType();
4792    } else if (!Base->isTypeDependent()) {
4793      // The user wrote "p->" when she probably meant "p."; fix it.
4794      S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
4795        << ObjectType << true
4796        << FixItHint::CreateReplacement(OpLoc, ".");
4797      if (S.isSFINAEContext())
4798        return true;
4799
4800      OpKind = tok::period;
4801    }
4802  }
4803
4804  return false;
4805}
4806
4807ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
4808                                           SourceLocation OpLoc,
4809                                           tok::TokenKind OpKind,
4810                                           const CXXScopeSpec &SS,
4811                                           TypeSourceInfo *ScopeTypeInfo,
4812                                           SourceLocation CCLoc,
4813                                           SourceLocation TildeLoc,
4814                                         PseudoDestructorTypeStorage Destructed,
4815                                           bool HasTrailingLParen) {
4816  TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
4817
4818  QualType ObjectType;
4819  if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
4820    return ExprError();
4821
4822  if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
4823    if (getLangOptions().MicrosoftMode && ObjectType->isVoidType())
4824      Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
4825    else
4826      Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
4827        << ObjectType << Base->getSourceRange();
4828    return ExprError();
4829  }
4830
4831  // C++ [expr.pseudo]p2:
4832  //   [...] The cv-unqualified versions of the object type and of the type
4833  //   designated by the pseudo-destructor-name shall be the same type.
4834  if (DestructedTypeInfo) {
4835    QualType DestructedType = DestructedTypeInfo->getType();
4836    SourceLocation DestructedTypeStart
4837      = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
4838    if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
4839      if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
4840        Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
4841          << ObjectType << DestructedType << Base->getSourceRange()
4842          << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
4843
4844        // Recover by setting the destructed type to the object type.
4845        DestructedType = ObjectType;
4846        DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
4847                                                           DestructedTypeStart);
4848        Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
4849      } else if (DestructedType.getObjCLifetime() !=
4850                                                ObjectType.getObjCLifetime()) {
4851
4852        if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
4853          // Okay: just pretend that the user provided the correctly-qualified
4854          // type.
4855        } else {
4856          Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
4857            << ObjectType << DestructedType << Base->getSourceRange()
4858            << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
4859        }
4860
4861        // Recover by setting the destructed type to the object type.
4862        DestructedType = ObjectType;
4863        DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
4864                                                           DestructedTypeStart);
4865        Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
4866      }
4867    }
4868  }
4869
4870  // C++ [expr.pseudo]p2:
4871  //   [...] Furthermore, the two type-names in a pseudo-destructor-name of the
4872  //   form
4873  //
4874  //     ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
4875  //
4876  //   shall designate the same scalar type.
4877  if (ScopeTypeInfo) {
4878    QualType ScopeType = ScopeTypeInfo->getType();
4879    if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
4880        !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
4881
4882      Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
4883           diag::err_pseudo_dtor_type_mismatch)
4884        << ObjectType << ScopeType << Base->getSourceRange()
4885        << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
4886
4887      ScopeType = QualType();
4888      ScopeTypeInfo = 0;
4889    }
4890  }
4891
4892  Expr *Result
4893    = new (Context) CXXPseudoDestructorExpr(Context, Base,
4894                                            OpKind == tok::arrow, OpLoc,
4895                                            SS.getWithLocInContext(Context),
4896                                            ScopeTypeInfo,
4897                                            CCLoc,
4898                                            TildeLoc,
4899                                            Destructed);
4900
4901  if (HasTrailingLParen)
4902    return Owned(Result);
4903
4904  return DiagnoseDtorReference(Destructed.getLocation(), Result);
4905}
4906
4907ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
4908                                           SourceLocation OpLoc,
4909                                           tok::TokenKind OpKind,
4910                                           CXXScopeSpec &SS,
4911                                           UnqualifiedId &FirstTypeName,
4912                                           SourceLocation CCLoc,
4913                                           SourceLocation TildeLoc,
4914                                           UnqualifiedId &SecondTypeName,
4915                                           bool HasTrailingLParen) {
4916  assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
4917          FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
4918         "Invalid first type name in pseudo-destructor");
4919  assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
4920          SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
4921         "Invalid second type name in pseudo-destructor");
4922
4923  QualType ObjectType;
4924  if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
4925    return ExprError();
4926
4927  // Compute the object type that we should use for name lookup purposes. Only
4928  // record types and dependent types matter.
4929  ParsedType ObjectTypePtrForLookup;
4930  if (!SS.isSet()) {
4931    if (ObjectType->isRecordType())
4932      ObjectTypePtrForLookup = ParsedType::make(ObjectType);
4933    else if (ObjectType->isDependentType())
4934      ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
4935  }
4936
4937  // Convert the name of the type being destructed (following the ~) into a
4938  // type (with source-location information).
4939  QualType DestructedType;
4940  TypeSourceInfo *DestructedTypeInfo = 0;
4941  PseudoDestructorTypeStorage Destructed;
4942  if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
4943    ParsedType T = getTypeName(*SecondTypeName.Identifier,
4944                               SecondTypeName.StartLocation,
4945                               S, &SS, true, false, ObjectTypePtrForLookup);
4946    if (!T &&
4947        ((SS.isSet() && !computeDeclContext(SS, false)) ||
4948         (!SS.isSet() && ObjectType->isDependentType()))) {
4949      // The name of the type being destroyed is a dependent name, and we
4950      // couldn't find anything useful in scope. Just store the identifier and
4951      // it's location, and we'll perform (qualified) name lookup again at
4952      // template instantiation time.
4953      Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
4954                                               SecondTypeName.StartLocation);
4955    } else if (!T) {
4956      Diag(SecondTypeName.StartLocation,
4957           diag::err_pseudo_dtor_destructor_non_type)
4958        << SecondTypeName.Identifier << ObjectType;
4959      if (isSFINAEContext())
4960        return ExprError();
4961
4962      // Recover by assuming we had the right type all along.
4963      DestructedType = ObjectType;
4964    } else
4965      DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
4966  } else {
4967    // Resolve the template-id to a type.
4968    TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
4969    ASTTemplateArgsPtr TemplateArgsPtr(*this,
4970                                       TemplateId->getTemplateArgs(),
4971                                       TemplateId->NumArgs);
4972    TypeResult T = ActOnTemplateIdType(TemplateId->SS,
4973                                       TemplateId->TemplateKWLoc,
4974                                       TemplateId->Template,
4975                                       TemplateId->TemplateNameLoc,
4976                                       TemplateId->LAngleLoc,
4977                                       TemplateArgsPtr,
4978                                       TemplateId->RAngleLoc);
4979    if (T.isInvalid() || !T.get()) {
4980      // Recover by assuming we had the right type all along.
4981      DestructedType = ObjectType;
4982    } else
4983      DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
4984  }
4985
4986  // If we've performed some kind of recovery, (re-)build the type source
4987  // information.
4988  if (!DestructedType.isNull()) {
4989    if (!DestructedTypeInfo)
4990      DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
4991                                                  SecondTypeName.StartLocation);
4992    Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
4993  }
4994
4995  // Convert the name of the scope type (the type prior to '::') into a type.
4996  TypeSourceInfo *ScopeTypeInfo = 0;
4997  QualType ScopeType;
4998  if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
4999      FirstTypeName.Identifier) {
5000    if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
5001      ParsedType T = getTypeName(*FirstTypeName.Identifier,
5002                                 FirstTypeName.StartLocation,
5003                                 S, &SS, true, false, ObjectTypePtrForLookup);
5004      if (!T) {
5005        Diag(FirstTypeName.StartLocation,
5006             diag::err_pseudo_dtor_destructor_non_type)
5007          << FirstTypeName.Identifier << ObjectType;
5008
5009        if (isSFINAEContext())
5010          return ExprError();
5011
5012        // Just drop this type. It's unnecessary anyway.
5013        ScopeType = QualType();
5014      } else
5015        ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
5016    } else {
5017      // Resolve the template-id to a type.
5018      TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
5019      ASTTemplateArgsPtr TemplateArgsPtr(*this,
5020                                         TemplateId->getTemplateArgs(),
5021                                         TemplateId->NumArgs);
5022      TypeResult T = ActOnTemplateIdType(TemplateId->SS,
5023                                         TemplateId->TemplateKWLoc,
5024                                         TemplateId->Template,
5025                                         TemplateId->TemplateNameLoc,
5026                                         TemplateId->LAngleLoc,
5027                                         TemplateArgsPtr,
5028                                         TemplateId->RAngleLoc);
5029      if (T.isInvalid() || !T.get()) {
5030        // Recover by dropping this type.
5031        ScopeType = QualType();
5032      } else
5033        ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
5034    }
5035  }
5036
5037  if (!ScopeType.isNull() && !ScopeTypeInfo)
5038    ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
5039                                                  FirstTypeName.StartLocation);
5040
5041
5042  return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
5043                                   ScopeTypeInfo, CCLoc, TildeLoc,
5044                                   Destructed, HasTrailingLParen);
5045}
5046
5047ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
5048                                           SourceLocation OpLoc,
5049                                           tok::TokenKind OpKind,
5050                                           SourceLocation TildeLoc,
5051                                           const DeclSpec& DS,
5052                                           bool HasTrailingLParen) {
5053  QualType ObjectType;
5054  if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
5055    return ExprError();
5056
5057  QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
5058
5059  TypeLocBuilder TLB;
5060  DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
5061  DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
5062  TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
5063  PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
5064
5065  return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
5066                                   0, SourceLocation(), TildeLoc,
5067                                   Destructed, HasTrailingLParen);
5068}
5069
5070ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
5071                                        CXXMethodDecl *Method,
5072                                        bool HadMultipleCandidates) {
5073  ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/0,
5074                                          FoundDecl, Method);
5075  if (Exp.isInvalid())
5076    return true;
5077
5078  MemberExpr *ME =
5079      new (Context) MemberExpr(Exp.take(), /*IsArrow=*/false, Method,
5080                               SourceLocation(), Context.BoundMemberTy,
5081                               VK_RValue, OK_Ordinary);
5082  if (HadMultipleCandidates)
5083    ME->setHadMultipleCandidates(true);
5084
5085  QualType ResultType = Method->getResultType();
5086  ExprValueKind VK = Expr::getValueKindForType(ResultType);
5087  ResultType = ResultType.getNonLValueExprType(Context);
5088
5089  MarkFunctionReferenced(Exp.get()->getLocStart(), Method);
5090  CXXMemberCallExpr *CE =
5091    new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType, VK,
5092                                    Exp.get()->getLocEnd());
5093  return CE;
5094}
5095
5096ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
5097                                      SourceLocation RParen) {
5098  return Owned(new (Context) CXXNoexceptExpr(Context.BoolTy, Operand,
5099                                             Operand->CanThrow(Context),
5100                                             KeyLoc, RParen));
5101}
5102
5103ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
5104                                   Expr *Operand, SourceLocation RParen) {
5105  return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
5106}
5107
5108/// Perform the conversions required for an expression used in a
5109/// context that ignores the result.
5110ExprResult Sema::IgnoredValueConversions(Expr *E) {
5111  if (E->hasPlaceholderType()) {
5112    ExprResult result = CheckPlaceholderExpr(E);
5113    if (result.isInvalid()) return Owned(E);
5114    E = result.take();
5115  }
5116
5117  // C99 6.3.2.1:
5118  //   [Except in specific positions,] an lvalue that does not have
5119  //   array type is converted to the value stored in the
5120  //   designated object (and is no longer an lvalue).
5121  if (E->isRValue()) {
5122    // In C, function designators (i.e. expressions of function type)
5123    // are r-values, but we still want to do function-to-pointer decay
5124    // on them.  This is both technically correct and convenient for
5125    // some clients.
5126    if (!getLangOptions().CPlusPlus && E->getType()->isFunctionType())
5127      return DefaultFunctionArrayConversion(E);
5128
5129    return Owned(E);
5130  }
5131
5132  // Otherwise, this rule does not apply in C++, at least not for the moment.
5133  if (getLangOptions().CPlusPlus) return Owned(E);
5134
5135  // GCC seems to also exclude expressions of incomplete enum type.
5136  if (const EnumType *T = E->getType()->getAs<EnumType>()) {
5137    if (!T->getDecl()->isComplete()) {
5138      // FIXME: stupid workaround for a codegen bug!
5139      E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).take();
5140      return Owned(E);
5141    }
5142  }
5143
5144  ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
5145  if (Res.isInvalid())
5146    return Owned(E);
5147  E = Res.take();
5148
5149  if (!E->getType()->isVoidType())
5150    RequireCompleteType(E->getExprLoc(), E->getType(),
5151                        diag::err_incomplete_type);
5152  return Owned(E);
5153}
5154
5155ExprResult Sema::ActOnFinishFullExpr(Expr *FE) {
5156  ExprResult FullExpr = Owned(FE);
5157
5158  if (!FullExpr.get())
5159    return ExprError();
5160
5161  if (DiagnoseUnexpandedParameterPack(FullExpr.get()))
5162    return ExprError();
5163
5164  // Top-level message sends default to 'id' when we're in a debugger.
5165  if (getLangOptions().DebuggerCastResultToId &&
5166      FullExpr.get()->getType() == Context.UnknownAnyTy &&
5167      isa<ObjCMessageExpr>(FullExpr.get())) {
5168    FullExpr = forceUnknownAnyToType(FullExpr.take(), Context.getObjCIdType());
5169    if (FullExpr.isInvalid())
5170      return ExprError();
5171  }
5172
5173  FullExpr = CheckPlaceholderExpr(FullExpr.take());
5174  if (FullExpr.isInvalid())
5175    return ExprError();
5176
5177  FullExpr = IgnoredValueConversions(FullExpr.take());
5178  if (FullExpr.isInvalid())
5179    return ExprError();
5180
5181  CheckImplicitConversions(FullExpr.get(), FullExpr.get()->getExprLoc());
5182  return MaybeCreateExprWithCleanups(FullExpr);
5183}
5184
5185StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
5186  if (!FullStmt) return StmtError();
5187
5188  return MaybeCreateStmtWithCleanups(FullStmt);
5189}
5190
5191Sema::IfExistsResult
5192Sema::CheckMicrosoftIfExistsSymbol(Scope *S,
5193                                   CXXScopeSpec &SS,
5194                                   const DeclarationNameInfo &TargetNameInfo) {
5195  DeclarationName TargetName = TargetNameInfo.getName();
5196  if (!TargetName)
5197    return IER_DoesNotExist;
5198
5199  // If the name itself is dependent, then the result is dependent.
5200  if (TargetName.isDependentName())
5201    return IER_Dependent;
5202
5203  // Do the redeclaration lookup in the current scope.
5204  LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
5205                 Sema::NotForRedeclaration);
5206  LookupParsedName(R, S, &SS);
5207  R.suppressDiagnostics();
5208
5209  switch (R.getResultKind()) {
5210  case LookupResult::Found:
5211  case LookupResult::FoundOverloaded:
5212  case LookupResult::FoundUnresolvedValue:
5213  case LookupResult::Ambiguous:
5214    return IER_Exists;
5215
5216  case LookupResult::NotFound:
5217    return IER_DoesNotExist;
5218
5219  case LookupResult::NotFoundInCurrentInstantiation:
5220    return IER_Dependent;
5221  }
5222
5223  llvm_unreachable("Invalid LookupResult Kind!");
5224}
5225
5226Sema::IfExistsResult
5227Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
5228                                   bool IsIfExists, CXXScopeSpec &SS,
5229                                   UnqualifiedId &Name) {
5230  DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
5231
5232  // Check for unexpanded parameter packs.
5233  SmallVector<UnexpandedParameterPack, 4> Unexpanded;
5234  collectUnexpandedParameterPacks(SS, Unexpanded);
5235  collectUnexpandedParameterPacks(TargetNameInfo, Unexpanded);
5236  if (!Unexpanded.empty()) {
5237    DiagnoseUnexpandedParameterPacks(KeywordLoc,
5238                                     IsIfExists? UPPC_IfExists
5239                                               : UPPC_IfNotExists,
5240                                     Unexpanded);
5241    return IER_Error;
5242  }
5243
5244  return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
5245}
5246