1193326Sed//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2193326Sed//
3193326Sed//                     The LLVM Compiler Infrastructure
4193326Sed//
5193326Sed// This file is distributed under the University of Illinois Open Source
6193326Sed// License. See LICENSE.TXT for details.
7193326Sed//
8193326Sed//===----------------------------------------------------------------------===//
9239462Sdim///
10239462Sdim/// \file
11239462Sdim/// \brief Implements semantic analysis for C++ expressions.
12239462Sdim///
13193326Sed//===----------------------------------------------------------------------===//
14193326Sed
15212904Sdim#include "clang/Sema/SemaInternal.h"
16249423Sdim#include "TypeLocBuilder.h"
17198092Srdivacky#include "clang/AST/ASTContext.h"
18249423Sdim#include "clang/AST/CXXInheritance.h"
19234353Sdim#include "clang/AST/CharUnits.h"
20212904Sdim#include "clang/AST/DeclObjC.h"
21249423Sdim#include "clang/AST/EvaluatedExprVisitor.h"
22193326Sed#include "clang/AST/ExprCXX.h"
23210299Sed#include "clang/AST/ExprObjC.h"
24263508Sdim#include "clang/AST/RecursiveASTVisitor.h"
25204643Srdivacky#include "clang/AST/TypeLoc.h"
26198092Srdivacky#include "clang/Basic/PartialDiagnostic.h"
27198092Srdivacky#include "clang/Basic/TargetInfo.h"
28198092Srdivacky#include "clang/Lex/Preprocessor.h"
29249423Sdim#include "clang/Sema/DeclSpec.h"
30249423Sdim#include "clang/Sema/Initialization.h"
31249423Sdim#include "clang/Sema/Lookup.h"
32249423Sdim#include "clang/Sema/ParsedTemplate.h"
33249423Sdim#include "clang/Sema/Scope.h"
34249423Sdim#include "clang/Sema/ScopeInfo.h"
35263508Sdim#include "clang/Sema/SemaLambda.h"
36249423Sdim#include "clang/Sema/TemplateDeduction.h"
37234353Sdim#include "llvm/ADT/APInt.h"
38193326Sed#include "llvm/ADT/STLExtras.h"
39221345Sdim#include "llvm/Support/ErrorHandling.h"
40193326Sedusing namespace clang;
41212904Sdimusing namespace sema;
42193326Sed
43249423Sdim/// \brief Handle the result of the special case name lookup for inheriting
44249423Sdim/// constructor declarations. 'NS::X::X' and 'NS::X<...>::X' are treated as
45249423Sdim/// constructor names in member using declarations, even if 'X' is not the
46249423Sdim/// name of the corresponding type.
47249423SdimParsedType Sema::getInheritingConstructorName(CXXScopeSpec &SS,
48249423Sdim                                              SourceLocation NameLoc,
49249423Sdim                                              IdentifierInfo &Name) {
50249423Sdim  NestedNameSpecifier *NNS = SS.getScopeRep();
51249423Sdim
52249423Sdim  // Convert the nested-name-specifier into a type.
53249423Sdim  QualType Type;
54249423Sdim  switch (NNS->getKind()) {
55249423Sdim  case NestedNameSpecifier::TypeSpec:
56249423Sdim  case NestedNameSpecifier::TypeSpecWithTemplate:
57249423Sdim    Type = QualType(NNS->getAsType(), 0);
58249423Sdim    break;
59249423Sdim
60249423Sdim  case NestedNameSpecifier::Identifier:
61249423Sdim    // Strip off the last layer of the nested-name-specifier and build a
62249423Sdim    // typename type for it.
63249423Sdim    assert(NNS->getAsIdentifier() == &Name && "not a constructor name");
64249423Sdim    Type = Context.getDependentNameType(ETK_None, NNS->getPrefix(),
65249423Sdim                                        NNS->getAsIdentifier());
66249423Sdim    break;
67249423Sdim
68249423Sdim  case NestedNameSpecifier::Global:
69249423Sdim  case NestedNameSpecifier::Namespace:
70249423Sdim  case NestedNameSpecifier::NamespaceAlias:
71249423Sdim    llvm_unreachable("Nested name specifier is not a type for inheriting ctor");
72249423Sdim  }
73249423Sdim
74249423Sdim  // This reference to the type is located entirely at the location of the
75249423Sdim  // final identifier in the qualified-id.
76249423Sdim  return CreateParsedType(Type,
77249423Sdim                          Context.getTrivialTypeSourceInfo(Type, NameLoc));
78249423Sdim}
79249423Sdim
80212904SdimParsedType Sema::getDestructorName(SourceLocation TildeLoc,
81218893Sdim                                   IdentifierInfo &II,
82212904Sdim                                   SourceLocation NameLoc,
83212904Sdim                                   Scope *S, CXXScopeSpec &SS,
84212904Sdim                                   ParsedType ObjectTypePtr,
85212904Sdim                                   bool EnteringContext) {
86204643Srdivacky  // Determine where to perform name lookup.
87204643Srdivacky
88204643Srdivacky  // FIXME: This area of the standard is very messy, and the current
89204643Srdivacky  // wording is rather unclear about which scopes we search for the
90204643Srdivacky  // destructor name; see core issues 399 and 555. Issue 399 in
91204643Srdivacky  // particular shows where the current description of destructor name
92204643Srdivacky  // lookup is completely out of line with existing practice, e.g.,
93204643Srdivacky  // this appears to be ill-formed:
94204643Srdivacky  //
95204643Srdivacky  //   namespace N {
96204643Srdivacky  //     template <typename T> struct S {
97204643Srdivacky  //       ~S();
98204643Srdivacky  //     };
99204643Srdivacky  //   }
100204643Srdivacky  //
101204643Srdivacky  //   void f(N::S<int>* s) {
102204643Srdivacky  //     s->N::S<int>::~S();
103204643Srdivacky  //   }
104204643Srdivacky  //
105204643Srdivacky  // See also PR6358 and PR6359.
106210299Sed  // For this reason, we're currently only doing the C++03 version of this
107210299Sed  // code; the C++0x version has to wait until we get a proper spec.
108204643Srdivacky  QualType SearchType;
109204643Srdivacky  DeclContext *LookupCtx = 0;
110204643Srdivacky  bool isDependent = false;
111204643Srdivacky  bool LookInScope = false;
112204643Srdivacky
113204643Srdivacky  // If we have an object type, it's because we are in a
114204643Srdivacky  // pseudo-destructor-expression or a member access expression, and
115204643Srdivacky  // we know what type we're looking for.
116204643Srdivacky  if (ObjectTypePtr)
117204643Srdivacky    SearchType = GetTypeFromParser(ObjectTypePtr);
118204643Srdivacky
119204643Srdivacky  if (SS.isSet()) {
120204643Srdivacky    NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
121218893Sdim
122204643Srdivacky    bool AlreadySearched = false;
123204643Srdivacky    bool LookAtPrefix = true;
124210299Sed    // C++ [basic.lookup.qual]p6:
125218893Sdim    //   If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
126210299Sed    //   the type-names are looked up as types in the scope designated by the
127210299Sed    //   nested-name-specifier. In a qualified-id of the form:
128210299Sed    //
129218893Sdim    //     ::[opt] nested-name-specifier  ~ class-name
130218893Sdim    //
131210299Sed    //   where the nested-name-specifier designates a namespace scope, and in
132204643Srdivacky    //   a qualified-id of the form:
133204643Srdivacky    //
134218893Sdim    //     ::opt nested-name-specifier class-name ::  ~ class-name
135204643Srdivacky    //
136218893Sdim    //   the class-names are looked up as types in the scope designated by
137210299Sed    //   the nested-name-specifier.
138204643Srdivacky    //
139210299Sed    // Here, we check the first case (completely) and determine whether the
140218893Sdim    // code below is permitted to look at the prefix of the
141210299Sed    // nested-name-specifier.
142210299Sed    DeclContext *DC = computeDeclContext(SS, EnteringContext);
143210299Sed    if (DC && DC->isFileContext()) {
144210299Sed      AlreadySearched = true;
145210299Sed      LookupCtx = DC;
146210299Sed      isDependent = false;
147210299Sed    } else if (DC && isa<CXXRecordDecl>(DC))
148210299Sed      LookAtPrefix = false;
149218893Sdim
150210299Sed    // The second case from the C++03 rules quoted further above.
151204643Srdivacky    NestedNameSpecifier *Prefix = 0;
152204643Srdivacky    if (AlreadySearched) {
153204643Srdivacky      // Nothing left to do.
154204643Srdivacky    } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
155204643Srdivacky      CXXScopeSpec PrefixSS;
156219077Sdim      PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
157204643Srdivacky      LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
158204643Srdivacky      isDependent = isDependentScopeSpecifier(PrefixSS);
159204643Srdivacky    } else if (ObjectTypePtr) {
160204643Srdivacky      LookupCtx = computeDeclContext(SearchType);
161204643Srdivacky      isDependent = SearchType->isDependentType();
162204643Srdivacky    } else {
163204643Srdivacky      LookupCtx = computeDeclContext(SS, EnteringContext);
164204643Srdivacky      isDependent = LookupCtx && LookupCtx->isDependentContext();
165204643Srdivacky    }
166218893Sdim
167204643Srdivacky    LookInScope = false;
168204643Srdivacky  } else if (ObjectTypePtr) {
169204643Srdivacky    // C++ [basic.lookup.classref]p3:
170204643Srdivacky    //   If the unqualified-id is ~type-name, the type-name is looked up
171204643Srdivacky    //   in the context of the entire postfix-expression. If the type T
172204643Srdivacky    //   of the object expression is of a class type C, the type-name is
173204643Srdivacky    //   also looked up in the scope of class C. At least one of the
174204643Srdivacky    //   lookups shall find a name that refers to (possibly
175204643Srdivacky    //   cv-qualified) T.
176204643Srdivacky    LookupCtx = computeDeclContext(SearchType);
177204643Srdivacky    isDependent = SearchType->isDependentType();
178218893Sdim    assert((isDependent || !SearchType->isIncompleteType()) &&
179204643Srdivacky           "Caller should have completed object type");
180204643Srdivacky
181204643Srdivacky    LookInScope = true;
182204643Srdivacky  } else {
183204643Srdivacky    // Perform lookup into the current scope (only).
184204643Srdivacky    LookInScope = true;
185204643Srdivacky  }
186204643Srdivacky
187221345Sdim  TypeDecl *NonMatchingTypeDecl = 0;
188204643Srdivacky  LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
189204643Srdivacky  for (unsigned Step = 0; Step != 2; ++Step) {
190204643Srdivacky    // Look for the name first in the computed lookup context (if we
191221345Sdim    // have one) and, if that fails to find a match, in the scope (if
192204643Srdivacky    // we're allowed to look there).
193204643Srdivacky    Found.clear();
194204643Srdivacky    if (Step == 0 && LookupCtx)
195204643Srdivacky      LookupQualifiedName(Found, LookupCtx);
196204643Srdivacky    else if (Step == 1 && LookInScope && S)
197204643Srdivacky      LookupName(Found, S);
198204643Srdivacky    else
199204643Srdivacky      continue;
200204643Srdivacky
201204643Srdivacky    // FIXME: Should we be suppressing ambiguities here?
202204643Srdivacky    if (Found.isAmbiguous())
203212904Sdim      return ParsedType();
204204643Srdivacky
205204643Srdivacky    if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
206204643Srdivacky      QualType T = Context.getTypeDeclType(Type);
207204643Srdivacky
208204643Srdivacky      if (SearchType.isNull() || SearchType->isDependentType() ||
209204643Srdivacky          Context.hasSameUnqualifiedType(T, SearchType)) {
210204643Srdivacky        // We found our type!
211204643Srdivacky
212212904Sdim        return ParsedType::make(T);
213204643Srdivacky      }
214221345Sdim
215221345Sdim      if (!SearchType.isNull())
216221345Sdim        NonMatchingTypeDecl = Type;
217204643Srdivacky    }
218204643Srdivacky
219204643Srdivacky    // If the name that we found is a class template name, and it is
220204643Srdivacky    // the same name as the template name in the last part of the
221204643Srdivacky    // nested-name-specifier (if present) or the object type, then
222204643Srdivacky    // this is the destructor for that class.
223204643Srdivacky    // FIXME: This is a workaround until we get real drafting for core
224218893Sdim    // issue 399, for which there isn't even an obvious direction.
225204643Srdivacky    if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
226204643Srdivacky      QualType MemberOfType;
227204643Srdivacky      if (SS.isSet()) {
228204643Srdivacky        if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
229204643Srdivacky          // Figure out the type of the context, if it has one.
230204962Srdivacky          if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
231204962Srdivacky            MemberOfType = Context.getTypeDeclType(Record);
232204643Srdivacky        }
233204643Srdivacky      }
234204643Srdivacky      if (MemberOfType.isNull())
235204643Srdivacky        MemberOfType = SearchType;
236218893Sdim
237204643Srdivacky      if (MemberOfType.isNull())
238204643Srdivacky        continue;
239204643Srdivacky
240204643Srdivacky      // We're referring into a class template specialization. If the
241204643Srdivacky      // class template we found is the same as the template being
242204643Srdivacky      // specialized, we found what we are looking for.
243204643Srdivacky      if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
244204643Srdivacky        if (ClassTemplateSpecializationDecl *Spec
245204643Srdivacky              = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
246204643Srdivacky          if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
247204643Srdivacky                Template->getCanonicalDecl())
248212904Sdim            return ParsedType::make(MemberOfType);
249204643Srdivacky        }
250204643Srdivacky
251204643Srdivacky        continue;
252204643Srdivacky      }
253218893Sdim
254204643Srdivacky      // We're referring to an unresolved class template
255204643Srdivacky      // specialization. Determine whether we class template we found
256204643Srdivacky      // is the same as the template being specialized or, if we don't
257204643Srdivacky      // know which template is being specialized, that it at least
258204643Srdivacky      // has the same name.
259204643Srdivacky      if (const TemplateSpecializationType *SpecType
260204643Srdivacky            = MemberOfType->getAs<TemplateSpecializationType>()) {
261204643Srdivacky        TemplateName SpecName = SpecType->getTemplateName();
262204643Srdivacky
263204643Srdivacky        // The class template we found is the same template being
264204643Srdivacky        // specialized.
265204643Srdivacky        if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
266204643Srdivacky          if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
267212904Sdim            return ParsedType::make(MemberOfType);
268204643Srdivacky
269204643Srdivacky          continue;
270204643Srdivacky        }
271204643Srdivacky
272204643Srdivacky        // The class template we found has the same name as the
273204643Srdivacky        // (dependent) template name being specialized.
274218893Sdim        if (DependentTemplateName *DepTemplate
275204643Srdivacky                                    = SpecName.getAsDependentTemplateName()) {
276204643Srdivacky          if (DepTemplate->isIdentifier() &&
277204643Srdivacky              DepTemplate->getIdentifier() == Template->getIdentifier())
278212904Sdim            return ParsedType::make(MemberOfType);
279204643Srdivacky
280204643Srdivacky          continue;
281204643Srdivacky        }
282204643Srdivacky      }
283204643Srdivacky    }
284204643Srdivacky  }
285204643Srdivacky
286204643Srdivacky  if (isDependent) {
287204643Srdivacky    // We didn't find our type, but that's okay: it's dependent
288204643Srdivacky    // anyway.
289221345Sdim
290221345Sdim    // FIXME: What if we have no nested-name-specifier?
291221345Sdim    QualType T = CheckTypenameType(ETK_None, SourceLocation(),
292221345Sdim                                   SS.getWithLocInContext(Context),
293221345Sdim                                   II, NameLoc);
294212904Sdim    return ParsedType::make(T);
295204643Srdivacky  }
296204643Srdivacky
297221345Sdim  if (NonMatchingTypeDecl) {
298221345Sdim    QualType T = Context.getTypeDeclType(NonMatchingTypeDecl);
299221345Sdim    Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
300221345Sdim      << T << SearchType;
301221345Sdim    Diag(NonMatchingTypeDecl->getLocation(), diag::note_destructor_type_here)
302221345Sdim      << T;
303221345Sdim  } else if (ObjectTypePtr)
304221345Sdim    Diag(NameLoc, diag::err_ident_in_dtor_not_a_type)
305218893Sdim      << &II;
306249423Sdim  else {
307249423Sdim    SemaDiagnosticBuilder DtorDiag = Diag(NameLoc,
308249423Sdim                                          diag::err_destructor_class_name);
309249423Sdim    if (S) {
310263508Sdim      const DeclContext *Ctx = S->getEntity();
311249423Sdim      if (const CXXRecordDecl *Class = dyn_cast_or_null<CXXRecordDecl>(Ctx))
312249423Sdim        DtorDiag << FixItHint::CreateReplacement(SourceRange(NameLoc),
313249423Sdim                                                 Class->getNameAsString());
314249423Sdim    }
315249423Sdim  }
316204643Srdivacky
317212904Sdim  return ParsedType();
318204643Srdivacky}
319204643Srdivacky
320234353SdimParsedType Sema::getDestructorType(const DeclSpec& DS, ParsedType ObjectType) {
321234353Sdim    if (DS.getTypeSpecType() == DeclSpec::TST_error || !ObjectType)
322234353Sdim      return ParsedType();
323234353Sdim    assert(DS.getTypeSpecType() == DeclSpec::TST_decltype
324234353Sdim           && "only get destructor types from declspecs");
325234353Sdim    QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
326234353Sdim    QualType SearchType = GetTypeFromParser(ObjectType);
327234353Sdim    if (SearchType->isDependentType() || Context.hasSameUnqualifiedType(SearchType, T)) {
328234353Sdim      return ParsedType::make(T);
329234353Sdim    }
330234353Sdim
331234353Sdim    Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)
332234353Sdim      << T << SearchType;
333234353Sdim    return ParsedType();
334234353Sdim}
335234353Sdim
336207619Srdivacky/// \brief Build a C++ typeid expression with a type operand.
337212904SdimExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
338218893Sdim                                SourceLocation TypeidLoc,
339218893Sdim                                TypeSourceInfo *Operand,
340218893Sdim                                SourceLocation RParenLoc) {
341207619Srdivacky  // C++ [expr.typeid]p4:
342218893Sdim  //   The top-level cv-qualifiers of the lvalue expression or the type-id
343207619Srdivacky  //   that is the operand of typeid are always ignored.
344218893Sdim  //   If the type of the type-id is a class type or a reference to a class
345207619Srdivacky  //   type, the class shall be completely-defined.
346210299Sed  Qualifiers Quals;
347210299Sed  QualType T
348210299Sed    = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
349210299Sed                                      Quals);
350207619Srdivacky  if (T->getAs<RecordType>() &&
351207619Srdivacky      RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
352207619Srdivacky    return ExprError();
353218893Sdim
354207619Srdivacky  return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
355207619Srdivacky                                           Operand,
356207619Srdivacky                                           SourceRange(TypeidLoc, RParenLoc)));
357207619Srdivacky}
358207619Srdivacky
359207619Srdivacky/// \brief Build a C++ typeid expression with an expression operand.
360212904SdimExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
361218893Sdim                                SourceLocation TypeidLoc,
362218893Sdim                                Expr *E,
363218893Sdim                                SourceLocation RParenLoc) {
364207619Srdivacky  if (E && !E->isTypeDependent()) {
365226633Sdim    if (E->getType()->isPlaceholderType()) {
366226633Sdim      ExprResult result = CheckPlaceholderExpr(E);
367226633Sdim      if (result.isInvalid()) return ExprError();
368226633Sdim      E = result.take();
369226633Sdim    }
370226633Sdim
371207619Srdivacky    QualType T = E->getType();
372207619Srdivacky    if (const RecordType *RecordT = T->getAs<RecordType>()) {
373207619Srdivacky      CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
374207619Srdivacky      // C++ [expr.typeid]p3:
375207619Srdivacky      //   [...] If the type of the expression is a class type, the class
376207619Srdivacky      //   shall be completely-defined.
377207619Srdivacky      if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
378207619Srdivacky        return ExprError();
379218893Sdim
380207619Srdivacky      // C++ [expr.typeid]p3:
381212904Sdim      //   When typeid is applied to an expression other than an glvalue of a
382207619Srdivacky      //   polymorphic class type [...] [the] expression is an unevaluated
383207619Srdivacky      //   operand. [...]
384239462Sdim      if (RecordD->isPolymorphic() && E->isGLValue()) {
385234353Sdim        // The subexpression is potentially evaluated; switch the context
386234353Sdim        // and recheck the subexpression.
387249423Sdim        ExprResult Result = TransformToPotentiallyEvaluated(E);
388234353Sdim        if (Result.isInvalid()) return ExprError();
389234353Sdim        E = Result.take();
390208600Srdivacky
391208600Srdivacky        // We require a vtable to query the type at run time.
392208600Srdivacky        MarkVTableUsed(TypeidLoc, RecordD);
393208600Srdivacky      }
394207619Srdivacky    }
395218893Sdim
396207619Srdivacky    // C++ [expr.typeid]p4:
397207619Srdivacky    //   [...] If the type of the type-id is a reference to a possibly
398218893Sdim    //   cv-qualified type, the result of the typeid expression refers to a
399218893Sdim    //   std::type_info object representing the cv-unqualified referenced
400207619Srdivacky    //   type.
401210299Sed    Qualifiers Quals;
402210299Sed    QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
403210299Sed    if (!Context.hasSameType(T, UnqualT)) {
404210299Sed      T = UnqualT;
405226633Sdim      E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).take();
406207619Srdivacky    }
407207619Srdivacky  }
408218893Sdim
409207619Srdivacky  return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
410212904Sdim                                           E,
411218893Sdim                                           SourceRange(TypeidLoc, RParenLoc)));
412207619Srdivacky}
413207619Srdivacky
414207619Srdivacky/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
415212904SdimExprResult
416193326SedSema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
417193326Sed                     bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
418207619Srdivacky  // Find the std::type_info type.
419221345Sdim  if (!getStdNamespace())
420193326Sed    return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
421198092Srdivacky
422218893Sdim  if (!CXXTypeInfoDecl) {
423218893Sdim    IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
424218893Sdim    LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
425218893Sdim    LookupQualifiedName(R, getStdNamespace());
426218893Sdim    CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
427239462Sdim    // Microsoft's typeinfo doesn't have type_info in std but in the global
428239462Sdim    // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153.
429239462Sdim    if (!CXXTypeInfoDecl && LangOpts.MicrosoftMode) {
430239462Sdim      LookupQualifiedName(R, Context.getTranslationUnitDecl());
431239462Sdim      CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
432239462Sdim    }
433218893Sdim    if (!CXXTypeInfoDecl)
434218893Sdim      return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
435218893Sdim  }
436218893Sdim
437239462Sdim  if (!getLangOpts().RTTI) {
438239462Sdim    return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti));
439239462Sdim  }
440239462Sdim
441218893Sdim  QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
442218893Sdim
443207619Srdivacky  if (isType) {
444207619Srdivacky    // The operand is a type; handle it as such.
445207619Srdivacky    TypeSourceInfo *TInfo = 0;
446212904Sdim    QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
447212904Sdim                                   &TInfo);
448207619Srdivacky    if (T.isNull())
449207619Srdivacky      return ExprError();
450218893Sdim
451207619Srdivacky    if (!TInfo)
452207619Srdivacky      TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
453193326Sed
454207619Srdivacky    return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
455194711Sed  }
456198092Srdivacky
457218893Sdim  // The operand is an expression.
458212904Sdim  return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
459193326Sed}
460193326Sed
461218893Sdim/// \brief Build a Microsoft __uuidof expression with a type operand.
462218893SdimExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
463218893Sdim                                SourceLocation TypeidLoc,
464218893Sdim                                TypeSourceInfo *Operand,
465218893Sdim                                SourceLocation RParenLoc) {
466218893Sdim  if (!Operand->getType()->isDependentType()) {
467263508Sdim    bool HasMultipleGUIDs = false;
468263508Sdim    if (!CXXUuidofExpr::GetUuidAttrOfType(Operand->getType(),
469263508Sdim                                          &HasMultipleGUIDs)) {
470263508Sdim      if (HasMultipleGUIDs)
471263508Sdim        return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
472263508Sdim      else
473263508Sdim        return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
474263508Sdim    }
475218893Sdim  }
476218893Sdim
477218893Sdim  return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
478218893Sdim                                           Operand,
479218893Sdim                                           SourceRange(TypeidLoc, RParenLoc)));
480218893Sdim}
481218893Sdim
482218893Sdim/// \brief Build a Microsoft __uuidof expression with an expression operand.
483218893SdimExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
484218893Sdim                                SourceLocation TypeidLoc,
485218893Sdim                                Expr *E,
486218893Sdim                                SourceLocation RParenLoc) {
487218893Sdim  if (!E->getType()->isDependentType()) {
488263508Sdim    bool HasMultipleGUIDs = false;
489263508Sdim    if (!CXXUuidofExpr::GetUuidAttrOfType(E->getType(), &HasMultipleGUIDs) &&
490263508Sdim        !E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
491263508Sdim      if (HasMultipleGUIDs)
492263508Sdim        return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
493263508Sdim      else
494263508Sdim        return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
495263508Sdim    }
496218893Sdim  }
497263508Sdim
498218893Sdim  return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
499218893Sdim                                           E,
500218893Sdim                                           SourceRange(TypeidLoc, RParenLoc)));
501218893Sdim}
502218893Sdim
503218893Sdim/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
504218893SdimExprResult
505218893SdimSema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
506218893Sdim                     bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
507218893Sdim  // If MSVCGuidDecl has not been cached, do the lookup.
508218893Sdim  if (!MSVCGuidDecl) {
509218893Sdim    IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
510218893Sdim    LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
511218893Sdim    LookupQualifiedName(R, Context.getTranslationUnitDecl());
512218893Sdim    MSVCGuidDecl = R.getAsSingle<RecordDecl>();
513218893Sdim    if (!MSVCGuidDecl)
514218893Sdim      return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
515218893Sdim  }
516218893Sdim
517218893Sdim  QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
518218893Sdim
519218893Sdim  if (isType) {
520218893Sdim    // The operand is a type; handle it as such.
521218893Sdim    TypeSourceInfo *TInfo = 0;
522218893Sdim    QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
523218893Sdim                                   &TInfo);
524218893Sdim    if (T.isNull())
525218893Sdim      return ExprError();
526218893Sdim
527218893Sdim    if (!TInfo)
528218893Sdim      TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
529218893Sdim
530218893Sdim    return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
531218893Sdim  }
532218893Sdim
533218893Sdim  // The operand is an expression.
534218893Sdim  return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
535218893Sdim}
536218893Sdim
537193326Sed/// ActOnCXXBoolLiteral - Parse {true,false} literals.
538212904SdimExprResult
539193326SedSema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
540193326Sed  assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
541193326Sed         "Unknown C++ Boolean value!");
542193326Sed  return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
543193326Sed                                                Context.BoolTy, OpLoc));
544193326Sed}
545193326Sed
546193326Sed/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
547212904SdimExprResult
548193326SedSema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
549193326Sed  return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
550193326Sed}
551193326Sed
552193326Sed/// ActOnCXXThrow - Parse throw expressions.
553212904SdimExprResult
554224145SdimSema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) {
555224145Sdim  bool IsThrownVarInScope = false;
556224145Sdim  if (Ex) {
557224145Sdim    // C++0x [class.copymove]p31:
558224145Sdim    //   When certain criteria are met, an implementation is allowed to omit the
559224145Sdim    //   copy/move construction of a class object [...]
560224145Sdim    //
561224145Sdim    //     - in a throw-expression, when the operand is the name of a
562224145Sdim    //       non-volatile automatic object (other than a function or catch-
563224145Sdim    //       clause parameter) whose scope does not extend beyond the end of the
564224145Sdim    //       innermost enclosing try-block (if there is one), the copy/move
565224145Sdim    //       operation from the operand to the exception object (15.1) can be
566224145Sdim    //       omitted by constructing the automatic object directly into the
567224145Sdim    //       exception object
568224145Sdim    if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
569224145Sdim      if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
570224145Sdim        if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) {
571224145Sdim          for( ; S; S = S->getParent()) {
572224145Sdim            if (S->isDeclScope(Var)) {
573224145Sdim              IsThrownVarInScope = true;
574224145Sdim              break;
575224145Sdim            }
576224145Sdim
577224145Sdim            if (S->getFlags() &
578224145Sdim                (Scope::FnScope | Scope::ClassScope | Scope::BlockScope |
579224145Sdim                 Scope::FunctionPrototypeScope | Scope::ObjCMethodScope |
580224145Sdim                 Scope::TryScope))
581224145Sdim              break;
582224145Sdim          }
583224145Sdim        }
584224145Sdim      }
585224145Sdim  }
586224145Sdim
587224145Sdim  return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
588224145Sdim}
589224145Sdim
590224145SdimExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
591224145Sdim                               bool IsThrownVarInScope) {
592219077Sdim  // Don't report an error if 'throw' is used in system headers.
593234353Sdim  if (!getLangOpts().CXXExceptions &&
594219077Sdim      !getSourceManager().isInSystemHeader(OpLoc))
595218893Sdim    Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
596224145Sdim
597221345Sdim  if (Ex && !Ex->isTypeDependent()) {
598224145Sdim    ExprResult ExRes = CheckCXXThrowOperand(OpLoc, Ex, IsThrownVarInScope);
599221345Sdim    if (ExRes.isInvalid())
600221345Sdim      return ExprError();
601221345Sdim    Ex = ExRes.take();
602221345Sdim  }
603224145Sdim
604224145Sdim  return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc,
605224145Sdim                                          IsThrownVarInScope));
606193326Sed}
607193326Sed
608193326Sed/// CheckCXXThrowOperand - Validate the operand of a throw.
609224145SdimExprResult Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *E,
610224145Sdim                                      bool IsThrownVarInScope) {
611193326Sed  // C++ [except.throw]p3:
612201361Srdivacky  //   A throw-expression initializes a temporary object, called the exception
613201361Srdivacky  //   object, the type of which is determined by removing any top-level
614201361Srdivacky  //   cv-qualifiers from the static type of the operand of throw and adjusting
615218893Sdim  //   the type from "array of T" or "function returning T" to "pointer to T"
616201361Srdivacky  //   or "pointer to function returning T", [...]
617201361Srdivacky  if (E->getType().hasQualifiers())
618221345Sdim    E = ImpCastExprToType(E, E->getType().getUnqualifiedType(), CK_NoOp,
619226633Sdim                          E->getValueKind()).take();
620218893Sdim
621221345Sdim  ExprResult Res = DefaultFunctionArrayConversion(E);
622221345Sdim  if (Res.isInvalid())
623221345Sdim    return ExprError();
624221345Sdim  E = Res.take();
625193326Sed
626193326Sed  //   If the type of the exception would be an incomplete type or a pointer
627193326Sed  //   to an incomplete type other than (cv) void the program is ill-formed.
628193326Sed  QualType Ty = E->getType();
629207619Srdivacky  bool isPointer = false;
630198092Srdivacky  if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
631193326Sed    Ty = Ptr->getPointeeType();
632207619Srdivacky    isPointer = true;
633193326Sed  }
634193326Sed  if (!isPointer || !Ty->isVoidType()) {
635193326Sed    if (RequireCompleteType(ThrowLoc, Ty,
636239462Sdim                            isPointer? diag::err_throw_incomplete_ptr
637239462Sdim                                     : diag::err_throw_incomplete,
638239462Sdim                            E->getSourceRange()))
639221345Sdim      return ExprError();
640204643Srdivacky
641207619Srdivacky    if (RequireNonAbstractType(ThrowLoc, E->getType(),
642239462Sdim                               diag::err_throw_abstract_type, E))
643221345Sdim      return ExprError();
644193326Sed  }
645193326Sed
646207619Srdivacky  // Initialize the exception result.  This implicitly weeds out
647207619Srdivacky  // abstract types or types with inaccessible copy constructors.
648224145Sdim
649224145Sdim  // C++0x [class.copymove]p31:
650224145Sdim  //   When certain criteria are met, an implementation is allowed to omit the
651224145Sdim  //   copy/move construction of a class object [...]
652224145Sdim  //
653224145Sdim  //     - in a throw-expression, when the operand is the name of a
654224145Sdim  //       non-volatile automatic object (other than a function or catch-clause
655224145Sdim  //       parameter) whose scope does not extend beyond the end of the
656224145Sdim  //       innermost enclosing try-block (if there is one), the copy/move
657224145Sdim  //       operation from the operand to the exception object (15.1) can be
658224145Sdim  //       omitted by constructing the automatic object directly into the
659224145Sdim  //       exception object
660224145Sdim  const VarDecl *NRVOVariable = 0;
661224145Sdim  if (IsThrownVarInScope)
662224145Sdim    NRVOVariable = getCopyElisionCandidate(QualType(), E, false);
663224145Sdim
664207619Srdivacky  InitializedEntity Entity =
665218893Sdim      InitializedEntity::InitializeException(ThrowLoc, E->getType(),
666224145Sdim                                             /*NRVO=*/NRVOVariable != 0);
667221345Sdim  Res = PerformMoveOrCopyInitialization(Entity, NRVOVariable,
668224145Sdim                                        QualType(), E,
669224145Sdim                                        IsThrownVarInScope);
670207619Srdivacky  if (Res.isInvalid())
671221345Sdim    return ExprError();
672221345Sdim  E = Res.take();
673208600Srdivacky
674210299Sed  // If the exception has class type, we need additional handling.
675210299Sed  const RecordType *RecordTy = Ty->getAs<RecordType>();
676210299Sed  if (!RecordTy)
677221345Sdim    return Owned(E);
678210299Sed  CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
679210299Sed
680208600Srdivacky  // If we are throwing a polymorphic class type or pointer thereof,
681208600Srdivacky  // exception handling will make use of the vtable.
682210299Sed  MarkVTableUsed(ThrowLoc, RD);
683210299Sed
684218893Sdim  // If a pointer is thrown, the referenced object will not be destroyed.
685218893Sdim  if (isPointer)
686221345Sdim    return Owned(E);
687218893Sdim
688234353Sdim  // If the class has a destructor, we must be able to call it.
689234353Sdim  if (RD->hasIrrelevantDestructor())
690221345Sdim    return Owned(E);
691210299Sed
692234353Sdim  CXXDestructorDecl *Destructor = LookupDestructor(RD);
693210299Sed  if (!Destructor)
694221345Sdim    return Owned(E);
695210299Sed
696234353Sdim  MarkFunctionReferenced(E->getExprLoc(), Destructor);
697210299Sed  CheckDestructorAccess(E->getExprLoc(), Destructor,
698210299Sed                        PDiag(diag::err_access_dtor_exception) << Ty);
699251662Sdim  if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
700251662Sdim    return ExprError();
701221345Sdim  return Owned(E);
702193326Sed}
703193326Sed
704234353SdimQualType Sema::getCurrentThisType() {
705234353Sdim  DeclContext *DC = getFunctionLevelDeclContext();
706234982Sdim  QualType ThisTy = CXXThisTypeOverride;
707223017Sdim  if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
708223017Sdim    if (method && method->isInstance())
709223017Sdim      ThisTy = method->getThisType(Context);
710223017Sdim  }
711234982Sdim
712223017Sdim  return ThisTy;
713218893Sdim}
714218893Sdim
715234982SdimSema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S,
716234982Sdim                                         Decl *ContextDecl,
717234982Sdim                                         unsigned CXXThisTypeQuals,
718234982Sdim                                         bool Enabled)
719234982Sdim  : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
720234982Sdim{
721234982Sdim  if (!Enabled || !ContextDecl)
722234982Sdim    return;
723234982Sdim
724234982Sdim  CXXRecordDecl *Record = 0;
725234982Sdim  if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))
726234982Sdim    Record = Template->getTemplatedDecl();
727234982Sdim  else
728234982Sdim    Record = cast<CXXRecordDecl>(ContextDecl);
729234982Sdim
730234982Sdim  S.CXXThisTypeOverride
731234982Sdim    = S.Context.getPointerType(
732234982Sdim        S.Context.getRecordType(Record).withCVRQualifiers(CXXThisTypeQuals));
733234982Sdim
734234982Sdim  this->Enabled = true;
735234982Sdim}
736234982Sdim
737234982Sdim
738234982SdimSema::CXXThisScopeRAII::~CXXThisScopeRAII() {
739234982Sdim  if (Enabled) {
740234982Sdim    S.CXXThisTypeOverride = OldCXXThisTypeOverride;
741234982Sdim  }
742234982Sdim}
743234982Sdim
744251662Sdimstatic Expr *captureThis(ASTContext &Context, RecordDecl *RD,
745251662Sdim                         QualType ThisTy, SourceLocation Loc) {
746251662Sdim  FieldDecl *Field
747251662Sdim    = FieldDecl::Create(Context, RD, Loc, Loc, 0, ThisTy,
748251662Sdim                        Context.getTrivialTypeSourceInfo(ThisTy, Loc),
749251662Sdim                        0, false, ICIS_NoInit);
750251662Sdim  Field->setImplicit(true);
751251662Sdim  Field->setAccess(AS_private);
752251662Sdim  RD->addDecl(Field);
753251662Sdim  return new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit*/true);
754251662Sdim}
755251662Sdim
756263508Sdimbool Sema::CheckCXXThisCapture(SourceLocation Loc, bool Explicit,
757263508Sdim    bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt) {
758234353Sdim  // We don't need to capture this in an unevaluated context.
759251662Sdim  if (isUnevaluatedContext() && !Explicit)
760263508Sdim    return true;
761234353Sdim
762263508Sdim  const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt ?
763263508Sdim    *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
764263508Sdim // Otherwise, check that we can capture 'this'.
765234353Sdim  unsigned NumClosures = 0;
766263508Sdim  for (unsigned idx = MaxFunctionScopesIndex; idx != 0; idx--) {
767234353Sdim    if (CapturingScopeInfo *CSI =
768234353Sdim            dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
769234353Sdim      if (CSI->CXXThisCaptureIndex != 0) {
770234353Sdim        // 'this' is already being captured; there isn't anything more to do.
771234353Sdim        break;
772234353Sdim      }
773263508Sdim      LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI);
774263508Sdim      if (LSI && isGenericLambdaCallOperatorSpecialization(LSI->CallOperator)) {
775263508Sdim        // This context can't implicitly capture 'this'; fail out.
776263508Sdim        if (BuildAndDiagnose)
777263508Sdim          Diag(Loc, diag::err_this_capture) << Explicit;
778263508Sdim        return true;
779263508Sdim      }
780234353Sdim      if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
781234353Sdim          CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
782234353Sdim          CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
783251662Sdim          CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion ||
784234353Sdim          Explicit) {
785234353Sdim        // This closure can capture 'this'; continue looking upwards.
786234353Sdim        NumClosures++;
787234353Sdim        Explicit = false;
788234353Sdim        continue;
789234353Sdim      }
790234353Sdim      // This context can't implicitly capture 'this'; fail out.
791263508Sdim      if (BuildAndDiagnose)
792263508Sdim        Diag(Loc, diag::err_this_capture) << Explicit;
793263508Sdim      return true;
794234353Sdim    }
795234353Sdim    break;
796234353Sdim  }
797263508Sdim  if (!BuildAndDiagnose) return false;
798234353Sdim  // Mark that we're implicitly capturing 'this' in all the scopes we skipped.
799234353Sdim  // FIXME: We need to delay this marking in PotentiallyPotentiallyEvaluated
800234353Sdim  // contexts.
801263508Sdim  for (unsigned idx = MaxFunctionScopesIndex; NumClosures;
802263508Sdim      --idx, --NumClosures) {
803234353Sdim    CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
804234353Sdim    Expr *ThisExpr = 0;
805234353Sdim    QualType ThisTy = getCurrentThisType();
806251662Sdim    if (LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI))
807234353Sdim      // For lambda expressions, build a field and an initializing expression.
808251662Sdim      ThisExpr = captureThis(Context, LSI->Lambda, ThisTy, Loc);
809251662Sdim    else if (CapturedRegionScopeInfo *RSI
810251662Sdim        = dyn_cast<CapturedRegionScopeInfo>(FunctionScopes[idx]))
811251662Sdim      ThisExpr = captureThis(Context, RSI->TheRecordDecl, ThisTy, Loc);
812251662Sdim
813234353Sdim    bool isNested = NumClosures > 1;
814234353Sdim    CSI->addThisCapture(isNested, Loc, ThisTy, ThisExpr);
815234353Sdim  }
816263508Sdim  return false;
817234353Sdim}
818234353Sdim
819223017SdimExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
820193326Sed  /// C++ 9.3.2: In the body of a non-static member function, the keyword this
821193326Sed  /// is a non-lvalue expression whose value is the address of the object for
822193326Sed  /// which the function is called.
823193326Sed
824234353Sdim  QualType ThisTy = getCurrentThisType();
825223017Sdim  if (ThisTy.isNull()) return Diag(Loc, diag::err_invalid_this_use);
826193326Sed
827234353Sdim  CheckCXXThisCapture(Loc);
828223017Sdim  return Owned(new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/false));
829193326Sed}
830193326Sed
831234982Sdimbool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) {
832234982Sdim  // If we're outside the body of a member function, then we'll have a specified
833234982Sdim  // type for 'this'.
834234982Sdim  if (CXXThisTypeOverride.isNull())
835234982Sdim    return false;
836234982Sdim
837234982Sdim  // Determine whether we're looking into a class that's currently being
838234982Sdim  // defined.
839234982Sdim  CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
840234982Sdim  return Class && Class->isBeingDefined();
841234982Sdim}
842234982Sdim
843212904SdimExprResult
844218893SdimSema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
845193326Sed                                SourceLocation LParenLoc,
846193326Sed                                MultiExprArg exprs,
847193326Sed                                SourceLocation RParenLoc) {
848203955Srdivacky  if (!TypeRep)
849203955Srdivacky    return ExprError();
850203955Srdivacky
851202879Srdivacky  TypeSourceInfo *TInfo;
852202879Srdivacky  QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
853202879Srdivacky  if (!TInfo)
854202879Srdivacky    TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
855218893Sdim
856218893Sdim  return BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc);
857218893Sdim}
858218893Sdim
859218893Sdim/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
860218893Sdim/// Can be interpreted either as function-style casting ("int(x)")
861218893Sdim/// or class type construction ("ClassType(x,y,z)")
862218893Sdim/// or creation of a value-initialized type ("int()").
863218893SdimExprResult
864218893SdimSema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
865218893Sdim                                SourceLocation LParenLoc,
866251662Sdim                                MultiExprArg Exprs,
867218893Sdim                                SourceLocation RParenLoc) {
868218893Sdim  QualType Ty = TInfo->getType();
869218893Sdim  SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
870193326Sed
871251662Sdim  if (Ty->isDependentType() || CallExpr::hasAnyTypeDependentArguments(Exprs)) {
872218893Sdim    return Owned(CXXUnresolvedConstructExpr::Create(Context, TInfo,
873193326Sed                                                    LParenLoc,
874251662Sdim                                                    Exprs,
875193326Sed                                                    RParenLoc));
876193326Sed  }
877193326Sed
878234353Sdim  bool ListInitialization = LParenLoc.isInvalid();
879251662Sdim  assert((!ListInitialization || (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0])))
880234353Sdim         && "List initialization must have initializer list as expression.");
881234353Sdim  SourceRange FullRange = SourceRange(TyBeginLoc,
882234353Sdim      ListInitialization ? Exprs[0]->getSourceRange().getEnd() : RParenLoc);
883218893Sdim
884193326Sed  // C++ [expr.type.conv]p1:
885193326Sed  // If the expression list is a single expression, the type conversion
886193326Sed  // expression is equivalent (in definedness, and if defined in meaning) to the
887193326Sed  // corresponding cast expression.
888251662Sdim  if (Exprs.size() == 1 && !ListInitialization) {
889226633Sdim    Expr *Arg = Exprs[0];
890226633Sdim    return BuildCXXFunctionalCastExpr(TInfo, LParenLoc, Arg, RParenLoc);
891193326Sed  }
892193326Sed
893234353Sdim  QualType ElemTy = Ty;
894234353Sdim  if (Ty->isArrayType()) {
895234353Sdim    if (!ListInitialization)
896234353Sdim      return ExprError(Diag(TyBeginLoc,
897234353Sdim                            diag::err_value_init_for_array_type) << FullRange);
898234353Sdim    ElemTy = Context.getBaseElementType(Ty);
899234353Sdim  }
900234353Sdim
901234353Sdim  if (!Ty->isVoidType() &&
902234353Sdim      RequireCompleteType(TyBeginLoc, ElemTy,
903239462Sdim                          diag::err_invalid_incomplete_type_use, FullRange))
904234353Sdim    return ExprError();
905234353Sdim
906234353Sdim  if (RequireNonAbstractType(TyBeginLoc, Ty,
907234353Sdim                             diag::err_allocation_of_abstract_type))
908234353Sdim    return ExprError();
909234353Sdim
910218893Sdim  InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
911251662Sdim  InitializationKind Kind =
912251662Sdim      Exprs.size() ? ListInitialization
913251662Sdim      ? InitializationKind::CreateDirectList(TyBeginLoc)
914251662Sdim      : InitializationKind::CreateDirect(TyBeginLoc, LParenLoc, RParenLoc)
915251662Sdim      : InitializationKind::CreateValue(TyBeginLoc, LParenLoc, RParenLoc);
916251662Sdim  InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
917251662Sdim  ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs);
918193326Sed
919263508Sdim  if (Result.isInvalid() || !ListInitialization)
920263508Sdim    return Result;
921263508Sdim
922263508Sdim  Expr *Inner = Result.get();
923263508Sdim  if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner))
924263508Sdim    Inner = BTE->getSubExpr();
925263508Sdim  if (isa<InitListExpr>(Inner)) {
926234353Sdim    // If the list-initialization doesn't involve a constructor call, we'll get
927234353Sdim    // the initializer-list (with corrected type) back, but that's not what we
928234353Sdim    // want, since it will be treated as an initializer list in further
929234353Sdim    // processing. Explicitly insert a cast here.
930263508Sdim    QualType ResultType = Result.get()->getType();
931263508Sdim    Result = Owned(CXXFunctionalCastExpr::Create(
932263508Sdim        Context, ResultType, Expr::getValueKindForType(TInfo->getType()), TInfo,
933263508Sdim        CK_NoOp, Result.take(), /*Path=*/ 0, LParenLoc, RParenLoc));
934234353Sdim  }
935234353Sdim
936218893Sdim  // FIXME: Improve AST representation?
937243830Sdim  return Result;
938218893Sdim}
939218893Sdim
940218893Sdim/// doesUsualArrayDeleteWantSize - Answers whether the usual
941218893Sdim/// operator delete[] for the given type has a size_t parameter.
942218893Sdimstatic bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
943218893Sdim                                         QualType allocType) {
944218893Sdim  const RecordType *record =
945218893Sdim    allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
946218893Sdim  if (!record) return false;
947218893Sdim
948218893Sdim  // Try to find an operator delete[] in class scope.
949218893Sdim
950218893Sdim  DeclarationName deleteName =
951218893Sdim    S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
952218893Sdim  LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
953218893Sdim  S.LookupQualifiedName(ops, record->getDecl());
954218893Sdim
955218893Sdim  // We're just doing this for information.
956218893Sdim  ops.suppressDiagnostics();
957218893Sdim
958218893Sdim  // Very likely: there's no operator delete[].
959218893Sdim  if (ops.empty()) return false;
960218893Sdim
961218893Sdim  // If it's ambiguous, it should be illegal to call operator delete[]
962218893Sdim  // on this thing, so it doesn't matter if we allocate extra space or not.
963218893Sdim  if (ops.isAmbiguous()) return false;
964218893Sdim
965218893Sdim  LookupResult::Filter filter = ops.makeFilter();
966218893Sdim  while (filter.hasNext()) {
967218893Sdim    NamedDecl *del = filter.next()->getUnderlyingDecl();
968218893Sdim
969218893Sdim    // C++0x [basic.stc.dynamic.deallocation]p2:
970218893Sdim    //   A template instance is never a usual deallocation function,
971218893Sdim    //   regardless of its signature.
972218893Sdim    if (isa<FunctionTemplateDecl>(del)) {
973218893Sdim      filter.erase();
974218893Sdim      continue;
975218893Sdim    }
976218893Sdim
977218893Sdim    // C++0x [basic.stc.dynamic.deallocation]p2:
978218893Sdim    //   If class T does not declare [an operator delete[] with one
979218893Sdim    //   parameter] but does declare a member deallocation function
980218893Sdim    //   named operator delete[] with exactly two parameters, the
981218893Sdim    //   second of which has type std::size_t, then this function
982218893Sdim    //   is a usual deallocation function.
983218893Sdim    if (!cast<CXXMethodDecl>(del)->isUsualDeallocationFunction()) {
984218893Sdim      filter.erase();
985218893Sdim      continue;
986218893Sdim    }
987193326Sed  }
988218893Sdim  filter.done();
989193326Sed
990218893Sdim  if (!ops.isSingleResult()) return false;
991193326Sed
992218893Sdim  const FunctionDecl *del = cast<FunctionDecl>(ops.getFoundDecl());
993218893Sdim  return (del->getNumParams() == 2);
994193326Sed}
995193326Sed
996234353Sdim/// \brief Parsed a C++ 'new' expression (C++ 5.3.4).
997239462Sdim///
998234353Sdim/// E.g.:
999193326Sed/// @code new (memory) int[size][4] @endcode
1000193326Sed/// or
1001193326Sed/// @code ::new Foo(23, "hello") @endcode
1002234353Sdim///
1003234353Sdim/// \param StartLoc The first location of the expression.
1004234353Sdim/// \param UseGlobal True if 'new' was prefixed with '::'.
1005234353Sdim/// \param PlacementLParen Opening paren of the placement arguments.
1006234353Sdim/// \param PlacementArgs Placement new arguments.
1007234353Sdim/// \param PlacementRParen Closing paren of the placement arguments.
1008234353Sdim/// \param TypeIdParens If the type is in parens, the source range.
1009234353Sdim/// \param D The type to be allocated, as well as array dimensions.
1010239462Sdim/// \param Initializer The initializing expression or initializer-list, or null
1011239462Sdim///   if there is none.
1012212904SdimExprResult
1013193326SedSema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
1014193326Sed                  SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
1015218893Sdim                  SourceLocation PlacementRParen, SourceRange TypeIdParens,
1016234353Sdim                  Declarator &D, Expr *Initializer) {
1017251662Sdim  bool TypeContainsAuto = D.getDeclSpec().containsPlaceholderType();
1018218893Sdim
1019193326Sed  Expr *ArraySize = 0;
1020193326Sed  // If the specified type is an array, unwrap it and save the expression.
1021193326Sed  if (D.getNumTypeObjects() > 0 &&
1022193326Sed      D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
1023239462Sdim     DeclaratorChunk &Chunk = D.getTypeObject(0);
1024218893Sdim    if (TypeContainsAuto)
1025218893Sdim      return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
1026218893Sdim        << D.getSourceRange());
1027193326Sed    if (Chunk.Arr.hasStatic)
1028193326Sed      return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
1029193326Sed        << D.getSourceRange());
1030193326Sed    if (!Chunk.Arr.NumElts)
1031193326Sed      return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
1032193326Sed        << D.getSourceRange());
1033198893Srdivacky
1034193326Sed    ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
1035198893Srdivacky    D.DropFirstTypeObject();
1036193326Sed  }
1037193326Sed
1038198092Srdivacky  // Every dimension shall be of constant size.
1039198893Srdivacky  if (ArraySize) {
1040198893Srdivacky    for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
1041198092Srdivacky      if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
1042198092Srdivacky        break;
1043193326Sed
1044198092Srdivacky      DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
1045198092Srdivacky      if (Expr *NumElts = (Expr *)Array.NumElts) {
1046234353Sdim        if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
1047263508Sdim          if (getLangOpts().CPlusPlus1y) {
1048263508Sdim	    // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator
1049263508Sdim	    //   shall be a converted constant expression (5.19) of type std::size_t
1050263508Sdim	    //   and shall evaluate to a strictly positive value.
1051263508Sdim            unsigned IntWidth = Context.getTargetInfo().getIntWidth();
1052263508Sdim            assert(IntWidth && "Builtin type of size 0?");
1053263508Sdim            llvm::APSInt Value(IntWidth);
1054263508Sdim            Array.NumElts
1055263508Sdim             = CheckConvertedConstantExpression(NumElts, Context.getSizeType(), Value,
1056263508Sdim                                                CCEK_NewExpr)
1057263508Sdim                 .take();
1058263508Sdim          } else {
1059263508Sdim            Array.NumElts
1060263508Sdim              = VerifyIntegerConstantExpression(NumElts, 0,
1061263508Sdim                                                diag::err_new_array_nonconst)
1062263508Sdim                  .take();
1063263508Sdim          }
1064234353Sdim          if (!Array.NumElts)
1065234353Sdim            return ExprError();
1066198092Srdivacky        }
1067198092Srdivacky      }
1068193326Sed    }
1069193326Sed  }
1070198893Srdivacky
1071224145Sdim  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/0);
1072210299Sed  QualType AllocType = TInfo->getType();
1073198092Srdivacky  if (D.isInvalidType())
1074198092Srdivacky    return ExprError();
1075218893Sdim
1076234353Sdim  SourceRange DirectInitRange;
1077234353Sdim  if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer))
1078234353Sdim    DirectInitRange = List->getSourceRange();
1079234353Sdim
1080243830Sdim  return BuildCXXNew(SourceRange(StartLoc, D.getLocEnd()), UseGlobal,
1081193326Sed                     PlacementLParen,
1082243830Sdim                     PlacementArgs,
1083193326Sed                     PlacementRParen,
1084210299Sed                     TypeIdParens,
1085198092Srdivacky                     AllocType,
1086218893Sdim                     TInfo,
1087212904Sdim                     ArraySize,
1088234353Sdim                     DirectInitRange,
1089234353Sdim                     Initializer,
1090218893Sdim                     TypeContainsAuto);
1091193326Sed}
1092193326Sed
1093234353Sdimstatic bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style,
1094234353Sdim                                       Expr *Init) {
1095234353Sdim  if (!Init)
1096234353Sdim    return true;
1097234353Sdim  if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
1098234353Sdim    return PLE->getNumExprs() == 0;
1099234353Sdim  if (isa<ImplicitValueInitExpr>(Init))
1100234353Sdim    return true;
1101234353Sdim  else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
1102234353Sdim    return !CCE->isListInitialization() &&
1103234353Sdim           CCE->getConstructor()->isDefaultConstructor();
1104234353Sdim  else if (Style == CXXNewExpr::ListInit) {
1105234353Sdim    assert(isa<InitListExpr>(Init) &&
1106234353Sdim           "Shouldn't create list CXXConstructExprs for arrays.");
1107234353Sdim    return true;
1108234353Sdim  }
1109234353Sdim  return false;
1110234353Sdim}
1111234353Sdim
1112212904SdimExprResult
1113243830SdimSema::BuildCXXNew(SourceRange Range, bool UseGlobal,
1114193326Sed                  SourceLocation PlacementLParen,
1115193326Sed                  MultiExprArg PlacementArgs,
1116193326Sed                  SourceLocation PlacementRParen,
1117210299Sed                  SourceRange TypeIdParens,
1118193326Sed                  QualType AllocType,
1119218893Sdim                  TypeSourceInfo *AllocTypeInfo,
1120212904Sdim                  Expr *ArraySize,
1121234353Sdim                  SourceRange DirectInitRange,
1122234353Sdim                  Expr *Initializer,
1123218893Sdim                  bool TypeMayContainAuto) {
1124218893Sdim  SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
1125243830Sdim  SourceLocation StartLoc = Range.getBegin();
1126193326Sed
1127234353Sdim  CXXNewExpr::InitializationStyle initStyle;
1128234353Sdim  if (DirectInitRange.isValid()) {
1129234353Sdim    assert(Initializer && "Have parens but no initializer.");
1130234353Sdim    initStyle = CXXNewExpr::CallInit;
1131234353Sdim  } else if (Initializer && isa<InitListExpr>(Initializer))
1132234353Sdim    initStyle = CXXNewExpr::ListInit;
1133234353Sdim  else {
1134234353Sdim    assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||
1135234353Sdim            isa<CXXConstructExpr>(Initializer)) &&
1136234353Sdim           "Initializer expression that cannot have been implicitly created.");
1137234353Sdim    initStyle = CXXNewExpr::NoInit;
1138234353Sdim  }
1139234353Sdim
1140234353Sdim  Expr **Inits = &Initializer;
1141234353Sdim  unsigned NumInits = Initializer ? 1 : 0;
1142249423Sdim  if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {
1143249423Sdim    assert(initStyle == CXXNewExpr::CallInit && "paren init for non-call init");
1144249423Sdim    Inits = List->getExprs();
1145249423Sdim    NumInits = List->getNumExprs();
1146234353Sdim  }
1147234353Sdim
1148249423Sdim  // Determine whether we've already built the initializer.
1149249423Sdim  bool HaveCompleteInit = false;
1150249423Sdim  if (Initializer && isa<CXXConstructExpr>(Initializer) &&
1151249423Sdim      !isa<CXXTemporaryObjectExpr>(Initializer))
1152249423Sdim    HaveCompleteInit = true;
1153249423Sdim  else if (Initializer && isa<ImplicitValueInitExpr>(Initializer))
1154249423Sdim    HaveCompleteInit = true;
1155249423Sdim
1156239462Sdim  // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
1157251662Sdim  if (TypeMayContainAuto && AllocType->isUndeducedType()) {
1158234353Sdim    if (initStyle == CXXNewExpr::NoInit || NumInits == 0)
1159218893Sdim      return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
1160218893Sdim                       << AllocType << TypeRange);
1161234353Sdim    if (initStyle == CXXNewExpr::ListInit)
1162234353Sdim      return ExprError(Diag(Inits[0]->getLocStart(),
1163234353Sdim                            diag::err_auto_new_requires_parens)
1164234353Sdim                       << AllocType << TypeRange);
1165234353Sdim    if (NumInits > 1) {
1166234353Sdim      Expr *FirstBad = Inits[1];
1167234353Sdim      return ExprError(Diag(FirstBad->getLocStart(),
1168218893Sdim                            diag::err_auto_new_ctor_multiple_expressions)
1169218893Sdim                       << AllocType << TypeRange);
1170218893Sdim    }
1171234353Sdim    Expr *Deduce = Inits[0];
1172251662Sdim    QualType DeducedType;
1173239462Sdim    if (DeduceAutoType(AllocTypeInfo, Deduce, DeducedType) == DAR_Failed)
1174218893Sdim      return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
1175234353Sdim                       << AllocType << Deduce->getType()
1176234353Sdim                       << TypeRange << Deduce->getSourceRange());
1177251662Sdim    if (DeducedType.isNull())
1178221345Sdim      return ExprError();
1179251662Sdim    AllocType = DeducedType;
1180218893Sdim  }
1181234353Sdim
1182208600Srdivacky  // Per C++0x [expr.new]p5, the type being constructed may be a
1183208600Srdivacky  // typedef of an array type.
1184212904Sdim  if (!ArraySize) {
1185208600Srdivacky    if (const ConstantArrayType *Array
1186208600Srdivacky                              = Context.getAsConstantArrayType(AllocType)) {
1187212904Sdim      ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
1188212904Sdim                                         Context.getSizeType(),
1189212904Sdim                                         TypeRange.getEnd());
1190208600Srdivacky      AllocType = Array->getElementType();
1191208600Srdivacky    }
1192208600Srdivacky  }
1193208600Srdivacky
1194218893Sdim  if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
1195218893Sdim    return ExprError();
1196218893Sdim
1197234353Sdim  if (initStyle == CXXNewExpr::ListInit && isStdInitializerList(AllocType, 0)) {
1198234353Sdim    Diag(AllocTypeInfo->getTypeLoc().getBeginLoc(),
1199234353Sdim         diag::warn_dangling_std_initializer_list)
1200234353Sdim        << /*at end of FE*/0 << Inits[0]->getSourceRange();
1201234353Sdim  }
1202234353Sdim
1203224145Sdim  // In ARC, infer 'retaining' for the allocated
1204234353Sdim  if (getLangOpts().ObjCAutoRefCount &&
1205224145Sdim      AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1206224145Sdim      AllocType->isObjCLifetimeType()) {
1207224145Sdim    AllocType = Context.getLifetimeQualifiedType(AllocType,
1208224145Sdim                                    AllocType->getObjCARCImplicitLifetime());
1209224145Sdim  }
1210224145Sdim
1211193326Sed  QualType ResultType = Context.getPointerType(AllocType);
1212224145Sdim
1213251662Sdim  if (ArraySize && ArraySize->getType()->isNonOverloadPlaceholderType()) {
1214251662Sdim    ExprResult result = CheckPlaceholderExpr(ArraySize);
1215251662Sdim    if (result.isInvalid()) return ExprError();
1216251662Sdim    ArraySize = result.take();
1217251662Sdim  }
1218234353Sdim  // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
1219234353Sdim  //   integral or enumeration type with a non-negative value."
1220234353Sdim  // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
1221234353Sdim  //   enumeration type, or a class type for which a single non-explicit
1222234353Sdim  //   conversion function to integral or unscoped enumeration type exists.
1223263508Sdim  // C++1y [expr.new]p6: The expression [...] is implicitly converted to
1224263508Sdim  //   std::size_t.
1225193326Sed  if (ArraySize && !ArraySize->isTypeDependent()) {
1226263508Sdim    ExprResult ConvertedSize;
1227263508Sdim    if (getLangOpts().CPlusPlus1y) {
1228263508Sdim      unsigned IntWidth = Context.getTargetInfo().getIntWidth();
1229263508Sdim      assert(IntWidth && "Builtin type of size 0?");
1230263508Sdim      llvm::APSInt Value(IntWidth);
1231263508Sdim      ConvertedSize = PerformImplicitConversion(ArraySize, Context.getSizeType(),
1232263508Sdim						AA_Converting);
1233239462Sdim
1234263508Sdim      if (!ConvertedSize.isInvalid() &&
1235263508Sdim          ArraySize->getType()->getAs<RecordType>())
1236263508Sdim        // Diagnose the compatibility of this conversion.
1237263508Sdim        Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion)
1238263508Sdim          << ArraySize->getType() << 0 << "'size_t'";
1239263508Sdim    } else {
1240263508Sdim      class SizeConvertDiagnoser : public ICEConvertDiagnoser {
1241263508Sdim      protected:
1242263508Sdim        Expr *ArraySize;
1243263508Sdim
1244263508Sdim      public:
1245263508Sdim        SizeConvertDiagnoser(Expr *ArraySize)
1246263508Sdim            : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false),
1247263508Sdim              ArraySize(ArraySize) {}
1248263508Sdim
1249263508Sdim        virtual SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
1250263508Sdim                                                     QualType T) {
1251263508Sdim          return S.Diag(Loc, diag::err_array_size_not_integral)
1252263508Sdim                   << S.getLangOpts().CPlusPlus11 << T;
1253263508Sdim        }
1254263508Sdim
1255263508Sdim        virtual SemaDiagnosticBuilder diagnoseIncomplete(
1256263508Sdim            Sema &S, SourceLocation Loc, QualType T) {
1257263508Sdim          return S.Diag(Loc, diag::err_array_size_incomplete_type)
1258263508Sdim                   << T << ArraySize->getSourceRange();
1259263508Sdim        }
1260263508Sdim
1261263508Sdim        virtual SemaDiagnosticBuilder diagnoseExplicitConv(
1262263508Sdim            Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) {
1263263508Sdim          return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;
1264263508Sdim        }
1265263508Sdim
1266263508Sdim        virtual SemaDiagnosticBuilder noteExplicitConv(
1267263508Sdim            Sema &S, CXXConversionDecl *Conv, QualType ConvTy) {
1268263508Sdim          return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1269263508Sdim                   << ConvTy->isEnumeralType() << ConvTy;
1270263508Sdim        }
1271263508Sdim
1272263508Sdim        virtual SemaDiagnosticBuilder diagnoseAmbiguous(
1273263508Sdim            Sema &S, SourceLocation Loc, QualType T) {
1274263508Sdim          return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;
1275263508Sdim        }
1276263508Sdim
1277263508Sdim        virtual SemaDiagnosticBuilder noteAmbiguous(
1278263508Sdim            Sema &S, CXXConversionDecl *Conv, QualType ConvTy) {
1279263508Sdim          return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1280263508Sdim                   << ConvTy->isEnumeralType() << ConvTy;
1281263508Sdim        }
1282263508Sdim
1283263508Sdim        virtual SemaDiagnosticBuilder diagnoseConversion(
1284263508Sdim            Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) {
1285263508Sdim          return S.Diag(Loc,
1286263508Sdim                        S.getLangOpts().CPlusPlus11
1287263508Sdim                          ? diag::warn_cxx98_compat_array_size_conversion
1288263508Sdim                          : diag::ext_array_size_conversion)
1289263508Sdim                   << T << ConvTy->isEnumeralType() << ConvTy;
1290263508Sdim        }
1291263508Sdim      } SizeDiagnoser(ArraySize);
1292263508Sdim
1293263508Sdim      ConvertedSize = PerformContextualImplicitConversion(StartLoc, ArraySize,
1294263508Sdim                                                          SizeDiagnoser);
1295263508Sdim    }
1296210299Sed    if (ConvertedSize.isInvalid())
1297210299Sed      return ExprError();
1298218893Sdim
1299212904Sdim    ArraySize = ConvertedSize.take();
1300234353Sdim    QualType SizeType = ArraySize->getType();
1301263508Sdim
1302218893Sdim    if (!SizeType->isIntegralOrUnscopedEnumerationType())
1303210299Sed      return ExprError();
1304218893Sdim
1305234353Sdim    // C++98 [expr.new]p7:
1306234353Sdim    //   The expression in a direct-new-declarator shall have integral type
1307234353Sdim    //   with a non-negative value.
1308234353Sdim    //
1309234353Sdim    // Let's see if this is a constant < 0. If so, we reject it out of
1310234353Sdim    // hand. Otherwise, if it's not a constant, we must have an unparenthesized
1311234353Sdim    // array type.
1312234353Sdim    //
1313234353Sdim    // Note: such a construct has well-defined semantics in C++11: it throws
1314234353Sdim    // std::bad_array_new_length.
1315193326Sed    if (!ArraySize->isValueDependent()) {
1316193326Sed      llvm::APSInt Value;
1317234353Sdim      // We've already performed any required implicit conversion to integer or
1318234353Sdim      // unscoped enumeration type.
1319234353Sdim      if (ArraySize->isIntegerConstantExpr(Value, Context)) {
1320193326Sed        if (Value < llvm::APSInt(
1321218893Sdim                        llvm::APInt::getNullValue(Value.getBitWidth()),
1322234353Sdim                                 Value.isUnsigned())) {
1323249423Sdim          if (getLangOpts().CPlusPlus11)
1324234353Sdim            Diag(ArraySize->getLocStart(),
1325234353Sdim                 diag::warn_typecheck_negative_array_new_size)
1326234353Sdim              << ArraySize->getSourceRange();
1327234353Sdim          else
1328234353Sdim            return ExprError(Diag(ArraySize->getLocStart(),
1329234353Sdim                                  diag::err_typecheck_negative_array_size)
1330234353Sdim                             << ArraySize->getSourceRange());
1331234353Sdim        } else if (!AllocType->isDependentType()) {
1332234353Sdim          unsigned ActiveSizeBits =
1333234353Sdim            ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
1334212904Sdim          if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
1335249423Sdim            if (getLangOpts().CPlusPlus11)
1336234353Sdim              Diag(ArraySize->getLocStart(),
1337234353Sdim                   diag::warn_array_new_too_large)
1338234353Sdim                << Value.toString(10)
1339234353Sdim                << ArraySize->getSourceRange();
1340234353Sdim            else
1341234353Sdim              return ExprError(Diag(ArraySize->getLocStart(),
1342234353Sdim                                    diag::err_array_too_large)
1343234353Sdim                               << Value.toString(10)
1344234353Sdim                               << ArraySize->getSourceRange());
1345212904Sdim          }
1346212904Sdim        }
1347210299Sed      } else if (TypeIdParens.isValid()) {
1348210299Sed        // Can't have dynamic array size when the type-id is in parentheses.
1349210299Sed        Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
1350210299Sed          << ArraySize->getSourceRange()
1351210299Sed          << FixItHint::CreateRemoval(TypeIdParens.getBegin())
1352210299Sed          << FixItHint::CreateRemoval(TypeIdParens.getEnd());
1353218893Sdim
1354210299Sed        TypeIdParens = SourceRange();
1355193326Sed      }
1356193326Sed    }
1357218893Sdim
1358223017Sdim    // Note that we do *not* convert the argument in any way.  It can
1359223017Sdim    // be signed, larger than size_t, whatever.
1360193326Sed  }
1361193326Sed
1362193326Sed  FunctionDecl *OperatorNew = 0;
1363193326Sed  FunctionDecl *OperatorDelete = 0;
1364218893Sdim
1365193326Sed  if (!AllocType->isDependentType() &&
1366263508Sdim      !Expr::hasAnyTypeDependentArguments(PlacementArgs) &&
1367193326Sed      FindAllocationFunctions(StartLoc,
1368193326Sed                              SourceRange(PlacementLParen, PlacementRParen),
1369263508Sdim                              UseGlobal, AllocType, ArraySize, PlacementArgs,
1370263508Sdim                              OperatorNew, OperatorDelete))
1371193326Sed    return ExprError();
1372218893Sdim
1373218893Sdim  // If this is an array allocation, compute whether the usual array
1374218893Sdim  // deallocation function for the type has a size_t parameter.
1375218893Sdim  bool UsualArrayDeleteWantsSize = false;
1376218893Sdim  if (ArraySize && !AllocType->isDependentType())
1377218893Sdim    UsualArrayDeleteWantsSize
1378218893Sdim      = doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
1379218893Sdim
1380226633Sdim  SmallVector<Expr *, 8> AllPlaceArgs;
1381199990Srdivacky  if (OperatorNew) {
1382199990Srdivacky    // Add default arguments, if any.
1383218893Sdim    const FunctionProtoType *Proto =
1384199990Srdivacky      OperatorNew->getType()->getAs<FunctionProtoType>();
1385218893Sdim    VariadicCallType CallType =
1386199990Srdivacky      Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
1387218893Sdim
1388263508Sdim    if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto, 1,
1389263508Sdim                               PlacementArgs, AllPlaceArgs, CallType))
1390199990Srdivacky      return ExprError();
1391218893Sdim
1392263508Sdim    if (!AllPlaceArgs.empty())
1393263508Sdim      PlacementArgs = AllPlaceArgs;
1394218893Sdim
1395263508Sdim    DiagnoseSentinelCalls(OperatorNew, PlacementLParen, PlacementArgs);
1396199482Srdivacky
1397234353Sdim    // FIXME: Missing call to CheckFunctionCall or equivalent
1398234353Sdim  }
1399218893Sdim
1400234353Sdim  // Warn if the type is over-aligned and is being allocated by global operator
1401234353Sdim  // new.
1402263508Sdim  if (PlacementArgs.empty() && OperatorNew &&
1403234353Sdim      (OperatorNew->isImplicit() ||
1404234353Sdim       getSourceManager().isInSystemHeader(OperatorNew->getLocStart()))) {
1405234353Sdim    if (unsigned Align = Context.getPreferredTypeAlign(AllocType.getTypePtr())){
1406234353Sdim      unsigned SuitableAlign = Context.getTargetInfo().getSuitableAlign();
1407234353Sdim      if (Align > SuitableAlign)
1408234353Sdim        Diag(StartLoc, diag::warn_overaligned_type)
1409234353Sdim            << AllocType
1410234353Sdim            << unsigned(Align / Context.getCharWidth())
1411234353Sdim            << unsigned(SuitableAlign / Context.getCharWidth());
1412234353Sdim    }
1413207619Srdivacky  }
1414207619Srdivacky
1415234353Sdim  QualType InitType = AllocType;
1416234353Sdim  // Array 'new' can't have any initializers except empty parentheses.
1417234353Sdim  // Initializer lists are also allowed, in C++11. Rely on the parser for the
1418234353Sdim  // dialect distinction.
1419234353Sdim  if (ResultType->isArrayType() || ArraySize) {
1420234353Sdim    if (!isLegalArrayNewInitializer(initStyle, Initializer)) {
1421234353Sdim      SourceRange InitRange(Inits[0]->getLocStart(),
1422234353Sdim                            Inits[NumInits - 1]->getLocEnd());
1423234353Sdim      Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
1424234353Sdim      return ExprError();
1425234353Sdim    }
1426234353Sdim    if (InitListExpr *ILE = dyn_cast_or_null<InitListExpr>(Initializer)) {
1427234353Sdim      // We do the initialization typechecking against the array type
1428234353Sdim      // corresponding to the number of initializers + 1 (to also check
1429234353Sdim      // default-initialization).
1430234353Sdim      unsigned NumElements = ILE->getNumInits() + 1;
1431234353Sdim      InitType = Context.getConstantArrayType(AllocType,
1432234353Sdim          llvm::APInt(Context.getTypeSize(Context.getSizeType()), NumElements),
1433234353Sdim                                              ArrayType::Normal, 0);
1434234353Sdim    }
1435234353Sdim  }
1436234353Sdim
1437249423Sdim  // If we can perform the initialization, and we've not already done so,
1438249423Sdim  // do it now.
1439201361Srdivacky  if (!AllocType->isDependentType() &&
1440234353Sdim      !Expr::hasAnyTypeDependentArguments(
1441249423Sdim        llvm::makeArrayRef(Inits, NumInits)) &&
1442249423Sdim      !HaveCompleteInit) {
1443234353Sdim    // C++11 [expr.new]p15:
1444201361Srdivacky    //   A new-expression that creates an object of type T initializes that
1445201361Srdivacky    //   object as follows:
1446201361Srdivacky    InitializationKind Kind
1447201361Srdivacky    //     - If the new-initializer is omitted, the object is default-
1448201361Srdivacky    //       initialized (8.5); if no initialization is performed,
1449201361Srdivacky    //       the object has indeterminate value
1450234353Sdim      = initStyle == CXXNewExpr::NoInit
1451234353Sdim          ? InitializationKind::CreateDefault(TypeRange.getBegin())
1452218893Sdim    //     - Otherwise, the new-initializer is interpreted according to the
1453201361Srdivacky    //       initialization rules of 8.5 for direct-initialization.
1454234353Sdim          : initStyle == CXXNewExpr::ListInit
1455234353Sdim              ? InitializationKind::CreateDirectList(TypeRange.getBegin())
1456234353Sdim              : InitializationKind::CreateDirect(TypeRange.getBegin(),
1457234353Sdim                                                 DirectInitRange.getBegin(),
1458234353Sdim                                                 DirectInitRange.getEnd());
1459218893Sdim
1460201361Srdivacky    InitializedEntity Entity
1461234353Sdim      = InitializedEntity::InitializeNew(StartLoc, InitType);
1462251662Sdim    InitializationSequence InitSeq(*this, Entity, Kind, MultiExprArg(Inits, NumInits));
1463218893Sdim    ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
1464234353Sdim                                          MultiExprArg(Inits, NumInits));
1465201361Srdivacky    if (FullInit.isInvalid())
1466193326Sed      return ExprError();
1467218893Sdim
1468234353Sdim    // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
1469234353Sdim    // we don't want the initialized object to be destructed.
1470234353Sdim    if (CXXBindTemporaryExpr *Binder =
1471234353Sdim            dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
1472234353Sdim      FullInit = Owned(Binder->getSubExpr());
1473218893Sdim
1474234353Sdim    Initializer = FullInit.take();
1475193326Sed  }
1476218893Sdim
1477204643Srdivacky  // Mark the new and delete operators as referenced.
1478249423Sdim  if (OperatorNew) {
1479251662Sdim    if (DiagnoseUseOfDecl(OperatorNew, StartLoc))
1480251662Sdim      return ExprError();
1481234353Sdim    MarkFunctionReferenced(StartLoc, OperatorNew);
1482249423Sdim  }
1483249423Sdim  if (OperatorDelete) {
1484251662Sdim    if (DiagnoseUseOfDecl(OperatorDelete, StartLoc))
1485251662Sdim      return ExprError();
1486234353Sdim    MarkFunctionReferenced(StartLoc, OperatorDelete);
1487249423Sdim  }
1488204643Srdivacky
1489224145Sdim  // C++0x [expr.new]p17:
1490224145Sdim  //   If the new expression creates an array of objects of class type,
1491224145Sdim  //   access and ambiguity control are done for the destructor.
1492234353Sdim  QualType BaseAllocType = Context.getBaseElementType(AllocType);
1493234353Sdim  if (ArraySize && !BaseAllocType->isDependentType()) {
1494234353Sdim    if (const RecordType *BaseRecordType = BaseAllocType->getAs<RecordType>()) {
1495234353Sdim      if (CXXDestructorDecl *dtor = LookupDestructor(
1496234353Sdim              cast<CXXRecordDecl>(BaseRecordType->getDecl()))) {
1497234353Sdim        MarkFunctionReferenced(StartLoc, dtor);
1498234353Sdim        CheckDestructorAccess(StartLoc, dtor,
1499234353Sdim                              PDiag(diag::err_access_dtor)
1500234353Sdim                                << BaseAllocType);
1501251662Sdim        if (DiagnoseUseOfDecl(dtor, StartLoc))
1502251662Sdim          return ExprError();
1503234353Sdim      }
1504224145Sdim    }
1505224145Sdim  }
1506218893Sdim
1507203955Srdivacky  return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
1508226633Sdim                                        OperatorDelete,
1509218893Sdim                                        UsualArrayDeleteWantsSize,
1510263508Sdim                                        PlacementArgs, TypeIdParens,
1511234353Sdim                                        ArraySize, initStyle, Initializer,
1512218893Sdim                                        ResultType, AllocTypeInfo,
1513243830Sdim                                        Range, DirectInitRange));
1514193326Sed}
1515193326Sed
1516234353Sdim/// \brief Checks that a type is suitable as the allocated type
1517193326Sed/// in a new-expression.
1518193326Sedbool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
1519198092Srdivacky                              SourceRange R) {
1520193326Sed  // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
1521193326Sed  //   abstract class type or array thereof.
1522193326Sed  if (AllocType->isFunctionType())
1523193326Sed    return Diag(Loc, diag::err_bad_new_type)
1524193326Sed      << AllocType << 0 << R;
1525193326Sed  else if (AllocType->isReferenceType())
1526193326Sed    return Diag(Loc, diag::err_bad_new_type)
1527193326Sed      << AllocType << 1 << R;
1528193326Sed  else if (!AllocType->isDependentType() &&
1529239462Sdim           RequireCompleteType(Loc, AllocType, diag::err_new_incomplete_type,R))
1530193326Sed    return true;
1531193326Sed  else if (RequireNonAbstractType(Loc, AllocType,
1532193326Sed                                  diag::err_allocation_of_abstract_type))
1533193326Sed    return true;
1534218893Sdim  else if (AllocType->isVariablyModifiedType())
1535218893Sdim    return Diag(Loc, diag::err_variably_modified_new_type)
1536218893Sdim             << AllocType;
1537221345Sdim  else if (unsigned AddressSpace = AllocType.getAddressSpace())
1538221345Sdim    return Diag(Loc, diag::err_address_space_qualified_new)
1539221345Sdim      << AllocType.getUnqualifiedType() << AddressSpace;
1540234353Sdim  else if (getLangOpts().ObjCAutoRefCount) {
1541224145Sdim    if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
1542224145Sdim      QualType BaseAllocType = Context.getBaseElementType(AT);
1543224145Sdim      if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1544224145Sdim          BaseAllocType->isObjCLifetimeType())
1545224145Sdim        return Diag(Loc, diag::err_arc_new_array_without_ownership)
1546224145Sdim          << BaseAllocType;
1547224145Sdim    }
1548224145Sdim  }
1549221345Sdim
1550193326Sed  return false;
1551193326Sed}
1552193326Sed
1553204643Srdivacky/// \brief Determine whether the given function is a non-placement
1554204643Srdivacky/// deallocation function.
1555263508Sdimstatic bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD) {
1556204643Srdivacky  if (FD->isInvalidDecl())
1557204643Srdivacky    return false;
1558204643Srdivacky
1559204643Srdivacky  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1560204643Srdivacky    return Method->isUsualDeallocationFunction();
1561204643Srdivacky
1562263508Sdim  if (FD->getOverloadedOperator() != OO_Delete &&
1563263508Sdim      FD->getOverloadedOperator() != OO_Array_Delete)
1564263508Sdim    return false;
1565263508Sdim
1566263508Sdim  if (FD->getNumParams() == 1)
1567263508Sdim    return true;
1568263508Sdim
1569263508Sdim  return S.getLangOpts().SizedDeallocation && FD->getNumParams() == 2 &&
1570263508Sdim         S.Context.hasSameUnqualifiedType(FD->getParamDecl(1)->getType(),
1571263508Sdim                                          S.Context.getSizeType());
1572204643Srdivacky}
1573204643Srdivacky
1574193326Sed/// FindAllocationFunctions - Finds the overloads of operator new and delete
1575193326Sed/// that are appropriate for the allocation.
1576193326Sedbool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
1577193326Sed                                   bool UseGlobal, QualType AllocType,
1578263508Sdim                                   bool IsArray, MultiExprArg PlaceArgs,
1579193326Sed                                   FunctionDecl *&OperatorNew,
1580198092Srdivacky                                   FunctionDecl *&OperatorDelete) {
1581193326Sed  // --- Choosing an allocation function ---
1582193326Sed  // C++ 5.3.4p8 - 14 & 18
1583193326Sed  // 1) If UseGlobal is true, only look in the global scope. Else, also look
1584193326Sed  //   in the scope of the allocated class.
1585193326Sed  // 2) If an array size is given, look for operator new[], else look for
1586193326Sed  //   operator new.
1587193326Sed  // 3) The first argument is always size_t. Append the arguments from the
1588193326Sed  //   placement form.
1589193326Sed
1590263508Sdim  SmallVector<Expr*, 8> AllocArgs(1 + PlaceArgs.size());
1591193326Sed  // We don't care about the actual value of this argument.
1592193326Sed  // FIXME: Should the Sema create the expression and embed it in the syntax
1593193326Sed  // tree? Or should the consumer just recalculate the value?
1594212904Sdim  IntegerLiteral Size(Context, llvm::APInt::getNullValue(
1595226633Sdim                      Context.getTargetInfo().getPointerWidth(0)),
1596198092Srdivacky                      Context.getSizeType(),
1597198092Srdivacky                      SourceLocation());
1598198092Srdivacky  AllocArgs[0] = &Size;
1599263508Sdim  std::copy(PlaceArgs.begin(), PlaceArgs.end(), AllocArgs.begin() + 1);
1600193326Sed
1601204643Srdivacky  // C++ [expr.new]p8:
1602204643Srdivacky  //   If the allocated type is a non-array type, the allocation
1603218893Sdim  //   function's name is operator new and the deallocation function's
1604204643Srdivacky  //   name is operator delete. If the allocated type is an array
1605218893Sdim  //   type, the allocation function's name is operator new[] and the
1606218893Sdim  //   deallocation function's name is operator delete[].
1607193326Sed  DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
1608193326Sed                                        IsArray ? OO_Array_New : OO_New);
1609204643Srdivacky  DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1610204643Srdivacky                                        IsArray ? OO_Array_Delete : OO_Delete);
1611204643Srdivacky
1612212904Sdim  QualType AllocElemType = Context.getBaseElementType(AllocType);
1613212904Sdim
1614212904Sdim  if (AllocElemType->isRecordType() && !UseGlobal) {
1615198092Srdivacky    CXXRecordDecl *Record
1616212904Sdim      = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
1617263508Sdim    if (FindAllocationOverload(StartLoc, Range, NewName, AllocArgs, Record,
1618263508Sdim                               /*AllowMissing=*/true, OperatorNew))
1619193326Sed      return true;
1620193326Sed  }
1621263508Sdim
1622193326Sed  if (!OperatorNew) {
1623193326Sed    // Didn't find a member overload. Look for a global one.
1624193326Sed    DeclareGlobalNewDelete();
1625193326Sed    DeclContext *TUDecl = Context.getTranslationUnitDecl();
1626263508Sdim    bool FallbackEnabled = IsArray && Context.getLangOpts().MicrosoftMode;
1627263508Sdim    if (FindAllocationOverload(StartLoc, Range, NewName, AllocArgs, TUDecl,
1628263508Sdim                               /*AllowMissing=*/FallbackEnabled, OperatorNew,
1629263508Sdim                               /*Diagnose=*/!FallbackEnabled)) {
1630263508Sdim      if (!FallbackEnabled)
1631263508Sdim        return true;
1632263508Sdim
1633263508Sdim      // MSVC will fall back on trying to find a matching global operator new
1634263508Sdim      // if operator new[] cannot be found.  Also, MSVC will leak by not
1635263508Sdim      // generating a call to operator delete or operator delete[], but we
1636263508Sdim      // will not replicate that bug.
1637263508Sdim      NewName = Context.DeclarationNames.getCXXOperatorName(OO_New);
1638263508Sdim      DeleteName = Context.DeclarationNames.getCXXOperatorName(OO_Delete);
1639263508Sdim      if (FindAllocationOverload(StartLoc, Range, NewName, AllocArgs, TUDecl,
1640263508Sdim                               /*AllowMissing=*/false, OperatorNew))
1641193326Sed      return true;
1642263508Sdim    }
1643193326Sed  }
1644193326Sed
1645207619Srdivacky  // We don't need an operator delete if we're running under
1646207619Srdivacky  // -fno-exceptions.
1647234353Sdim  if (!getLangOpts().Exceptions) {
1648207619Srdivacky    OperatorDelete = 0;
1649207619Srdivacky    return false;
1650207619Srdivacky  }
1651207619Srdivacky
1652193326Sed  // FindAllocationOverload can change the passed in arguments, so we need to
1653193326Sed  // copy them back.
1654263508Sdim  if (!PlaceArgs.empty())
1655263508Sdim    std::copy(AllocArgs.begin() + 1, AllocArgs.end(), PlaceArgs.data());
1656198092Srdivacky
1657204643Srdivacky  // C++ [expr.new]p19:
1658204643Srdivacky  //
1659204643Srdivacky  //   If the new-expression begins with a unary :: operator, the
1660218893Sdim  //   deallocation function's name is looked up in the global
1661204643Srdivacky  //   scope. Otherwise, if the allocated type is a class type T or an
1662218893Sdim  //   array thereof, the deallocation function's name is looked up in
1663204643Srdivacky  //   the scope of T. If this lookup fails to find the name, or if
1664204643Srdivacky  //   the allocated type is not a class type or array thereof, the
1665218893Sdim  //   deallocation function's name is looked up in the global scope.
1666204643Srdivacky  LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
1667212904Sdim  if (AllocElemType->isRecordType() && !UseGlobal) {
1668204643Srdivacky    CXXRecordDecl *RD
1669212904Sdim      = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
1670204643Srdivacky    LookupQualifiedName(FoundDelete, RD);
1671204643Srdivacky  }
1672205408Srdivacky  if (FoundDelete.isAmbiguous())
1673205408Srdivacky    return true; // FIXME: clean up expressions?
1674204643Srdivacky
1675204643Srdivacky  if (FoundDelete.empty()) {
1676204643Srdivacky    DeclareGlobalNewDelete();
1677204643Srdivacky    LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
1678204643Srdivacky  }
1679204643Srdivacky
1680204643Srdivacky  FoundDelete.suppressDiagnostics();
1681205408Srdivacky
1682226633Sdim  SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
1683205408Srdivacky
1684218893Sdim  // Whether we're looking for a placement operator delete is dictated
1685218893Sdim  // by whether we selected a placement operator new, not by whether
1686218893Sdim  // we had explicit placement arguments.  This matters for things like
1687218893Sdim  //   struct A { void *operator new(size_t, int = 0); ... };
1688218893Sdim  //   A *a = new A()
1689263508Sdim  bool isPlacementNew = (!PlaceArgs.empty() || OperatorNew->param_size() != 1);
1690218893Sdim
1691218893Sdim  if (isPlacementNew) {
1692204643Srdivacky    // C++ [expr.new]p20:
1693204643Srdivacky    //   A declaration of a placement deallocation function matches the
1694204643Srdivacky    //   declaration of a placement allocation function if it has the
1695204643Srdivacky    //   same number of parameters and, after parameter transformations
1696204643Srdivacky    //   (8.3.5), all parameter types except the first are
1697204643Srdivacky    //   identical. [...]
1698218893Sdim    //
1699204643Srdivacky    // To perform this comparison, we compute the function type that
1700204643Srdivacky    // the deallocation function should have, and use that type both
1701204643Srdivacky    // for template argument deduction and for comparison purposes.
1702218893Sdim    //
1703218893Sdim    // FIXME: this comparison should ignore CC and the like.
1704204643Srdivacky    QualType ExpectedFunctionType;
1705204643Srdivacky    {
1706204643Srdivacky      const FunctionProtoType *Proto
1707204643Srdivacky        = OperatorNew->getType()->getAs<FunctionProtoType>();
1708218893Sdim
1709226633Sdim      SmallVector<QualType, 4> ArgTypes;
1710218893Sdim      ArgTypes.push_back(Context.VoidPtrTy);
1711204643Srdivacky      for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
1712204643Srdivacky        ArgTypes.push_back(Proto->getArgType(I));
1713204643Srdivacky
1714218893Sdim      FunctionProtoType::ExtProtoInfo EPI;
1715218893Sdim      EPI.Variadic = Proto->isVariadic();
1716218893Sdim
1717204643Srdivacky      ExpectedFunctionType
1718249423Sdim        = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
1719204643Srdivacky    }
1720204643Srdivacky
1721218893Sdim    for (LookupResult::iterator D = FoundDelete.begin(),
1722204643Srdivacky                             DEnd = FoundDelete.end();
1723204643Srdivacky         D != DEnd; ++D) {
1724204643Srdivacky      FunctionDecl *Fn = 0;
1725218893Sdim      if (FunctionTemplateDecl *FnTmpl
1726204643Srdivacky            = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
1727204643Srdivacky        // Perform template argument deduction to try to match the
1728204643Srdivacky        // expected function type.
1729243830Sdim        TemplateDeductionInfo Info(StartLoc);
1730204643Srdivacky        if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
1731204643Srdivacky          continue;
1732204643Srdivacky      } else
1733204643Srdivacky        Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
1734204643Srdivacky
1735204643Srdivacky      if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
1736205408Srdivacky        Matches.push_back(std::make_pair(D.getPair(), Fn));
1737204643Srdivacky    }
1738204643Srdivacky  } else {
1739204643Srdivacky    // C++ [expr.new]p20:
1740204643Srdivacky    //   [...] Any non-placement deallocation function matches a
1741204643Srdivacky    //   non-placement allocation function. [...]
1742218893Sdim    for (LookupResult::iterator D = FoundDelete.begin(),
1743204643Srdivacky                             DEnd = FoundDelete.end();
1744204643Srdivacky         D != DEnd; ++D) {
1745204643Srdivacky      if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
1746263508Sdim        if (isNonPlacementDeallocationFunction(*this, Fn))
1747205408Srdivacky          Matches.push_back(std::make_pair(D.getPair(), Fn));
1748204643Srdivacky    }
1749263508Sdim
1750263508Sdim    // C++1y [expr.new]p22:
1751263508Sdim    //   For a non-placement allocation function, the normal deallocation
1752263508Sdim    //   function lookup is used
1753263508Sdim    // C++1y [expr.delete]p?:
1754263508Sdim    //   If [...] deallocation function lookup finds both a usual deallocation
1755263508Sdim    //   function with only a pointer parameter and a usual deallocation
1756263508Sdim    //   function with both a pointer parameter and a size parameter, then the
1757263508Sdim    //   selected deallocation function shall be the one with two parameters.
1758263508Sdim    //   Otherwise, the selected deallocation function shall be the function
1759263508Sdim    //   with one parameter.
1760263508Sdim    if (getLangOpts().SizedDeallocation && Matches.size() == 2) {
1761263508Sdim      if (Matches[0].second->getNumParams() == 1)
1762263508Sdim        Matches.erase(Matches.begin());
1763263508Sdim      else
1764263508Sdim        Matches.erase(Matches.begin() + 1);
1765263508Sdim      assert(Matches[0].second->getNumParams() == 2 &&
1766263508Sdim             "found an unexpected uusal deallocation function");
1767263508Sdim    }
1768204643Srdivacky  }
1769204643Srdivacky
1770204643Srdivacky  // C++ [expr.new]p20:
1771204643Srdivacky  //   [...] If the lookup finds a single matching deallocation
1772204643Srdivacky  //   function, that function will be called; otherwise, no
1773204643Srdivacky  //   deallocation function will be called.
1774204643Srdivacky  if (Matches.size() == 1) {
1775205408Srdivacky    OperatorDelete = Matches[0].second;
1776204643Srdivacky
1777204643Srdivacky    // C++0x [expr.new]p20:
1778204643Srdivacky    //   If the lookup finds the two-parameter form of a usual
1779204643Srdivacky    //   deallocation function (3.7.4.2) and that function, considered
1780204643Srdivacky    //   as a placement deallocation function, would have been
1781204643Srdivacky    //   selected as a match for the allocation function, the program
1782204643Srdivacky    //   is ill-formed.
1783263508Sdim    if (!PlaceArgs.empty() && getLangOpts().CPlusPlus11 &&
1784263508Sdim        isNonPlacementDeallocationFunction(*this, OperatorDelete)) {
1785204643Srdivacky      Diag(StartLoc, diag::err_placement_new_non_placement_delete)
1786263508Sdim        << SourceRange(PlaceArgs.front()->getLocStart(),
1787263508Sdim                       PlaceArgs.back()->getLocEnd());
1788263508Sdim      if (!OperatorDelete->isImplicit())
1789263508Sdim        Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1790263508Sdim          << DeleteName;
1791205408Srdivacky    } else {
1792205408Srdivacky      CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
1793205408Srdivacky                            Matches[0].first);
1794204643Srdivacky    }
1795204643Srdivacky  }
1796204643Srdivacky
1797193326Sed  return false;
1798193326Sed}
1799193326Sed
1800193326Sed/// FindAllocationOverload - Find an fitting overload for the allocation
1801193326Sed/// function in the specified scope.
1802193326Sedbool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1803263508Sdim                                  DeclarationName Name, MultiExprArg Args,
1804263508Sdim                                  DeclContext *Ctx,
1805223017Sdim                                  bool AllowMissing, FunctionDecl *&Operator,
1806223017Sdim                                  bool Diagnose) {
1807199482Srdivacky  LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1808199482Srdivacky  LookupQualifiedName(R, Ctx);
1809198092Srdivacky  if (R.empty()) {
1810223017Sdim    if (AllowMissing || !Diagnose)
1811193326Sed      return false;
1812193326Sed    return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
1813193326Sed      << Name << Range;
1814193326Sed  }
1815193326Sed
1816205408Srdivacky  if (R.isAmbiguous())
1817205408Srdivacky    return true;
1818198092Srdivacky
1819205408Srdivacky  R.suppressDiagnostics();
1820205408Srdivacky
1821203955Srdivacky  OverloadCandidateSet Candidates(StartLoc);
1822218893Sdim  for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
1823198092Srdivacky       Alloc != AllocEnd; ++Alloc) {
1824193326Sed    // Even member operator new/delete are implicitly treated as
1825193326Sed    // static, so don't use AddMemberCandidate.
1826205408Srdivacky    NamedDecl *D = (*Alloc)->getUnderlyingDecl();
1827203955Srdivacky
1828205408Srdivacky    if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1829205408Srdivacky      AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
1830234353Sdim                                   /*ExplicitTemplateArgs=*/0,
1831263508Sdim                                   Args, Candidates,
1832203955Srdivacky                                   /*SuppressUserConversions=*/false);
1833198092Srdivacky      continue;
1834203955Srdivacky    }
1835203955Srdivacky
1836205408Srdivacky    FunctionDecl *Fn = cast<FunctionDecl>(D);
1837263508Sdim    AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates,
1838203955Srdivacky                         /*SuppressUserConversions=*/false);
1839193326Sed  }
1840193326Sed
1841193326Sed  // Do the resolution.
1842193326Sed  OverloadCandidateSet::iterator Best;
1843212904Sdim  switch (Candidates.BestViableFunction(*this, StartLoc, Best)) {
1844193326Sed  case OR_Success: {
1845193326Sed    // Got one!
1846193326Sed    FunctionDecl *FnDecl = Best->Function;
1847234353Sdim    MarkFunctionReferenced(StartLoc, FnDecl);
1848193326Sed    // The first argument is size_t, and the first parameter must be size_t,
1849193326Sed    // too. This is checked on declaration and can be assumed. (It can't be
1850193326Sed    // asserted on, though, since invalid decls are left in there.)
1851205408Srdivacky    // Watch out for variadic allocator function.
1852199990Srdivacky    unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1853263508Sdim    for (unsigned i = 0; (i < Args.size() && i < NumArgsInFnDecl); ++i) {
1854223017Sdim      InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1855223017Sdim                                                       FnDecl->getParamDecl(i));
1856223017Sdim
1857223017Sdim      if (!Diagnose && !CanPerformCopyInitialization(Entity, Owned(Args[i])))
1858223017Sdim        return true;
1859223017Sdim
1860212904Sdim      ExprResult Result
1861223017Sdim        = PerformCopyInitialization(Entity, SourceLocation(), Owned(Args[i]));
1862206084Srdivacky      if (Result.isInvalid())
1863193326Sed        return true;
1864218893Sdim
1865206084Srdivacky      Args[i] = Result.takeAs<Expr>();
1866193326Sed    }
1867234353Sdim
1868193326Sed    Operator = FnDecl;
1869234353Sdim
1870234353Sdim    if (CheckAllocationAccess(StartLoc, Range, R.getNamingClass(),
1871234353Sdim                              Best->FoundDecl, Diagnose) == AR_inaccessible)
1872234353Sdim      return true;
1873234353Sdim
1874193326Sed    return false;
1875193326Sed  }
1876193326Sed
1877193326Sed  case OR_No_Viable_Function:
1878223017Sdim    if (Diagnose) {
1879223017Sdim      Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
1880223017Sdim        << Name << Range;
1881263508Sdim      Candidates.NoteCandidates(*this, OCD_AllCandidates, Args);
1882223017Sdim    }
1883193326Sed    return true;
1884193326Sed
1885193326Sed  case OR_Ambiguous:
1886223017Sdim    if (Diagnose) {
1887223017Sdim      Diag(StartLoc, diag::err_ovl_ambiguous_call)
1888223017Sdim        << Name << Range;
1889263508Sdim      Candidates.NoteCandidates(*this, OCD_ViableCandidates, Args);
1890223017Sdim    }
1891193326Sed    return true;
1892193326Sed
1893221345Sdim  case OR_Deleted: {
1894223017Sdim    if (Diagnose) {
1895223017Sdim      Diag(StartLoc, diag::err_ovl_deleted_call)
1896223017Sdim        << Best->Function->isDeleted()
1897223017Sdim        << Name
1898223017Sdim        << getDeletedOrUnavailableSuffix(Best->Function)
1899223017Sdim        << Range;
1900263508Sdim      Candidates.NoteCandidates(*this, OCD_AllCandidates, Args);
1901223017Sdim    }
1902193326Sed    return true;
1903193326Sed  }
1904221345Sdim  }
1905226633Sdim  llvm_unreachable("Unreachable, bad result from BestViableFunction");
1906193326Sed}
1907193326Sed
1908193326Sed
1909193326Sed/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1910193326Sed/// delete. These are:
1911193326Sed/// @code
1912221345Sdim///   // C++03:
1913193326Sed///   void* operator new(std::size_t) throw(std::bad_alloc);
1914193326Sed///   void* operator new[](std::size_t) throw(std::bad_alloc);
1915193326Sed///   void operator delete(void *) throw();
1916193326Sed///   void operator delete[](void *) throw();
1917263508Sdim///   // C++11:
1918221345Sdim///   void* operator new(std::size_t);
1919221345Sdim///   void* operator new[](std::size_t);
1920263508Sdim///   void operator delete(void *) noexcept;
1921263508Sdim///   void operator delete[](void *) noexcept;
1922263508Sdim///   // C++1y:
1923263508Sdim///   void* operator new(std::size_t);
1924263508Sdim///   void* operator new[](std::size_t);
1925263508Sdim///   void operator delete(void *) noexcept;
1926263508Sdim///   void operator delete[](void *) noexcept;
1927263508Sdim///   void operator delete(void *, std::size_t) noexcept;
1928263508Sdim///   void operator delete[](void *, std::size_t) noexcept;
1929193326Sed/// @endcode
1930193326Sed/// Note that the placement and nothrow forms of new are *not* implicitly
1931193326Sed/// declared. Their use requires including \<new\>.
1932198092Srdivackyvoid Sema::DeclareGlobalNewDelete() {
1933193326Sed  if (GlobalNewDeleteDeclared)
1934193326Sed    return;
1935218893Sdim
1936198092Srdivacky  // C++ [basic.std.dynamic]p2:
1937218893Sdim  //   [...] The following allocation and deallocation functions (18.4) are
1938218893Sdim  //   implicitly declared in global scope in each translation unit of a
1939198092Srdivacky  //   program
1940218893Sdim  //
1941221345Sdim  //     C++03:
1942198092Srdivacky  //     void* operator new(std::size_t) throw(std::bad_alloc);
1943218893Sdim  //     void* operator new[](std::size_t) throw(std::bad_alloc);
1944218893Sdim  //     void  operator delete(void*) throw();
1945198092Srdivacky  //     void  operator delete[](void*) throw();
1946263508Sdim  //     C++11:
1947221345Sdim  //     void* operator new(std::size_t);
1948221345Sdim  //     void* operator new[](std::size_t);
1949263508Sdim  //     void  operator delete(void*) noexcept;
1950263508Sdim  //     void  operator delete[](void*) noexcept;
1951263508Sdim  //     C++1y:
1952263508Sdim  //     void* operator new(std::size_t);
1953263508Sdim  //     void* operator new[](std::size_t);
1954263508Sdim  //     void  operator delete(void*) noexcept;
1955263508Sdim  //     void  operator delete[](void*) noexcept;
1956263508Sdim  //     void  operator delete(void*, std::size_t) noexcept;
1957263508Sdim  //     void  operator delete[](void*, std::size_t) noexcept;
1958198092Srdivacky  //
1959218893Sdim  //   These implicit declarations introduce only the function names operator
1960198092Srdivacky  //   new, operator new[], operator delete, operator delete[].
1961198092Srdivacky  //
1962198092Srdivacky  // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1963198092Srdivacky  // "std" or "bad_alloc" as necessary to form the exception specification.
1964198092Srdivacky  // However, we do not make these implicit declarations visible to name
1965198092Srdivacky  // lookup.
1966249423Sdim  if (!StdBadAlloc && !getLangOpts().CPlusPlus11) {
1967198092Srdivacky    // The "std::bad_alloc" class has not yet been declared, so build it
1968198092Srdivacky    // implicitly.
1969218893Sdim    StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
1970218893Sdim                                        getOrCreateStdNamespace(),
1971221345Sdim                                        SourceLocation(), SourceLocation(),
1972218893Sdim                                      &PP.getIdentifierTable().get("bad_alloc"),
1973221345Sdim                                        0);
1974212904Sdim    getStdBadAlloc()->setImplicit(true);
1975198092Srdivacky  }
1976218893Sdim
1977193326Sed  GlobalNewDeleteDeclared = true;
1978193326Sed
1979193326Sed  QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1980193326Sed  QualType SizeT = Context.getSizeType();
1981234353Sdim  bool AssumeSaneOperatorNew = getLangOpts().AssumeSaneOperatorNew;
1982193326Sed
1983193326Sed  DeclareGlobalAllocationFunction(
1984193326Sed      Context.DeclarationNames.getCXXOperatorName(OO_New),
1985263508Sdim      VoidPtr, SizeT, QualType(), AssumeSaneOperatorNew);
1986193326Sed  DeclareGlobalAllocationFunction(
1987193326Sed      Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
1988263508Sdim      VoidPtr, SizeT, QualType(), AssumeSaneOperatorNew);
1989193326Sed  DeclareGlobalAllocationFunction(
1990193326Sed      Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1991193326Sed      Context.VoidTy, VoidPtr);
1992193326Sed  DeclareGlobalAllocationFunction(
1993193326Sed      Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1994193326Sed      Context.VoidTy, VoidPtr);
1995263508Sdim  if (getLangOpts().SizedDeallocation) {
1996263508Sdim    DeclareGlobalAllocationFunction(
1997263508Sdim        Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1998263508Sdim        Context.VoidTy, VoidPtr, Context.getSizeType());
1999263508Sdim    DeclareGlobalAllocationFunction(
2000263508Sdim        Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
2001263508Sdim        Context.VoidTy, VoidPtr, Context.getSizeType());
2002263508Sdim  }
2003193326Sed}
2004193326Sed
2005193326Sed/// DeclareGlobalAllocationFunction - Declares a single implicit global
2006193326Sed/// allocation function if it doesn't already exist.
2007193326Sedvoid Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
2008263508Sdim                                           QualType Return,
2009263508Sdim                                           QualType Param1, QualType Param2,
2010201361Srdivacky                                           bool AddMallocAttr) {
2011193326Sed  DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
2012263508Sdim  unsigned NumParams = Param2.isNull() ? 1 : 2;
2013193326Sed
2014193326Sed  // Check if this function is already declared.
2015263508Sdim  DeclContext::lookup_result R = GlobalCtx->lookup(Name);
2016263508Sdim  for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end();
2017263508Sdim       Alloc != AllocEnd; ++Alloc) {
2018263508Sdim    // Only look at non-template functions, as it is the predefined,
2019263508Sdim    // non-templated allocation function we are trying to declare here.
2020263508Sdim    if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
2021263508Sdim      if (Func->getNumParams() == NumParams) {
2022263508Sdim        QualType InitialParam1Type =
2023263508Sdim            Context.getCanonicalType(Func->getParamDecl(0)
2024263508Sdim                                         ->getType().getUnqualifiedType());
2025263508Sdim        QualType InitialParam2Type =
2026263508Sdim            NumParams == 2
2027263508Sdim                ? Context.getCanonicalType(Func->getParamDecl(1)
2028263508Sdim                                               ->getType().getUnqualifiedType())
2029263508Sdim                : QualType();
2030203955Srdivacky        // FIXME: Do we need to check for default arguments here?
2031263508Sdim        if (InitialParam1Type == Param1 &&
2032263508Sdim            (NumParams == 1 || InitialParam2Type == Param2)) {
2033263508Sdim          if (AddMallocAttr && !Func->hasAttr<MallocAttr>())
2034263508Sdim            Func->addAttr(::new (Context) MallocAttr(SourceLocation(),
2035263508Sdim                                                     Context));
2036263508Sdim          // Make the function visible to name lookup, even if we found it in
2037263508Sdim          // an unimported module. It either is an implicitly-declared global
2038263508Sdim          // allocation function, or is suppressing that function.
2039263508Sdim          Func->setHidden(false);
2040203955Srdivacky          return;
2041212904Sdim        }
2042203955Srdivacky      }
2043193326Sed    }
2044193326Sed  }
2045193326Sed
2046198092Srdivacky  QualType BadAllocType;
2047218893Sdim  bool HasBadAllocExceptionSpec
2048198092Srdivacky    = (Name.getCXXOverloadedOperator() == OO_New ||
2049198092Srdivacky       Name.getCXXOverloadedOperator() == OO_Array_New);
2050249423Sdim  if (HasBadAllocExceptionSpec && !getLangOpts().CPlusPlus11) {
2051198092Srdivacky    assert(StdBadAlloc && "Must have std::bad_alloc declared");
2052212904Sdim    BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
2053198092Srdivacky  }
2054218893Sdim
2055218893Sdim  FunctionProtoType::ExtProtoInfo EPI;
2056218893Sdim  if (HasBadAllocExceptionSpec) {
2057249423Sdim    if (!getLangOpts().CPlusPlus11) {
2058221345Sdim      EPI.ExceptionSpecType = EST_Dynamic;
2059221345Sdim      EPI.NumExceptions = 1;
2060221345Sdim      EPI.Exceptions = &BadAllocType;
2061221345Sdim    }
2062221345Sdim  } else {
2063249423Sdim    EPI.ExceptionSpecType = getLangOpts().CPlusPlus11 ?
2064221345Sdim                                EST_BasicNoexcept : EST_DynamicNone;
2065218893Sdim  }
2066218893Sdim
2067263508Sdim  QualType Params[] = { Param1, Param2 };
2068263508Sdim
2069263508Sdim  QualType FnType = Context.getFunctionType(
2070263508Sdim      Return, ArrayRef<QualType>(Params, NumParams), EPI);
2071193326Sed  FunctionDecl *Alloc =
2072221345Sdim    FunctionDecl::Create(Context, GlobalCtx, SourceLocation(),
2073221345Sdim                         SourceLocation(), Name,
2074249423Sdim                         FnType, /*TInfo=*/0, SC_None, false, true);
2075193326Sed  Alloc->setImplicit();
2076218893Sdim
2077201361Srdivacky  if (AddMallocAttr)
2078212904Sdim    Alloc->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
2079218893Sdim
2080263508Sdim  ParmVarDecl *ParamDecls[2];
2081263508Sdim  for (unsigned I = 0; I != NumParams; ++I)
2082263508Sdim    ParamDecls[I] = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
2083263508Sdim                                        SourceLocation(), 0,
2084263508Sdim                                        Params[I], /*TInfo=*/0,
2085263508Sdim                                        SC_None, 0);
2086263508Sdim  Alloc->setParams(ArrayRef<ParmVarDecl*>(ParamDecls, NumParams));
2087193326Sed
2088193326Sed  // FIXME: Also add this declaration to the IdentifierResolver, but
2089193326Sed  // make sure it is at the end of the chain to coincide with the
2090193326Sed  // global scope.
2091212904Sdim  Context.getTranslationUnitDecl()->addDecl(Alloc);
2092193326Sed}
2093193326Sed
2094263508SdimFunctionDecl *Sema::FindUsualDeallocationFunction(SourceLocation StartLoc,
2095263508Sdim                                                  bool CanProvideSize,
2096263508Sdim                                                  DeclarationName Name) {
2097263508Sdim  DeclareGlobalNewDelete();
2098263508Sdim
2099263508Sdim  LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName);
2100263508Sdim  LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2101263508Sdim
2102263508Sdim  // C++ [expr.new]p20:
2103263508Sdim  //   [...] Any non-placement deallocation function matches a
2104263508Sdim  //   non-placement allocation function. [...]
2105263508Sdim  llvm::SmallVector<FunctionDecl*, 2> Matches;
2106263508Sdim  for (LookupResult::iterator D = FoundDelete.begin(),
2107263508Sdim                           DEnd = FoundDelete.end();
2108263508Sdim       D != DEnd; ++D) {
2109263508Sdim    if (FunctionDecl *Fn = dyn_cast<FunctionDecl>(*D))
2110263508Sdim      if (isNonPlacementDeallocationFunction(*this, Fn))
2111263508Sdim        Matches.push_back(Fn);
2112263508Sdim  }
2113263508Sdim
2114263508Sdim  // C++1y [expr.delete]p?:
2115263508Sdim  //   If the type is complete and deallocation function lookup finds both a
2116263508Sdim  //   usual deallocation function with only a pointer parameter and a usual
2117263508Sdim  //   deallocation function with both a pointer parameter and a size
2118263508Sdim  //   parameter, then the selected deallocation function shall be the one
2119263508Sdim  //   with two parameters.  Otherwise, the selected deallocation function
2120263508Sdim  //   shall be the function with one parameter.
2121263508Sdim  if (getLangOpts().SizedDeallocation && Matches.size() == 2) {
2122263508Sdim    unsigned NumArgs = CanProvideSize ? 2 : 1;
2123263508Sdim    if (Matches[0]->getNumParams() != NumArgs)
2124263508Sdim      Matches.erase(Matches.begin());
2125263508Sdim    else
2126263508Sdim      Matches.erase(Matches.begin() + 1);
2127263508Sdim    assert(Matches[0]->getNumParams() == NumArgs &&
2128263508Sdim           "found an unexpected uusal deallocation function");
2129263508Sdim  }
2130263508Sdim
2131263508Sdim  assert(Matches.size() == 1 &&
2132263508Sdim         "unexpectedly have multiple usual deallocation functions");
2133263508Sdim  return Matches.front();
2134263508Sdim}
2135263508Sdim
2136199482Srdivackybool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
2137199482Srdivacky                                    DeclarationName Name,
2138223017Sdim                                    FunctionDecl* &Operator, bool Diagnose) {
2139199482Srdivacky  LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
2140199482Srdivacky  // Try to find operator delete/operator delete[] in class scope.
2141199482Srdivacky  LookupQualifiedName(Found, RD);
2142218893Sdim
2143199482Srdivacky  if (Found.isAmbiguous())
2144199482Srdivacky    return true;
2145199482Srdivacky
2146210299Sed  Found.suppressDiagnostics();
2147210299Sed
2148226633Sdim  SmallVector<DeclAccessPair,4> Matches;
2149199482Srdivacky  for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
2150199482Srdivacky       F != FEnd; ++F) {
2151212904Sdim    NamedDecl *ND = (*F)->getUnderlyingDecl();
2152212904Sdim
2153212904Sdim    // Ignore template operator delete members from the check for a usual
2154212904Sdim    // deallocation function.
2155212904Sdim    if (isa<FunctionTemplateDecl>(ND))
2156212904Sdim      continue;
2157212904Sdim
2158212904Sdim    if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction())
2159212904Sdim      Matches.push_back(F.getPair());
2160199482Srdivacky  }
2161199482Srdivacky
2162212904Sdim  // There's exactly one suitable operator;  pick it.
2163212904Sdim  if (Matches.size() == 1) {
2164212904Sdim    Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl());
2165223017Sdim
2166223017Sdim    if (Operator->isDeleted()) {
2167223017Sdim      if (Diagnose) {
2168223017Sdim        Diag(StartLoc, diag::err_deleted_function_use);
2169234353Sdim        NoteDeletedFunction(Operator);
2170223017Sdim      }
2171223017Sdim      return true;
2172223017Sdim    }
2173223017Sdim
2174234353Sdim    if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
2175234353Sdim                              Matches[0], Diagnose) == AR_inaccessible)
2176234353Sdim      return true;
2177234353Sdim
2178212904Sdim    return false;
2179212904Sdim
2180212904Sdim  // We found multiple suitable operators;  complain about the ambiguity.
2181212904Sdim  } else if (!Matches.empty()) {
2182223017Sdim    if (Diagnose) {
2183223017Sdim      Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
2184223017Sdim        << Name << RD;
2185212904Sdim
2186226633Sdim      for (SmallVectorImpl<DeclAccessPair>::iterator
2187223017Sdim             F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F)
2188223017Sdim        Diag((*F)->getUnderlyingDecl()->getLocation(),
2189223017Sdim             diag::note_member_declared_here) << Name;
2190223017Sdim    }
2191212904Sdim    return true;
2192212904Sdim  }
2193212904Sdim
2194199482Srdivacky  // We did find operator delete/operator delete[] declarations, but
2195199482Srdivacky  // none of them were suitable.
2196199482Srdivacky  if (!Found.empty()) {
2197223017Sdim    if (Diagnose) {
2198223017Sdim      Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
2199223017Sdim        << Name << RD;
2200218893Sdim
2201223017Sdim      for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
2202223017Sdim           F != FEnd; ++F)
2203223017Sdim        Diag((*F)->getUnderlyingDecl()->getLocation(),
2204223017Sdim             diag::note_member_declared_here) << Name;
2205223017Sdim    }
2206199482Srdivacky    return true;
2207199482Srdivacky  }
2208199482Srdivacky
2209263508Sdim  Operator = 0;
2210199482Srdivacky  return false;
2211199482Srdivacky}
2212199482Srdivacky
2213193326Sed/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
2214193326Sed/// @code ::delete ptr; @endcode
2215193326Sed/// or
2216193326Sed/// @code delete [] ptr; @endcode
2217212904SdimExprResult
2218193326SedSema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
2219221345Sdim                     bool ArrayForm, Expr *ExE) {
2220198092Srdivacky  // C++ [expr.delete]p1:
2221198092Srdivacky  //   The operand shall have a pointer type, or a class type having a single
2222263508Sdim  //   non-explicit conversion function to a pointer type. The result has type
2223263508Sdim  //   void.
2224198092Srdivacky  //
2225193326Sed  // DR599 amends "pointer type" to "pointer to object type" in both cases.
2226193326Sed
2227221345Sdim  ExprResult Ex = Owned(ExE);
2228198092Srdivacky  FunctionDecl *OperatorDelete = 0;
2229218893Sdim  bool ArrayFormAsWritten = ArrayForm;
2230218893Sdim  bool UsualArrayDeleteWantsSize = false;
2231198092Srdivacky
2232221345Sdim  if (!Ex.get()->isTypeDependent()) {
2233234353Sdim    // Perform lvalue-to-rvalue cast, if needed.
2234234353Sdim    Ex = DefaultLvalueConversion(Ex.take());
2235249423Sdim    if (Ex.isInvalid())
2236249423Sdim      return ExprError();
2237234353Sdim
2238221345Sdim    QualType Type = Ex.get()->getType();
2239193326Sed
2240263508Sdim    class DeleteConverter : public ContextualImplicitConverter {
2241263508Sdim    public:
2242263508Sdim      DeleteConverter() : ContextualImplicitConverter(false, true) {}
2243218893Sdim
2244263508Sdim      bool match(QualType ConvType) {
2245263508Sdim        // FIXME: If we have an operator T* and an operator void*, we must pick
2246263508Sdim        // the operator T*.
2247263508Sdim        if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
2248263508Sdim          if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
2249263508Sdim            return true;
2250263508Sdim        return false;
2251263508Sdim      }
2252206084Srdivacky
2253263508Sdim      SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
2254263508Sdim                                            QualType T) {
2255263508Sdim        return S.Diag(Loc, diag::err_delete_operand) << T;
2256263508Sdim      }
2257206084Srdivacky
2258263508Sdim      SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
2259263508Sdim                                               QualType T) {
2260263508Sdim        return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T;
2261263508Sdim      }
2262218893Sdim
2263263508Sdim      SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
2264263508Sdim                                                 QualType T, QualType ConvTy) {
2265263508Sdim        return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy;
2266263508Sdim      }
2267218893Sdim
2268263508Sdim      SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
2269263508Sdim                                             QualType ConvTy) {
2270263508Sdim        return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
2271263508Sdim          << ConvTy;
2272198092Srdivacky      }
2273263508Sdim
2274263508Sdim      SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
2275263508Sdim                                              QualType T) {
2276263508Sdim        return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T;
2277198092Srdivacky      }
2278263508Sdim
2279263508Sdim      SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
2280263508Sdim                                          QualType ConvTy) {
2281263508Sdim        return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
2282263508Sdim          << ConvTy;
2283198092Srdivacky      }
2284193326Sed
2285263508Sdim      SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
2286263508Sdim                                               QualType T, QualType ConvTy) {
2287263508Sdim        llvm_unreachable("conversion functions are permitted");
2288263508Sdim      }
2289263508Sdim    } Converter;
2290193326Sed
2291263508Sdim    Ex = PerformContextualImplicitConversion(StartLoc, Ex.take(), Converter);
2292263508Sdim    if (Ex.isInvalid())
2293263508Sdim      return ExprError();
2294263508Sdim    Type = Ex.get()->getType();
2295263508Sdim    if (!Converter.match(Type))
2296263508Sdim      // FIXME: PerformContextualImplicitConversion should return ExprError
2297263508Sdim      //        itself in this case.
2298263508Sdim      return ExprError();
2299263508Sdim
2300198092Srdivacky    QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
2301226633Sdim    QualType PointeeElem = Context.getBaseElementType(Pointee);
2302226633Sdim
2303226633Sdim    if (unsigned AddressSpace = Pointee.getAddressSpace())
2304226633Sdim      return Diag(Ex.get()->getLocStart(),
2305226633Sdim                  diag::err_address_space_qualified_delete)
2306226633Sdim               << Pointee.getUnqualifiedType() << AddressSpace;
2307226633Sdim
2308226633Sdim    CXXRecordDecl *PointeeRD = 0;
2309208600Srdivacky    if (Pointee->isVoidType() && !isSFINAEContext()) {
2310218893Sdim      // The C++ standard bans deleting a pointer to a non-object type, which
2311208600Srdivacky      // effectively bans deletion of "void*". However, most compilers support
2312208600Srdivacky      // this, so we treat it as a warning unless we're in a SFINAE context.
2313208600Srdivacky      Diag(StartLoc, diag::ext_delete_void_ptr_operand)
2314221345Sdim        << Type << Ex.get()->getSourceRange();
2315226633Sdim    } else if (Pointee->isFunctionType() || Pointee->isVoidType()) {
2316193326Sed      return ExprError(Diag(StartLoc, diag::err_delete_operand)
2317221345Sdim        << Type << Ex.get()->getSourceRange());
2318226633Sdim    } else if (!Pointee->isDependentType()) {
2319226633Sdim      if (!RequireCompleteType(StartLoc, Pointee,
2320239462Sdim                               diag::warn_delete_incomplete, Ex.get())) {
2321226633Sdim        if (const RecordType *RT = PointeeElem->getAs<RecordType>())
2322226633Sdim          PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
2323226633Sdim      }
2324226633Sdim    }
2325226633Sdim
2326198092Srdivacky    // C++ [expr.delete]p2:
2327218893Sdim    //   [Note: a pointer to a const type can be the operand of a
2328218893Sdim    //   delete-expression; it is not necessary to cast away the constness
2329218893Sdim    //   (5.2.11) of the pointer expression before it is used as the operand
2330198092Srdivacky    //   of the delete-expression. ]
2331218893Sdim
2332218893Sdim    if (Pointee->isArrayType() && !ArrayForm) {
2333218893Sdim      Diag(StartLoc, diag::warn_delete_array_type)
2334221345Sdim          << Type << Ex.get()->getSourceRange()
2335218893Sdim          << FixItHint::CreateInsertion(PP.getLocForEndOfToken(StartLoc), "[]");
2336218893Sdim      ArrayForm = true;
2337218893Sdim    }
2338218893Sdim
2339198092Srdivacky    DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
2340198092Srdivacky                                      ArrayForm ? OO_Array_Delete : OO_Delete);
2341198092Srdivacky
2342226633Sdim    if (PointeeRD) {
2343218893Sdim      if (!UseGlobal &&
2344226633Sdim          FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
2345226633Sdim                                   OperatorDelete))
2346199482Srdivacky        return ExprError();
2347218893Sdim
2348218893Sdim      // If we're allocating an array of records, check whether the
2349218893Sdim      // usual operator delete[] has a size_t parameter.
2350218893Sdim      if (ArrayForm) {
2351218893Sdim        // If the user specifically asked to use the global allocator,
2352218893Sdim        // we'll need to do the lookup into the class.
2353218893Sdim        if (UseGlobal)
2354218893Sdim          UsualArrayDeleteWantsSize =
2355218893Sdim            doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
2356218893Sdim
2357218893Sdim        // Otherwise, the usual operator delete[] should be the
2358218893Sdim        // function we just found.
2359263508Sdim        else if (OperatorDelete && isa<CXXMethodDecl>(OperatorDelete))
2360218893Sdim          UsualArrayDeleteWantsSize = (OperatorDelete->getNumParams() == 2);
2361218893Sdim      }
2362218893Sdim
2363234353Sdim      if (!PointeeRD->hasIrrelevantDestructor())
2364226633Sdim        if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
2365234353Sdim          MarkFunctionReferenced(StartLoc,
2366198092Srdivacky                                    const_cast<CXXDestructorDecl*>(Dtor));
2367251662Sdim          if (DiagnoseUseOfDecl(Dtor, StartLoc))
2368251662Sdim            return ExprError();
2369218893Sdim        }
2370223017Sdim
2371223017Sdim      // C++ [expr.delete]p3:
2372223017Sdim      //   In the first alternative (delete object), if the static type of the
2373223017Sdim      //   object to be deleted is different from its dynamic type, the static
2374223017Sdim      //   type shall be a base class of the dynamic type of the object to be
2375223017Sdim      //   deleted and the static type shall have a virtual destructor or the
2376223017Sdim      //   behavior is undefined.
2377223017Sdim      //
2378223017Sdim      // Note: a final class cannot be derived from, no issue there
2379226633Sdim      if (PointeeRD->isPolymorphic() && !PointeeRD->hasAttr<FinalAttr>()) {
2380226633Sdim        CXXDestructorDecl *dtor = PointeeRD->getDestructor();
2381226633Sdim        if (dtor && !dtor->isVirtual()) {
2382226633Sdim          if (PointeeRD->isAbstract()) {
2383226633Sdim            // If the class is abstract, we warn by default, because we're
2384226633Sdim            // sure the code has undefined behavior.
2385226633Sdim            Diag(StartLoc, diag::warn_delete_abstract_non_virtual_dtor)
2386226633Sdim                << PointeeElem;
2387226633Sdim          } else if (!ArrayForm) {
2388226633Sdim            // Otherwise, if this is not an array delete, it's a bit suspect,
2389226633Sdim            // but not necessarily wrong.
2390226633Sdim            Diag(StartLoc, diag::warn_delete_non_virtual_dtor) << PointeeElem;
2391226633Sdim          }
2392226633Sdim        }
2393223017Sdim      }
2394224145Sdim
2395198092Srdivacky    }
2396218893Sdim
2397263508Sdim    if (!OperatorDelete)
2398199482Srdivacky      // Look for a global declaration.
2399263508Sdim      OperatorDelete = FindUsualDeallocationFunction(
2400263508Sdim          StartLoc, !RequireCompleteType(StartLoc, Pointee, 0) &&
2401263508Sdim                    (!ArrayForm || UsualArrayDeleteWantsSize ||
2402263508Sdim                     Pointee.isDestructedType()),
2403263508Sdim          DeleteName);
2404198092Srdivacky
2405234353Sdim    MarkFunctionReferenced(StartLoc, OperatorDelete);
2406218893Sdim
2407218893Sdim    // Check access and ambiguity of operator delete and destructor.
2408226633Sdim    if (PointeeRD) {
2409226633Sdim      if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
2410221345Sdim          CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
2411218893Sdim                      PDiag(diag::err_access_dtor) << PointeeElem);
2412218893Sdim      }
2413218893Sdim    }
2414193326Sed  }
2415193326Sed
2416193326Sed  return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
2417218893Sdim                                           ArrayFormAsWritten,
2418218893Sdim                                           UsualArrayDeleteWantsSize,
2419221345Sdim                                           OperatorDelete, Ex.take(), StartLoc));
2420193326Sed}
2421193326Sed
2422199990Srdivacky/// \brief Check the use of the given variable as a C++ condition in an if,
2423199990Srdivacky/// while, do-while, or switch statement.
2424212904SdimExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
2425218893Sdim                                        SourceLocation StmtLoc,
2426218893Sdim                                        bool ConvertToBoolean) {
2427251662Sdim  if (ConditionVar->isInvalidDecl())
2428251662Sdim    return ExprError();
2429251662Sdim
2430199990Srdivacky  QualType T = ConditionVar->getType();
2431218893Sdim
2432199990Srdivacky  // C++ [stmt.select]p2:
2433199990Srdivacky  //   The declarator shall not specify a function or an array.
2434199990Srdivacky  if (T->isFunctionType())
2435218893Sdim    return ExprError(Diag(ConditionVar->getLocation(),
2436199990Srdivacky                          diag::err_invalid_use_of_function_type)
2437199990Srdivacky                       << ConditionVar->getSourceRange());
2438199990Srdivacky  else if (T->isArrayType())
2439218893Sdim    return ExprError(Diag(ConditionVar->getLocation(),
2440199990Srdivacky                          diag::err_invalid_use_of_array_type)
2441199990Srdivacky                     << ConditionVar->getSourceRange());
2442193326Sed
2443221345Sdim  ExprResult Condition =
2444234353Sdim    Owned(DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
2445234353Sdim                              SourceLocation(),
2446234353Sdim                              ConditionVar,
2447234353Sdim                              /*enclosing*/ false,
2448234353Sdim                              ConditionVar->getLocation(),
2449234353Sdim                              ConditionVar->getType().getNonReferenceType(),
2450221345Sdim                              VK_LValue));
2451234353Sdim
2452234353Sdim  MarkDeclRefReferenced(cast<DeclRefExpr>(Condition.get()));
2453234353Sdim
2454221345Sdim  if (ConvertToBoolean) {
2455221345Sdim    Condition = CheckBooleanCondition(Condition.take(), StmtLoc);
2456221345Sdim    if (Condition.isInvalid())
2457221345Sdim      return ExprError();
2458221345Sdim  }
2459218893Sdim
2460243830Sdim  return Condition;
2461193326Sed}
2462193326Sed
2463193326Sed/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
2464221345SdimExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr) {
2465193326Sed  // C++ 6.4p4:
2466193326Sed  // The value of a condition that is an initialized declaration in a statement
2467193326Sed  // other than a switch statement is the value of the declared variable
2468193326Sed  // implicitly converted to type bool. If that conversion is ill-formed, the
2469193326Sed  // program is ill-formed.
2470193326Sed  // The value of a condition that is an expression is the value of the
2471193326Sed  // expression, implicitly converted to bool.
2472193326Sed  //
2473193326Sed  return PerformContextuallyConvertToBool(CondExpr);
2474193326Sed}
2475193326Sed
2476193326Sed/// Helper function to determine whether this is the (deprecated) C++
2477193326Sed/// conversion from a string literal to a pointer to non-const char or
2478193326Sed/// non-const wchar_t (for narrow and wide string literals,
2479193326Sed/// respectively).
2480198092Srdivackybool
2481193326SedSema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
2482193326Sed  // Look inside the implicit cast, if it exists.
2483193326Sed  if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
2484193326Sed    From = Cast->getSubExpr();
2485193326Sed
2486193326Sed  // A string literal (2.13.4) that is not a wide string literal can
2487193326Sed  // be converted to an rvalue of type "pointer to char"; a wide
2488193326Sed  // string literal can be converted to an rvalue of type "pointer
2489193326Sed  // to wchar_t" (C++ 4.2p2).
2490210299Sed  if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
2491198092Srdivacky    if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
2492198092Srdivacky      if (const BuiltinType *ToPointeeType
2493198092Srdivacky          = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
2494193326Sed        // This conversion is considered only when there is an
2495193326Sed        // explicit appropriate pointer target type (C++ 4.2p2).
2496226633Sdim        if (!ToPtrType->getPointeeType().hasQualifiers()) {
2497226633Sdim          switch (StrLit->getKind()) {
2498226633Sdim            case StringLiteral::UTF8:
2499226633Sdim            case StringLiteral::UTF16:
2500226633Sdim            case StringLiteral::UTF32:
2501226633Sdim              // We don't allow UTF literals to be implicitly converted
2502226633Sdim              break;
2503226633Sdim            case StringLiteral::Ascii:
2504226633Sdim              return (ToPointeeType->getKind() == BuiltinType::Char_U ||
2505226633Sdim                      ToPointeeType->getKind() == BuiltinType::Char_S);
2506226633Sdim            case StringLiteral::Wide:
2507226633Sdim              return ToPointeeType->isWideCharType();
2508226633Sdim          }
2509226633Sdim        }
2510193326Sed      }
2511193326Sed
2512193326Sed  return false;
2513193326Sed}
2514193326Sed
2515218893Sdimstatic ExprResult BuildCXXCastArgument(Sema &S,
2516212904Sdim                                       SourceLocation CastLoc,
2517212904Sdim                                       QualType Ty,
2518212904Sdim                                       CastKind Kind,
2519212904Sdim                                       CXXMethodDecl *Method,
2520226633Sdim                                       DeclAccessPair FoundDecl,
2521226633Sdim                                       bool HadMultipleCandidates,
2522212904Sdim                                       Expr *From) {
2523207619Srdivacky  switch (Kind) {
2524226633Sdim  default: llvm_unreachable("Unhandled cast kind!");
2525212904Sdim  case CK_ConstructorConversion: {
2526226633Sdim    CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
2527243830Sdim    SmallVector<Expr*, 8> ConstructorArgs;
2528218893Sdim
2529263508Sdim    if (S.RequireNonAbstractType(CastLoc, Ty,
2530263508Sdim                                 diag::err_allocation_of_abstract_type))
2531263508Sdim      return ExprError();
2532263508Sdim
2533243830Sdim    if (S.CompleteConstructorCall(Constructor, From, CastLoc, ConstructorArgs))
2534212904Sdim      return ExprError();
2535218893Sdim
2536234353Sdim    S.CheckConstructorAccess(CastLoc, Constructor,
2537234353Sdim                             InitializedEntity::InitializeTemporary(Ty),
2538234353Sdim                             Constructor->getAccess());
2539249423Sdim
2540226633Sdim    ExprResult Result
2541226633Sdim      = S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
2542249423Sdim                                ConstructorArgs, HadMultipleCandidates,
2543249423Sdim                                /*ListInit*/ false, /*ZeroInit*/ false,
2544226633Sdim                                CXXConstructExpr::CK_Complete, SourceRange());
2545207619Srdivacky    if (Result.isInvalid())
2546212904Sdim      return ExprError();
2547218893Sdim
2548207619Srdivacky    return S.MaybeBindToTemporary(Result.takeAs<Expr>());
2549193326Sed  }
2550218893Sdim
2551212904Sdim  case CK_UserDefinedConversion: {
2552207619Srdivacky    assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
2553218893Sdim
2554207619Srdivacky    // Create an implicit call expr that calls it.
2555234353Sdim    CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
2556234353Sdim    ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
2557226633Sdim                                                 HadMultipleCandidates);
2558218893Sdim    if (Result.isInvalid())
2559218893Sdim      return ExprError();
2560234353Sdim    // Record usage of conversion in an implicit cast.
2561234353Sdim    Result = S.Owned(ImplicitCastExpr::Create(S.Context,
2562234353Sdim                                              Result.get()->getType(),
2563234353Sdim                                              CK_UserDefinedConversion,
2564234353Sdim                                              Result.get(), 0,
2565234353Sdim                                              Result.get()->getValueKind()));
2566218893Sdim
2567226633Sdim    S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ 0, FoundDecl);
2568226633Sdim
2569218893Sdim    return S.MaybeBindToTemporary(Result.get());
2570193326Sed  }
2571207619Srdivacky  }
2572218893Sdim}
2573193326Sed
2574193326Sed/// PerformImplicitConversion - Perform an implicit conversion of the
2575193326Sed/// expression From to the type ToType using the pre-computed implicit
2576221345Sdim/// conversion sequence ICS. Returns the converted
2577201361Srdivacky/// expression. Action is the kind of conversion we're performing,
2578193326Sed/// used in the error message.
2579221345SdimExprResult
2580221345SdimSema::PerformImplicitConversion(Expr *From, QualType ToType,
2581193326Sed                                const ImplicitConversionSequence &ICS,
2582224145Sdim                                AssignmentAction Action,
2583224145Sdim                                CheckedConversionKind CCK) {
2584202379Srdivacky  switch (ICS.getKind()) {
2585221345Sdim  case ImplicitConversionSequence::StandardConversion: {
2586221345Sdim    ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
2587224145Sdim                                               Action, CCK);
2588221345Sdim    if (Res.isInvalid())
2589221345Sdim      return ExprError();
2590221345Sdim    From = Res.take();
2591193326Sed    break;
2592221345Sdim  }
2593193326Sed
2594198092Srdivacky  case ImplicitConversionSequence::UserDefinedConversion: {
2595218893Sdim
2596198092Srdivacky      FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
2597218893Sdim      CastKind CastKind;
2598198092Srdivacky      QualType BeforeToType;
2599234353Sdim      assert(FD && "FIXME: aggregate initialization from init list");
2600198092Srdivacky      if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
2601212904Sdim        CastKind = CK_UserDefinedConversion;
2602218893Sdim
2603198092Srdivacky        // If the user-defined conversion is specified by a conversion function,
2604198092Srdivacky        // the initial standard conversion sequence converts the source type to
2605198092Srdivacky        // the implicit object parameter of the conversion function.
2606198092Srdivacky        BeforeToType = Context.getTagDeclType(Conv->getParent());
2607218893Sdim      } else {
2608218893Sdim        const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
2609212904Sdim        CastKind = CK_ConstructorConversion;
2610199482Srdivacky        // Do no conversion if dealing with ... for the first conversion.
2611199990Srdivacky        if (!ICS.UserDefined.EllipsisConversion) {
2612218893Sdim          // If the user-defined conversion is specified by a constructor, the
2613199482Srdivacky          // initial standard conversion sequence converts the source type to the
2614199482Srdivacky          // type required by the argument of the constructor
2615199990Srdivacky          BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
2616199990Srdivacky        }
2617218893Sdim      }
2618263508Sdim      // Watch out for ellipsis conversion.
2619199482Srdivacky      if (!ICS.UserDefined.EllipsisConversion) {
2620221345Sdim        ExprResult Res =
2621221345Sdim          PerformImplicitConversion(From, BeforeToType,
2622221345Sdim                                    ICS.UserDefined.Before, AA_Converting,
2623224145Sdim                                    CCK);
2624221345Sdim        if (Res.isInvalid())
2625221345Sdim          return ExprError();
2626221345Sdim        From = Res.take();
2627199482Srdivacky      }
2628218893Sdim
2629218893Sdim      ExprResult CastArg
2630207619Srdivacky        = BuildCXXCastArgument(*this,
2631207619Srdivacky                               From->getLocStart(),
2632198092Srdivacky                               ToType.getNonReferenceType(),
2633218893Sdim                               CastKind, cast<CXXMethodDecl>(FD),
2634218893Sdim                               ICS.UserDefined.FoundConversionFunction,
2635226633Sdim                               ICS.UserDefined.HadMultipleCandidates,
2636212904Sdim                               From);
2637198092Srdivacky
2638198092Srdivacky      if (CastArg.isInvalid())
2639221345Sdim        return ExprError();
2640199990Srdivacky
2641221345Sdim      From = CastArg.take();
2642199990Srdivacky
2643199990Srdivacky      return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
2644224145Sdim                                       AA_Converting, CCK);
2645198398Srdivacky  }
2646202379Srdivacky
2647202379Srdivacky  case ImplicitConversionSequence::AmbiguousConversion:
2648212904Sdim    ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
2649202379Srdivacky                          PDiag(diag::err_typecheck_ambiguous_condition)
2650202379Srdivacky                            << From->getSourceRange());
2651221345Sdim     return ExprError();
2652218893Sdim
2653193326Sed  case ImplicitConversionSequence::EllipsisConversion:
2654226633Sdim    llvm_unreachable("Cannot perform an ellipsis conversion");
2655193326Sed
2656193326Sed  case ImplicitConversionSequence::BadConversion:
2657221345Sdim    return ExprError();
2658193326Sed  }
2659193326Sed
2660193326Sed  // Everything went well.
2661221345Sdim  return Owned(From);
2662193326Sed}
2663193326Sed
2664193326Sed/// PerformImplicitConversion - Perform an implicit conversion of the
2665193326Sed/// expression From to the type ToType by following the standard
2666221345Sdim/// conversion sequence SCS. Returns the converted
2667193326Sed/// expression. Flavor is the context in which we're performing this
2668193326Sed/// conversion, for use in error messages.
2669221345SdimExprResult
2670221345SdimSema::PerformImplicitConversion(Expr *From, QualType ToType,
2671193326Sed                                const StandardConversionSequence& SCS,
2672224145Sdim                                AssignmentAction Action,
2673224145Sdim                                CheckedConversionKind CCK) {
2674224145Sdim  bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
2675224145Sdim
2676193326Sed  // Overall FIXME: we are recomputing too many types here and doing far too
2677193326Sed  // much extra work. What this means is that we need to keep track of more
2678193326Sed  // information that is computed when we try the implicit conversion initially,
2679193326Sed  // so that we don't need to recompute anything here.
2680193326Sed  QualType FromType = From->getType();
2681224145Sdim
2682193326Sed  if (SCS.CopyConstructor) {
2683193326Sed    // FIXME: When can ToType be a reference type?
2684193326Sed    assert(!ToType->isReferenceType());
2685198092Srdivacky    if (SCS.Second == ICK_Derived_To_Base) {
2686243830Sdim      SmallVector<Expr*, 8> ConstructorArgs;
2687198092Srdivacky      if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
2688243830Sdim                                  From, /*FIXME:ConstructLoc*/SourceLocation(),
2689198092Srdivacky                                  ConstructorArgs))
2690221345Sdim        return ExprError();
2691221345Sdim      return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2692221345Sdim                                   ToType, SCS.CopyConstructor,
2693243830Sdim                                   ConstructorArgs,
2694226633Sdim                                   /*HadMultipleCandidates*/ false,
2695249423Sdim                                   /*ListInit*/ false, /*ZeroInit*/ false,
2696221345Sdim                                   CXXConstructExpr::CK_Complete,
2697221345Sdim                                   SourceRange());
2698198092Srdivacky    }
2699221345Sdim    return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2700221345Sdim                                 ToType, SCS.CopyConstructor,
2701243830Sdim                                 From, /*HadMultipleCandidates*/ false,
2702249423Sdim                                 /*ListInit*/ false, /*ZeroInit*/ false,
2703221345Sdim                                 CXXConstructExpr::CK_Complete,
2704221345Sdim                                 SourceRange());
2705193326Sed  }
2706193326Sed
2707207619Srdivacky  // Resolve overloaded function references.
2708207619Srdivacky  if (Context.hasSameType(FromType, Context.OverloadTy)) {
2709207619Srdivacky    DeclAccessPair Found;
2710207619Srdivacky    FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
2711207619Srdivacky                                                          true, Found);
2712207619Srdivacky    if (!Fn)
2713221345Sdim      return ExprError();
2714207619Srdivacky
2715234353Sdim    if (DiagnoseUseOfDecl(Fn, From->getLocStart()))
2716221345Sdim      return ExprError();
2717207619Srdivacky
2718207619Srdivacky    From = FixOverloadedFunctionReference(From, Found, Fn);
2719207619Srdivacky    FromType = From->getType();
2720207619Srdivacky  }
2721207619Srdivacky
2722263508Sdim  // If we're converting to an atomic type, first convert to the corresponding
2723263508Sdim  // non-atomic type.
2724263508Sdim  QualType ToAtomicType;
2725263508Sdim  if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) {
2726263508Sdim    ToAtomicType = ToType;
2727263508Sdim    ToType = ToAtomic->getValueType();
2728263508Sdim  }
2729263508Sdim
2730193326Sed  // Perform the first implicit conversion.
2731193326Sed  switch (SCS.First) {
2732193326Sed  case ICK_Identity:
2733193326Sed    // Nothing to do.
2734193326Sed    break;
2735193326Sed
2736234353Sdim  case ICK_Lvalue_To_Rvalue: {
2737234353Sdim    assert(From->getObjectKind() != OK_ObjCProperty);
2738218893Sdim    FromType = FromType.getUnqualifiedType();
2739234353Sdim    ExprResult FromRes = DefaultLvalueConversion(From);
2740234353Sdim    assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!");
2741234353Sdim    From = FromRes.take();
2742218893Sdim    break;
2743234353Sdim  }
2744218893Sdim
2745193326Sed  case ICK_Array_To_Pointer:
2746193326Sed    FromType = Context.getArrayDecayedType(FromType);
2747224145Sdim    From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
2748224145Sdim                             VK_RValue, /*BasePath=*/0, CCK).take();
2749193326Sed    break;
2750193326Sed
2751193326Sed  case ICK_Function_To_Pointer:
2752193326Sed    FromType = Context.getPointerType(FromType);
2753224145Sdim    From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
2754224145Sdim                             VK_RValue, /*BasePath=*/0, CCK).take();
2755193326Sed    break;
2756193326Sed
2757193326Sed  default:
2758226633Sdim    llvm_unreachable("Improper first standard conversion");
2759193326Sed  }
2760193326Sed
2761193326Sed  // Perform the second implicit conversion
2762193326Sed  switch (SCS.Second) {
2763193326Sed  case ICK_Identity:
2764198092Srdivacky    // If both sides are functions (or pointers/references to them), there could
2765198092Srdivacky    // be incompatible exception declarations.
2766198092Srdivacky    if (CheckExceptionSpecCompatibility(From, ToType))
2767221345Sdim      return ExprError();
2768198092Srdivacky    // Nothing else to do.
2769193326Sed    break;
2770193326Sed
2771200583Srdivacky  case ICK_NoReturn_Adjustment:
2772200583Srdivacky    // If both sides are functions (or pointers/references to them), there could
2773200583Srdivacky    // be incompatible exception declarations.
2774200583Srdivacky    if (CheckExceptionSpecCompatibility(From, ToType))
2775221345Sdim      return ExprError();
2776218893Sdim
2777224145Sdim    From = ImpCastExprToType(From, ToType, CK_NoOp,
2778224145Sdim                             VK_RValue, /*BasePath=*/0, CCK).take();
2779200583Srdivacky    break;
2780218893Sdim
2781193326Sed  case ICK_Integral_Promotion:
2782198398Srdivacky  case ICK_Integral_Conversion:
2783243830Sdim    if (ToType->isBooleanType()) {
2784243830Sdim      assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&
2785243830Sdim             SCS.Second == ICK_Integral_Promotion &&
2786243830Sdim             "only enums with fixed underlying type can promote to bool");
2787243830Sdim      From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean,
2788243830Sdim                               VK_RValue, /*BasePath=*/0, CCK).take();
2789243830Sdim    } else {
2790243830Sdim      From = ImpCastExprToType(From, ToType, CK_IntegralCast,
2791243830Sdim                               VK_RValue, /*BasePath=*/0, CCK).take();
2792243830Sdim    }
2793198398Srdivacky    break;
2794198398Srdivacky
2795193326Sed  case ICK_Floating_Promotion:
2796198398Srdivacky  case ICK_Floating_Conversion:
2797224145Sdim    From = ImpCastExprToType(From, ToType, CK_FloatingCast,
2798224145Sdim                             VK_RValue, /*BasePath=*/0, CCK).take();
2799198398Srdivacky    break;
2800198398Srdivacky
2801193326Sed  case ICK_Complex_Promotion:
2802218893Sdim  case ICK_Complex_Conversion: {
2803218893Sdim    QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
2804218893Sdim    QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
2805218893Sdim    CastKind CK;
2806218893Sdim    if (FromEl->isRealFloatingType()) {
2807218893Sdim      if (ToEl->isRealFloatingType())
2808218893Sdim        CK = CK_FloatingComplexCast;
2809218893Sdim      else
2810218893Sdim        CK = CK_FloatingComplexToIntegralComplex;
2811218893Sdim    } else if (ToEl->isRealFloatingType()) {
2812218893Sdim      CK = CK_IntegralComplexToFloatingComplex;
2813218893Sdim    } else {
2814218893Sdim      CK = CK_IntegralComplexCast;
2815218893Sdim    }
2816224145Sdim    From = ImpCastExprToType(From, ToType, CK,
2817224145Sdim                             VK_RValue, /*BasePath=*/0, CCK).take();
2818198398Srdivacky    break;
2819218893Sdim  }
2820198398Srdivacky
2821193326Sed  case ICK_Floating_Integral:
2822210299Sed    if (ToType->isRealFloatingType())
2823224145Sdim      From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
2824224145Sdim                               VK_RValue, /*BasePath=*/0, CCK).take();
2825198398Srdivacky    else
2826224145Sdim      From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
2827224145Sdim                               VK_RValue, /*BasePath=*/0, CCK).take();
2828198398Srdivacky    break;
2829198398Srdivacky
2830193326Sed  case ICK_Compatible_Conversion:
2831224145Sdim      From = ImpCastExprToType(From, ToType, CK_NoOp,
2832224145Sdim                               VK_RValue, /*BasePath=*/0, CCK).take();
2833193326Sed    break;
2834193326Sed
2835224145Sdim  case ICK_Writeback_Conversion:
2836198092Srdivacky  case ICK_Pointer_Conversion: {
2837218893Sdim    if (SCS.IncompatibleObjC && Action != AA_Casting) {
2838193326Sed      // Diagnose incompatible Objective-C conversions
2839223017Sdim      if (Action == AA_Initializing || Action == AA_Assigning)
2840234353Sdim        Diag(From->getLocStart(),
2841221345Sdim             diag::ext_typecheck_convert_incompatible_pointer)
2842221345Sdim          << ToType << From->getType() << Action
2843226633Sdim          << From->getSourceRange() << 0;
2844221345Sdim      else
2845234353Sdim        Diag(From->getLocStart(),
2846221345Sdim             diag::ext_typecheck_convert_incompatible_pointer)
2847221345Sdim          << From->getType() << ToType << Action
2848226633Sdim          << From->getSourceRange() << 0;
2849224145Sdim
2850223017Sdim      if (From->getType()->isObjCObjectPointerType() &&
2851223017Sdim          ToType->isObjCObjectPointerType())
2852223017Sdim        EmitRelatedResultTypeNote(From);
2853224145Sdim    }
2854234353Sdim    else if (getLangOpts().ObjCAutoRefCount &&
2855224145Sdim             !CheckObjCARCUnavailableWeakConversion(ToType,
2856224145Sdim                                                    From->getType())) {
2857226633Sdim      if (Action == AA_Initializing)
2858234353Sdim        Diag(From->getLocStart(),
2859226633Sdim             diag::err_arc_weak_unavailable_assign);
2860226633Sdim      else
2861234353Sdim        Diag(From->getLocStart(),
2862226633Sdim             diag::err_arc_convesion_of_weak_unavailable)
2863226633Sdim          << (Action == AA_Casting) << From->getType() << ToType
2864226633Sdim          << From->getSourceRange();
2865226633Sdim    }
2866224145Sdim
2867218893Sdim    CastKind Kind = CK_Invalid;
2868212904Sdim    CXXCastPath BasePath;
2869218893Sdim    if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
2870221345Sdim      return ExprError();
2871226633Sdim
2872226633Sdim    // Make sure we extend blocks if necessary.
2873226633Sdim    // FIXME: doing this here is really ugly.
2874226633Sdim    if (Kind == CK_BlockPointerToObjCPointerCast) {
2875226633Sdim      ExprResult E = From;
2876226633Sdim      (void) PrepareCastToObjCObjectPointer(E);
2877226633Sdim      From = E.take();
2878226633Sdim    }
2879263508Sdim    if (getLangOpts().ObjCAutoRefCount)
2880263508Sdim      CheckObjCARCConversion(SourceRange(), ToType, From, CCK);
2881224145Sdim    From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
2882224145Sdim             .take();
2883193326Sed    break;
2884198092Srdivacky  }
2885218893Sdim
2886198092Srdivacky  case ICK_Pointer_Member: {
2887218893Sdim    CastKind Kind = CK_Invalid;
2888212904Sdim    CXXCastPath BasePath;
2889218893Sdim    if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
2890221345Sdim      return ExprError();
2891198092Srdivacky    if (CheckExceptionSpecCompatibility(From, ToType))
2892221345Sdim      return ExprError();
2893224145Sdim    From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
2894224145Sdim             .take();
2895193326Sed    break;
2896198092Srdivacky  }
2897218893Sdim
2898221345Sdim  case ICK_Boolean_Conversion:
2899226633Sdim    // Perform half-to-boolean conversion via float.
2900226633Sdim    if (From->getType()->isHalfType()) {
2901226633Sdim      From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).take();
2902226633Sdim      FromType = Context.FloatTy;
2903226633Sdim    }
2904226633Sdim
2905221345Sdim    From = ImpCastExprToType(From, Context.BoolTy,
2906224145Sdim                             ScalarTypeToBooleanCastKind(FromType),
2907224145Sdim                             VK_RValue, /*BasePath=*/0, CCK).take();
2908193326Sed    break;
2909193326Sed
2910208600Srdivacky  case ICK_Derived_To_Base: {
2911212904Sdim    CXXCastPath BasePath;
2912218893Sdim    if (CheckDerivedToBaseConversion(From->getType(),
2913199482Srdivacky                                     ToType.getNonReferenceType(),
2914199482Srdivacky                                     From->getLocStart(),
2915218893Sdim                                     From->getSourceRange(),
2916208600Srdivacky                                     &BasePath,
2917218893Sdim                                     CStyle))
2918221345Sdim      return ExprError();
2919208600Srdivacky
2920221345Sdim    From = ImpCastExprToType(From, ToType.getNonReferenceType(),
2921226633Sdim                      CK_DerivedToBase, From->getValueKind(),
2922224145Sdim                      &BasePath, CCK).take();
2923199482Srdivacky    break;
2924208600Srdivacky  }
2925208600Srdivacky
2926208600Srdivacky  case ICK_Vector_Conversion:
2927224145Sdim    From = ImpCastExprToType(From, ToType, CK_BitCast,
2928224145Sdim                             VK_RValue, /*BasePath=*/0, CCK).take();
2929208600Srdivacky    break;
2930208600Srdivacky
2931208600Srdivacky  case ICK_Vector_Splat:
2932224145Sdim    From = ImpCastExprToType(From, ToType, CK_VectorSplat,
2933224145Sdim                             VK_RValue, /*BasePath=*/0, CCK).take();
2934208600Srdivacky    break;
2935218893Sdim
2936208600Srdivacky  case ICK_Complex_Real:
2937218893Sdim    // Case 1.  x -> _Complex y
2938218893Sdim    if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
2939218893Sdim      QualType ElType = ToComplex->getElementType();
2940218893Sdim      bool isFloatingComplex = ElType->isRealFloatingType();
2941218893Sdim
2942218893Sdim      // x -> y
2943218893Sdim      if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
2944218893Sdim        // do nothing
2945218893Sdim      } else if (From->getType()->isRealFloatingType()) {
2946221345Sdim        From = ImpCastExprToType(From, ElType,
2947221345Sdim                isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).take();
2948218893Sdim      } else {
2949218893Sdim        assert(From->getType()->isIntegerType());
2950221345Sdim        From = ImpCastExprToType(From, ElType,
2951221345Sdim                isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).take();
2952218893Sdim      }
2953218893Sdim      // y -> _Complex y
2954221345Sdim      From = ImpCastExprToType(From, ToType,
2955218893Sdim                   isFloatingComplex ? CK_FloatingRealToComplex
2956221345Sdim                                     : CK_IntegralRealToComplex).take();
2957218893Sdim
2958218893Sdim    // Case 2.  _Complex x -> y
2959218893Sdim    } else {
2960218893Sdim      const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
2961218893Sdim      assert(FromComplex);
2962218893Sdim
2963218893Sdim      QualType ElType = FromComplex->getElementType();
2964218893Sdim      bool isFloatingComplex = ElType->isRealFloatingType();
2965218893Sdim
2966218893Sdim      // _Complex x -> x
2967221345Sdim      From = ImpCastExprToType(From, ElType,
2968218893Sdim                   isFloatingComplex ? CK_FloatingComplexToReal
2969224145Sdim                                     : CK_IntegralComplexToReal,
2970224145Sdim                               VK_RValue, /*BasePath=*/0, CCK).take();
2971218893Sdim
2972218893Sdim      // x -> y
2973218893Sdim      if (Context.hasSameUnqualifiedType(ElType, ToType)) {
2974218893Sdim        // do nothing
2975218893Sdim      } else if (ToType->isRealFloatingType()) {
2976221345Sdim        From = ImpCastExprToType(From, ToType,
2977224145Sdim                   isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating,
2978224145Sdim                                 VK_RValue, /*BasePath=*/0, CCK).take();
2979218893Sdim      } else {
2980218893Sdim        assert(ToType->isIntegerType());
2981221345Sdim        From = ImpCastExprToType(From, ToType,
2982224145Sdim                   isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
2983224145Sdim                                 VK_RValue, /*BasePath=*/0, CCK).take();
2984218893Sdim      }
2985218893Sdim    }
2986208600Srdivacky    break;
2987218893Sdim
2988218893Sdim  case ICK_Block_Pointer_Conversion: {
2989224145Sdim    From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast,
2990224145Sdim                             VK_RValue, /*BasePath=*/0, CCK).take();
2991224145Sdim    break;
2992224145Sdim  }
2993208600Srdivacky
2994221345Sdim  case ICK_TransparentUnionConversion: {
2995221345Sdim    ExprResult FromRes = Owned(From);
2996221345Sdim    Sema::AssignConvertType ConvTy =
2997221345Sdim      CheckTransparentUnionArgumentConstraints(ToType, FromRes);
2998221345Sdim    if (FromRes.isInvalid())
2999221345Sdim      return ExprError();
3000221345Sdim    From = FromRes.take();
3001221345Sdim    assert ((ConvTy == Sema::Compatible) &&
3002221345Sdim            "Improper transparent union conversion");
3003221345Sdim    (void)ConvTy;
3004221345Sdim    break;
3005221345Sdim  }
3006221345Sdim
3007249423Sdim  case ICK_Zero_Event_Conversion:
3008249423Sdim    From = ImpCastExprToType(From, ToType,
3009249423Sdim                             CK_ZeroToOCLEvent,
3010249423Sdim                             From->getValueKind()).take();
3011249423Sdim    break;
3012249423Sdim
3013208600Srdivacky  case ICK_Lvalue_To_Rvalue:
3014208600Srdivacky  case ICK_Array_To_Pointer:
3015208600Srdivacky  case ICK_Function_To_Pointer:
3016208600Srdivacky  case ICK_Qualification:
3017208600Srdivacky  case ICK_Num_Conversion_Kinds:
3018226633Sdim    llvm_unreachable("Improper second standard conversion");
3019193326Sed  }
3020193326Sed
3021193326Sed  switch (SCS.Third) {
3022193326Sed  case ICK_Identity:
3023193326Sed    // Nothing to do.
3024193326Sed    break;
3025193326Sed
3026212904Sdim  case ICK_Qualification: {
3027212904Sdim    // The qualification keeps the category of the inner expression, unless the
3028212904Sdim    // target type isn't a reference.
3029212904Sdim    ExprValueKind VK = ToType->isReferenceType() ?
3030226633Sdim                                  From->getValueKind() : VK_RValue;
3031221345Sdim    From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
3032224145Sdim                             CK_NoOp, VK, /*BasePath=*/0, CCK).take();
3033204643Srdivacky
3034221345Sdim    if (SCS.DeprecatedStringLiteralToCharPtr &&
3035234353Sdim        !getLangOpts().WritableStrings)
3036204643Srdivacky      Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
3037204643Srdivacky        << ToType.getNonReferenceType();
3038204643Srdivacky
3039193326Sed    break;
3040263508Sdim  }
3041212904Sdim
3042193326Sed  default:
3043226633Sdim    llvm_unreachable("Improper third standard conversion");
3044193326Sed  }
3045193326Sed
3046234353Sdim  // If this conversion sequence involved a scalar -> atomic conversion, perform
3047234353Sdim  // that conversion now.
3048263508Sdim  if (!ToAtomicType.isNull()) {
3049263508Sdim    assert(Context.hasSameType(
3050263508Sdim        ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()));
3051263508Sdim    From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic,
3052263508Sdim                             VK_RValue, 0, CCK).take();
3053263508Sdim  }
3054263508Sdim
3055221345Sdim  return Owned(From);
3056193326Sed}
3057193326Sed
3058218893SdimExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait UTT,
3059218893Sdim                                     SourceLocation KWLoc,
3060218893Sdim                                     ParsedType Ty,
3061218893Sdim                                     SourceLocation RParen) {
3062218893Sdim  TypeSourceInfo *TSInfo;
3063218893Sdim  QualType T = GetTypeFromParser(Ty, &TSInfo);
3064193326Sed
3065218893Sdim  if (!TSInfo)
3066218893Sdim    TSInfo = Context.getTrivialTypeSourceInfo(T);
3067218893Sdim  return BuildUnaryTypeTrait(UTT, KWLoc, TSInfo, RParen);
3068218893Sdim}
3069218893Sdim
3070221345Sdim/// \brief Check the completeness of a type in a unary type trait.
3071221345Sdim///
3072221345Sdim/// If the particular type trait requires a complete type, tries to complete
3073221345Sdim/// it. If completing the type fails, a diagnostic is emitted and false
3074221345Sdim/// returned. If completing the type succeeds or no completion was required,
3075221345Sdim/// returns true.
3076221345Sdimstatic bool CheckUnaryTypeTraitTypeCompleteness(Sema &S,
3077221345Sdim                                                UnaryTypeTrait UTT,
3078221345Sdim                                                SourceLocation Loc,
3079221345Sdim                                                QualType ArgTy) {
3080221345Sdim  // C++0x [meta.unary.prop]p3:
3081221345Sdim  //   For all of the class templates X declared in this Clause, instantiating
3082221345Sdim  //   that template with a template argument that is a class template
3083221345Sdim  //   specialization may result in the implicit instantiation of the template
3084221345Sdim  //   argument if and only if the semantics of X require that the argument
3085221345Sdim  //   must be a complete type.
3086221345Sdim  // We apply this rule to all the type trait expressions used to implement
3087221345Sdim  // these class templates. We also try to follow any GCC documented behavior
3088221345Sdim  // in these expressions to ensure portability of standard libraries.
3089221345Sdim  switch (UTT) {
3090221345Sdim    // is_complete_type somewhat obviously cannot require a complete type.
3091221345Sdim  case UTT_IsCompleteType:
3092221345Sdim    // Fall-through
3093221345Sdim
3094221345Sdim    // These traits are modeled on the type predicates in C++0x
3095221345Sdim    // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
3096221345Sdim    // requiring a complete type, as whether or not they return true cannot be
3097221345Sdim    // impacted by the completeness of the type.
3098221345Sdim  case UTT_IsVoid:
3099221345Sdim  case UTT_IsIntegral:
3100221345Sdim  case UTT_IsFloatingPoint:
3101221345Sdim  case UTT_IsArray:
3102221345Sdim  case UTT_IsPointer:
3103221345Sdim  case UTT_IsLvalueReference:
3104221345Sdim  case UTT_IsRvalueReference:
3105221345Sdim  case UTT_IsMemberFunctionPointer:
3106221345Sdim  case UTT_IsMemberObjectPointer:
3107221345Sdim  case UTT_IsEnum:
3108221345Sdim  case UTT_IsUnion:
3109221345Sdim  case UTT_IsClass:
3110221345Sdim  case UTT_IsFunction:
3111221345Sdim  case UTT_IsReference:
3112221345Sdim  case UTT_IsArithmetic:
3113221345Sdim  case UTT_IsFundamental:
3114221345Sdim  case UTT_IsObject:
3115221345Sdim  case UTT_IsScalar:
3116221345Sdim  case UTT_IsCompound:
3117221345Sdim  case UTT_IsMemberPointer:
3118221345Sdim    // Fall-through
3119221345Sdim
3120221345Sdim    // These traits are modeled on type predicates in C++0x [meta.unary.prop]
3121221345Sdim    // which requires some of its traits to have the complete type. However,
3122221345Sdim    // the completeness of the type cannot impact these traits' semantics, and
3123221345Sdim    // so they don't require it. This matches the comments on these traits in
3124221345Sdim    // Table 49.
3125221345Sdim  case UTT_IsConst:
3126221345Sdim  case UTT_IsVolatile:
3127221345Sdim  case UTT_IsSigned:
3128221345Sdim  case UTT_IsUnsigned:
3129221345Sdim    return true;
3130221345Sdim
3131221345Sdim    // C++0x [meta.unary.prop] Table 49 requires the following traits to be
3132221345Sdim    // applied to a complete type.
3133221345Sdim  case UTT_IsTrivial:
3134223017Sdim  case UTT_IsTriviallyCopyable:
3135221345Sdim  case UTT_IsStandardLayout:
3136221345Sdim  case UTT_IsPOD:
3137221345Sdim  case UTT_IsLiteral:
3138221345Sdim  case UTT_IsEmpty:
3139221345Sdim  case UTT_IsPolymorphic:
3140221345Sdim  case UTT_IsAbstract:
3141243830Sdim  case UTT_IsInterfaceClass:
3142221345Sdim    // Fall-through
3143221345Sdim
3144234353Sdim  // These traits require a complete type.
3145234353Sdim  case UTT_IsFinal:
3146263508Sdim  case UTT_IsSealed:
3147234353Sdim
3148221345Sdim    // These trait expressions are designed to help implement predicates in
3149221345Sdim    // [meta.unary.prop] despite not being named the same. They are specified
3150221345Sdim    // by both GCC and the Embarcadero C++ compiler, and require the complete
3151221345Sdim    // type due to the overarching C++0x type predicates being implemented
3152221345Sdim    // requiring the complete type.
3153221345Sdim  case UTT_HasNothrowAssign:
3154249423Sdim  case UTT_HasNothrowMoveAssign:
3155221345Sdim  case UTT_HasNothrowConstructor:
3156221345Sdim  case UTT_HasNothrowCopy:
3157221345Sdim  case UTT_HasTrivialAssign:
3158249423Sdim  case UTT_HasTrivialMoveAssign:
3159223017Sdim  case UTT_HasTrivialDefaultConstructor:
3160249423Sdim  case UTT_HasTrivialMoveConstructor:
3161221345Sdim  case UTT_HasTrivialCopy:
3162221345Sdim  case UTT_HasTrivialDestructor:
3163221345Sdim  case UTT_HasVirtualDestructor:
3164221345Sdim    // Arrays of unknown bound are expressly allowed.
3165221345Sdim    QualType ElTy = ArgTy;
3166221345Sdim    if (ArgTy->isIncompleteArrayType())
3167221345Sdim      ElTy = S.Context.getAsArrayType(ArgTy)->getElementType();
3168221345Sdim
3169221345Sdim    // The void type is expressly allowed.
3170221345Sdim    if (ElTy->isVoidType())
3171221345Sdim      return true;
3172221345Sdim
3173221345Sdim    return !S.RequireCompleteType(
3174221345Sdim      Loc, ElTy, diag::err_incomplete_type_used_in_type_trait_expr);
3175221345Sdim  }
3176221345Sdim  llvm_unreachable("Type trait not handled by switch");
3177221345Sdim}
3178221345Sdim
3179249423Sdimstatic bool HasNoThrowOperator(const RecordType *RT, OverloadedOperatorKind Op,
3180249423Sdim                               Sema &Self, SourceLocation KeyLoc, ASTContext &C,
3181249423Sdim                               bool (CXXRecordDecl::*HasTrivial)() const,
3182249423Sdim                               bool (CXXRecordDecl::*HasNonTrivial)() const,
3183249423Sdim                               bool (CXXMethodDecl::*IsDesiredOp)() const)
3184249423Sdim{
3185249423Sdim  CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3186249423Sdim  if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)())
3187249423Sdim    return true;
3188249423Sdim
3189249423Sdim  DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op);
3190249423Sdim  DeclarationNameInfo NameInfo(Name, KeyLoc);
3191249423Sdim  LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName);
3192249423Sdim  if (Self.LookupQualifiedName(Res, RD)) {
3193249423Sdim    bool FoundOperator = false;
3194249423Sdim    Res.suppressDiagnostics();
3195249423Sdim    for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
3196249423Sdim         Op != OpEnd; ++Op) {
3197249423Sdim      if (isa<FunctionTemplateDecl>(*Op))
3198249423Sdim        continue;
3199249423Sdim
3200249423Sdim      CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
3201249423Sdim      if((Operator->*IsDesiredOp)()) {
3202249423Sdim        FoundOperator = true;
3203249423Sdim        const FunctionProtoType *CPT =
3204249423Sdim          Operator->getType()->getAs<FunctionProtoType>();
3205249423Sdim        CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
3206249423Sdim        if (!CPT || !CPT->isNothrow(Self.Context))
3207249423Sdim          return false;
3208249423Sdim      }
3209249423Sdim    }
3210249423Sdim    return FoundOperator;
3211249423Sdim  }
3212249423Sdim  return false;
3213249423Sdim}
3214249423Sdim
3215221345Sdimstatic bool EvaluateUnaryTypeTrait(Sema &Self, UnaryTypeTrait UTT,
3216221345Sdim                                   SourceLocation KeyLoc, QualType T) {
3217221345Sdim  assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
3218221345Sdim
3219218893Sdim  ASTContext &C = Self.Context;
3220218893Sdim  switch(UTT) {
3221221345Sdim    // Type trait expressions corresponding to the primary type category
3222221345Sdim    // predicates in C++0x [meta.unary.cat].
3223221345Sdim  case UTT_IsVoid:
3224221345Sdim    return T->isVoidType();
3225221345Sdim  case UTT_IsIntegral:
3226221345Sdim    return T->isIntegralType(C);
3227221345Sdim  case UTT_IsFloatingPoint:
3228221345Sdim    return T->isFloatingType();
3229221345Sdim  case UTT_IsArray:
3230221345Sdim    return T->isArrayType();
3231221345Sdim  case UTT_IsPointer:
3232221345Sdim    return T->isPointerType();
3233221345Sdim  case UTT_IsLvalueReference:
3234221345Sdim    return T->isLValueReferenceType();
3235221345Sdim  case UTT_IsRvalueReference:
3236221345Sdim    return T->isRValueReferenceType();
3237221345Sdim  case UTT_IsMemberFunctionPointer:
3238221345Sdim    return T->isMemberFunctionPointerType();
3239221345Sdim  case UTT_IsMemberObjectPointer:
3240221345Sdim    return T->isMemberDataPointerType();
3241221345Sdim  case UTT_IsEnum:
3242221345Sdim    return T->isEnumeralType();
3243218893Sdim  case UTT_IsUnion:
3244221345Sdim    return T->isUnionType();
3245221345Sdim  case UTT_IsClass:
3246243830Sdim    return T->isClassType() || T->isStructureType() || T->isInterfaceType();
3247221345Sdim  case UTT_IsFunction:
3248221345Sdim    return T->isFunctionType();
3249221345Sdim
3250221345Sdim    // Type trait expressions which correspond to the convenient composition
3251221345Sdim    // predicates in C++0x [meta.unary.comp].
3252221345Sdim  case UTT_IsReference:
3253221345Sdim    return T->isReferenceType();
3254221345Sdim  case UTT_IsArithmetic:
3255221345Sdim    return T->isArithmeticType() && !T->isEnumeralType();
3256221345Sdim  case UTT_IsFundamental:
3257221345Sdim    return T->isFundamentalType();
3258221345Sdim  case UTT_IsObject:
3259221345Sdim    return T->isObjectType();
3260221345Sdim  case UTT_IsScalar:
3261224145Sdim    // Note: semantic analysis depends on Objective-C lifetime types to be
3262224145Sdim    // considered scalar types. However, such types do not actually behave
3263224145Sdim    // like scalar types at run time (since they may require retain/release
3264224145Sdim    // operations), so we report them as non-scalar.
3265224145Sdim    if (T->isObjCLifetimeType()) {
3266224145Sdim      switch (T.getObjCLifetime()) {
3267224145Sdim      case Qualifiers::OCL_None:
3268224145Sdim      case Qualifiers::OCL_ExplicitNone:
3269224145Sdim        return true;
3270224145Sdim
3271224145Sdim      case Qualifiers::OCL_Strong:
3272224145Sdim      case Qualifiers::OCL_Weak:
3273224145Sdim      case Qualifiers::OCL_Autoreleasing:
3274224145Sdim        return false;
3275224145Sdim      }
3276224145Sdim    }
3277224145Sdim
3278221345Sdim    return T->isScalarType();
3279221345Sdim  case UTT_IsCompound:
3280221345Sdim    return T->isCompoundType();
3281221345Sdim  case UTT_IsMemberPointer:
3282221345Sdim    return T->isMemberPointerType();
3283221345Sdim
3284221345Sdim    // Type trait expressions which correspond to the type property predicates
3285221345Sdim    // in C++0x [meta.unary.prop].
3286221345Sdim  case UTT_IsConst:
3287221345Sdim    return T.isConstQualified();
3288221345Sdim  case UTT_IsVolatile:
3289221345Sdim    return T.isVolatileQualified();
3290221345Sdim  case UTT_IsTrivial:
3291224145Sdim    return T.isTrivialType(Self.Context);
3292223017Sdim  case UTT_IsTriviallyCopyable:
3293224145Sdim    return T.isTriviallyCopyableType(Self.Context);
3294221345Sdim  case UTT_IsStandardLayout:
3295221345Sdim    return T->isStandardLayoutType();
3296221345Sdim  case UTT_IsPOD:
3297224145Sdim    return T.isPODType(Self.Context);
3298221345Sdim  case UTT_IsLiteral:
3299251662Sdim    return T->isLiteralType(Self.Context);
3300221345Sdim  case UTT_IsEmpty:
3301221345Sdim    if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3302221345Sdim      return !RD->isUnion() && RD->isEmpty();
3303218893Sdim    return false;
3304218893Sdim  case UTT_IsPolymorphic:
3305221345Sdim    if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3306221345Sdim      return RD->isPolymorphic();
3307218893Sdim    return false;
3308218893Sdim  case UTT_IsAbstract:
3309221345Sdim    if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3310221345Sdim      return RD->isAbstract();
3311218893Sdim    return false;
3312243830Sdim  case UTT_IsInterfaceClass:
3313243830Sdim    if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3314243830Sdim      return RD->isInterface();
3315243830Sdim    return false;
3316234353Sdim  case UTT_IsFinal:
3317234353Sdim    if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3318234353Sdim      return RD->hasAttr<FinalAttr>();
3319234353Sdim    return false;
3320263508Sdim  case UTT_IsSealed:
3321263508Sdim    if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3322263508Sdim      if (FinalAttr *FA = RD->getAttr<FinalAttr>())
3323263508Sdim        return FA->isSpelledAsSealed();
3324263508Sdim    return false;
3325221345Sdim  case UTT_IsSigned:
3326221345Sdim    return T->isSignedIntegerType();
3327221345Sdim  case UTT_IsUnsigned:
3328221345Sdim    return T->isUnsignedIntegerType();
3329221345Sdim
3330221345Sdim    // Type trait expressions which query classes regarding their construction,
3331221345Sdim    // destruction, and copying. Rather than being based directly on the
3332221345Sdim    // related type predicates in the standard, they are specified by both
3333221345Sdim    // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
3334221345Sdim    // specifications.
3335221345Sdim    //
3336221345Sdim    //   1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
3337221345Sdim    //   2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
3338249423Sdim    //
3339249423Sdim    // Note that these builtins do not behave as documented in g++: if a class
3340249423Sdim    // has both a trivial and a non-trivial special member of a particular kind,
3341249423Sdim    // they return false! For now, we emulate this behavior.
3342249423Sdim    // FIXME: This appears to be a g++ bug: more complex cases reveal that it
3343249423Sdim    // does not correctly compute triviality in the presence of multiple special
3344249423Sdim    // members of the same kind. Revisit this once the g++ bug is fixed.
3345223017Sdim  case UTT_HasTrivialDefaultConstructor:
3346218893Sdim    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3347218893Sdim    //   If __is_pod (type) is true then the trait is true, else if type is
3348218893Sdim    //   a cv class or union type (or array thereof) with a trivial default
3349218893Sdim    //   constructor ([class.ctor]) then the trait is true, else it is false.
3350224145Sdim    if (T.isPODType(Self.Context))
3351218893Sdim      return true;
3352249423Sdim    if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
3353249423Sdim      return RD->hasTrivialDefaultConstructor() &&
3354249423Sdim             !RD->hasNonTrivialDefaultConstructor();
3355218893Sdim    return false;
3356249423Sdim  case UTT_HasTrivialMoveConstructor:
3357249423Sdim    //  This trait is implemented by MSVC 2012 and needed to parse the
3358249423Sdim    //  standard library headers. Specifically this is used as the logic
3359249423Sdim    //  behind std::is_trivially_move_constructible (20.9.4.3).
3360249423Sdim    if (T.isPODType(Self.Context))
3361249423Sdim      return true;
3362249423Sdim    if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
3363249423Sdim      return RD->hasTrivialMoveConstructor() && !RD->hasNonTrivialMoveConstructor();
3364249423Sdim    return false;
3365218893Sdim  case UTT_HasTrivialCopy:
3366218893Sdim    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3367218893Sdim    //   If __is_pod (type) is true or type is a reference type then
3368218893Sdim    //   the trait is true, else if type is a cv class or union type
3369218893Sdim    //   with a trivial copy constructor ([class.copy]) then the trait
3370218893Sdim    //   is true, else it is false.
3371224145Sdim    if (T.isPODType(Self.Context) || T->isReferenceType())
3372218893Sdim      return true;
3373249423Sdim    if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3374249423Sdim      return RD->hasTrivialCopyConstructor() &&
3375249423Sdim             !RD->hasNonTrivialCopyConstructor();
3376218893Sdim    return false;
3377249423Sdim  case UTT_HasTrivialMoveAssign:
3378249423Sdim    //  This trait is implemented by MSVC 2012 and needed to parse the
3379249423Sdim    //  standard library headers. Specifically it is used as the logic
3380249423Sdim    //  behind std::is_trivially_move_assignable (20.9.4.3)
3381249423Sdim    if (T.isPODType(Self.Context))
3382249423Sdim      return true;
3383249423Sdim    if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
3384249423Sdim      return RD->hasTrivialMoveAssignment() && !RD->hasNonTrivialMoveAssignment();
3385249423Sdim    return false;
3386218893Sdim  case UTT_HasTrivialAssign:
3387218893Sdim    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3388218893Sdim    //   If type is const qualified or is a reference type then the
3389218893Sdim    //   trait is false. Otherwise if __is_pod (type) is true then the
3390218893Sdim    //   trait is true, else if type is a cv class or union type with
3391218893Sdim    //   a trivial copy assignment ([class.copy]) then the trait is
3392218893Sdim    //   true, else it is false.
3393218893Sdim    // Note: the const and reference restrictions are interesting,
3394218893Sdim    // given that const and reference members don't prevent a class
3395218893Sdim    // from having a trivial copy assignment operator (but do cause
3396218893Sdim    // errors if the copy assignment operator is actually used, q.v.
3397218893Sdim    // [class.copy]p12).
3398218893Sdim
3399249423Sdim    if (T.isConstQualified())
3400218893Sdim      return false;
3401224145Sdim    if (T.isPODType(Self.Context))
3402218893Sdim      return true;
3403249423Sdim    if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3404249423Sdim      return RD->hasTrivialCopyAssignment() &&
3405249423Sdim             !RD->hasNonTrivialCopyAssignment();
3406218893Sdim    return false;
3407218893Sdim  case UTT_HasTrivialDestructor:
3408218893Sdim    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3409218893Sdim    //   If __is_pod (type) is true or type is a reference type
3410218893Sdim    //   then the trait is true, else if type is a cv class or union
3411218893Sdim    //   type (or array thereof) with a trivial destructor
3412218893Sdim    //   ([class.dtor]) then the trait is true, else it is
3413218893Sdim    //   false.
3414224145Sdim    if (T.isPODType(Self.Context) || T->isReferenceType())
3415218893Sdim      return true;
3416224145Sdim
3417224145Sdim    // Objective-C++ ARC: autorelease types don't require destruction.
3418224145Sdim    if (T->isObjCLifetimeType() &&
3419224145Sdim        T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
3420224145Sdim      return true;
3421224145Sdim
3422249423Sdim    if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
3423249423Sdim      return RD->hasTrivialDestructor();
3424218893Sdim    return false;
3425218893Sdim  // TODO: Propagate nothrowness for implicitly declared special members.
3426218893Sdim  case UTT_HasNothrowAssign:
3427218893Sdim    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3428218893Sdim    //   If type is const qualified or is a reference type then the
3429218893Sdim    //   trait is false. Otherwise if __has_trivial_assign (type)
3430218893Sdim    //   is true then the trait is true, else if type is a cv class
3431218893Sdim    //   or union type with copy assignment operators that are known
3432218893Sdim    //   not to throw an exception then the trait is true, else it is
3433218893Sdim    //   false.
3434218893Sdim    if (C.getBaseElementType(T).isConstQualified())
3435218893Sdim      return false;
3436218893Sdim    if (T->isReferenceType())
3437218893Sdim      return false;
3438224145Sdim    if (T.isPODType(Self.Context) || T->isObjCLifetimeType())
3439249423Sdim      return true;
3440218893Sdim
3441249423Sdim    if (const RecordType *RT = T->getAs<RecordType>())
3442249423Sdim      return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
3443249423Sdim                                &CXXRecordDecl::hasTrivialCopyAssignment,
3444249423Sdim                                &CXXRecordDecl::hasNonTrivialCopyAssignment,
3445249423Sdim                                &CXXMethodDecl::isCopyAssignmentOperator);
3446218893Sdim    return false;
3447249423Sdim  case UTT_HasNothrowMoveAssign:
3448249423Sdim    //  This trait is implemented by MSVC 2012 and needed to parse the
3449249423Sdim    //  standard library headers. Specifically this is used as the logic
3450249423Sdim    //  behind std::is_nothrow_move_assignable (20.9.4.3).
3451249423Sdim    if (T.isPODType(Self.Context))
3452249423Sdim      return true;
3453249423Sdim
3454249423Sdim    if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>())
3455249423Sdim      return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
3456249423Sdim                                &CXXRecordDecl::hasTrivialMoveAssignment,
3457249423Sdim                                &CXXRecordDecl::hasNonTrivialMoveAssignment,
3458249423Sdim                                &CXXMethodDecl::isMoveAssignmentOperator);
3459249423Sdim    return false;
3460218893Sdim  case UTT_HasNothrowCopy:
3461218893Sdim    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3462218893Sdim    //   If __has_trivial_copy (type) is true then the trait is true, else
3463218893Sdim    //   if type is a cv class or union type with copy constructors that are
3464218893Sdim    //   known not to throw an exception then the trait is true, else it is
3465218893Sdim    //   false.
3466224145Sdim    if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
3467218893Sdim      return true;
3468249423Sdim    if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
3469249423Sdim      if (RD->hasTrivialCopyConstructor() &&
3470249423Sdim          !RD->hasNonTrivialCopyConstructor())
3471218893Sdim        return true;
3472218893Sdim
3473218893Sdim      bool FoundConstructor = false;
3474218893Sdim      unsigned FoundTQs;
3475249423Sdim      DeclContext::lookup_const_result R = Self.LookupConstructors(RD);
3476249423Sdim      for (DeclContext::lookup_const_iterator Con = R.begin(),
3477249423Sdim           ConEnd = R.end(); Con != ConEnd; ++Con) {
3478218893Sdim        // A template constructor is never a copy constructor.
3479218893Sdim        // FIXME: However, it may actually be selected at the actual overload
3480218893Sdim        // resolution point.
3481218893Sdim        if (isa<FunctionTemplateDecl>(*Con))
3482218893Sdim          continue;
3483218893Sdim        CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
3484218893Sdim        if (Constructor->isCopyConstructor(FoundTQs)) {
3485218893Sdim          FoundConstructor = true;
3486218893Sdim          const FunctionProtoType *CPT
3487218893Sdim              = Constructor->getType()->getAs<FunctionProtoType>();
3488234982Sdim          CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
3489234982Sdim          if (!CPT)
3490234982Sdim            return false;
3491221345Sdim          // FIXME: check whether evaluating default arguments can throw.
3492218893Sdim          // For now, we'll be conservative and assume that they can throw.
3493223017Sdim          if (!CPT->isNothrow(Self.Context) || CPT->getNumArgs() > 1)
3494223017Sdim            return false;
3495218893Sdim        }
3496218893Sdim      }
3497218893Sdim
3498223017Sdim      return FoundConstructor;
3499218893Sdim    }
3500218893Sdim    return false;
3501218893Sdim  case UTT_HasNothrowConstructor:
3502218893Sdim    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3503218893Sdim    //   If __has_trivial_constructor (type) is true then the trait is
3504218893Sdim    //   true, else if type is a cv class or union type (or array
3505218893Sdim    //   thereof) with a default constructor that is known not to
3506218893Sdim    //   throw an exception then the trait is true, else it is false.
3507224145Sdim    if (T.isPODType(C) || T->isObjCLifetimeType())
3508218893Sdim      return true;
3509249423Sdim    if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
3510249423Sdim      if (RD->hasTrivialDefaultConstructor() &&
3511249423Sdim          !RD->hasNonTrivialDefaultConstructor())
3512218893Sdim        return true;
3513218893Sdim
3514249423Sdim      DeclContext::lookup_const_result R = Self.LookupConstructors(RD);
3515249423Sdim      for (DeclContext::lookup_const_iterator Con = R.begin(),
3516249423Sdim           ConEnd = R.end(); Con != ConEnd; ++Con) {
3517218893Sdim        // FIXME: In C++0x, a constructor template can be a default constructor.
3518218893Sdim        if (isa<FunctionTemplateDecl>(*Con))
3519218893Sdim          continue;
3520218893Sdim        CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
3521218893Sdim        if (Constructor->isDefaultConstructor()) {
3522218893Sdim          const FunctionProtoType *CPT
3523218893Sdim              = Constructor->getType()->getAs<FunctionProtoType>();
3524234982Sdim          CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
3525234982Sdim          if (!CPT)
3526234982Sdim            return false;
3527218893Sdim          // TODO: check whether evaluating default arguments can throw.
3528218893Sdim          // For now, we'll be conservative and assume that they can throw.
3529221345Sdim          return CPT->isNothrow(Self.Context) && CPT->getNumArgs() == 0;
3530218893Sdim        }
3531218893Sdim      }
3532218893Sdim    }
3533218893Sdim    return false;
3534218893Sdim  case UTT_HasVirtualDestructor:
3535218893Sdim    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3536218893Sdim    //   If type is a class type with a virtual destructor ([class.dtor])
3537218893Sdim    //   then the trait is true, else it is false.
3538249423Sdim    if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3539218893Sdim      if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
3540218893Sdim        return Destructor->isVirtual();
3541218893Sdim    return false;
3542221345Sdim
3543221345Sdim    // These type trait expressions are modeled on the specifications for the
3544221345Sdim    // Embarcadero C++0x type trait functions:
3545221345Sdim    //   http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
3546221345Sdim  case UTT_IsCompleteType:
3547221345Sdim    // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
3548221345Sdim    //   Returns True if and only if T is a complete type at the point of the
3549221345Sdim    //   function call.
3550221345Sdim    return !T->isIncompleteType();
3551218893Sdim  }
3552221345Sdim  llvm_unreachable("Type trait not covered by switch");
3553218893Sdim}
3554218893Sdim
3555218893SdimExprResult Sema::BuildUnaryTypeTrait(UnaryTypeTrait UTT,
3556218893Sdim                                     SourceLocation KWLoc,
3557218893Sdim                                     TypeSourceInfo *TSInfo,
3558218893Sdim                                     SourceLocation RParen) {
3559218893Sdim  QualType T = TSInfo->getType();
3560221345Sdim  if (!CheckUnaryTypeTraitTypeCompleteness(*this, UTT, KWLoc, T))
3561221345Sdim    return ExprError();
3562218893Sdim
3563218893Sdim  bool Value = false;
3564218893Sdim  if (!T->isDependentType())
3565221345Sdim    Value = EvaluateUnaryTypeTrait(*this, UTT, KWLoc, T);
3566218893Sdim
3567218893Sdim  return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, UTT, TSInfo, Value,
3568198092Srdivacky                                                RParen, Context.BoolTy));
3569193326Sed}
3570193326Sed
3571218893SdimExprResult Sema::ActOnBinaryTypeTrait(BinaryTypeTrait BTT,
3572218893Sdim                                      SourceLocation KWLoc,
3573218893Sdim                                      ParsedType LhsTy,
3574218893Sdim                                      ParsedType RhsTy,
3575218893Sdim                                      SourceLocation RParen) {
3576218893Sdim  TypeSourceInfo *LhsTSInfo;
3577218893Sdim  QualType LhsT = GetTypeFromParser(LhsTy, &LhsTSInfo);
3578218893Sdim  if (!LhsTSInfo)
3579218893Sdim    LhsTSInfo = Context.getTrivialTypeSourceInfo(LhsT);
3580218893Sdim
3581218893Sdim  TypeSourceInfo *RhsTSInfo;
3582218893Sdim  QualType RhsT = GetTypeFromParser(RhsTy, &RhsTSInfo);
3583218893Sdim  if (!RhsTSInfo)
3584218893Sdim    RhsTSInfo = Context.getTrivialTypeSourceInfo(RhsT);
3585218893Sdim
3586218893Sdim  return BuildBinaryTypeTrait(BTT, KWLoc, LhsTSInfo, RhsTSInfo, RParen);
3587218893Sdim}
3588218893Sdim
3589239462Sdim/// \brief Determine whether T has a non-trivial Objective-C lifetime in
3590239462Sdim/// ARC mode.
3591239462Sdimstatic bool hasNontrivialObjCLifetime(QualType T) {
3592239462Sdim  switch (T.getObjCLifetime()) {
3593239462Sdim  case Qualifiers::OCL_ExplicitNone:
3594239462Sdim    return false;
3595239462Sdim
3596239462Sdim  case Qualifiers::OCL_Strong:
3597239462Sdim  case Qualifiers::OCL_Weak:
3598239462Sdim  case Qualifiers::OCL_Autoreleasing:
3599239462Sdim    return true;
3600239462Sdim
3601239462Sdim  case Qualifiers::OCL_None:
3602239462Sdim    return T->isObjCLifetimeType();
3603239462Sdim  }
3604239462Sdim
3605239462Sdim  llvm_unreachable("Unknown ObjC lifetime qualifier");
3606239462Sdim}
3607239462Sdim
3608234353Sdimstatic bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc,
3609234353Sdim                              ArrayRef<TypeSourceInfo *> Args,
3610234353Sdim                              SourceLocation RParenLoc) {
3611234353Sdim  switch (Kind) {
3612234353Sdim  case clang::TT_IsTriviallyConstructible: {
3613234353Sdim    // C++11 [meta.unary.prop]:
3614234353Sdim    //   is_trivially_constructible is defined as:
3615234353Sdim    //
3616234353Sdim    //     is_constructible<T, Args...>::value is true and the variable
3617263508Sdim    //     definition for is_constructible, as defined below, is known to call
3618263508Sdim    //     no operation that is not trivial.
3619234353Sdim    //
3620234353Sdim    //   The predicate condition for a template specialization
3621234353Sdim    //   is_constructible<T, Args...> shall be satisfied if and only if the
3622234353Sdim    //   following variable definition would be well-formed for some invented
3623234353Sdim    //   variable t:
3624234353Sdim    //
3625234353Sdim    //     T t(create<Args>()...);
3626234353Sdim    if (Args.empty()) {
3627234353Sdim      S.Diag(KWLoc, diag::err_type_trait_arity)
3628234353Sdim        << 1 << 1 << 1 << (int)Args.size();
3629234353Sdim      return false;
3630234353Sdim    }
3631263508Sdim
3632263508Sdim    // Precondition: T and all types in the parameter pack Args shall be
3633263508Sdim    // complete types, (possibly cv-qualified) void, or arrays of
3634263508Sdim    // unknown bound.
3635234353Sdim    for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3636263508Sdim      QualType ArgTy = Args[I]->getType();
3637263508Sdim      if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType())
3638234353Sdim        continue;
3639263508Sdim
3640263508Sdim      if (S.RequireCompleteType(KWLoc, ArgTy,
3641234353Sdim          diag::err_incomplete_type_used_in_type_trait_expr))
3642234353Sdim        return false;
3643234353Sdim    }
3644263508Sdim
3645263508Sdim    // Make sure the first argument is a complete type.
3646263508Sdim    if (Args[0]->getType()->isIncompleteType())
3647234353Sdim      return false;
3648263508Sdim
3649249423Sdim    SmallVector<OpaqueValueExpr, 2> OpaqueArgExprs;
3650249423Sdim    SmallVector<Expr *, 2> ArgExprs;
3651234353Sdim    ArgExprs.reserve(Args.size() - 1);
3652234353Sdim    for (unsigned I = 1, N = Args.size(); I != N; ++I) {
3653234353Sdim      QualType T = Args[I]->getType();
3654234353Sdim      if (T->isObjectType() || T->isFunctionType())
3655234353Sdim        T = S.Context.getRValueReferenceType(T);
3656234353Sdim      OpaqueArgExprs.push_back(
3657234353Sdim        OpaqueValueExpr(Args[I]->getTypeLoc().getLocStart(),
3658234353Sdim                        T.getNonLValueExprType(S.Context),
3659234353Sdim                        Expr::getValueKindForType(T)));
3660234353Sdim      ArgExprs.push_back(&OpaqueArgExprs.back());
3661234353Sdim    }
3662234353Sdim
3663234353Sdim    // Perform the initialization in an unevaluated context within a SFINAE
3664234353Sdim    // trap at translation unit scope.
3665234353Sdim    EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
3666234353Sdim    Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
3667234353Sdim    Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
3668234353Sdim    InitializedEntity To(InitializedEntity::InitializeTemporary(Args[0]));
3669234353Sdim    InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc,
3670234353Sdim                                                                 RParenLoc));
3671251662Sdim    InitializationSequence Init(S, To, InitKind, ArgExprs);
3672234353Sdim    if (Init.Failed())
3673234353Sdim      return false;
3674234353Sdim
3675243830Sdim    ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs);
3676234353Sdim    if (Result.isInvalid() || SFINAE.hasErrorOccurred())
3677234353Sdim      return false;
3678239462Sdim
3679239462Sdim    // Under Objective-C ARC, if the destination has non-trivial Objective-C
3680239462Sdim    // lifetime, this is a non-trivial construction.
3681239462Sdim    if (S.getLangOpts().ObjCAutoRefCount &&
3682239462Sdim        hasNontrivialObjCLifetime(Args[0]->getType().getNonReferenceType()))
3683239462Sdim      return false;
3684239462Sdim
3685239462Sdim    // The initialization succeeded; now make sure there are no non-trivial
3686234353Sdim    // calls.
3687234353Sdim    return !Result.get()->hasNonTrivialCall(S.Context);
3688234353Sdim  }
3689234353Sdim  }
3690234353Sdim
3691234353Sdim  return false;
3692234353Sdim}
3693234353Sdim
3694234353SdimExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
3695234353Sdim                                ArrayRef<TypeSourceInfo *> Args,
3696234353Sdim                                SourceLocation RParenLoc) {
3697234353Sdim  bool Dependent = false;
3698234353Sdim  for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3699234353Sdim    if (Args[I]->getType()->isDependentType()) {
3700234353Sdim      Dependent = true;
3701234353Sdim      break;
3702234353Sdim    }
3703234353Sdim  }
3704234353Sdim
3705234353Sdim  bool Value = false;
3706234353Sdim  if (!Dependent)
3707234353Sdim    Value = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc);
3708234353Sdim
3709234353Sdim  return TypeTraitExpr::Create(Context, Context.BoolTy, KWLoc, Kind,
3710234353Sdim                               Args, RParenLoc, Value);
3711234353Sdim}
3712234353Sdim
3713234353SdimExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
3714234353Sdim                                ArrayRef<ParsedType> Args,
3715234353Sdim                                SourceLocation RParenLoc) {
3716249423Sdim  SmallVector<TypeSourceInfo *, 4> ConvertedArgs;
3717234353Sdim  ConvertedArgs.reserve(Args.size());
3718234353Sdim
3719234353Sdim  for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3720234353Sdim    TypeSourceInfo *TInfo;
3721234353Sdim    QualType T = GetTypeFromParser(Args[I], &TInfo);
3722234353Sdim    if (!TInfo)
3723234353Sdim      TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);
3724234353Sdim
3725234353Sdim    ConvertedArgs.push_back(TInfo);
3726234353Sdim  }
3727234353Sdim
3728234353Sdim  return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
3729234353Sdim}
3730234353Sdim
3731218893Sdimstatic bool EvaluateBinaryTypeTrait(Sema &Self, BinaryTypeTrait BTT,
3732218893Sdim                                    QualType LhsT, QualType RhsT,
3733218893Sdim                                    SourceLocation KeyLoc) {
3734221345Sdim  assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
3735221345Sdim         "Cannot evaluate traits of dependent types");
3736218893Sdim
3737218893Sdim  switch(BTT) {
3738218893Sdim  case BTT_IsBaseOf: {
3739218893Sdim    // C++0x [meta.rel]p2
3740218893Sdim    // Base is a base class of Derived without regard to cv-qualifiers or
3741218893Sdim    // Base and Derived are not unions and name the same class type without
3742218893Sdim    // regard to cv-qualifiers.
3743218893Sdim
3744218893Sdim    const RecordType *lhsRecord = LhsT->getAs<RecordType>();
3745218893Sdim    if (!lhsRecord) return false;
3746218893Sdim
3747218893Sdim    const RecordType *rhsRecord = RhsT->getAs<RecordType>();
3748218893Sdim    if (!rhsRecord) return false;
3749218893Sdim
3750218893Sdim    assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
3751218893Sdim             == (lhsRecord == rhsRecord));
3752218893Sdim
3753218893Sdim    if (lhsRecord == rhsRecord)
3754218893Sdim      return !lhsRecord->getDecl()->isUnion();
3755218893Sdim
3756218893Sdim    // C++0x [meta.rel]p2:
3757218893Sdim    //   If Base and Derived are class types and are different types
3758218893Sdim    //   (ignoring possible cv-qualifiers) then Derived shall be a
3759218893Sdim    //   complete type.
3760218893Sdim    if (Self.RequireCompleteType(KeyLoc, RhsT,
3761218893Sdim                          diag::err_incomplete_type_used_in_type_trait_expr))
3762218893Sdim      return false;
3763218893Sdim
3764218893Sdim    return cast<CXXRecordDecl>(rhsRecord->getDecl())
3765218893Sdim      ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
3766218893Sdim  }
3767221345Sdim  case BTT_IsSame:
3768221345Sdim    return Self.Context.hasSameType(LhsT, RhsT);
3769218893Sdim  case BTT_TypeCompatible:
3770218893Sdim    return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(),
3771218893Sdim                                           RhsT.getUnqualifiedType());
3772221345Sdim  case BTT_IsConvertible:
3773218893Sdim  case BTT_IsConvertibleTo: {
3774218893Sdim    // C++0x [meta.rel]p4:
3775218893Sdim    //   Given the following function prototype:
3776218893Sdim    //
3777218893Sdim    //     template <class T>
3778218893Sdim    //       typename add_rvalue_reference<T>::type create();
3779218893Sdim    //
3780218893Sdim    //   the predicate condition for a template specialization
3781218893Sdim    //   is_convertible<From, To> shall be satisfied if and only if
3782218893Sdim    //   the return expression in the following code would be
3783218893Sdim    //   well-formed, including any implicit conversions to the return
3784218893Sdim    //   type of the function:
3785218893Sdim    //
3786218893Sdim    //     To test() {
3787218893Sdim    //       return create<From>();
3788218893Sdim    //     }
3789218893Sdim    //
3790218893Sdim    //   Access checking is performed as if in a context unrelated to To and
3791218893Sdim    //   From. Only the validity of the immediate context of the expression
3792218893Sdim    //   of the return-statement (including conversions to the return type)
3793218893Sdim    //   is considered.
3794218893Sdim    //
3795218893Sdim    // We model the initialization as a copy-initialization of a temporary
3796218893Sdim    // of the appropriate type, which for this expression is identical to the
3797218893Sdim    // return statement (since NRVO doesn't apply).
3798239462Sdim
3799239462Sdim    // Functions aren't allowed to return function or array types.
3800239462Sdim    if (RhsT->isFunctionType() || RhsT->isArrayType())
3801239462Sdim      return false;
3802239462Sdim
3803239462Sdim    // A return statement in a void function must have void type.
3804239462Sdim    if (RhsT->isVoidType())
3805239462Sdim      return LhsT->isVoidType();
3806239462Sdim
3807239462Sdim    // A function definition requires a complete, non-abstract return type.
3808239462Sdim    if (Self.RequireCompleteType(KeyLoc, RhsT, 0) ||
3809239462Sdim        Self.RequireNonAbstractType(KeyLoc, RhsT, 0))
3810239462Sdim      return false;
3811239462Sdim
3812239462Sdim    // Compute the result of add_rvalue_reference.
3813218893Sdim    if (LhsT->isObjectType() || LhsT->isFunctionType())
3814218893Sdim      LhsT = Self.Context.getRValueReferenceType(LhsT);
3815239462Sdim
3816239462Sdim    // Build a fake source and destination for initialization.
3817218893Sdim    InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
3818218893Sdim    OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
3819218893Sdim                         Expr::getValueKindForType(LhsT));
3820218893Sdim    Expr *FromPtr = &From;
3821218893Sdim    InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
3822218893Sdim                                                           SourceLocation()));
3823218893Sdim
3824234353Sdim    // Perform the initialization in an unevaluated context within a SFINAE
3825234353Sdim    // trap at translation unit scope.
3826234353Sdim    EnterExpressionEvaluationContext Unevaluated(Self, Sema::Unevaluated);
3827218893Sdim    Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
3828218893Sdim    Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
3829251662Sdim    InitializationSequence Init(Self, To, Kind, FromPtr);
3830223017Sdim    if (Init.Failed())
3831218893Sdim      return false;
3832218893Sdim
3833243830Sdim    ExprResult Result = Init.Perform(Self, To, Kind, FromPtr);
3834218893Sdim    return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
3835218893Sdim  }
3836234353Sdim
3837234353Sdim  case BTT_IsTriviallyAssignable: {
3838234353Sdim    // C++11 [meta.unary.prop]p3:
3839234353Sdim    //   is_trivially_assignable is defined as:
3840234353Sdim    //     is_assignable<T, U>::value is true and the assignment, as defined by
3841234353Sdim    //     is_assignable, is known to call no operation that is not trivial
3842234353Sdim    //
3843234353Sdim    //   is_assignable is defined as:
3844234353Sdim    //     The expression declval<T>() = declval<U>() is well-formed when
3845234353Sdim    //     treated as an unevaluated operand (Clause 5).
3846234353Sdim    //
3847234353Sdim    //   For both, T and U shall be complete types, (possibly cv-qualified)
3848234353Sdim    //   void, or arrays of unknown bound.
3849234353Sdim    if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
3850234353Sdim        Self.RequireCompleteType(KeyLoc, LhsT,
3851234353Sdim          diag::err_incomplete_type_used_in_type_trait_expr))
3852234353Sdim      return false;
3853234353Sdim    if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
3854234353Sdim        Self.RequireCompleteType(KeyLoc, RhsT,
3855234353Sdim          diag::err_incomplete_type_used_in_type_trait_expr))
3856234353Sdim      return false;
3857234353Sdim
3858234353Sdim    // cv void is never assignable.
3859234353Sdim    if (LhsT->isVoidType() || RhsT->isVoidType())
3860234353Sdim      return false;
3861234353Sdim
3862234353Sdim    // Build expressions that emulate the effect of declval<T>() and
3863234353Sdim    // declval<U>().
3864234353Sdim    if (LhsT->isObjectType() || LhsT->isFunctionType())
3865234353Sdim      LhsT = Self.Context.getRValueReferenceType(LhsT);
3866234353Sdim    if (RhsT->isObjectType() || RhsT->isFunctionType())
3867234353Sdim      RhsT = Self.Context.getRValueReferenceType(RhsT);
3868234353Sdim    OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
3869234353Sdim                        Expr::getValueKindForType(LhsT));
3870234353Sdim    OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
3871234353Sdim                        Expr::getValueKindForType(RhsT));
3872234353Sdim
3873234353Sdim    // Attempt the assignment in an unevaluated context within a SFINAE
3874234353Sdim    // trap at translation unit scope.
3875234353Sdim    EnterExpressionEvaluationContext Unevaluated(Self, Sema::Unevaluated);
3876234353Sdim    Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
3877234353Sdim    Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
3878234353Sdim    ExprResult Result = Self.BuildBinOp(/*S=*/0, KeyLoc, BO_Assign, &Lhs, &Rhs);
3879234353Sdim    if (Result.isInvalid() || SFINAE.hasErrorOccurred())
3880234353Sdim      return false;
3881234353Sdim
3882239462Sdim    // Under Objective-C ARC, if the destination has non-trivial Objective-C
3883239462Sdim    // lifetime, this is a non-trivial assignment.
3884239462Sdim    if (Self.getLangOpts().ObjCAutoRefCount &&
3885239462Sdim        hasNontrivialObjCLifetime(LhsT.getNonReferenceType()))
3886239462Sdim      return false;
3887239462Sdim
3888234353Sdim    return !Result.get()->hasNonTrivialCall(Self.Context);
3889218893Sdim  }
3890234353Sdim  }
3891218893Sdim  llvm_unreachable("Unknown type trait or not implemented");
3892218893Sdim}
3893218893Sdim
3894218893SdimExprResult Sema::BuildBinaryTypeTrait(BinaryTypeTrait BTT,
3895218893Sdim                                      SourceLocation KWLoc,
3896218893Sdim                                      TypeSourceInfo *LhsTSInfo,
3897218893Sdim                                      TypeSourceInfo *RhsTSInfo,
3898218893Sdim                                      SourceLocation RParen) {
3899218893Sdim  QualType LhsT = LhsTSInfo->getType();
3900218893Sdim  QualType RhsT = RhsTSInfo->getType();
3901218893Sdim
3902218893Sdim  if (BTT == BTT_TypeCompatible) {
3903234353Sdim    if (getLangOpts().CPlusPlus) {
3904218893Sdim      Diag(KWLoc, diag::err_types_compatible_p_in_cplusplus)
3905218893Sdim        << SourceRange(KWLoc, RParen);
3906218893Sdim      return ExprError();
3907218893Sdim    }
3908218893Sdim  }
3909218893Sdim
3910218893Sdim  bool Value = false;
3911218893Sdim  if (!LhsT->isDependentType() && !RhsT->isDependentType())
3912218893Sdim    Value = EvaluateBinaryTypeTrait(*this, BTT, LhsT, RhsT, KWLoc);
3913218893Sdim
3914218893Sdim  // Select trait result type.
3915218893Sdim  QualType ResultType;
3916218893Sdim  switch (BTT) {
3917218893Sdim  case BTT_IsBaseOf:       ResultType = Context.BoolTy; break;
3918221345Sdim  case BTT_IsConvertible:  ResultType = Context.BoolTy; break;
3919221345Sdim  case BTT_IsSame:         ResultType = Context.BoolTy; break;
3920218893Sdim  case BTT_TypeCompatible: ResultType = Context.IntTy; break;
3921218893Sdim  case BTT_IsConvertibleTo: ResultType = Context.BoolTy; break;
3922234353Sdim  case BTT_IsTriviallyAssignable: ResultType = Context.BoolTy;
3923218893Sdim  }
3924218893Sdim
3925218893Sdim  return Owned(new (Context) BinaryTypeTraitExpr(KWLoc, BTT, LhsTSInfo,
3926218893Sdim                                                 RhsTSInfo, Value, RParen,
3927218893Sdim                                                 ResultType));
3928218893Sdim}
3929218893Sdim
3930221345SdimExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
3931221345Sdim                                     SourceLocation KWLoc,
3932221345Sdim                                     ParsedType Ty,
3933221345Sdim                                     Expr* DimExpr,
3934221345Sdim                                     SourceLocation RParen) {
3935221345Sdim  TypeSourceInfo *TSInfo;
3936221345Sdim  QualType T = GetTypeFromParser(Ty, &TSInfo);
3937221345Sdim  if (!TSInfo)
3938221345Sdim    TSInfo = Context.getTrivialTypeSourceInfo(T);
3939221345Sdim
3940221345Sdim  return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
3941221345Sdim}
3942221345Sdim
3943221345Sdimstatic uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
3944221345Sdim                                           QualType T, Expr *DimExpr,
3945221345Sdim                                           SourceLocation KeyLoc) {
3946221345Sdim  assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
3947221345Sdim
3948221345Sdim  switch(ATT) {
3949221345Sdim  case ATT_ArrayRank:
3950221345Sdim    if (T->isArrayType()) {
3951221345Sdim      unsigned Dim = 0;
3952221345Sdim      while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
3953221345Sdim        ++Dim;
3954221345Sdim        T = AT->getElementType();
3955221345Sdim      }
3956221345Sdim      return Dim;
3957221345Sdim    }
3958221345Sdim    return 0;
3959221345Sdim
3960221345Sdim  case ATT_ArrayExtent: {
3961221345Sdim    llvm::APSInt Value;
3962221345Sdim    uint64_t Dim;
3963234353Sdim    if (Self.VerifyIntegerConstantExpression(DimExpr, &Value,
3964239462Sdim          diag::err_dimension_expr_not_constant_integer,
3965234353Sdim          false).isInvalid())
3966234353Sdim      return 0;
3967234353Sdim    if (Value.isSigned() && Value.isNegative()) {
3968234353Sdim      Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)
3969234353Sdim        << DimExpr->getSourceRange();
3970234353Sdim      return 0;
3971221345Sdim    }
3972234353Sdim    Dim = Value.getLimitedValue();
3973221345Sdim
3974221345Sdim    if (T->isArrayType()) {
3975221345Sdim      unsigned D = 0;
3976221345Sdim      bool Matched = false;
3977221345Sdim      while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
3978221345Sdim        if (Dim == D) {
3979221345Sdim          Matched = true;
3980221345Sdim          break;
3981221345Sdim        }
3982221345Sdim        ++D;
3983221345Sdim        T = AT->getElementType();
3984221345Sdim      }
3985221345Sdim
3986221345Sdim      if (Matched && T->isArrayType()) {
3987221345Sdim        if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
3988221345Sdim          return CAT->getSize().getLimitedValue();
3989221345Sdim      }
3990221345Sdim    }
3991221345Sdim    return 0;
3992221345Sdim  }
3993221345Sdim  }
3994221345Sdim  llvm_unreachable("Unknown type trait or not implemented");
3995221345Sdim}
3996221345Sdim
3997221345SdimExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
3998221345Sdim                                     SourceLocation KWLoc,
3999221345Sdim                                     TypeSourceInfo *TSInfo,
4000221345Sdim                                     Expr* DimExpr,
4001221345Sdim                                     SourceLocation RParen) {
4002221345Sdim  QualType T = TSInfo->getType();
4003221345Sdim
4004221345Sdim  // FIXME: This should likely be tracked as an APInt to remove any host
4005221345Sdim  // assumptions about the width of size_t on the target.
4006221345Sdim  uint64_t Value = 0;
4007221345Sdim  if (!T->isDependentType())
4008221345Sdim    Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
4009221345Sdim
4010221345Sdim  // While the specification for these traits from the Embarcadero C++
4011221345Sdim  // compiler's documentation says the return type is 'unsigned int', Clang
4012221345Sdim  // returns 'size_t'. On Windows, the primary platform for the Embarcadero
4013221345Sdim  // compiler, there is no difference. On several other platforms this is an
4014221345Sdim  // important distinction.
4015221345Sdim  return Owned(new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value,
4016221345Sdim                                                DimExpr, RParen,
4017221345Sdim                                                Context.getSizeType()));
4018221345Sdim}
4019221345Sdim
4020221345SdimExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
4021221345Sdim                                      SourceLocation KWLoc,
4022221345Sdim                                      Expr *Queried,
4023221345Sdim                                      SourceLocation RParen) {
4024221345Sdim  // If error parsing the expression, ignore.
4025221345Sdim  if (!Queried)
4026221345Sdim    return ExprError();
4027221345Sdim
4028221345Sdim  ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
4029221345Sdim
4030243830Sdim  return Result;
4031221345Sdim}
4032221345Sdim
4033221345Sdimstatic bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
4034221345Sdim  switch (ET) {
4035221345Sdim  case ET_IsLValueExpr: return E->isLValue();
4036221345Sdim  case ET_IsRValueExpr: return E->isRValue();
4037221345Sdim  }
4038221345Sdim  llvm_unreachable("Expression trait not covered by switch");
4039221345Sdim}
4040221345Sdim
4041221345SdimExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
4042221345Sdim                                      SourceLocation KWLoc,
4043221345Sdim                                      Expr *Queried,
4044221345Sdim                                      SourceLocation RParen) {
4045221345Sdim  if (Queried->isTypeDependent()) {
4046221345Sdim    // Delay type-checking for type-dependent expressions.
4047221345Sdim  } else if (Queried->getType()->isPlaceholderType()) {
4048221345Sdim    ExprResult PE = CheckPlaceholderExpr(Queried);
4049221345Sdim    if (PE.isInvalid()) return ExprError();
4050221345Sdim    return BuildExpressionTrait(ET, KWLoc, PE.take(), RParen);
4051221345Sdim  }
4052221345Sdim
4053221345Sdim  bool Value = EvaluateExpressionTrait(ET, Queried);
4054221345Sdim
4055221345Sdim  return Owned(new (Context) ExpressionTraitExpr(KWLoc, ET, Queried, Value,
4056221345Sdim                                                 RParen, Context.BoolTy));
4057221345Sdim}
4058221345Sdim
4059226633SdimQualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
4060218893Sdim                                            ExprValueKind &VK,
4061218893Sdim                                            SourceLocation Loc,
4062218893Sdim                                            bool isIndirect) {
4063226633Sdim  assert(!LHS.get()->getType()->isPlaceholderType() &&
4064226633Sdim         !RHS.get()->getType()->isPlaceholderType() &&
4065224145Sdim         "placeholders should have been weeded out by now");
4066224145Sdim
4067224145Sdim  // The LHS undergoes lvalue conversions if this is ->*.
4068224145Sdim  if (isIndirect) {
4069226633Sdim    LHS = DefaultLvalueConversion(LHS.take());
4070226633Sdim    if (LHS.isInvalid()) return QualType();
4071224145Sdim  }
4072224145Sdim
4073224145Sdim  // The RHS always undergoes lvalue conversions.
4074226633Sdim  RHS = DefaultLvalueConversion(RHS.take());
4075226633Sdim  if (RHS.isInvalid()) return QualType();
4076224145Sdim
4077193326Sed  const char *OpSpelling = isIndirect ? "->*" : ".*";
4078193326Sed  // C++ 5.5p2
4079193326Sed  //   The binary operator .* [p3: ->*] binds its second operand, which shall
4080193326Sed  //   be of type "pointer to member of T" (where T is a completely-defined
4081193326Sed  //   class type) [...]
4082226633Sdim  QualType RHSType = RHS.get()->getType();
4083226633Sdim  const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
4084193326Sed  if (!MemPtr) {
4085193326Sed    Diag(Loc, diag::err_bad_memptr_rhs)
4086226633Sdim      << OpSpelling << RHSType << RHS.get()->getSourceRange();
4087193326Sed    return QualType();
4088198092Srdivacky  }
4089193326Sed
4090193326Sed  QualType Class(MemPtr->getClass(), 0);
4091193326Sed
4092218893Sdim  // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
4093218893Sdim  // member pointer points must be completely-defined. However, there is no
4094218893Sdim  // reason for this semantic distinction, and the rule is not enforced by
4095218893Sdim  // other compilers. Therefore, we do not check this property, as it is
4096218893Sdim  // likely to be considered a defect.
4097207619Srdivacky
4098193326Sed  // C++ 5.5p2
4099193326Sed  //   [...] to its first operand, which shall be of class T or of a class of
4100193326Sed  //   which T is an unambiguous and accessible base class. [p3: a pointer to
4101193326Sed  //   such a class]
4102226633Sdim  QualType LHSType = LHS.get()->getType();
4103193326Sed  if (isIndirect) {
4104226633Sdim    if (const PointerType *Ptr = LHSType->getAs<PointerType>())
4105226633Sdim      LHSType = Ptr->getPointeeType();
4106193326Sed    else {
4107193326Sed      Diag(Loc, diag::err_bad_memptr_lhs)
4108226633Sdim        << OpSpelling << 1 << LHSType
4109206084Srdivacky        << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
4110193326Sed      return QualType();
4111193326Sed    }
4112193326Sed  }
4113193326Sed
4114226633Sdim  if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
4115207619Srdivacky    // If we want to check the hierarchy, we need a complete type.
4116239462Sdim    if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs,
4117239462Sdim                            OpSpelling, (int)isIndirect)) {
4118207619Srdivacky      return QualType();
4119207619Srdivacky    }
4120207619Srdivacky    CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
4121198092Srdivacky                       /*DetectVirtual=*/false);
4122193326Sed    // FIXME: Would it be useful to print full ambiguity paths, or is that
4123193326Sed    // overkill?
4124226633Sdim    if (!IsDerivedFrom(LHSType, Class, Paths) ||
4125193326Sed        Paths.isAmbiguous(Context.getCanonicalType(Class))) {
4126193326Sed      Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
4127226633Sdim        << (int)isIndirect << LHS.get()->getType();
4128193326Sed      return QualType();
4129193326Sed    }
4130202879Srdivacky    // Cast LHS to type of use.
4131202879Srdivacky    QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
4132226633Sdim    ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind();
4133212904Sdim
4134212904Sdim    CXXCastPath BasePath;
4135207619Srdivacky    BuildBasePathArray(Paths, BasePath);
4136226633Sdim    LHS = ImpCastExprToType(LHS.take(), UseType, CK_DerivedToBase, VK,
4137226633Sdim                            &BasePath);
4138193326Sed  }
4139193326Sed
4140226633Sdim  if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
4141199512Srdivacky    // Diagnose use of pointer-to-member type which when used as
4142199512Srdivacky    // the functional cast in a pointer-to-member expression.
4143199512Srdivacky    Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
4144199512Srdivacky     return QualType();
4145199512Srdivacky  }
4146218893Sdim
4147193326Sed  // C++ 5.5p2
4148193326Sed  //   The result is an object or a function of the type specified by the
4149193326Sed  //   second operand.
4150193326Sed  // The cv qualifiers are the union of those in the pointer and the left side,
4151193326Sed  // in accordance with 5.5p5 and 5.2.5.
4152193326Sed  QualType Result = MemPtr->getPointeeType();
4153226633Sdim  Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
4154218893Sdim
4155218893Sdim  // C++0x [expr.mptr.oper]p6:
4156218893Sdim  //   In a .* expression whose object expression is an rvalue, the program is
4157218893Sdim  //   ill-formed if the second operand is a pointer to member function with
4158218893Sdim  //   ref-qualifier &. In a ->* expression or in a .* expression whose object
4159218893Sdim  //   expression is an lvalue, the program is ill-formed if the second operand
4160218893Sdim  //   is a pointer to member function with ref-qualifier &&.
4161218893Sdim  if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
4162218893Sdim    switch (Proto->getRefQualifier()) {
4163218893Sdim    case RQ_None:
4164218893Sdim      // Do nothing
4165218893Sdim      break;
4166218893Sdim
4167218893Sdim    case RQ_LValue:
4168226633Sdim      if (!isIndirect && !LHS.get()->Classify(Context).isLValue())
4169218893Sdim        Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
4170226633Sdim          << RHSType << 1 << LHS.get()->getSourceRange();
4171218893Sdim      break;
4172218893Sdim
4173218893Sdim    case RQ_RValue:
4174226633Sdim      if (isIndirect || !LHS.get()->Classify(Context).isRValue())
4175218893Sdim        Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
4176226633Sdim          << RHSType << 0 << LHS.get()->getSourceRange();
4177218893Sdim      break;
4178218893Sdim    }
4179218893Sdim  }
4180218893Sdim
4181218893Sdim  // C++ [expr.mptr.oper]p6:
4182218893Sdim  //   The result of a .* expression whose second operand is a pointer
4183218893Sdim  //   to a data member is of the same value category as its
4184218893Sdim  //   first operand. The result of a .* expression whose second
4185218893Sdim  //   operand is a pointer to a member function is a prvalue. The
4186218893Sdim  //   result of an ->* expression is an lvalue if its second operand
4187218893Sdim  //   is a pointer to data member and a prvalue otherwise.
4188221345Sdim  if (Result->isFunctionType()) {
4189218893Sdim    VK = VK_RValue;
4190221345Sdim    return Context.BoundMemberTy;
4191221345Sdim  } else if (isIndirect) {
4192218893Sdim    VK = VK_LValue;
4193221345Sdim  } else {
4194226633Sdim    VK = LHS.get()->getValueKind();
4195221345Sdim  }
4196218893Sdim
4197193326Sed  return Result;
4198193326Sed}
4199193326Sed
4200193326Sed/// \brief Try to convert a type to another according to C++0x 5.16p3.
4201193326Sed///
4202193326Sed/// This is part of the parameter validation for the ? operator. If either
4203193326Sed/// value operand is a class type, the two operands are attempted to be
4204193326Sed/// converted to each other. This function does the conversion in one direction.
4205206084Srdivacky/// It returns true if the program is ill-formed and has already been diagnosed
4206206084Srdivacky/// as such.
4207193326Sedstatic bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
4208193326Sed                                SourceLocation QuestionLoc,
4209206084Srdivacky                                bool &HaveConversion,
4210206084Srdivacky                                QualType &ToType) {
4211206084Srdivacky  HaveConversion = false;
4212206084Srdivacky  ToType = To->getType();
4213218893Sdim
4214218893Sdim  InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
4215206084Srdivacky                                                           SourceLocation());
4216193326Sed  // C++0x 5.16p3
4217193326Sed  //   The process for determining whether an operand expression E1 of type T1
4218193326Sed  //   can be converted to match an operand expression E2 of type T2 is defined
4219193326Sed  //   as follows:
4220193326Sed  //   -- If E2 is an lvalue:
4221218893Sdim  bool ToIsLvalue = To->isLValue();
4222206084Srdivacky  if (ToIsLvalue) {
4223193326Sed    //   E1 can be converted to match E2 if E1 can be implicitly converted to
4224193326Sed    //   type "lvalue reference to T2", subject to the constraint that in the
4225193326Sed    //   conversion the reference must bind directly to E1.
4226206084Srdivacky    QualType T = Self.Context.getLValueReferenceType(ToType);
4227206084Srdivacky    InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
4228218893Sdim
4229251662Sdim    InitializationSequence InitSeq(Self, Entity, Kind, From);
4230206084Srdivacky    if (InitSeq.isDirectReferenceBinding()) {
4231206084Srdivacky      ToType = T;
4232206084Srdivacky      HaveConversion = true;
4233206084Srdivacky      return false;
4234193326Sed    }
4235218893Sdim
4236206084Srdivacky    if (InitSeq.isAmbiguous())
4237251662Sdim      return InitSeq.Diagnose(Self, Entity, Kind, From);
4238193326Sed  }
4239204643Srdivacky
4240193326Sed  //   -- If E2 is an rvalue, or if the conversion above cannot be done:
4241193326Sed  //      -- if E1 and E2 have class type, and the underlying class types are
4242193326Sed  //         the same or one is a base class of the other:
4243193326Sed  QualType FTy = From->getType();
4244193326Sed  QualType TTy = To->getType();
4245198092Srdivacky  const RecordType *FRec = FTy->getAs<RecordType>();
4246198092Srdivacky  const RecordType *TRec = TTy->getAs<RecordType>();
4247218893Sdim  bool FDerivedFromT = FRec && TRec && FRec != TRec &&
4248206084Srdivacky                       Self.IsDerivedFrom(FTy, TTy);
4249218893Sdim  if (FRec && TRec &&
4250206084Srdivacky      (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
4251193326Sed    //         E1 can be converted to match E2 if the class of T2 is the
4252193326Sed    //         same type as, or a base class of, the class of T1, and
4253193326Sed    //         [cv2 > cv1].
4254204643Srdivacky    if (FRec == TRec || FDerivedFromT) {
4255204643Srdivacky      if (TTy.isAtLeastAsQualifiedAs(FTy)) {
4256206084Srdivacky        InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
4257251662Sdim        InitializationSequence InitSeq(Self, Entity, Kind, From);
4258223017Sdim        if (InitSeq) {
4259206084Srdivacky          HaveConversion = true;
4260206084Srdivacky          return false;
4261206084Srdivacky        }
4262218893Sdim
4263206084Srdivacky        if (InitSeq.isAmbiguous())
4264251662Sdim          return InitSeq.Diagnose(Self, Entity, Kind, From);
4265218893Sdim      }
4266193326Sed    }
4267218893Sdim
4268206084Srdivacky    return false;
4269206084Srdivacky  }
4270218893Sdim
4271206084Srdivacky  //     -- Otherwise: E1 can be converted to match E2 if E1 can be
4272206084Srdivacky  //        implicitly converted to the type that expression E2 would have
4273218893Sdim  //        if E2 were converted to an rvalue (or the type it has, if E2 is
4274206084Srdivacky  //        an rvalue).
4275206084Srdivacky  //
4276206084Srdivacky  // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
4277206084Srdivacky  // to the array-to-pointer or function-to-pointer conversions.
4278206084Srdivacky  if (!TTy->getAs<TagType>())
4279206084Srdivacky    TTy = TTy.getUnqualifiedType();
4280218893Sdim
4281206084Srdivacky  InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
4282251662Sdim  InitializationSequence InitSeq(Self, Entity, Kind, From);
4283223017Sdim  HaveConversion = !InitSeq.Failed();
4284206084Srdivacky  ToType = TTy;
4285206084Srdivacky  if (InitSeq.isAmbiguous())
4286251662Sdim    return InitSeq.Diagnose(Self, Entity, Kind, From);
4287193326Sed
4288193326Sed  return false;
4289193326Sed}
4290193326Sed
4291193326Sed/// \brief Try to find a common type for two according to C++0x 5.16p5.
4292193326Sed///
4293193326Sed/// This is part of the parameter validation for the ? operator. If either
4294193326Sed/// value operand is a class type, overload resolution is used to find a
4295193326Sed/// conversion to a common type.
4296221345Sdimstatic bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
4297218893Sdim                                    SourceLocation QuestionLoc) {
4298221345Sdim  Expr *Args[2] = { LHS.get(), RHS.get() };
4299218893Sdim  OverloadCandidateSet CandidateSet(QuestionLoc);
4300251662Sdim  Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args,
4301218893Sdim                                    CandidateSet);
4302193326Sed
4303193326Sed  OverloadCandidateSet::iterator Best;
4304218893Sdim  switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
4305221345Sdim    case OR_Success: {
4306193326Sed      // We found a match. Perform the conversions on the arguments and move on.
4307221345Sdim      ExprResult LHSRes =
4308221345Sdim        Self.PerformImplicitConversion(LHS.get(), Best->BuiltinTypes.ParamTypes[0],
4309221345Sdim                                       Best->Conversions[0], Sema::AA_Converting);
4310221345Sdim      if (LHSRes.isInvalid())
4311193326Sed        break;
4312243830Sdim      LHS = LHSRes;
4313221345Sdim
4314221345Sdim      ExprResult RHSRes =
4315221345Sdim        Self.PerformImplicitConversion(RHS.get(), Best->BuiltinTypes.ParamTypes[1],
4316221345Sdim                                       Best->Conversions[1], Sema::AA_Converting);
4317221345Sdim      if (RHSRes.isInvalid())
4318221345Sdim        break;
4319243830Sdim      RHS = RHSRes;
4320219077Sdim      if (Best->Function)
4321234353Sdim        Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
4322193326Sed      return false;
4323221345Sdim    }
4324221345Sdim
4325200583Srdivacky    case OR_No_Viable_Function:
4326218893Sdim
4327218893Sdim      // Emit a better diagnostic if one of the expressions is a null pointer
4328218893Sdim      // constant and the other is a pointer type. In this case, the user most
4329218893Sdim      // likely forgot to take the address of the other expression.
4330221345Sdim      if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
4331218893Sdim        return true;
4332218893Sdim
4333218893Sdim      Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
4334221345Sdim        << LHS.get()->getType() << RHS.get()->getType()
4335221345Sdim        << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
4336193326Sed      return true;
4337193326Sed
4338200583Srdivacky    case OR_Ambiguous:
4339218893Sdim      Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
4340221345Sdim        << LHS.get()->getType() << RHS.get()->getType()
4341221345Sdim        << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
4342193326Sed      // FIXME: Print the possible common types by printing the return types of
4343193326Sed      // the viable candidates.
4344193326Sed      break;
4345193326Sed
4346200583Srdivacky    case OR_Deleted:
4347226633Sdim      llvm_unreachable("Conditional operator has only built-in overloads");
4348193326Sed  }
4349193326Sed  return true;
4350193326Sed}
4351193326Sed
4352193326Sed/// \brief Perform an "extended" implicit conversion as returned by
4353193326Sed/// TryClassUnification.
4354221345Sdimstatic bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
4355206084Srdivacky  InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
4356221345Sdim  InitializationKind Kind = InitializationKind::CreateCopy(E.get()->getLocStart(),
4357206084Srdivacky                                                           SourceLocation());
4358221345Sdim  Expr *Arg = E.take();
4359251662Sdim  InitializationSequence InitSeq(Self, Entity, Kind, Arg);
4360243830Sdim  ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg);
4361206084Srdivacky  if (Result.isInvalid())
4362193326Sed    return true;
4363218893Sdim
4364221345Sdim  E = Result;
4365193326Sed  return false;
4366193326Sed}
4367193326Sed
4368193326Sed/// \brief Check the operands of ?: under C++ semantics.
4369193326Sed///
4370193326Sed/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
4371193326Sed/// extension. In this case, LHS == Cond. (But they're not aliases.)
4372239462SdimQualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
4373239462Sdim                                           ExprResult &RHS, ExprValueKind &VK,
4374239462Sdim                                           ExprObjectKind &OK,
4375193326Sed                                           SourceLocation QuestionLoc) {
4376193326Sed  // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
4377193326Sed  // interface pointers.
4378193326Sed
4379239462Sdim  // C++11 [expr.cond]p1
4380193326Sed  //   The first expression is contextually converted to bool.
4381221345Sdim  if (!Cond.get()->isTypeDependent()) {
4382221345Sdim    ExprResult CondRes = CheckCXXBooleanCondition(Cond.take());
4383221345Sdim    if (CondRes.isInvalid())
4384193326Sed      return QualType();
4385243830Sdim    Cond = CondRes;
4386193326Sed  }
4387193326Sed
4388218893Sdim  // Assume r-value.
4389218893Sdim  VK = VK_RValue;
4390218893Sdim  OK = OK_Ordinary;
4391218893Sdim
4392193326Sed  // Either of the arguments dependent?
4393221345Sdim  if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
4394193326Sed    return Context.DependentTy;
4395193326Sed
4396239462Sdim  // C++11 [expr.cond]p2
4397193326Sed  //   If either the second or the third operand has type (cv) void, ...
4398221345Sdim  QualType LTy = LHS.get()->getType();
4399221345Sdim  QualType RTy = RHS.get()->getType();
4400193326Sed  bool LVoid = LTy->isVoidType();
4401193326Sed  bool RVoid = RTy->isVoidType();
4402193326Sed  if (LVoid || RVoid) {
4403193326Sed    //   ... then the [l2r] conversions are performed on the second and third
4404193326Sed    //   operands ...
4405221345Sdim    LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
4406221345Sdim    RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
4407221345Sdim    if (LHS.isInvalid() || RHS.isInvalid())
4408221345Sdim      return QualType();
4409239462Sdim
4410239462Sdim    // Finish off the lvalue-to-rvalue conversion by copy-initializing a
4411239462Sdim    // temporary if necessary. DefaultFunctionArrayLvalueConversion doesn't
4412239462Sdim    // do this part for us.
4413239462Sdim    ExprResult &NonVoid = LVoid ? RHS : LHS;
4414239462Sdim    if (NonVoid.get()->getType()->isRecordType() &&
4415239462Sdim        NonVoid.get()->isGLValue()) {
4416243830Sdim      if (RequireNonAbstractType(QuestionLoc, NonVoid.get()->getType(),
4417243830Sdim                             diag::err_allocation_of_abstract_type))
4418243830Sdim        return QualType();
4419239462Sdim      InitializedEntity Entity =
4420239462Sdim          InitializedEntity::InitializeTemporary(NonVoid.get()->getType());
4421239462Sdim      NonVoid = PerformCopyInitialization(Entity, SourceLocation(), NonVoid);
4422239462Sdim      if (NonVoid.isInvalid())
4423239462Sdim        return QualType();
4424239462Sdim    }
4425239462Sdim
4426221345Sdim    LTy = LHS.get()->getType();
4427221345Sdim    RTy = RHS.get()->getType();
4428193326Sed
4429193326Sed    //   ... and one of the following shall hold:
4430193326Sed    //   -- The second or the third operand (but not both) is a throw-
4431239462Sdim    //      expression; the result is of the type of the other and is a prvalue.
4432263508Sdim    bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenCasts());
4433263508Sdim    bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenCasts());
4434193326Sed    if (LThrow && !RThrow)
4435193326Sed      return RTy;
4436193326Sed    if (RThrow && !LThrow)
4437193326Sed      return LTy;
4438193326Sed
4439193326Sed    //   -- Both the second and third operands have type void; the result is of
4440239462Sdim    //      type void and is a prvalue.
4441193326Sed    if (LVoid && RVoid)
4442193326Sed      return Context.VoidTy;
4443193326Sed
4444193326Sed    // Neither holds, error.
4445193326Sed    Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
4446193326Sed      << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
4447221345Sdim      << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
4448193326Sed    return QualType();
4449193326Sed  }
4450193326Sed
4451193326Sed  // Neither is void.
4452193326Sed
4453239462Sdim  // C++11 [expr.cond]p3
4454193326Sed  //   Otherwise, if the second and third operand have different types, and
4455239462Sdim  //   either has (cv) class type [...] an attempt is made to convert each of
4456239462Sdim  //   those operands to the type of the other.
4457218893Sdim  if (!Context.hasSameType(LTy, RTy) &&
4458193326Sed      (LTy->isRecordType() || RTy->isRecordType())) {
4459193326Sed    ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
4460193326Sed    // These return true if a single direction is already ambiguous.
4461206084Srdivacky    QualType L2RType, R2LType;
4462206084Srdivacky    bool HaveL2R, HaveR2L;
4463221345Sdim    if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
4464193326Sed      return QualType();
4465221345Sdim    if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
4466193326Sed      return QualType();
4467218893Sdim
4468193326Sed    //   If both can be converted, [...] the program is ill-formed.
4469193326Sed    if (HaveL2R && HaveR2L) {
4470193326Sed      Diag(QuestionLoc, diag::err_conditional_ambiguous)
4471221345Sdim        << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
4472193326Sed      return QualType();
4473193326Sed    }
4474193326Sed
4475193326Sed    //   If exactly one conversion is possible, that conversion is applied to
4476193326Sed    //   the chosen operand and the converted operands are used in place of the
4477193326Sed    //   original operands for the remainder of this section.
4478193326Sed    if (HaveL2R) {
4479221345Sdim      if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
4480193326Sed        return QualType();
4481221345Sdim      LTy = LHS.get()->getType();
4482193326Sed    } else if (HaveR2L) {
4483221345Sdim      if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
4484193326Sed        return QualType();
4485221345Sdim      RTy = RHS.get()->getType();
4486193326Sed    }
4487193326Sed  }
4488193326Sed
4489239462Sdim  // C++11 [expr.cond]p3
4490239462Sdim  //   if both are glvalues of the same value category and the same type except
4491239462Sdim  //   for cv-qualification, an attempt is made to convert each of those
4492239462Sdim  //   operands to the type of the other.
4493239462Sdim  ExprValueKind LVK = LHS.get()->getValueKind();
4494239462Sdim  ExprValueKind RVK = RHS.get()->getValueKind();
4495239462Sdim  if (!Context.hasSameType(LTy, RTy) &&
4496239462Sdim      Context.hasSameUnqualifiedType(LTy, RTy) &&
4497239462Sdim      LVK == RVK && LVK != VK_RValue) {
4498239462Sdim    // Since the unqualified types are reference-related and we require the
4499239462Sdim    // result to be as if a reference bound directly, the only conversion
4500239462Sdim    // we can perform is to add cv-qualifiers.
4501239462Sdim    Qualifiers LCVR = Qualifiers::fromCVRMask(LTy.getCVRQualifiers());
4502239462Sdim    Qualifiers RCVR = Qualifiers::fromCVRMask(RTy.getCVRQualifiers());
4503239462Sdim    if (RCVR.isStrictSupersetOf(LCVR)) {
4504239462Sdim      LHS = ImpCastExprToType(LHS.take(), RTy, CK_NoOp, LVK);
4505239462Sdim      LTy = LHS.get()->getType();
4506239462Sdim    }
4507239462Sdim    else if (LCVR.isStrictSupersetOf(RCVR)) {
4508239462Sdim      RHS = ImpCastExprToType(RHS.take(), LTy, CK_NoOp, RVK);
4509239462Sdim      RTy = RHS.get()->getType();
4510239462Sdim    }
4511239462Sdim  }
4512239462Sdim
4513239462Sdim  // C++11 [expr.cond]p4
4514218893Sdim  //   If the second and third operands are glvalues of the same value
4515218893Sdim  //   category and have the same type, the result is of that type and
4516218893Sdim  //   value category and it is a bit-field if the second or the third
4517218893Sdim  //   operand is a bit-field, or if both are bit-fields.
4518218893Sdim  // We only extend this to bitfields, not to the crazy other kinds of
4519218893Sdim  // l-values.
4520206084Srdivacky  bool Same = Context.hasSameType(LTy, RTy);
4521239462Sdim  if (Same && LVK == RVK && LVK != VK_RValue &&
4522221345Sdim      LHS.get()->isOrdinaryOrBitFieldObject() &&
4523221345Sdim      RHS.get()->isOrdinaryOrBitFieldObject()) {
4524221345Sdim    VK = LHS.get()->getValueKind();
4525221345Sdim    if (LHS.get()->getObjectKind() == OK_BitField ||
4526221345Sdim        RHS.get()->getObjectKind() == OK_BitField)
4527218893Sdim      OK = OK_BitField;
4528193326Sed    return LTy;
4529218893Sdim  }
4530193326Sed
4531239462Sdim  // C++11 [expr.cond]p5
4532239462Sdim  //   Otherwise, the result is a prvalue. If the second and third operands
4533193326Sed  //   do not have the same type, and either has (cv) class type, ...
4534193326Sed  if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
4535193326Sed    //   ... overload resolution is used to determine the conversions (if any)
4536193326Sed    //   to be applied to the operands. If the overload resolution fails, the
4537193326Sed    //   program is ill-formed.
4538193326Sed    if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
4539193326Sed      return QualType();
4540193326Sed  }
4541193326Sed
4542239462Sdim  // C++11 [expr.cond]p6
4543239462Sdim  //   Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
4544193326Sed  //   conversions are performed on the second and third operands.
4545221345Sdim  LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
4546221345Sdim  RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
4547221345Sdim  if (LHS.isInvalid() || RHS.isInvalid())
4548221345Sdim    return QualType();
4549221345Sdim  LTy = LHS.get()->getType();
4550221345Sdim  RTy = RHS.get()->getType();
4551193326Sed
4552193326Sed  //   After those conversions, one of the following shall hold:
4553193326Sed  //   -- The second and third operands have the same type; the result
4554208600Srdivacky  //      is of that type. If the operands have class type, the result
4555208600Srdivacky  //      is a prvalue temporary of the result type, which is
4556208600Srdivacky  //      copy-initialized from either the second operand or the third
4557208600Srdivacky  //      operand depending on the value of the first operand.
4558208600Srdivacky  if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
4559208600Srdivacky    if (LTy->isRecordType()) {
4560208600Srdivacky      // The operands have class type. Make a temporary copy.
4561243830Sdim      if (RequireNonAbstractType(QuestionLoc, LTy,
4562243830Sdim                                 diag::err_allocation_of_abstract_type))
4563243830Sdim        return QualType();
4564208600Srdivacky      InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
4565243830Sdim
4566218893Sdim      ExprResult LHSCopy = PerformCopyInitialization(Entity,
4567218893Sdim                                                     SourceLocation(),
4568221345Sdim                                                     LHS);
4569208600Srdivacky      if (LHSCopy.isInvalid())
4570208600Srdivacky        return QualType();
4571218893Sdim
4572218893Sdim      ExprResult RHSCopy = PerformCopyInitialization(Entity,
4573218893Sdim                                                     SourceLocation(),
4574221345Sdim                                                     RHS);
4575208600Srdivacky      if (RHSCopy.isInvalid())
4576208600Srdivacky        return QualType();
4577218893Sdim
4578221345Sdim      LHS = LHSCopy;
4579221345Sdim      RHS = RHSCopy;
4580208600Srdivacky    }
4581208600Srdivacky
4582193326Sed    return LTy;
4583208600Srdivacky  }
4584193326Sed
4585208600Srdivacky  // Extension: conditional operator involving vector types.
4586218893Sdim  if (LTy->isVectorType() || RTy->isVectorType())
4587224145Sdim    return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
4588208600Srdivacky
4589193326Sed  //   -- The second and third operands have arithmetic or enumeration type;
4590193326Sed  //      the usual arithmetic conversions are performed to bring them to a
4591193326Sed  //      common type, and the result is of that type.
4592193326Sed  if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
4593193326Sed    UsualArithmeticConversions(LHS, RHS);
4594221345Sdim    if (LHS.isInvalid() || RHS.isInvalid())
4595221345Sdim      return QualType();
4596221345Sdim    return LHS.get()->getType();
4597193326Sed  }
4598193326Sed
4599193326Sed  //   -- The second and third operands have pointer type, or one has pointer
4600239462Sdim  //      type and the other is a null pointer constant, or both are null
4601239462Sdim  //      pointer constants, at least one of which is non-integral; pointer
4602239462Sdim  //      conversions and qualification conversions are performed to bring them
4603239462Sdim  //      to their composite pointer type. The result is of the composite
4604239462Sdim  //      pointer type.
4605202379Srdivacky  //   -- The second and third operands have pointer to member type, or one has
4606202379Srdivacky  //      pointer to member type and the other is a null pointer constant;
4607202379Srdivacky  //      pointer to member conversions and qualification conversions are
4608202379Srdivacky  //      performed to bring them to a common type, whose cv-qualification
4609202379Srdivacky  //      shall match the cv-qualification of either the second or the third
4610202379Srdivacky  //      operand. The result is of the common type.
4611204643Srdivacky  bool NonStandardCompositeType = false;
4612207619Srdivacky  QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
4613204643Srdivacky                              isSFINAEContext()? 0 : &NonStandardCompositeType);
4614204643Srdivacky  if (!Composite.isNull()) {
4615204643Srdivacky    if (NonStandardCompositeType)
4616218893Sdim      Diag(QuestionLoc,
4617204643Srdivacky           diag::ext_typecheck_cond_incompatible_operands_nonstandard)
4618204643Srdivacky        << LTy << RTy << Composite
4619221345Sdim        << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
4620218893Sdim
4621193326Sed    return Composite;
4622204643Srdivacky  }
4623218893Sdim
4624206084Srdivacky  // Similarly, attempt to find composite type of two objective-c pointers.
4625200583Srdivacky  Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
4626200583Srdivacky  if (!Composite.isNull())
4627200583Srdivacky    return Composite;
4628193326Sed
4629218893Sdim  // Check if we are using a null with a non-pointer type.
4630221345Sdim  if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
4631218893Sdim    return QualType();
4632218893Sdim
4633193326Sed  Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
4634221345Sdim    << LHS.get()->getType() << RHS.get()->getType()
4635221345Sdim    << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
4636193326Sed  return QualType();
4637193326Sed}
4638193326Sed
4639193326Sed/// \brief Find a merged pointer type and convert the two expressions to it.
4640193326Sed///
4641198092Srdivacky/// This finds the composite pointer type (or member pointer type) for @p E1
4642239462Sdim/// and @p E2 according to C++11 5.9p2. It converts both expressions to this
4643198092Srdivacky/// type and returns it.
4644193326Sed/// It does not emit diagnostics.
4645204643Srdivacky///
4646207619Srdivacky/// \param Loc The location of the operator requiring these two expressions to
4647207619Srdivacky/// be converted to the composite pointer type.
4648207619Srdivacky///
4649204643Srdivacky/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
4650204643Srdivacky/// a non-standard (but still sane) composite type to which both expressions
4651204643Srdivacky/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
4652204643Srdivacky/// will be set true.
4653218893SdimQualType Sema::FindCompositePointerType(SourceLocation Loc,
4654207619Srdivacky                                        Expr *&E1, Expr *&E2,
4655204643Srdivacky                                        bool *NonStandardCompositeType) {
4656204643Srdivacky  if (NonStandardCompositeType)
4657204643Srdivacky    *NonStandardCompositeType = false;
4658218893Sdim
4659234353Sdim  assert(getLangOpts().CPlusPlus && "This function assumes C++");
4660193326Sed  QualType T1 = E1->getType(), T2 = E2->getType();
4661193326Sed
4662239462Sdim  // C++11 5.9p2
4663193326Sed  //   Pointer conversions and qualification conversions are performed on
4664193326Sed  //   pointer operands to bring them to their composite pointer type. If
4665193326Sed  //   one operand is a null pointer constant, the composite pointer type is
4666239462Sdim  //   std::nullptr_t if the other operand is also a null pointer constant or,
4667239462Sdim  //   if the other operand is a pointer, the type of the other operand.
4668239462Sdim  if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
4669239462Sdim      !T2->isAnyPointerType() && !T2->isMemberPointerType()) {
4670239462Sdim    if (T1->isNullPtrType() &&
4671239462Sdim        E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
4672239462Sdim      E2 = ImpCastExprToType(E2, T1, CK_NullToPointer).take();
4673239462Sdim      return T1;
4674239462Sdim    }
4675239462Sdim    if (T2->isNullPtrType() &&
4676239462Sdim        E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
4677239462Sdim      E1 = ImpCastExprToType(E1, T2, CK_NullToPointer).take();
4678239462Sdim      return T2;
4679239462Sdim    }
4680239462Sdim    return QualType();
4681239462Sdim  }
4682239462Sdim
4683198092Srdivacky  if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
4684198398Srdivacky    if (T2->isMemberPointerType())
4685221345Sdim      E1 = ImpCastExprToType(E1, T2, CK_NullToMemberPointer).take();
4686198398Srdivacky    else
4687221345Sdim      E1 = ImpCastExprToType(E1, T2, CK_NullToPointer).take();
4688193326Sed    return T2;
4689193326Sed  }
4690198092Srdivacky  if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
4691198398Srdivacky    if (T1->isMemberPointerType())
4692221345Sdim      E2 = ImpCastExprToType(E2, T1, CK_NullToMemberPointer).take();
4693198398Srdivacky    else
4694221345Sdim      E2 = ImpCastExprToType(E2, T1, CK_NullToPointer).take();
4695193326Sed    return T1;
4696193326Sed  }
4697198092Srdivacky
4698198092Srdivacky  // Now both have to be pointers or member pointers.
4699199482Srdivacky  if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
4700199482Srdivacky      (!T2->isPointerType() && !T2->isMemberPointerType()))
4701193326Sed    return QualType();
4702193326Sed
4703193326Sed  //   Otherwise, of one of the operands has type "pointer to cv1 void," then
4704193326Sed  //   the other has type "pointer to cv2 T" and the composite pointer type is
4705193326Sed  //   "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
4706193326Sed  //   Otherwise, the composite pointer type is a pointer type similar to the
4707193326Sed  //   type of one of the operands, with a cv-qualification signature that is
4708193326Sed  //   the union of the cv-qualification signatures of the operand types.
4709193326Sed  // In practice, the first part here is redundant; it's subsumed by the second.
4710193326Sed  // What we do here is, we build the two possible composite types, and try the
4711193326Sed  // conversions in both directions. If only one works, or if the two composite
4712193326Sed  // types are the same, we have succeeded.
4713198092Srdivacky  // FIXME: extended qualifiers?
4714226633Sdim  typedef SmallVector<unsigned, 4> QualifierVector;
4715199482Srdivacky  QualifierVector QualifierUnion;
4716226633Sdim  typedef SmallVector<std::pair<const Type *, const Type *>, 4>
4717199482Srdivacky      ContainingClassVector;
4718199482Srdivacky  ContainingClassVector MemberOfClass;
4719199482Srdivacky  QualType Composite1 = Context.getCanonicalType(T1),
4720199482Srdivacky           Composite2 = Context.getCanonicalType(T2);
4721218893Sdim  unsigned NeedConstBefore = 0;
4722198092Srdivacky  do {
4723198092Srdivacky    const PointerType *Ptr1, *Ptr2;
4724198092Srdivacky    if ((Ptr1 = Composite1->getAs<PointerType>()) &&
4725198092Srdivacky        (Ptr2 = Composite2->getAs<PointerType>())) {
4726198092Srdivacky      Composite1 = Ptr1->getPointeeType();
4727198092Srdivacky      Composite2 = Ptr2->getPointeeType();
4728218893Sdim
4729204643Srdivacky      // If we're allowed to create a non-standard composite type, keep track
4730218893Sdim      // of where we need to fill in additional 'const' qualifiers.
4731204643Srdivacky      if (NonStandardCompositeType &&
4732204643Srdivacky          Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
4733204643Srdivacky        NeedConstBefore = QualifierUnion.size();
4734218893Sdim
4735198092Srdivacky      QualifierUnion.push_back(
4736198092Srdivacky                 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
4737198092Srdivacky      MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
4738198092Srdivacky      continue;
4739198092Srdivacky    }
4740198092Srdivacky
4741198092Srdivacky    const MemberPointerType *MemPtr1, *MemPtr2;
4742198092Srdivacky    if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
4743198092Srdivacky        (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
4744198092Srdivacky      Composite1 = MemPtr1->getPointeeType();
4745198092Srdivacky      Composite2 = MemPtr2->getPointeeType();
4746218893Sdim
4747204643Srdivacky      // If we're allowed to create a non-standard composite type, keep track
4748218893Sdim      // of where we need to fill in additional 'const' qualifiers.
4749204643Srdivacky      if (NonStandardCompositeType &&
4750204643Srdivacky          Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
4751204643Srdivacky        NeedConstBefore = QualifierUnion.size();
4752218893Sdim
4753198092Srdivacky      QualifierUnion.push_back(
4754198092Srdivacky                 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
4755198092Srdivacky      MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
4756198092Srdivacky                                             MemPtr2->getClass()));
4757198092Srdivacky      continue;
4758198092Srdivacky    }
4759198092Srdivacky
4760198092Srdivacky    // FIXME: block pointer types?
4761198092Srdivacky
4762198092Srdivacky    // Cannot unwrap any more types.
4763198092Srdivacky    break;
4764198092Srdivacky  } while (true);
4765198092Srdivacky
4766204643Srdivacky  if (NeedConstBefore && NonStandardCompositeType) {
4767204643Srdivacky    // Extension: Add 'const' to qualifiers that come before the first qualifier
4768218893Sdim    // mismatch, so that our (non-standard!) composite type meets the
4769204643Srdivacky    // requirements of C++ [conv.qual]p4 bullet 3.
4770204643Srdivacky    for (unsigned I = 0; I != NeedConstBefore; ++I) {
4771204643Srdivacky      if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
4772204643Srdivacky        QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
4773204643Srdivacky        *NonStandardCompositeType = true;
4774204643Srdivacky      }
4775204643Srdivacky    }
4776204643Srdivacky  }
4777218893Sdim
4778198092Srdivacky  // Rewrap the composites as pointers or member pointers with the union CVRs.
4779199482Srdivacky  ContainingClassVector::reverse_iterator MOC
4780199482Srdivacky    = MemberOfClass.rbegin();
4781199482Srdivacky  for (QualifierVector::reverse_iterator
4782199482Srdivacky         I = QualifierUnion.rbegin(),
4783199482Srdivacky         E = QualifierUnion.rend();
4784198092Srdivacky       I != E; (void)++I, ++MOC) {
4785198092Srdivacky    Qualifiers Quals = Qualifiers::fromCVRMask(*I);
4786198092Srdivacky    if (MOC->first && MOC->second) {
4787198092Srdivacky      // Rebuild member pointer type
4788198092Srdivacky      Composite1 = Context.getMemberPointerType(
4789198092Srdivacky                                    Context.getQualifiedType(Composite1, Quals),
4790198092Srdivacky                                    MOC->first);
4791198092Srdivacky      Composite2 = Context.getMemberPointerType(
4792198092Srdivacky                                    Context.getQualifiedType(Composite2, Quals),
4793198092Srdivacky                                    MOC->second);
4794198092Srdivacky    } else {
4795198092Srdivacky      // Rebuild pointer type
4796198092Srdivacky      Composite1
4797198092Srdivacky        = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
4798198092Srdivacky      Composite2
4799198092Srdivacky        = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
4800198092Srdivacky    }
4801193326Sed  }
4802193326Sed
4803207619Srdivacky  // Try to convert to the first composite pointer type.
4804207619Srdivacky  InitializedEntity Entity1
4805207619Srdivacky    = InitializedEntity::InitializeTemporary(Composite1);
4806207619Srdivacky  InitializationKind Kind
4807207619Srdivacky    = InitializationKind::CreateCopy(Loc, SourceLocation());
4808251662Sdim  InitializationSequence E1ToC1(*this, Entity1, Kind, E1);
4809251662Sdim  InitializationSequence E2ToC1(*this, Entity1, Kind, E2);
4810198092Srdivacky
4811207619Srdivacky  if (E1ToC1 && E2ToC1) {
4812207619Srdivacky    // Conversion to Composite1 is viable.
4813207619Srdivacky    if (!Context.hasSameType(Composite1, Composite2)) {
4814207619Srdivacky      // Composite2 is a different type from Composite1. Check whether
4815207619Srdivacky      // Composite2 is also viable.
4816207619Srdivacky      InitializedEntity Entity2
4817207619Srdivacky        = InitializedEntity::InitializeTemporary(Composite2);
4818251662Sdim      InitializationSequence E1ToC2(*this, Entity2, Kind, E1);
4819251662Sdim      InitializationSequence E2ToC2(*this, Entity2, Kind, E2);
4820207619Srdivacky      if (E1ToC2 && E2ToC2) {
4821207619Srdivacky        // Both Composite1 and Composite2 are viable and are different;
4822207619Srdivacky        // this is an ambiguity.
4823207619Srdivacky        return QualType();
4824207619Srdivacky      }
4825207619Srdivacky    }
4826207619Srdivacky
4827207619Srdivacky    // Convert E1 to Composite1
4828212904Sdim    ExprResult E1Result
4829243830Sdim      = E1ToC1.Perform(*this, Entity1, Kind, E1);
4830207619Srdivacky    if (E1Result.isInvalid())
4831207619Srdivacky      return QualType();
4832207619Srdivacky    E1 = E1Result.takeAs<Expr>();
4833207619Srdivacky
4834207619Srdivacky    // Convert E2 to Composite1
4835212904Sdim    ExprResult E2Result
4836243830Sdim      = E2ToC1.Perform(*this, Entity1, Kind, E2);
4837207619Srdivacky    if (E2Result.isInvalid())
4838207619Srdivacky      return QualType();
4839207619Srdivacky    E2 = E2Result.takeAs<Expr>();
4840218893Sdim
4841207619Srdivacky    return Composite1;
4842193326Sed  }
4843193326Sed
4844207619Srdivacky  // Check whether Composite2 is viable.
4845207619Srdivacky  InitializedEntity Entity2
4846207619Srdivacky    = InitializedEntity::InitializeTemporary(Composite2);
4847251662Sdim  InitializationSequence E1ToC2(*this, Entity2, Kind, E1);
4848251662Sdim  InitializationSequence E2ToC2(*this, Entity2, Kind, E2);
4849207619Srdivacky  if (!E1ToC2 || !E2ToC2)
4850207619Srdivacky    return QualType();
4851218893Sdim
4852207619Srdivacky  // Convert E1 to Composite2
4853212904Sdim  ExprResult E1Result
4854243830Sdim    = E1ToC2.Perform(*this, Entity2, Kind, E1);
4855207619Srdivacky  if (E1Result.isInvalid())
4856207619Srdivacky    return QualType();
4857207619Srdivacky  E1 = E1Result.takeAs<Expr>();
4858218893Sdim
4859207619Srdivacky  // Convert E2 to Composite2
4860212904Sdim  ExprResult E2Result
4861243830Sdim    = E2ToC2.Perform(*this, Entity2, Kind, E2);
4862207619Srdivacky  if (E2Result.isInvalid())
4863207619Srdivacky    return QualType();
4864207619Srdivacky  E2 = E2Result.takeAs<Expr>();
4865218893Sdim
4866207619Srdivacky  return Composite2;
4867193326Sed}
4868193326Sed
4869212904SdimExprResult Sema::MaybeBindToTemporary(Expr *E) {
4870218893Sdim  if (!E)
4871218893Sdim    return ExprError();
4872218893Sdim
4873224145Sdim  assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
4874224145Sdim
4875224145Sdim  // If the result is a glvalue, we shouldn't bind it.
4876224145Sdim  if (!E->isRValue())
4877198092Srdivacky    return Owned(E);
4878198092Srdivacky
4879224145Sdim  // In ARC, calls that return a retainable type can return retained,
4880224145Sdim  // in which case we have to insert a consuming cast.
4881234353Sdim  if (getLangOpts().ObjCAutoRefCount &&
4882224145Sdim      E->getType()->isObjCRetainableType()) {
4883201361Srdivacky
4884224145Sdim    bool ReturnsRetained;
4885224145Sdim
4886224145Sdim    // For actual calls, we compute this by examining the type of the
4887224145Sdim    // called value.
4888224145Sdim    if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
4889224145Sdim      Expr *Callee = Call->getCallee()->IgnoreParens();
4890224145Sdim      QualType T = Callee->getType();
4891224145Sdim
4892224145Sdim      if (T == Context.BoundMemberTy) {
4893224145Sdim        // Handle pointer-to-members.
4894224145Sdim        if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
4895224145Sdim          T = BinOp->getRHS()->getType();
4896224145Sdim        else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
4897224145Sdim          T = Mem->getMemberDecl()->getType();
4898224145Sdim      }
4899224145Sdim
4900224145Sdim      if (const PointerType *Ptr = T->getAs<PointerType>())
4901224145Sdim        T = Ptr->getPointeeType();
4902224145Sdim      else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
4903224145Sdim        T = Ptr->getPointeeType();
4904224145Sdim      else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
4905224145Sdim        T = MemPtr->getPointeeType();
4906224145Sdim
4907224145Sdim      const FunctionType *FTy = T->getAs<FunctionType>();
4908224145Sdim      assert(FTy && "call to value not of function type?");
4909224145Sdim      ReturnsRetained = FTy->getExtInfo().getProducesResult();
4910224145Sdim
4911224145Sdim    // ActOnStmtExpr arranges things so that StmtExprs of retainable
4912224145Sdim    // type always produce a +1 object.
4913224145Sdim    } else if (isa<StmtExpr>(E)) {
4914224145Sdim      ReturnsRetained = true;
4915224145Sdim
4916234353Sdim    // We hit this case with the lambda conversion-to-block optimization;
4917234353Sdim    // we don't want any extra casts here.
4918234353Sdim    } else if (isa<CastExpr>(E) &&
4919234353Sdim               isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) {
4920234353Sdim      return Owned(E);
4921234353Sdim
4922224145Sdim    // For message sends and property references, we try to find an
4923224145Sdim    // actual method.  FIXME: we should infer retention by selector in
4924224145Sdim    // cases where we don't have an actual method.
4925224145Sdim    } else {
4926226633Sdim      ObjCMethodDecl *D = 0;
4927224145Sdim      if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
4928224145Sdim        D = Send->getMethodDecl();
4929239462Sdim      } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {
4930239462Sdim        D = BoxedExpr->getBoxingMethod();
4931234353Sdim      } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) {
4932234353Sdim        D = ArrayLit->getArrayWithObjectsMethod();
4933234353Sdim      } else if (ObjCDictionaryLiteral *DictLit
4934234353Sdim                                        = dyn_cast<ObjCDictionaryLiteral>(E)) {
4935234353Sdim        D = DictLit->getDictWithObjectsMethod();
4936224145Sdim      }
4937224145Sdim
4938224145Sdim      ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
4939226633Sdim
4940226633Sdim      // Don't do reclaims on performSelector calls; despite their
4941226633Sdim      // return type, the invoked method doesn't necessarily actually
4942226633Sdim      // return an object.
4943226633Sdim      if (!ReturnsRetained &&
4944226633Sdim          D && D->getMethodFamily() == OMF_performSelector)
4945226633Sdim        return Owned(E);
4946224145Sdim    }
4947224145Sdim
4948234353Sdim    // Don't reclaim an object of Class type.
4949234353Sdim    if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
4950234353Sdim      return Owned(E);
4951234353Sdim
4952224145Sdim    ExprNeedsCleanups = true;
4953224145Sdim
4954226633Sdim    CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
4955226633Sdim                                   : CK_ARCReclaimReturnedObject);
4956224145Sdim    return Owned(ImplicitCastExpr::Create(Context, E->getType(), ck, E, 0,
4957224145Sdim                                          VK_RValue));
4958224145Sdim  }
4959224145Sdim
4960234353Sdim  if (!getLangOpts().CPlusPlus)
4961224145Sdim    return Owned(E);
4962224145Sdim
4963234353Sdim  // Search for the base element type (cf. ASTContext::getBaseElementType) with
4964234353Sdim  // a fast path for the common case that the type is directly a RecordType.
4965234353Sdim  const Type *T = Context.getCanonicalType(E->getType().getTypePtr());
4966234353Sdim  const RecordType *RT = 0;
4967234353Sdim  while (!RT) {
4968234353Sdim    switch (T->getTypeClass()) {
4969234353Sdim    case Type::Record:
4970234353Sdim      RT = cast<RecordType>(T);
4971234353Sdim      break;
4972234353Sdim    case Type::ConstantArray:
4973234353Sdim    case Type::IncompleteArray:
4974234353Sdim    case Type::VariableArray:
4975234353Sdim    case Type::DependentSizedArray:
4976234353Sdim      T = cast<ArrayType>(T)->getElementType().getTypePtr();
4977234353Sdim      break;
4978234353Sdim    default:
4979234353Sdim      return Owned(E);
4980234353Sdim    }
4981234353Sdim  }
4982198092Srdivacky
4983234353Sdim  // That should be enough to guarantee that this type is complete, if we're
4984234353Sdim  // not processing a decltype expression.
4985203955Srdivacky  CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4986234353Sdim  if (RD->isInvalidDecl() || RD->isDependentContext())
4987203955Srdivacky    return Owned(E);
4988203955Srdivacky
4989234353Sdim  bool IsDecltype = ExprEvalContexts.back().IsDecltype;
4990234353Sdim  CXXDestructorDecl *Destructor = IsDecltype ? 0 : LookupDestructor(RD);
4991224145Sdim
4992224145Sdim  if (Destructor) {
4993234353Sdim    MarkFunctionReferenced(E->getExprLoc(), Destructor);
4994207619Srdivacky    CheckDestructorAccess(E->getExprLoc(), Destructor,
4995207619Srdivacky                          PDiag(diag::err_access_dtor_temp)
4996207619Srdivacky                            << E->getType());
4997251662Sdim    if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
4998251662Sdim      return ExprError();
4999224145Sdim
5000234353Sdim    // If destructor is trivial, we can avoid the extra copy.
5001234353Sdim    if (Destructor->isTrivial())
5002234353Sdim      return Owned(E);
5003234353Sdim
5004234353Sdim    // We need a cleanup, but we don't need to remember the temporary.
5005224145Sdim    ExprNeedsCleanups = true;
5006207619Srdivacky  }
5007193326Sed
5008234353Sdim  CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
5009234353Sdim  CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E);
5010198092Srdivacky
5011234353Sdim  if (IsDecltype)
5012234353Sdim    ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind);
5013198092Srdivacky
5014234353Sdim  return Owned(Bind);
5015193576Sed}
5016193576Sed
5017218893SdimExprResult
5018218893SdimSema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
5019201361Srdivacky  if (SubExpr.isInvalid())
5020201361Srdivacky    return ExprError();
5021218893Sdim
5022218893Sdim  return Owned(MaybeCreateExprWithCleanups(SubExpr.take()));
5023201361Srdivacky}
5024201361Srdivacky
5025234353SdimExpr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
5026234353Sdim  assert(SubExpr && "sub expression can't be null!");
5027234353Sdim
5028234353Sdim  CleanupVarDeclMarking();
5029234353Sdim
5030234353Sdim  unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
5031234353Sdim  assert(ExprCleanupObjects.size() >= FirstCleanup);
5032234353Sdim  assert(ExprNeedsCleanups || ExprCleanupObjects.size() == FirstCleanup);
5033234353Sdim  if (!ExprNeedsCleanups)
5034234353Sdim    return SubExpr;
5035234353Sdim
5036234353Sdim  ArrayRef<ExprWithCleanups::CleanupObject> Cleanups
5037234353Sdim    = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
5038234353Sdim                         ExprCleanupObjects.size() - FirstCleanup);
5039234353Sdim
5040234353Sdim  Expr *E = ExprWithCleanups::Create(Context, SubExpr, Cleanups);
5041234353Sdim  DiscardCleanupsInEvaluationContext();
5042234353Sdim
5043234353Sdim  return E;
5044234353Sdim}
5045234353Sdim
5046218893SdimStmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
5047218893Sdim  assert(SubStmt && "sub statement can't be null!");
5048218893Sdim
5049234353Sdim  CleanupVarDeclMarking();
5050234353Sdim
5051224145Sdim  if (!ExprNeedsCleanups)
5052218893Sdim    return SubStmt;
5053201361Srdivacky
5054218893Sdim  // FIXME: In order to attach the temporaries, wrap the statement into
5055218893Sdim  // a StmtExpr; currently this is only used for asm statements.
5056218893Sdim  // This is hacky, either create a new CXXStmtWithTemporaries statement or
5057218893Sdim  // a new AsmStmtWithTemporaries.
5058249423Sdim  CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, SubStmt,
5059218893Sdim                                                      SourceLocation(),
5060218893Sdim                                                      SourceLocation());
5061218893Sdim  Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
5062218893Sdim                                   SourceLocation());
5063218893Sdim  return MaybeCreateExprWithCleanups(E);
5064201361Srdivacky}
5065201361Srdivacky
5066234353Sdim/// Process the expression contained within a decltype. For such expressions,
5067234353Sdim/// certain semantic checks on temporaries are delayed until this point, and
5068234353Sdim/// are omitted for the 'topmost' call in the decltype expression. If the
5069234353Sdim/// topmost call bound a temporary, strip that temporary off the expression.
5070234353SdimExprResult Sema::ActOnDecltypeExpression(Expr *E) {
5071249423Sdim  assert(ExprEvalContexts.back().IsDecltype && "not in a decltype expression");
5072234353Sdim
5073234353Sdim  // C++11 [expr.call]p11:
5074234353Sdim  //   If a function call is a prvalue of object type,
5075234353Sdim  // -- if the function call is either
5076234353Sdim  //   -- the operand of a decltype-specifier, or
5077234353Sdim  //   -- the right operand of a comma operator that is the operand of a
5078234353Sdim  //      decltype-specifier,
5079234353Sdim  //   a temporary object is not introduced for the prvalue.
5080234353Sdim
5081234353Sdim  // Recursively rebuild ParenExprs and comma expressions to strip out the
5082234353Sdim  // outermost CXXBindTemporaryExpr, if any.
5083234353Sdim  if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
5084234353Sdim    ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr());
5085234353Sdim    if (SubExpr.isInvalid())
5086234353Sdim      return ExprError();
5087234353Sdim    if (SubExpr.get() == PE->getSubExpr())
5088234353Sdim      return Owned(E);
5089234353Sdim    return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.take());
5090234353Sdim  }
5091234353Sdim  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5092234353Sdim    if (BO->getOpcode() == BO_Comma) {
5093234353Sdim      ExprResult RHS = ActOnDecltypeExpression(BO->getRHS());
5094234353Sdim      if (RHS.isInvalid())
5095234353Sdim        return ExprError();
5096234353Sdim      if (RHS.get() == BO->getRHS())
5097234353Sdim        return Owned(E);
5098234353Sdim      return Owned(new (Context) BinaryOperator(BO->getLHS(), RHS.take(),
5099234353Sdim                                                BO_Comma, BO->getType(),
5100234353Sdim                                                BO->getValueKind(),
5101234353Sdim                                                BO->getObjectKind(),
5102243830Sdim                                                BO->getOperatorLoc(),
5103243830Sdim                                                BO->isFPContractable()));
5104234353Sdim    }
5105234353Sdim  }
5106234353Sdim
5107234353Sdim  CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E);
5108234353Sdim  if (TopBind)
5109234353Sdim    E = TopBind->getSubExpr();
5110234353Sdim
5111234353Sdim  // Disable the special decltype handling now.
5112249423Sdim  ExprEvalContexts.back().IsDecltype = false;
5113234353Sdim
5114239462Sdim  // In MS mode, don't perform any extra checking of call return types within a
5115239462Sdim  // decltype expression.
5116239462Sdim  if (getLangOpts().MicrosoftMode)
5117239462Sdim    return Owned(E);
5118239462Sdim
5119234353Sdim  // Perform the semantic checks we delayed until this point.
5120234353Sdim  CallExpr *TopCall = dyn_cast<CallExpr>(E);
5121249423Sdim  for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size();
5122249423Sdim       I != N; ++I) {
5123249423Sdim    CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I];
5124234353Sdim    if (Call == TopCall)
5125234353Sdim      continue;
5126234353Sdim
5127234353Sdim    if (CheckCallReturnType(Call->getCallReturnType(),
5128234353Sdim                            Call->getLocStart(),
5129234353Sdim                            Call, Call->getDirectCallee()))
5130234353Sdim      return ExprError();
5131234353Sdim  }
5132234353Sdim
5133234353Sdim  // Now all relevant types are complete, check the destructors are accessible
5134234353Sdim  // and non-deleted, and annotate them on the temporaries.
5135249423Sdim  for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size();
5136249423Sdim       I != N; ++I) {
5137249423Sdim    CXXBindTemporaryExpr *Bind =
5138249423Sdim      ExprEvalContexts.back().DelayedDecltypeBinds[I];
5139234353Sdim    if (Bind == TopBind)
5140234353Sdim      continue;
5141234353Sdim
5142234353Sdim    CXXTemporary *Temp = Bind->getTemporary();
5143234353Sdim
5144234353Sdim    CXXRecordDecl *RD =
5145234353Sdim      Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
5146234353Sdim    CXXDestructorDecl *Destructor = LookupDestructor(RD);
5147234353Sdim    Temp->setDestructor(Destructor);
5148234353Sdim
5149239462Sdim    MarkFunctionReferenced(Bind->getExprLoc(), Destructor);
5150239462Sdim    CheckDestructorAccess(Bind->getExprLoc(), Destructor,
5151234353Sdim                          PDiag(diag::err_access_dtor_temp)
5152239462Sdim                            << Bind->getType());
5153251662Sdim    if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc()))
5154251662Sdim      return ExprError();
5155234353Sdim
5156234353Sdim    // We need a cleanup, but we don't need to remember the temporary.
5157234353Sdim    ExprNeedsCleanups = true;
5158234353Sdim  }
5159234353Sdim
5160234353Sdim  // Possibly strip off the top CXXBindTemporaryExpr.
5161234353Sdim  return Owned(E);
5162234353Sdim}
5163234353Sdim
5164263508Sdim/// Note a set of 'operator->' functions that were used for a member access.
5165263508Sdimstatic void noteOperatorArrows(Sema &S,
5166263508Sdim                               llvm::ArrayRef<FunctionDecl *> OperatorArrows) {
5167263508Sdim  unsigned SkipStart = OperatorArrows.size(), SkipCount = 0;
5168263508Sdim  // FIXME: Make this configurable?
5169263508Sdim  unsigned Limit = 9;
5170263508Sdim  if (OperatorArrows.size() > Limit) {
5171263508Sdim    // Produce Limit-1 normal notes and one 'skipping' note.
5172263508Sdim    SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2;
5173263508Sdim    SkipCount = OperatorArrows.size() - (Limit - 1);
5174263508Sdim  }
5175263508Sdim
5176263508Sdim  for (unsigned I = 0; I < OperatorArrows.size(); /**/) {
5177263508Sdim    if (I == SkipStart) {
5178263508Sdim      S.Diag(OperatorArrows[I]->getLocation(),
5179263508Sdim             diag::note_operator_arrows_suppressed)
5180263508Sdim          << SkipCount;
5181263508Sdim      I += SkipCount;
5182263508Sdim    } else {
5183263508Sdim      S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here)
5184263508Sdim          << OperatorArrows[I]->getCallResultType();
5185263508Sdim      ++I;
5186263508Sdim    }
5187263508Sdim  }
5188263508Sdim}
5189263508Sdim
5190212904SdimExprResult
5191212904SdimSema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc,
5192212904Sdim                                   tok::TokenKind OpKind, ParsedType &ObjectType,
5193204643Srdivacky                                   bool &MayBePseudoDestructor) {
5194198092Srdivacky  // Since this might be a postfix expression, get rid of ParenListExprs.
5195212904Sdim  ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
5196212904Sdim  if (Result.isInvalid()) return ExprError();
5197212904Sdim  Base = Result.get();
5198198092Srdivacky
5199234353Sdim  Result = CheckPlaceholderExpr(Base);
5200234353Sdim  if (Result.isInvalid()) return ExprError();
5201234353Sdim  Base = Result.take();
5202234353Sdim
5203212904Sdim  QualType BaseType = Base->getType();
5204204643Srdivacky  MayBePseudoDestructor = false;
5205198092Srdivacky  if (BaseType->isDependentType()) {
5206198954Srdivacky    // If we have a pointer to a dependent type and are using the -> operator,
5207198954Srdivacky    // the object type is the type that the pointer points to. We might still
5208198954Srdivacky    // have enough information about that type to do something useful.
5209198954Srdivacky    if (OpKind == tok::arrow)
5210198954Srdivacky      if (const PointerType *Ptr = BaseType->getAs<PointerType>())
5211198954Srdivacky        BaseType = Ptr->getPointeeType();
5212218893Sdim
5213212904Sdim    ObjectType = ParsedType::make(BaseType);
5214204643Srdivacky    MayBePseudoDestructor = true;
5215212904Sdim    return Owned(Base);
5216198092Srdivacky  }
5217198092Srdivacky
5218198092Srdivacky  // C++ [over.match.oper]p8:
5219198092Srdivacky  //   [...] When operator->returns, the operator-> is applied  to the value
5220198092Srdivacky  //   returned, with the original second operand.
5221198092Srdivacky  if (OpKind == tok::arrow) {
5222263508Sdim    QualType StartingType = BaseType;
5223263508Sdim    bool NoArrowOperatorFound = false;
5224263508Sdim    bool FirstIteration = true;
5225263508Sdim    FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext);
5226198092Srdivacky    // The set of types we've considered so far.
5227198092Srdivacky    llvm::SmallPtrSet<CanQualType,8> CTypes;
5228263508Sdim    SmallVector<FunctionDecl*, 8> OperatorArrows;
5229198092Srdivacky    CTypes.insert(Context.getCanonicalType(BaseType));
5230218893Sdim
5231198092Srdivacky    while (BaseType->isRecordType()) {
5232263508Sdim      if (OperatorArrows.size() >= getLangOpts().ArrowDepth) {
5233263508Sdim        Diag(OpLoc, diag::err_operator_arrow_depth_exceeded)
5234263508Sdim          << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange();
5235263508Sdim        noteOperatorArrows(*this, OperatorArrows);
5236263508Sdim        Diag(OpLoc, diag::note_operator_arrow_depth)
5237263508Sdim          << getLangOpts().ArrowDepth;
5238198092Srdivacky        return ExprError();
5239263508Sdim      }
5240263508Sdim
5241263508Sdim      Result = BuildOverloadedArrowExpr(
5242263508Sdim          S, Base, OpLoc,
5243263508Sdim          // When in a template specialization and on the first loop iteration,
5244263508Sdim          // potentially give the default diagnostic (with the fixit in a
5245263508Sdim          // separate note) instead of having the error reported back to here
5246263508Sdim          // and giving a diagnostic with a fixit attached to the error itself.
5247263508Sdim          (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization())
5248263508Sdim              ? 0
5249263508Sdim              : &NoArrowOperatorFound);
5250263508Sdim      if (Result.isInvalid()) {
5251263508Sdim        if (NoArrowOperatorFound) {
5252263508Sdim          if (FirstIteration) {
5253263508Sdim            Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
5254263508Sdim              << BaseType << 1 << Base->getSourceRange()
5255263508Sdim              << FixItHint::CreateReplacement(OpLoc, ".");
5256263508Sdim            OpKind = tok::period;
5257263508Sdim            break;
5258263508Sdim          }
5259263508Sdim          Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
5260263508Sdim            << BaseType << Base->getSourceRange();
5261263508Sdim          CallExpr *CE = dyn_cast<CallExpr>(Base);
5262263508Sdim          if (Decl *CD = (CE ? CE->getCalleeDecl() : 0)) {
5263263508Sdim            Diag(CD->getLocStart(),
5264263508Sdim                 diag::note_member_reference_arrow_from_operator_arrow);
5265263508Sdim          }
5266263508Sdim        }
5267263508Sdim        return ExprError();
5268263508Sdim      }
5269212904Sdim      Base = Result.get();
5270212904Sdim      if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
5271263508Sdim        OperatorArrows.push_back(OpCall->getDirectCallee());
5272212904Sdim      BaseType = Base->getType();
5273198092Srdivacky      CanQualType CBaseType = Context.getCanonicalType(BaseType);
5274198092Srdivacky      if (!CTypes.insert(CBaseType)) {
5275263508Sdim        Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType;
5276263508Sdim        noteOperatorArrows(*this, OperatorArrows);
5277198092Srdivacky        return ExprError();
5278198092Srdivacky      }
5279263508Sdim      FirstIteration = false;
5280198092Srdivacky    }
5281199990Srdivacky
5282263508Sdim    if (OpKind == tok::arrow &&
5283263508Sdim        (BaseType->isPointerType() || BaseType->isObjCObjectPointerType()))
5284199990Srdivacky      BaseType = BaseType->getPointeeType();
5285198092Srdivacky  }
5286198092Srdivacky
5287234353Sdim  // Objective-C properties allow "." access on Objective-C pointer types,
5288234353Sdim  // so adjust the base type to the object type itself.
5289234353Sdim  if (BaseType->isObjCObjectPointerType())
5290234353Sdim    BaseType = BaseType->getPointeeType();
5291234353Sdim
5292234353Sdim  // C++ [basic.lookup.classref]p2:
5293234353Sdim  //   [...] If the type of the object expression is of pointer to scalar
5294234353Sdim  //   type, the unqualified-id is looked up in the context of the complete
5295234353Sdim  //   postfix-expression.
5296234353Sdim  //
5297234353Sdim  // This also indicates that we could be parsing a pseudo-destructor-name.
5298234353Sdim  // Note that Objective-C class and object types can be pseudo-destructor
5299234353Sdim  // expressions or normal member (ivar or property) access expressions.
5300234353Sdim  if (BaseType->isObjCObjectOrInterfaceType()) {
5301234353Sdim    MayBePseudoDestructor = true;
5302234353Sdim  } else if (!BaseType->isRecordType()) {
5303212904Sdim    ObjectType = ParsedType();
5304204643Srdivacky    MayBePseudoDestructor = true;
5305212904Sdim    return Owned(Base);
5306198092Srdivacky  }
5307198092Srdivacky
5308234982Sdim  // The object type must be complete (or dependent), or
5309234982Sdim  // C++11 [expr.prim.general]p3:
5310234982Sdim  //   Unlike the object expression in other contexts, *this is not required to
5311234982Sdim  //   be of complete type for purposes of class member access (5.2.5) outside
5312234982Sdim  //   the member function body.
5313199482Srdivacky  if (!BaseType->isDependentType() &&
5314234982Sdim      !isThisOutsideMemberFunctionBody(BaseType) &&
5315239462Sdim      RequireCompleteType(OpLoc, BaseType, diag::err_incomplete_member_access))
5316199482Srdivacky    return ExprError();
5317218893Sdim
5318198092Srdivacky  // C++ [basic.lookup.classref]p2:
5319198092Srdivacky  //   If the id-expression in a class member access (5.2.5) is an
5320199482Srdivacky  //   unqualified-id, and the type of the object expression is of a class
5321198092Srdivacky  //   type C (or of pointer to a class type C), the unqualified-id is looked
5322198092Srdivacky  //   up in the scope of class C. [...]
5323212904Sdim  ObjectType = ParsedType::make(BaseType);
5324243830Sdim  return Base;
5325198092Srdivacky}
5326198092Srdivacky
5327212904SdimExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
5328212904Sdim                                                   Expr *MemExpr) {
5329204643Srdivacky  SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
5330212904Sdim  Diag(MemExpr->getLocStart(), diag::err_dtor_expr_without_call)
5331212904Sdim    << isa<CXXPseudoDestructorExpr>(MemExpr)
5332206084Srdivacky    << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
5333218893Sdim
5334204643Srdivacky  return ActOnCallExpr(/*Scope*/ 0,
5335212904Sdim                       MemExpr,
5336204643Srdivacky                       /*LPLoc*/ ExpectedLParenLoc,
5337251662Sdim                       None,
5338204643Srdivacky                       /*RPLoc*/ ExpectedLParenLoc);
5339204643Srdivacky}
5340204643Srdivacky
5341234353Sdimstatic bool CheckArrow(Sema& S, QualType& ObjectType, Expr *&Base,
5342234353Sdim                   tok::TokenKind& OpKind, SourceLocation OpLoc) {
5343234353Sdim  if (Base->hasPlaceholderType()) {
5344234353Sdim    ExprResult result = S.CheckPlaceholderExpr(Base);
5345234353Sdim    if (result.isInvalid()) return true;
5346234353Sdim    Base = result.take();
5347234353Sdim  }
5348234353Sdim  ObjectType = Base->getType();
5349218893Sdim
5350204643Srdivacky  // C++ [expr.pseudo]p2:
5351218893Sdim  //   The left-hand side of the dot operator shall be of scalar type. The
5352204643Srdivacky  //   left-hand side of the arrow operator shall be of pointer to scalar type.
5353218893Sdim  //   This scalar type is the object type.
5354234353Sdim  // Note that this is rather different from the normal handling for the
5355234353Sdim  // arrow operator.
5356204643Srdivacky  if (OpKind == tok::arrow) {
5357204643Srdivacky    if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
5358204643Srdivacky      ObjectType = Ptr->getPointeeType();
5359212904Sdim    } else if (!Base->isTypeDependent()) {
5360204643Srdivacky      // The user wrote "p->" when she probably meant "p."; fix it.
5361234353Sdim      S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
5362204643Srdivacky        << ObjectType << true
5363206084Srdivacky        << FixItHint::CreateReplacement(OpLoc, ".");
5364234353Sdim      if (S.isSFINAEContext())
5365234353Sdim        return true;
5366218893Sdim
5367204643Srdivacky      OpKind = tok::period;
5368204643Srdivacky    }
5369204643Srdivacky  }
5370218893Sdim
5371234353Sdim  return false;
5372234353Sdim}
5373234353Sdim
5374234353SdimExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
5375234353Sdim                                           SourceLocation OpLoc,
5376234353Sdim                                           tok::TokenKind OpKind,
5377234353Sdim                                           const CXXScopeSpec &SS,
5378234353Sdim                                           TypeSourceInfo *ScopeTypeInfo,
5379234353Sdim                                           SourceLocation CCLoc,
5380234353Sdim                                           SourceLocation TildeLoc,
5381234353Sdim                                         PseudoDestructorTypeStorage Destructed,
5382234353Sdim                                           bool HasTrailingLParen) {
5383234353Sdim  TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
5384234353Sdim
5385234353Sdim  QualType ObjectType;
5386234353Sdim  if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
5387234353Sdim    return ExprError();
5388234353Sdim
5389243830Sdim  if (!ObjectType->isDependentType() && !ObjectType->isScalarType() &&
5390243830Sdim      !ObjectType->isVectorType()) {
5391234353Sdim    if (getLangOpts().MicrosoftMode && ObjectType->isVoidType())
5392234353Sdim      Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
5393234353Sdim    else
5394234353Sdim      Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
5395234353Sdim        << ObjectType << Base->getSourceRange();
5396204643Srdivacky    return ExprError();
5397204643Srdivacky  }
5398204643Srdivacky
5399204643Srdivacky  // C++ [expr.pseudo]p2:
5400218893Sdim  //   [...] The cv-unqualified versions of the object type and of the type
5401204643Srdivacky  //   designated by the pseudo-destructor-name shall be the same type.
5402204643Srdivacky  if (DestructedTypeInfo) {
5403204643Srdivacky    QualType DestructedType = DestructedTypeInfo->getType();
5404204643Srdivacky    SourceLocation DestructedTypeStart
5405208600Srdivacky      = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
5406224145Sdim    if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
5407224145Sdim      if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
5408224145Sdim        Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
5409224145Sdim          << ObjectType << DestructedType << Base->getSourceRange()
5410224145Sdim          << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
5411218893Sdim
5412224145Sdim        // Recover by setting the destructed type to the object type.
5413224145Sdim        DestructedType = ObjectType;
5414224145Sdim        DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
5415204643Srdivacky                                                           DestructedTypeStart);
5416224145Sdim        Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
5417224145Sdim      } else if (DestructedType.getObjCLifetime() !=
5418224145Sdim                                                ObjectType.getObjCLifetime()) {
5419224145Sdim
5420224145Sdim        if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
5421224145Sdim          // Okay: just pretend that the user provided the correctly-qualified
5422224145Sdim          // type.
5423224145Sdim        } else {
5424224145Sdim          Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
5425224145Sdim            << ObjectType << DestructedType << Base->getSourceRange()
5426224145Sdim            << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
5427224145Sdim        }
5428224145Sdim
5429224145Sdim        // Recover by setting the destructed type to the object type.
5430224145Sdim        DestructedType = ObjectType;
5431224145Sdim        DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
5432224145Sdim                                                           DestructedTypeStart);
5433224145Sdim        Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
5434224145Sdim      }
5435204643Srdivacky    }
5436204643Srdivacky  }
5437218893Sdim
5438204643Srdivacky  // C++ [expr.pseudo]p2:
5439204643Srdivacky  //   [...] Furthermore, the two type-names in a pseudo-destructor-name of the
5440204643Srdivacky  //   form
5441204643Srdivacky  //
5442218893Sdim  //     ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
5443204643Srdivacky  //
5444204643Srdivacky  //   shall designate the same scalar type.
5445204643Srdivacky  if (ScopeTypeInfo) {
5446204643Srdivacky    QualType ScopeType = ScopeTypeInfo->getType();
5447204643Srdivacky    if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
5448210299Sed        !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
5449218893Sdim
5450208600Srdivacky      Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
5451204643Srdivacky           diag::err_pseudo_dtor_type_mismatch)
5452212904Sdim        << ObjectType << ScopeType << Base->getSourceRange()
5453208600Srdivacky        << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
5454218893Sdim
5455204643Srdivacky      ScopeType = QualType();
5456204643Srdivacky      ScopeTypeInfo = 0;
5457204643Srdivacky    }
5458204643Srdivacky  }
5459218893Sdim
5460212904Sdim  Expr *Result
5461212904Sdim    = new (Context) CXXPseudoDestructorExpr(Context, Base,
5462212904Sdim                                            OpKind == tok::arrow, OpLoc,
5463219077Sdim                                            SS.getWithLocInContext(Context),
5464212904Sdim                                            ScopeTypeInfo,
5465212904Sdim                                            CCLoc,
5466212904Sdim                                            TildeLoc,
5467212904Sdim                                            Destructed);
5468218893Sdim
5469204643Srdivacky  if (HasTrailingLParen)
5470212904Sdim    return Owned(Result);
5471218893Sdim
5472212904Sdim  return DiagnoseDtorReference(Destructed.getLocation(), Result);
5473204643Srdivacky}
5474204643Srdivacky
5475212904SdimExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
5476219077Sdim                                           SourceLocation OpLoc,
5477219077Sdim                                           tok::TokenKind OpKind,
5478219077Sdim                                           CXXScopeSpec &SS,
5479219077Sdim                                           UnqualifiedId &FirstTypeName,
5480219077Sdim                                           SourceLocation CCLoc,
5481219077Sdim                                           SourceLocation TildeLoc,
5482219077Sdim                                           UnqualifiedId &SecondTypeName,
5483219077Sdim                                           bool HasTrailingLParen) {
5484204643Srdivacky  assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
5485204643Srdivacky          FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
5486204643Srdivacky         "Invalid first type name in pseudo-destructor");
5487204643Srdivacky  assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
5488204643Srdivacky          SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
5489204643Srdivacky         "Invalid second type name in pseudo-destructor");
5490204643Srdivacky
5491234353Sdim  QualType ObjectType;
5492234353Sdim  if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
5493234353Sdim    return ExprError();
5494218893Sdim
5495204643Srdivacky  // Compute the object type that we should use for name lookup purposes. Only
5496204643Srdivacky  // record types and dependent types matter.
5497212904Sdim  ParsedType ObjectTypePtrForLookup;
5498204643Srdivacky  if (!SS.isSet()) {
5499219077Sdim    if (ObjectType->isRecordType())
5500219077Sdim      ObjectTypePtrForLookup = ParsedType::make(ObjectType);
5501212904Sdim    else if (ObjectType->isDependentType())
5502212904Sdim      ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
5503204643Srdivacky  }
5504218893Sdim
5505218893Sdim  // Convert the name of the type being destructed (following the ~) into a
5506204643Srdivacky  // type (with source-location information).
5507204643Srdivacky  QualType DestructedType;
5508204643Srdivacky  TypeSourceInfo *DestructedTypeInfo = 0;
5509204643Srdivacky  PseudoDestructorTypeStorage Destructed;
5510204643Srdivacky  if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
5511218893Sdim    ParsedType T = getTypeName(*SecondTypeName.Identifier,
5512212904Sdim                               SecondTypeName.StartLocation,
5513218893Sdim                               S, &SS, true, false, ObjectTypePtrForLookup);
5514218893Sdim    if (!T &&
5515204643Srdivacky        ((SS.isSet() && !computeDeclContext(SS, false)) ||
5516204643Srdivacky         (!SS.isSet() && ObjectType->isDependentType()))) {
5517218893Sdim      // The name of the type being destroyed is a dependent name, and we
5518204643Srdivacky      // couldn't find anything useful in scope. Just store the identifier and
5519204643Srdivacky      // it's location, and we'll perform (qualified) name lookup again at
5520204643Srdivacky      // template instantiation time.
5521204643Srdivacky      Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
5522204643Srdivacky                                               SecondTypeName.StartLocation);
5523204643Srdivacky    } else if (!T) {
5524218893Sdim      Diag(SecondTypeName.StartLocation,
5525204643Srdivacky           diag::err_pseudo_dtor_destructor_non_type)
5526204643Srdivacky        << SecondTypeName.Identifier << ObjectType;
5527204643Srdivacky      if (isSFINAEContext())
5528204643Srdivacky        return ExprError();
5529218893Sdim
5530204643Srdivacky      // Recover by assuming we had the right type all along.
5531204643Srdivacky      DestructedType = ObjectType;
5532204643Srdivacky    } else
5533204643Srdivacky      DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
5534204643Srdivacky  } else {
5535204643Srdivacky    // Resolve the template-id to a type.
5536204643Srdivacky    TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
5537243830Sdim    ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
5538204643Srdivacky                                       TemplateId->NumArgs);
5539221345Sdim    TypeResult T = ActOnTemplateIdType(TemplateId->SS,
5540234353Sdim                                       TemplateId->TemplateKWLoc,
5541221345Sdim                                       TemplateId->Template,
5542204643Srdivacky                                       TemplateId->TemplateNameLoc,
5543204643Srdivacky                                       TemplateId->LAngleLoc,
5544204643Srdivacky                                       TemplateArgsPtr,
5545204643Srdivacky                                       TemplateId->RAngleLoc);
5546204643Srdivacky    if (T.isInvalid() || !T.get()) {
5547204643Srdivacky      // Recover by assuming we had the right type all along.
5548204643Srdivacky      DestructedType = ObjectType;
5549204643Srdivacky    } else
5550204643Srdivacky      DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
5551204643Srdivacky  }
5552218893Sdim
5553218893Sdim  // If we've performed some kind of recovery, (re-)build the type source
5554204643Srdivacky  // information.
5555204643Srdivacky  if (!DestructedType.isNull()) {
5556204643Srdivacky    if (!DestructedTypeInfo)
5557204643Srdivacky      DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
5558204643Srdivacky                                                  SecondTypeName.StartLocation);
5559204643Srdivacky    Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
5560204643Srdivacky  }
5561218893Sdim
5562204643Srdivacky  // Convert the name of the scope type (the type prior to '::') into a type.
5563204643Srdivacky  TypeSourceInfo *ScopeTypeInfo = 0;
5564204643Srdivacky  QualType ScopeType;
5565218893Sdim  if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
5566204643Srdivacky      FirstTypeName.Identifier) {
5567204643Srdivacky    if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
5568218893Sdim      ParsedType T = getTypeName(*FirstTypeName.Identifier,
5569212904Sdim                                 FirstTypeName.StartLocation,
5570219077Sdim                                 S, &SS, true, false, ObjectTypePtrForLookup);
5571204643Srdivacky      if (!T) {
5572218893Sdim        Diag(FirstTypeName.StartLocation,
5573204643Srdivacky             diag::err_pseudo_dtor_destructor_non_type)
5574204643Srdivacky          << FirstTypeName.Identifier << ObjectType;
5575218893Sdim
5576204643Srdivacky        if (isSFINAEContext())
5577204643Srdivacky          return ExprError();
5578218893Sdim
5579204643Srdivacky        // Just drop this type. It's unnecessary anyway.
5580204643Srdivacky        ScopeType = QualType();
5581204643Srdivacky      } else
5582204643Srdivacky        ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
5583204643Srdivacky    } else {
5584204643Srdivacky      // Resolve the template-id to a type.
5585204643Srdivacky      TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
5586243830Sdim      ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
5587204643Srdivacky                                         TemplateId->NumArgs);
5588221345Sdim      TypeResult T = ActOnTemplateIdType(TemplateId->SS,
5589234353Sdim                                         TemplateId->TemplateKWLoc,
5590221345Sdim                                         TemplateId->Template,
5591204643Srdivacky                                         TemplateId->TemplateNameLoc,
5592204643Srdivacky                                         TemplateId->LAngleLoc,
5593204643Srdivacky                                         TemplateArgsPtr,
5594204643Srdivacky                                         TemplateId->RAngleLoc);
5595204643Srdivacky      if (T.isInvalid() || !T.get()) {
5596204643Srdivacky        // Recover by dropping this type.
5597204643Srdivacky        ScopeType = QualType();
5598204643Srdivacky      } else
5599218893Sdim        ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
5600204643Srdivacky    }
5601204643Srdivacky  }
5602218893Sdim
5603204643Srdivacky  if (!ScopeType.isNull() && !ScopeTypeInfo)
5604204643Srdivacky    ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
5605204643Srdivacky                                                  FirstTypeName.StartLocation);
5606204643Srdivacky
5607218893Sdim
5608212904Sdim  return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
5609204643Srdivacky                                   ScopeTypeInfo, CCLoc, TildeLoc,
5610204643Srdivacky                                   Destructed, HasTrailingLParen);
5611204643Srdivacky}
5612204643Srdivacky
5613234353SdimExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
5614234353Sdim                                           SourceLocation OpLoc,
5615234353Sdim                                           tok::TokenKind OpKind,
5616234353Sdim                                           SourceLocation TildeLoc,
5617234353Sdim                                           const DeclSpec& DS,
5618234353Sdim                                           bool HasTrailingLParen) {
5619234353Sdim  QualType ObjectType;
5620234353Sdim  if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
5621234353Sdim    return ExprError();
5622234353Sdim
5623234353Sdim  QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
5624234353Sdim
5625234353Sdim  TypeLocBuilder TLB;
5626234353Sdim  DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
5627234353Sdim  DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
5628234353Sdim  TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
5629234353Sdim  PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
5630234353Sdim
5631234353Sdim  return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
5632234353Sdim                                   0, SourceLocation(), TildeLoc,
5633234353Sdim                                   Destructed, HasTrailingLParen);
5634234353Sdim}
5635234353Sdim
5636221345SdimExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
5637234353Sdim                                        CXXConversionDecl *Method,
5638226633Sdim                                        bool HadMultipleCandidates) {
5639234353Sdim  if (Method->getParent()->isLambda() &&
5640234353Sdim      Method->getConversionType()->isBlockPointerType()) {
5641234353Sdim    // This is a lambda coversion to block pointer; check if the argument
5642234353Sdim    // is a LambdaExpr.
5643234353Sdim    Expr *SubE = E;
5644234353Sdim    CastExpr *CE = dyn_cast<CastExpr>(SubE);
5645234353Sdim    if (CE && CE->getCastKind() == CK_NoOp)
5646234353Sdim      SubE = CE->getSubExpr();
5647234353Sdim    SubE = SubE->IgnoreParens();
5648234353Sdim    if (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
5649234353Sdim      SubE = BE->getSubExpr();
5650234353Sdim    if (isa<LambdaExpr>(SubE)) {
5651234353Sdim      // For the conversion to block pointer on a lambda expression, we
5652234353Sdim      // construct a special BlockLiteral instead; this doesn't really make
5653234353Sdim      // a difference in ARC, but outside of ARC the resulting block literal
5654234353Sdim      // follows the normal lifetime rules for block literals instead of being
5655234353Sdim      // autoreleased.
5656234353Sdim      DiagnosticErrorTrap Trap(Diags);
5657234353Sdim      ExprResult Exp = BuildBlockForLambdaConversion(E->getExprLoc(),
5658234353Sdim                                                     E->getExprLoc(),
5659234353Sdim                                                     Method, E);
5660234353Sdim      if (Exp.isInvalid())
5661234353Sdim        Diag(E->getExprLoc(), diag::note_lambda_to_block_conv);
5662234353Sdim      return Exp;
5663234353Sdim    }
5664234353Sdim  }
5665234353Sdim
5666234353Sdim
5667221345Sdim  ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/0,
5668221345Sdim                                          FoundDecl, Method);
5669221345Sdim  if (Exp.isInvalid())
5670218893Sdim    return true;
5671200583Srdivacky
5672218893Sdim  MemberExpr *ME =
5673221345Sdim      new (Context) MemberExpr(Exp.take(), /*IsArrow=*/false, Method,
5674234353Sdim                               SourceLocation(), Context.BoundMemberTy,
5675218893Sdim                               VK_RValue, OK_Ordinary);
5676226633Sdim  if (HadMultipleCandidates)
5677226633Sdim    ME->setHadMultipleCandidates(true);
5678249423Sdim  MarkMemberReferenced(ME);
5679226633Sdim
5680218893Sdim  QualType ResultType = Method->getResultType();
5681218893Sdim  ExprValueKind VK = Expr::getValueKindForType(ResultType);
5682218893Sdim  ResultType = ResultType.getNonLValueExprType(Context);
5683218893Sdim
5684199990Srdivacky  CXXMemberCallExpr *CE =
5685251662Sdim    new (Context) CXXMemberCallExpr(Context, ME, None, ResultType, VK,
5686221345Sdim                                    Exp.get()->getLocEnd());
5687198092Srdivacky  return CE;
5688198092Srdivacky}
5689198092Srdivacky
5690218893SdimExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
5691218893Sdim                                      SourceLocation RParen) {
5692234982Sdim  CanThrowResult CanThrow = canThrow(Operand);
5693218893Sdim  return Owned(new (Context) CXXNoexceptExpr(Context.BoolTy, Operand,
5694234982Sdim                                             CanThrow, KeyLoc, RParen));
5695218893Sdim}
5696218893Sdim
5697218893SdimExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
5698218893Sdim                                   Expr *Operand, SourceLocation RParen) {
5699218893Sdim  return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
5700218893Sdim}
5701218893Sdim
5702239462Sdimstatic bool IsSpecialDiscardedValue(Expr *E) {
5703239462Sdim  // In C++11, discarded-value expressions of a certain form are special,
5704239462Sdim  // according to [expr]p10:
5705239462Sdim  //   The lvalue-to-rvalue conversion (4.1) is applied only if the
5706239462Sdim  //   expression is an lvalue of volatile-qualified type and it has
5707239462Sdim  //   one of the following forms:
5708239462Sdim  E = E->IgnoreParens();
5709239462Sdim
5710239462Sdim  //   - id-expression (5.1.1),
5711239462Sdim  if (isa<DeclRefExpr>(E))
5712239462Sdim    return true;
5713239462Sdim
5714239462Sdim  //   - subscripting (5.2.1),
5715239462Sdim  if (isa<ArraySubscriptExpr>(E))
5716239462Sdim    return true;
5717239462Sdim
5718239462Sdim  //   - class member access (5.2.5),
5719239462Sdim  if (isa<MemberExpr>(E))
5720239462Sdim    return true;
5721239462Sdim
5722239462Sdim  //   - indirection (5.3.1),
5723239462Sdim  if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
5724239462Sdim    if (UO->getOpcode() == UO_Deref)
5725239462Sdim      return true;
5726239462Sdim
5727239462Sdim  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5728239462Sdim    //   - pointer-to-member operation (5.5),
5729239462Sdim    if (BO->isPtrMemOp())
5730239462Sdim      return true;
5731239462Sdim
5732239462Sdim    //   - comma expression (5.18) where the right operand is one of the above.
5733239462Sdim    if (BO->getOpcode() == BO_Comma)
5734239462Sdim      return IsSpecialDiscardedValue(BO->getRHS());
5735239462Sdim  }
5736239462Sdim
5737239462Sdim  //   - conditional expression (5.16) where both the second and the third
5738239462Sdim  //     operands are one of the above, or
5739239462Sdim  if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
5740239462Sdim    return IsSpecialDiscardedValue(CO->getTrueExpr()) &&
5741239462Sdim           IsSpecialDiscardedValue(CO->getFalseExpr());
5742239462Sdim  // The related edge case of "*x ?: *x".
5743239462Sdim  if (BinaryConditionalOperator *BCO =
5744239462Sdim          dyn_cast<BinaryConditionalOperator>(E)) {
5745239462Sdim    if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(BCO->getTrueExpr()))
5746239462Sdim      return IsSpecialDiscardedValue(OVE->getSourceExpr()) &&
5747239462Sdim             IsSpecialDiscardedValue(BCO->getFalseExpr());
5748239462Sdim  }
5749239462Sdim
5750239462Sdim  // Objective-C++ extensions to the rule.
5751239462Sdim  if (isa<PseudoObjectExpr>(E) || isa<ObjCIvarRefExpr>(E))
5752239462Sdim    return true;
5753239462Sdim
5754239462Sdim  return false;
5755239462Sdim}
5756239462Sdim
5757218893Sdim/// Perform the conversions required for an expression used in a
5758218893Sdim/// context that ignores the result.
5759221345SdimExprResult Sema::IgnoredValueConversions(Expr *E) {
5760234353Sdim  if (E->hasPlaceholderType()) {
5761234353Sdim    ExprResult result = CheckPlaceholderExpr(E);
5762234353Sdim    if (result.isInvalid()) return Owned(E);
5763234353Sdim    E = result.take();
5764234353Sdim  }
5765234353Sdim
5766218893Sdim  // C99 6.3.2.1:
5767218893Sdim  //   [Except in specific positions,] an lvalue that does not have
5768218893Sdim  //   array type is converted to the value stored in the
5769218893Sdim  //   designated object (and is no longer an lvalue).
5770224145Sdim  if (E->isRValue()) {
5771224145Sdim    // In C, function designators (i.e. expressions of function type)
5772224145Sdim    // are r-values, but we still want to do function-to-pointer decay
5773224145Sdim    // on them.  This is both technically correct and convenient for
5774224145Sdim    // some clients.
5775234353Sdim    if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType())
5776224145Sdim      return DefaultFunctionArrayConversion(E);
5777218893Sdim
5778224145Sdim    return Owned(E);
5779224145Sdim  }
5780224145Sdim
5781239462Sdim  if (getLangOpts().CPlusPlus)  {
5782239462Sdim    // The C++11 standard defines the notion of a discarded-value expression;
5783239462Sdim    // normally, we don't need to do anything to handle it, but if it is a
5784239462Sdim    // volatile lvalue with a special form, we perform an lvalue-to-rvalue
5785239462Sdim    // conversion.
5786249423Sdim    if (getLangOpts().CPlusPlus11 && E->isGLValue() &&
5787239462Sdim        E->getType().isVolatileQualified() &&
5788239462Sdim        IsSpecialDiscardedValue(E)) {
5789239462Sdim      ExprResult Res = DefaultLvalueConversion(E);
5790239462Sdim      if (Res.isInvalid())
5791239462Sdim        return Owned(E);
5792239462Sdim      E = Res.take();
5793263508Sdim    }
5794239462Sdim    return Owned(E);
5795239462Sdim  }
5796218893Sdim
5797218893Sdim  // GCC seems to also exclude expressions of incomplete enum type.
5798218893Sdim  if (const EnumType *T = E->getType()->getAs<EnumType>()) {
5799218893Sdim    if (!T->getDecl()->isComplete()) {
5800218893Sdim      // FIXME: stupid workaround for a codegen bug!
5801221345Sdim      E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).take();
5802221345Sdim      return Owned(E);
5803218893Sdim    }
5804218893Sdim  }
5805218893Sdim
5806221345Sdim  ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
5807221345Sdim  if (Res.isInvalid())
5808221345Sdim    return Owned(E);
5809221345Sdim  E = Res.take();
5810221345Sdim
5811218893Sdim  if (!E->getType()->isVoidType())
5812218893Sdim    RequireCompleteType(E->getExprLoc(), E->getType(),
5813218893Sdim                        diag::err_incomplete_type);
5814221345Sdim  return Owned(E);
5815218893Sdim}
5816218893Sdim
5817263508Sdim// If we can unambiguously determine whether Var can never be used
5818263508Sdim// in a constant expression, return true.
5819263508Sdim//  - if the variable and its initializer are non-dependent, then
5820263508Sdim//    we can unambiguously check if the variable is a constant expression.
5821263508Sdim//  - if the initializer is not value dependent - we can determine whether
5822263508Sdim//    it can be used to initialize a constant expression.  If Init can not
5823263508Sdim//    be used to initialize a constant expression we conclude that Var can
5824263508Sdim//    never be a constant expression.
5825263508Sdim//  - FXIME: if the initializer is dependent, we can still do some analysis and
5826263508Sdim//    identify certain cases unambiguously as non-const by using a Visitor:
5827263508Sdim//      - such as those that involve odr-use of a ParmVarDecl, involve a new
5828263508Sdim//        delete, lambda-expr, dynamic-cast, reinterpret-cast etc...
5829263508Sdimstatic inline bool VariableCanNeverBeAConstantExpression(VarDecl *Var,
5830263508Sdim    ASTContext &Context) {
5831263508Sdim  if (isa<ParmVarDecl>(Var)) return true;
5832263508Sdim  const VarDecl *DefVD = 0;
5833263508Sdim
5834263508Sdim  // If there is no initializer - this can not be a constant expression.
5835263508Sdim  if (!Var->getAnyInitializer(DefVD)) return true;
5836263508Sdim  assert(DefVD);
5837263508Sdim  if (DefVD->isWeak()) return false;
5838263508Sdim  EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
5839266715Sdim
5840263508Sdim  Expr *Init = cast<Expr>(Eval->Value);
5841263508Sdim
5842263508Sdim  if (Var->getType()->isDependentType() || Init->isValueDependent()) {
5843266715Sdim    // FIXME: Teach the constant evaluator to deal with the non-dependent parts
5844266715Sdim    // of value-dependent expressions, and use it here to determine whether the
5845266715Sdim    // initializer is a potential constant expression.
5846263508Sdim    return false;
5847266715Sdim  }
5848266715Sdim
5849263508Sdim  return !IsVariableAConstantExpression(Var, Context);
5850263508Sdim}
5851263508Sdim
5852263508Sdim/// \brief Check if the current lambda scope has any potential captures, and
5853263508Sdim///  whether they can be captured by any of the enclosing lambdas that are
5854263508Sdim///  ready to capture. If there is a lambda that can capture a nested
5855263508Sdim///  potential-capture, go ahead and do so.  Also, check to see if any
5856263508Sdim///  variables are uncaptureable or do not involve an odr-use so do not
5857263508Sdim///  need to be captured.
5858263508Sdim
5859263508Sdimstatic void CheckLambdaCaptures(Expr *const FE,
5860263508Sdim    LambdaScopeInfo *const CurrentLSI, Sema &S) {
5861263508Sdim
5862263508Sdim  assert(!S.isUnevaluatedContext());
5863263508Sdim  assert(S.CurContext->isDependentContext());
5864263508Sdim  const bool IsFullExprInstantiationDependent =
5865263508Sdim      FE->isInstantiationDependent();
5866263508Sdim  // All the potentially captureable variables in the current nested
5867263508Sdim  // lambda (within a generic outer lambda), must be captured by an
5868263508Sdim  // outer lambda that is enclosed within a non-dependent context.
5869263508Sdim
5870263508Sdim  for (size_t I = 0, N = CurrentLSI->getNumPotentialVariableCaptures();
5871263508Sdim      I != N; ++I) {
5872263508Sdim    Expr *VarExpr = 0;
5873263508Sdim    VarDecl *Var = 0;
5874263508Sdim    CurrentLSI->getPotentialVariableCapture(I, Var, VarExpr);
5875263508Sdim    //
5876263508Sdim    if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) &&
5877263508Sdim        !IsFullExprInstantiationDependent)
5878263508Sdim      continue;
5879263508Sdim    // Climb up until we find a lambda that can capture:
5880263508Sdim    //   - a generic-or-non-generic lambda call operator that is enclosed
5881263508Sdim    //     within a non-dependent context.
5882263508Sdim    unsigned FunctionScopeIndexOfCapturableLambda = 0;
5883263508Sdim    if (GetInnermostEnclosingCapturableLambda(
5884263508Sdim            S.FunctionScopes, FunctionScopeIndexOfCapturableLambda,
5885263508Sdim            S.CurContext, Var, S)) {
5886263508Sdim      MarkVarDeclODRUsed(Var, VarExpr->getExprLoc(),
5887263508Sdim          S, &FunctionScopeIndexOfCapturableLambda);
5888263508Sdim    }
5889263508Sdim    const bool IsVarNeverAConstantExpression =
5890263508Sdim        VariableCanNeverBeAConstantExpression(Var, S.Context);
5891263508Sdim    if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) {
5892263508Sdim      // This full expression is not instantiation dependent or the variable
5893263508Sdim      // can not be used in a constant expression - which means
5894263508Sdim      // this variable must be odr-used here, so diagnose a
5895263508Sdim      // capture violation early, if the variable is un-captureable.
5896263508Sdim      // This is purely for diagnosing errors early.  Otherwise, this
5897263508Sdim      // error would get diagnosed when the lambda becomes capture ready.
5898263508Sdim      QualType CaptureType, DeclRefType;
5899263508Sdim      SourceLocation ExprLoc = VarExpr->getExprLoc();
5900263508Sdim      if (S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
5901263508Sdim                          /*EllipsisLoc*/ SourceLocation(),
5902263508Sdim                          /*BuildAndDiagnose*/false, CaptureType,
5903263508Sdim                          DeclRefType, 0)) {
5904263508Sdim        // We will never be able to capture this variable, and we need
5905263508Sdim        // to be able to in any and all instantiations, so diagnose it.
5906263508Sdim        S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
5907263508Sdim                          /*EllipsisLoc*/ SourceLocation(),
5908263508Sdim                          /*BuildAndDiagnose*/true, CaptureType,
5909263508Sdim                          DeclRefType, 0);
5910263508Sdim      }
5911263508Sdim    }
5912263508Sdim  }
5913263508Sdim
5914263508Sdim  if (CurrentLSI->hasPotentialThisCapture()) {
5915263508Sdim    unsigned FunctionScopeIndexOfCapturableLambda = 0;
5916263508Sdim    if (GetInnermostEnclosingCapturableLambda(
5917263508Sdim            S.FunctionScopes, FunctionScopeIndexOfCapturableLambda,
5918263508Sdim            S.CurContext, /*0 is 'this'*/ 0, S)) {
5919263508Sdim      S.CheckCXXThisCapture(CurrentLSI->PotentialThisCaptureLocation,
5920263508Sdim          /*Explicit*/false, /*BuildAndDiagnose*/true,
5921263508Sdim          &FunctionScopeIndexOfCapturableLambda);
5922263508Sdim    }
5923263508Sdim  }
5924263508Sdim  CurrentLSI->clearPotentialCaptures();
5925263508Sdim}
5926263508Sdim
5927263508Sdim
5928249423SdimExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC,
5929249423Sdim                                     bool DiscardedValue,
5930263508Sdim                                     bool IsConstexpr,
5931263508Sdim                                     bool IsLambdaInitCaptureInitializer) {
5932221345Sdim  ExprResult FullExpr = Owned(FE);
5933221345Sdim
5934221345Sdim  if (!FullExpr.get())
5935218893Sdim    return ExprError();
5936263508Sdim
5937263508Sdim  // If we are an init-expression in a lambdas init-capture, we should not
5938263508Sdim  // diagnose an unexpanded pack now (will be diagnosed once lambda-expr
5939263508Sdim  // containing full-expression is done).
5940263508Sdim  // template<class ... Ts> void test(Ts ... t) {
5941263508Sdim  //   test([&a(t)]() { <-- (t) is an init-expr that shouldn't be diagnosed now.
5942263508Sdim  //     return a;
5943263508Sdim  //   }() ...);
5944263508Sdim  // }
5945263508Sdim  // FIXME: This is a hack. It would be better if we pushed the lambda scope
5946263508Sdim  // when we parse the lambda introducer, and teach capturing (but not
5947263508Sdim  // unexpanded pack detection) to walk over LambdaScopeInfos which don't have a
5948263508Sdim  // corresponding class yet (that is, have LambdaScopeInfo either represent a
5949263508Sdim  // lambda where we've entered the introducer but not the body, or represent a
5950263508Sdim  // lambda where we've entered the body, depending on where the
5951263508Sdim  // parser/instantiation has got to).
5952263508Sdim  if (!IsLambdaInitCaptureInitializer &&
5953263508Sdim      DiagnoseUnexpandedParameterPack(FullExpr.get()))
5954218893Sdim    return ExprError();
5955218893Sdim
5956249423Sdim  // Top-level expressions default to 'id' when we're in a debugger.
5957249423Sdim  if (DiscardedValue && getLangOpts().DebuggerCastResultToId &&
5958249423Sdim      FullExpr.get()->getType() == Context.UnknownAnyTy) {
5959234353Sdim    FullExpr = forceUnknownAnyToType(FullExpr.take(), Context.getObjCIdType());
5960234353Sdim    if (FullExpr.isInvalid())
5961234353Sdim      return ExprError();
5962234353Sdim  }
5963221345Sdim
5964249423Sdim  if (DiscardedValue) {
5965249423Sdim    FullExpr = CheckPlaceholderExpr(FullExpr.take());
5966249423Sdim    if (FullExpr.isInvalid())
5967249423Sdim      return ExprError();
5968221345Sdim
5969249423Sdim    FullExpr = IgnoredValueConversions(FullExpr.take());
5970249423Sdim    if (FullExpr.isInvalid())
5971249423Sdim      return ExprError();
5972249423Sdim  }
5973249423Sdim
5974249423Sdim  CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr);
5975263508Sdim
5976263508Sdim  // At the end of this full expression (which could be a deeply nested
5977263508Sdim  // lambda), if there is a potential capture within the nested lambda,
5978263508Sdim  // have the outer capture-able lambda try and capture it.
5979263508Sdim  // Consider the following code:
5980263508Sdim  // void f(int, int);
5981263508Sdim  // void f(const int&, double);
5982263508Sdim  // void foo() {
5983263508Sdim  //  const int x = 10, y = 20;
5984263508Sdim  //  auto L = [=](auto a) {
5985263508Sdim  //      auto M = [=](auto b) {
5986263508Sdim  //         f(x, b); <-- requires x to be captured by L and M
5987263508Sdim  //         f(y, a); <-- requires y to be captured by L, but not all Ms
5988263508Sdim  //      };
5989263508Sdim  //   };
5990263508Sdim  // }
5991263508Sdim
5992263508Sdim  // FIXME: Also consider what happens for something like this that involves
5993263508Sdim  // the gnu-extension statement-expressions or even lambda-init-captures:
5994263508Sdim  //   void f() {
5995263508Sdim  //     const int n = 0;
5996263508Sdim  //     auto L =  [&](auto a) {
5997263508Sdim  //       +n + ({ 0; a; });
5998263508Sdim  //     };
5999263508Sdim  //   }
6000263508Sdim  //
6001263508Sdim  // Here, we see +n, and then the full-expression 0; ends, so we don't
6002263508Sdim  // capture n (and instead remove it from our list of potential captures),
6003263508Sdim  // and then the full-expression +n + ({ 0; }); ends, but it's too late
6004263508Sdim  // for us to see that we need to capture n after all.
6005263508Sdim
6006263508Sdim  LambdaScopeInfo *const CurrentLSI = getCurLambda();
6007263508Sdim  // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer
6008263508Sdim  // even if CurContext is not a lambda call operator. Refer to that Bug Report
6009263508Sdim  // for an example of the code that might cause this asynchrony.
6010263508Sdim  // By ensuring we are in the context of a lambda's call operator
6011263508Sdim  // we can fix the bug (we only need to check whether we need to capture
6012263508Sdim  // if we are within a lambda's body); but per the comments in that
6013263508Sdim  // PR, a proper fix would entail :
6014263508Sdim  //   "Alternative suggestion:
6015263508Sdim  //   - Add to Sema an integer holding the smallest (outermost) scope
6016263508Sdim  //     index that we are *lexically* within, and save/restore/set to
6017263508Sdim  //     FunctionScopes.size() in InstantiatingTemplate's
6018263508Sdim  //     constructor/destructor.
6019263508Sdim  //  - Teach the handful of places that iterate over FunctionScopes to
6020263508Sdim  //    stop at the outermost enclosing lexical scope."
6021263508Sdim  const bool IsInLambdaDeclContext = isLambdaCallOperator(CurContext);
6022263508Sdim  if (IsInLambdaDeclContext && CurrentLSI &&
6023263508Sdim      CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid())
6024263508Sdim    CheckLambdaCaptures(FE, CurrentLSI, *this);
6025218893Sdim  return MaybeCreateExprWithCleanups(FullExpr);
6026193326Sed}
6027218893Sdim
6028218893SdimStmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
6029218893Sdim  if (!FullStmt) return StmtError();
6030218893Sdim
6031218893Sdim  return MaybeCreateStmtWithCleanups(FullStmt);
6032218893Sdim}
6033223017Sdim
6034234353SdimSema::IfExistsResult
6035234353SdimSema::CheckMicrosoftIfExistsSymbol(Scope *S,
6036234353Sdim                                   CXXScopeSpec &SS,
6037234353Sdim                                   const DeclarationNameInfo &TargetNameInfo) {
6038223017Sdim  DeclarationName TargetName = TargetNameInfo.getName();
6039223017Sdim  if (!TargetName)
6040234353Sdim    return IER_DoesNotExist;
6041234353Sdim
6042234353Sdim  // If the name itself is dependent, then the result is dependent.
6043234353Sdim  if (TargetName.isDependentName())
6044234353Sdim    return IER_Dependent;
6045234353Sdim
6046223017Sdim  // Do the redeclaration lookup in the current scope.
6047223017Sdim  LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
6048223017Sdim                 Sema::NotForRedeclaration);
6049234353Sdim  LookupParsedName(R, S, &SS);
6050223017Sdim  R.suppressDiagnostics();
6051234353Sdim
6052234353Sdim  switch (R.getResultKind()) {
6053234353Sdim  case LookupResult::Found:
6054234353Sdim  case LookupResult::FoundOverloaded:
6055234353Sdim  case LookupResult::FoundUnresolvedValue:
6056234353Sdim  case LookupResult::Ambiguous:
6057234353Sdim    return IER_Exists;
6058234353Sdim
6059234353Sdim  case LookupResult::NotFound:
6060234353Sdim    return IER_DoesNotExist;
6061234353Sdim
6062234353Sdim  case LookupResult::NotFoundInCurrentInstantiation:
6063234353Sdim    return IER_Dependent;
6064234353Sdim  }
6065234353Sdim
6066234353Sdim  llvm_unreachable("Invalid LookupResult Kind!");
6067223017Sdim}
6068234353Sdim
6069234353SdimSema::IfExistsResult
6070234353SdimSema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
6071234353Sdim                                   bool IsIfExists, CXXScopeSpec &SS,
6072234353Sdim                                   UnqualifiedId &Name) {
6073234353Sdim  DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
6074234353Sdim
6075234353Sdim  // Check for unexpanded parameter packs.
6076234353Sdim  SmallVector<UnexpandedParameterPack, 4> Unexpanded;
6077234353Sdim  collectUnexpandedParameterPacks(SS, Unexpanded);
6078234353Sdim  collectUnexpandedParameterPacks(TargetNameInfo, Unexpanded);
6079234353Sdim  if (!Unexpanded.empty()) {
6080234353Sdim    DiagnoseUnexpandedParameterPacks(KeywordLoc,
6081234353Sdim                                     IsIfExists? UPPC_IfExists
6082234353Sdim                                               : UPPC_IfNotExists,
6083234353Sdim                                     Unexpanded);
6084234353Sdim    return IER_Error;
6085234353Sdim  }
6086234353Sdim
6087234353Sdim  return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
6088234353Sdim}
6089