Coverage Report

Created: 2021-01-19 06:58

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Sema/SemaExprCXX.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
///
9
/// \file
10
/// Implements semantic analysis for C++ expressions.
11
///
12
//===----------------------------------------------------------------------===//
13
14
#include "clang/Sema/Template.h"
15
#include "clang/Sema/SemaInternal.h"
16
#include "TreeTransform.h"
17
#include "TypeLocBuilder.h"
18
#include "clang/AST/ASTContext.h"
19
#include "clang/AST/ASTLambda.h"
20
#include "clang/AST/CXXInheritance.h"
21
#include "clang/AST/CharUnits.h"
22
#include "clang/AST/DeclObjC.h"
23
#include "clang/AST/ExprCXX.h"
24
#include "clang/AST/ExprObjC.h"
25
#include "clang/AST/RecursiveASTVisitor.h"
26
#include "clang/AST/TypeLoc.h"
27
#include "clang/Basic/AlignedAllocation.h"
28
#include "clang/Basic/PartialDiagnostic.h"
29
#include "clang/Basic/TargetInfo.h"
30
#include "clang/Lex/Preprocessor.h"
31
#include "clang/Sema/DeclSpec.h"
32
#include "clang/Sema/Initialization.h"
33
#include "clang/Sema/Lookup.h"
34
#include "clang/Sema/ParsedTemplate.h"
35
#include "clang/Sema/Scope.h"
36
#include "clang/Sema/ScopeInfo.h"
37
#include "clang/Sema/SemaLambda.h"
38
#include "clang/Sema/TemplateDeduction.h"
39
#include "llvm/ADT/APInt.h"
40
#include "llvm/ADT/STLExtras.h"
41
#include "llvm/Support/ErrorHandling.h"
42
using namespace clang;
43
using namespace sema;
44
45
/// Handle the result of the special case name lookup for inheriting
46
/// constructor declarations. 'NS::X::X' and 'NS::X<...>::X' are treated as
47
/// constructor names in member using declarations, even if 'X' is not the
48
/// name of the corresponding type.
49
ParsedType Sema::getInheritingConstructorName(CXXScopeSpec &SS,
50
                                              SourceLocation NameLoc,
51
420
                                              IdentifierInfo &Name) {
52
420
  NestedNameSpecifier *NNS = SS.getScopeRep();
53
54
  // Convert the nested-name-specifier into a type.
55
420
  QualType Type;
56
420
  switch (NNS->getKind()) {
57
417
  case NestedNameSpecifier::TypeSpec:
58
418
  case NestedNameSpecifier::TypeSpecWithTemplate:
59
418
    Type = QualType(NNS->getAsType(), 0);
60
418
    break;
61
62
2
  case NestedNameSpecifier::Identifier:
63
    // Strip off the last layer of the nested-name-specifier and build a
64
    // typename type for it.
65
2
    assert(NNS->getAsIdentifier() == &Name && "not a constructor name");
66
2
    Type = Context.getDependentNameType(ETK_None, NNS->getPrefix(),
67
2
                                        NNS->getAsIdentifier());
68
2
    break;
69
70
0
  case NestedNameSpecifier::Global:
71
0
  case NestedNameSpecifier::Super:
72
0
  case NestedNameSpecifier::Namespace:
73
0
  case NestedNameSpecifier::NamespaceAlias:
74
0
    llvm_unreachable("Nested name specifier is not a type for inheriting ctor");
75
420
  }
76
77
  // This reference to the type is located entirely at the location of the
78
  // final identifier in the qualified-id.
79
420
  return CreateParsedType(Type,
80
420
                          Context.getTrivialTypeSourceInfo(Type, NameLoc));
81
420
}
82
83
ParsedType Sema::getConstructorName(IdentifierInfo &II,
84
                                    SourceLocation NameLoc,
85
                                    Scope *S, CXXScopeSpec &SS,
86
262k
                                    bool EnteringContext) {
87
262k
  CXXRecordDecl *CurClass = getCurrentClass(S, &SS);
88
262k
  assert(CurClass && &II == CurClass->getIdentifier() &&
89
262k
         "not a constructor name");
90
91
  // When naming a constructor as a member of a dependent context (eg, in a
92
  // friend declaration or an inherited constructor declaration), form an
93
  // unresolved "typename" type.
94
262k
  if (CurClass->isDependentContext() && 
!EnteringContext177k
&&
SS.getScopeRep()3
) {
95
1
    QualType T = Context.getDependentNameType(ETK_None, SS.getScopeRep(), &II);
96
1
    return ParsedType::make(T);
97
1
  }
98
99
262k
  if (SS.isNotEmpty() && 
RequireCompleteDeclContext(SS, CurClass)34.6k
)
100
0
    return ParsedType();
101
102
  // Find the injected-class-name declaration. Note that we make no attempt to
103
  // diagnose cases where the injected-class-name is shadowed: the only
104
  // declaration that can validly shadow the injected-class-name is a
105
  // non-static data member, and if the class contains both a non-static data
106
  // member and a constructor then it is ill-formed (we check that in
107
  // CheckCompletedCXXClass).
108
262k
  CXXRecordDecl *InjectedClassName = nullptr;
109
262k
  for (NamedDecl *ND : CurClass->lookup(&II)) {
110
262k
    auto *RD = dyn_cast<CXXRecordDecl>(ND);
111
262k
    if (RD && 
RD->isInjectedClassName()262k
) {
112
262k
      InjectedClassName = RD;
113
262k
      break;
114
262k
    }
115
262k
  }
116
262k
  if (!InjectedClassName) {
117
2
    if (!CurClass->isInvalidDecl()) {
118
      // FIXME: RequireCompleteDeclContext doesn't check dependent contexts
119
      // properly. Work around it here for now.
120
1
      Diag(SS.getLastQualifierNameLoc(),
121
1
           diag::err_incomplete_nested_name_spec) << CurClass << SS.getRange();
122
1
    }
123
2
    return ParsedType();
124
2
  }
125
126
262k
  QualType T = Context.getTypeDeclType(InjectedClassName);
127
262k
  DiagnoseUseOfDecl(InjectedClassName, NameLoc);
128
262k
  MarkAnyDeclReferenced(NameLoc, InjectedClassName, /*OdrUse=*/false);
129
130
262k
  return ParsedType::make(T);
131
262k
}
132
133
ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
134
                                   IdentifierInfo &II,
135
                                   SourceLocation NameLoc,
136
                                   Scope *S, CXXScopeSpec &SS,
137
                                   ParsedType ObjectTypePtr,
138
41.2k
                                   bool EnteringContext) {
139
  // Determine where to perform name lookup.
140
141
  // FIXME: This area of the standard is very messy, and the current
142
  // wording is rather unclear about which scopes we search for the
143
  // destructor name; see core issues 399 and 555. Issue 399 in
144
  // particular shows where the current description of destructor name
145
  // lookup is completely out of line with existing practice, e.g.,
146
  // this appears to be ill-formed:
147
  //
148
  //   namespace N {
149
  //     template <typename T> struct S {
150
  //       ~S();
151
  //     };
152
  //   }
153
  //
154
  //   void f(N::S<int>* s) {
155
  //     s->N::S<int>::~S();
156
  //   }
157
  //
158
  // See also PR6358 and PR6359.
159
  //
160
  // For now, we accept all the cases in which the name given could plausibly
161
  // be interpreted as a correct destructor name, issuing off-by-default
162
  // extension diagnostics on the cases that don't strictly conform to the
163
  // C++20 rules. This basically means we always consider looking in the
164
  // nested-name-specifier prefix, the complete nested-name-specifier, and
165
  // the scope, and accept if we find the expected type in any of the three
166
  // places.
167
168
41.2k
  if (SS.isInvalid())
169
7
    return nullptr;
170
171
  // Whether we've failed with a diagnostic already.
172
41.2k
  bool Failed = false;
173
174
41.2k
  llvm::SmallVector<NamedDecl*, 8> FoundDecls;
175
41.2k
  llvm::SmallPtrSet<CanonicalDeclPtr<Decl>, 8> FoundDeclSet;
176
177
  // If we have an object type, it's because we are in a
178
  // pseudo-destructor-expression or a member access expression, and
179
  // we know what type we're looking for.
180
41.2k
  QualType SearchType =
181
40.9k
      ObjectTypePtr ? 
GetTypeFromParser(ObjectTypePtr)266
: QualType();
182
183
41.3k
  auto CheckLookupResult = [&](LookupResult &Found) -> ParsedType {
184
82.4k
    auto IsAcceptableResult = [&](NamedDecl *D) -> bool {
185
82.4k
      auto *Type = dyn_cast<TypeDecl>(D->getUnderlyingDecl());
186
82.4k
      if (!Type)
187
30
        return false;
188
189
82.4k
      if (SearchType.isNull() || 
SearchType->isDependentType()584
)
190
81.8k
        return true;
191
192
584
      QualType T = Context.getTypeDeclType(Type);
193
584
      return Context.hasSameUnqualifiedType(T, SearchType);
194
584
    };
195
196
41.3k
    unsigned NumAcceptableResults = 0;
197
41.2k
    for (NamedDecl *D : Found) {
198
41.2k
      if (IsAcceptableResult(D))
199
41.1k
        ++NumAcceptableResults;
200
201
      // Don't list a class twice in the lookup failure diagnostic if it's
202
      // found by both its injected-class-name and by the name in the enclosing
203
      // scope.
204
41.2k
      if (auto *RD = dyn_cast<CXXRecordDecl>(D))
205
41.1k
        if (RD->isInjectedClassName())
206
40.7k
          D = cast<NamedDecl>(RD->getParent());
207
208
41.2k
      if (FoundDeclSet.insert(D).second)
209
41.2k
        FoundDecls.push_back(D);
210
41.2k
    }
211
212
    // As an extension, attempt to "fix" an ambiguity by erasing all non-type
213
    // results, and all non-matching results if we have a search type. It's not
214
    // clear what the right behavior is if destructor lookup hits an ambiguity,
215
    // but other compilers do generally accept at least some kinds of
216
    // ambiguity.
217
41.3k
    if (Found.isAmbiguous() && 
NumAcceptableResults == 16
) {
218
6
      Diag(NameLoc, diag::ext_dtor_name_ambiguous);
219
6
      LookupResult::Filter F = Found.makeFilter();
220
18
      while (F.hasNext()) {
221
12
        NamedDecl *D = F.next();
222
12
        if (auto *TD = dyn_cast<TypeDecl>(D->getUnderlyingDecl()))
223
12
          Diag(D->getLocation(), diag::note_destructor_type_here)
224
12
              << Context.getTypeDeclType(TD);
225
0
        else
226
0
          Diag(D->getLocation(), diag::note_destructor_nontype_here);
227
228
12
        if (!IsAcceptableResult(D))
229
6
          F.erase();
230
12
      }
231
6
      F.done();
232
6
    }
233
234
41.3k
    if (Found.isAmbiguous())
235
0
      Failed = true;
236
237
41.3k
    if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
238
41.1k
      if (IsAcceptableResult(Type)) {
239
41.1k
        QualType T = Context.getTypeDeclType(Type);
240
41.1k
        MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
241
41.1k
        return CreateParsedType(T,
242
41.1k
                                Context.getTrivialTypeSourceInfo(T, NameLoc));
243
41.1k
      }
244
161
    }
245
246
161
    return nullptr;
247
161
  };
248
249
41.2k
  bool IsDependent = false;
250
251
90
  auto LookupInObjectType = [&]() -> ParsedType {
252
90
    if (Failed || SearchType.isNull())
253
29
      return nullptr;
254
255
61
    IsDependent |= SearchType->isDependentType();
256
257
61
    LookupResult Found(*this, &II, NameLoc, LookupDestructorName);
258
61
    DeclContext *LookupCtx = computeDeclContext(SearchType);
259
61
    if (!LookupCtx)
260
1
      return nullptr;
261
60
    LookupQualifiedName(Found, LookupCtx);
262
60
    return CheckLookupResult(Found);
263
60
  };
264
265
240
  auto LookupInNestedNameSpec = [&](CXXScopeSpec &LookupSS) -> ParsedType {
266
240
    if (Failed)
267
0
      return nullptr;
268
269
240
    IsDependent |= isDependentScopeSpecifier(LookupSS);
270
240
    DeclContext *LookupCtx = computeDeclContext(LookupSS, EnteringContext);
271
240
    if (!LookupCtx)
272
1
      return nullptr;
273
274
239
    LookupResult Found(*this, &II, NameLoc, LookupDestructorName);
275
239
    if (RequireCompleteDeclContext(LookupSS, LookupCtx)) {
276
0
      Failed = true;
277
0
      return nullptr;
278
0
    }
279
239
    LookupQualifiedName(Found, LookupCtx);
280
239
    return CheckLookupResult(Found);
281
239
  };
282
283
41.0k
  auto LookupInScope = [&]() -> ParsedType {
284
41.0k
    if (Failed || !S)
285
7
      return nullptr;
286
287
41.0k
    LookupResult Found(*this, &II, NameLoc, LookupDestructorName);
288
41.0k
    LookupName(Found, S);
289
41.0k
    return CheckLookupResult(Found);
290
41.0k
  };
291
292
  // C++2a [basic.lookup.qual]p6:
293
  //   In a qualified-id of the form
294
  //
295
  //     nested-name-specifier[opt] type-name :: ~ type-name
296
  //
297
  //   the second type-name is looked up in the same scope as the first.
298
  //
299
  // We interpret this as meaning that if you do a dual-scope lookup for the
300
  // first name, you also do a dual-scope lookup for the second name, per
301
  // C++ [basic.lookup.classref]p4:
302
  //
303
  //   If the id-expression in a class member access is a qualified-id of the
304
  //   form
305
  //
306
  //     class-name-or-namespace-name :: ...
307
  //
308
  //   the class-name-or-namespace-name following the . or -> is first looked
309
  //   up in the class of the object expression and the name, if found, is used.
310
  //   Otherwise, it is looked up in the context of the entire
311
  //   postfix-expression.
312
  //
313
  // This looks in the same scopes as for an unqualified destructor name:
314
  //
315
  // C++ [basic.lookup.classref]p3:
316
  //   If the unqualified-id is ~ type-name, the type-name is looked up
317
  //   in the context of the entire postfix-expression. If the type T
318
  //   of the object expression is of a class type C, the type-name is
319
  //   also looked up in the scope of class C. At least one of the
320
  //   lookups shall find a name that refers to cv T.
321
  //
322
  // FIXME: The intent is unclear here. Should type-name::~type-name look in
323
  // the scope anyway if it finds a non-matching name declared in the class?
324
  // If both lookups succeed and find a dependent result, which result should
325
  // we retain? (Same question for p->~type-name().)
326
327
41.2k
  if (NestedNameSpecifier *Prefix =
328
191
      SS.isSet() ? SS.getScopeRep()->getPrefix() : nullptr) {
329
    // This is
330
    //
331
    //   nested-name-specifier type-name :: ~ type-name
332
    //
333
    // Look for the second type-name in the nested-name-specifier.
334
191
    CXXScopeSpec PrefixSS;
335
191
    PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
336
191
    if (ParsedType T = LookupInNestedNameSpec(PrefixSS))
337
157
      return T;
338
41.0k
  } else {
339
    // This is one of
340
    //
341
    //   type-name :: ~ type-name
342
    //   ~ type-name
343
    //
344
    // Look in the scope and (if any) the object type.
345
41.0k
    if (ParsedType T = LookupInScope())
346
40.9k
      return T;
347
90
    if (ParsedType T = LookupInObjectType())
348
34
      return T;
349
90
  }
350
351
90
  if (Failed)
352
0
    return nullptr;
353
354
90
  if (IsDependent) {
355
    // We didn't find our type, but that's OK: it's dependent anyway.
356
357
    // FIXME: What if we have no nested-name-specifier?
358
3
    QualType T = CheckTypenameType(ETK_None, SourceLocation(),
359
3
                                   SS.getWithLocInContext(Context),
360
3
                                   II, NameLoc);
361
3
    return ParsedType::make(T);
362
3
  }
363
364
  // The remaining cases are all non-standard extensions imitating the behavior
365
  // of various other compilers.
366
87
  unsigned NumNonExtensionDecls = FoundDecls.size();
367
368
87
  if (SS.isSet()) {
369
    // For compatibility with older broken C++ rules and existing code,
370
    //
371
    //   nested-name-specifier :: ~ type-name
372
    //
373
    // also looks for type-name within the nested-name-specifier.
374
49
    if (ParsedType T = LookupInNestedNameSpec(SS)) {
375
30
      Diag(SS.getEndLoc(), diag::ext_dtor_named_in_wrong_scope)
376
30
          << SS.getRange()
377
30
          << FixItHint::CreateInsertion(SS.getEndLoc(),
378
30
                                        ("::" + II.getName()).str());
379
30
      return T;
380
30
    }
381
382
    // For compatibility with other compilers and older versions of Clang,
383
    //
384
    //   nested-name-specifier type-name :: ~ type-name
385
    //
386
    // also looks for type-name in the scope. Unfortunately, we can't
387
    // reasonably apply this fallback for dependent nested-name-specifiers.
388
19
    if (SS.getScopeRep()->getPrefix()) {
389
10
      if (ParsedType T = LookupInScope()) {
390
10
        Diag(SS.getEndLoc(), diag::ext_qualified_dtor_named_in_lexical_scope)
391
10
            << FixItHint::CreateRemoval(SS.getRange());
392
10
        Diag(FoundDecls.back()->getLocation(), diag::note_destructor_type_here)
393
10
            << GetTypeFromParser(T);
394
10
        return T;
395
10
      }
396
47
    }
397
19
  }
398
399
  // We didn't find anything matching; tell the user what we did find (if
400
  // anything).
401
402
  // Don't tell the user about declarations we shouldn't have found.
403
47
  FoundDecls.resize(NumNonExtensionDecls);
404
405
  // List types before non-types.
406
47
  std::stable_sort(FoundDecls.begin(), FoundDecls.end(),
407
0
                   [](NamedDecl *A, NamedDecl *B) {
408
0
                     return isa<TypeDecl>(A->getUnderlyingDecl()) >
409
0
                            isa<TypeDecl>(B->getUnderlyingDecl());
410
0
                   });
411
412
  // Suggest a fixit to properly name the destroyed type.
413
47
  auto MakeFixItHint = [&]{
414
47
    const CXXRecordDecl *Destroyed = nullptr;
415
    // FIXME: If we have a scope specifier, suggest its last component?
416
47
    if (!SearchType.isNull())
417
27
      Destroyed = SearchType->getAsCXXRecordDecl();
418
20
    else if (S)
419
20
      Destroyed = dyn_cast_or_null<CXXRecordDecl>(S->getEntity());
420
47
    if (Destroyed)
421
39
      return FixItHint::CreateReplacement(SourceRange(NameLoc),
422
39
                                          Destroyed->getNameAsString());
423
8
    return FixItHint();
424
8
  };
425
426
47
  if (FoundDecls.empty()) {
427
    // FIXME: Attempt typo-correction?
428
26
    Diag(NameLoc, diag::err_undeclared_destructor_name)
429
26
      << &II << MakeFixItHint();
430
21
  } else if (!SearchType.isNull() && 
FoundDecls.size() == 119
) {
431
19
    if (auto *TD = dyn_cast<TypeDecl>(FoundDecls[0]->getUnderlyingDecl())) {
432
19
      assert(!SearchType.isNull() &&
433
19
             "should only reject a type result if we have a search type");
434
19
      QualType T = Context.getTypeDeclType(TD);
435
19
      Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
436
19
          << T << SearchType << MakeFixItHint();
437
0
    } else {
438
0
      Diag(NameLoc, diag::err_destructor_expr_nontype)
439
0
          << &II << MakeFixItHint();
440
0
    }
441
2
  } else {
442
2
    Diag(NameLoc, SearchType.isNull() ? diag::err_destructor_name_nontype
443
0
                                      : diag::err_destructor_expr_mismatch)
444
2
        << &II << SearchType << MakeFixItHint();
445
2
  }
446
447
21
  for (NamedDecl *FoundD : FoundDecls) {
448
21
    if (auto *TD = dyn_cast<TypeDecl>(FoundD->getUnderlyingDecl()))
449
19
      Diag(FoundD->getLocation(), diag::note_destructor_type_here)
450
19
          << Context.getTypeDeclType(TD);
451
2
    else
452
2
      Diag(FoundD->getLocation(), diag::note_destructor_nontype_here)
453
2
          << FoundD;
454
21
  }
455
456
47
  return nullptr;
457
47
}
458
459
ParsedType Sema::getDestructorTypeForDecltype(const DeclSpec &DS,
460
22
                                              ParsedType ObjectType) {
461
22
  if (DS.getTypeSpecType() == DeclSpec::TST_error)
462
1
    return nullptr;
463
464
21
  if (DS.getTypeSpecType() == DeclSpec::TST_decltype_auto) {
465
2
    Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
466
2
    return nullptr;
467
2
  }
468
469
19
  assert(DS.getTypeSpecType() == DeclSpec::TST_decltype &&
470
19
         "unexpected type in getDestructorType");
471
19
  QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
472
473
  // If we know the type of the object, check that the correct destructor
474
  // type was named now; we can give better diagnostics this way.
475
19
  QualType SearchType = GetTypeFromParser(ObjectType);
476
19
  if (!SearchType.isNull() && 
!SearchType->isDependentType()18
&&
477
18
      !Context.hasSameUnqualifiedType(T, SearchType)) {
478
5
    Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)
479
5
      << T << SearchType;
480
5
    return nullptr;
481
5
  }
482
483
14
  return ParsedType::make(T);
484
14
}
485
486
bool Sema::checkLiteralOperatorId(const CXXScopeSpec &SS,
487
738
                                  const UnqualifiedId &Name) {
488
738
  assert(Name.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId);
489
490
738
  if (!SS.isValid())
491
723
    return false;
492
493
15
  switch (SS.getScopeRep()->getKind()) {
494
0
  case NestedNameSpecifier::Identifier:
495
6
  case NestedNameSpecifier::TypeSpec:
496
6
  case NestedNameSpecifier::TypeSpecWithTemplate:
497
    // Per C++11 [over.literal]p2, literal operators can only be declared at
498
    // namespace scope. Therefore, this unqualified-id cannot name anything.
499
    // Reject it early, because we have no AST representation for this in the
500
    // case where the scope is dependent.
501
6
    Diag(Name.getBeginLoc(), diag::err_literal_operator_id_outside_namespace)
502
6
        << SS.getScopeRep();
503
6
    return true;
504
505
1
  case NestedNameSpecifier::Global:
506
1
  case NestedNameSpecifier::Super:
507
9
  case NestedNameSpecifier::Namespace:
508
9
  case NestedNameSpecifier::NamespaceAlias:
509
9
    return false;
510
0
  }
511
512
0
  llvm_unreachable("unknown nested name specifier kind");
513
0
}
514
515
/// Build a C++ typeid expression with a type operand.
516
ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
517
                                SourceLocation TypeidLoc,
518
                                TypeSourceInfo *Operand,
519
5.11k
                                SourceLocation RParenLoc) {
520
  // C++ [expr.typeid]p4:
521
  //   The top-level cv-qualifiers of the lvalue expression or the type-id
522
  //   that is the operand of typeid are always ignored.
523
  //   If the type of the type-id is a class type or a reference to a class
524
  //   type, the class shall be completely-defined.
525
5.11k
  Qualifiers Quals;
526
5.11k
  QualType T
527
5.11k
    = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
528
5.11k
                                      Quals);
529
5.11k
  if (T->getAs<RecordType>() &&
530
251
      RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
531
5
    return ExprError();
532
533
5.10k
  if (T->isVariablyModifiedType())
534
1
    return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) << T);
535
536
5.10k
  if (CheckQualifiedFunctionForTypeId(T, TypeidLoc))
537
6
    return ExprError();
538
539
5.09k
  return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), Operand,
540
5.09k
                                     SourceRange(TypeidLoc, RParenLoc));
541
5.09k
}
542
543
/// Build a C++ typeid expression with an expression operand.
544
ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
545
                                SourceLocation TypeidLoc,
546
                                Expr *E,
547
289
                                SourceLocation RParenLoc) {
548
289
  bool WasEvaluated = false;
549
289
  if (E && !E->isTypeDependent()) {
550
275
    if (E->getType()->isPlaceholderType()) {
551
1
      ExprResult result = CheckPlaceholderExpr(E);
552
1
      if (result.isInvalid()) 
return ExprError()0
;
553
1
      E = result.get();
554
1
    }
555
556
275
    QualType T = E->getType();
557
275
    if (const RecordType *RecordT = T->getAs<RecordType>()) {
558
131
      CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
559
      // C++ [expr.typeid]p3:
560
      //   [...] If the type of the expression is a class type, the class
561
      //   shall be completely-defined.
562
131
      if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
563
1
        return ExprError();
564
565
      // C++ [expr.typeid]p3:
566
      //   When typeid is applied to an expression other than an glvalue of a
567
      //   polymorphic class type [...] [the] expression is an unevaluated
568
      //   operand. [...]
569
130
      if (RecordD->isPolymorphic() && 
E->isGLValue()109
) {
570
        // The subexpression is potentially evaluated; switch the context
571
        // and recheck the subexpression.
572
105
        ExprResult Result = TransformToPotentiallyEvaluated(E);
573
105
        if (Result.isInvalid()) 
return ExprError()10
;
574
95
        E = Result.get();
575
576
        // We require a vtable to query the type at run time.
577
95
        MarkVTableUsed(TypeidLoc, RecordD);
578
95
        WasEvaluated = true;
579
95
      }
580
130
    }
581
582
264
    ExprResult Result = CheckUnevaluatedOperand(E);
583
264
    if (Result.isInvalid())
584
0
      return ExprError();
585
264
    E = Result.get();
586
587
    // C++ [expr.typeid]p4:
588
    //   [...] If the type of the type-id is a reference to a possibly
589
    //   cv-qualified type, the result of the typeid expression refers to a
590
    //   std::type_info object representing the cv-unqualified referenced
591
    //   type.
592
264
    Qualifiers Quals;
593
264
    QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
594
264
    if (!Context.hasSameType(T, UnqualT)) {
595
21
      T = UnqualT;
596
21
      E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).get();
597
21
    }
598
264
  }
599
600
278
  if (E->getType()->isVariablyModifiedType())
601
1
    return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid)
602
1
                     << E->getType());
603
277
  else if (!inTemplateInstantiation() &&
604
257
           E->HasSideEffects(Context, WasEvaluated)) {
605
    // The expression operand for typeid is in an unevaluated expression
606
    // context, so side effects could result in unintended consequences.
607
58
    Diag(E->getExprLoc(), WasEvaluated
608
37
                              ? diag::warn_side_effects_typeid
609
21
                              : diag::warn_side_effects_unevaluated_context);
610
58
  }
611
612
277
  return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E,
613
277
                                     SourceRange(TypeidLoc, RParenLoc));
614
278
}
615
616
/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
617
ExprResult
618
Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
619
5.28k
                     bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
620
  // typeid is not supported in OpenCL.
621
5.28k
  if (getLangOpts().OpenCLCPlusPlus) {
622
1
    return ExprError(Diag(OpLoc, diag::err_openclcxx_not_supported)
623
1
                     << "typeid");
624
1
  }
625
626
  // Find the std::type_info type.
627
5.28k
  if (!getStdNamespace())
628
1
    return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
629
630
5.28k
  if (!CXXTypeInfoDecl) {
631
550
    IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
632
550
    LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
633
550
    LookupQualifiedName(R, getStdNamespace());
634
550
    CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
635
    // Microsoft's typeinfo doesn't have type_info in std but in the global
636
    // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153.
637
550
    if (!CXXTypeInfoDecl && 
LangOpts.MSVCCompat4
) {
638
1
      LookupQualifiedName(R, Context.getTranslationUnitDecl());
639
1
      CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
640
1
    }
641
550
    if (!CXXTypeInfoDecl)
642
3
      return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
643
5.27k
  }
644
645
5.27k
  if (!getLangOpts().RTTI) {
646
1
    return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti));
647
1
  }
648
649
5.27k
  QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
650
651
5.27k
  if (isType) {
652
    // The operand is a type; handle it as such.
653
5.00k
    TypeSourceInfo *TInfo = nullptr;
654
5.00k
    QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
655
5.00k
                                   &TInfo);
656
5.00k
    if (T.isNull())
657
0
      return ExprError();
658
659
5.00k
    if (!TInfo)
660
0
      TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
661
662
5.00k
    return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
663
5.00k
  }
664
665
  // The operand is an expression.
666
269
  ExprResult Result =
667
269
      BuildCXXTypeId(TypeInfoType, OpLoc, (Expr *)TyOrExpr, RParenLoc);
668
669
269
  if (!getLangOpts().RTTIData && 
!Result.isInvalid()15
)
670
15
    if (auto *CTE = dyn_cast<CXXTypeidExpr>(Result.get()))
671
15
      if (CTE->isPotentiallyEvaluated() && 
!CTE->isMostDerived(Context)11
)
672
7
        Diag(OpLoc, diag::warn_no_typeid_with_rtti_disabled)
673
7
            << (getDiagnostics().getDiagnosticOptions().getFormat() ==
674
7
                DiagnosticOptions::MSVC);
675
269
  return Result;
676
269
}
677
678
/// Grabs __declspec(uuid()) off a type, or returns 0 if we cannot resolve to
679
/// a single GUID.
680
static void
681
getUuidAttrOfType(Sema &SemaRef, QualType QT,
682
173
                  llvm::SmallSetVector<const UuidAttr *, 1> &UuidAttrs) {
683
  // Optionally remove one level of pointer, reference or array indirection.
684
173
  const Type *Ty = QT.getTypePtr();
685
173
  if (QT->isPointerType() || 
QT->isReferenceType()167
)
686
6
    Ty = QT->getPointeeType().getTypePtr();
687
167
  else if (QT->isArrayType())
688
10
    Ty = Ty->getBaseElementTypeUnsafe();
689
690
173
  const auto *TD = Ty->getAsTagDecl();
691
173
  if (!TD)
692
5
    return;
693
694
168
  if (const auto *Uuid = TD->getMostRecentDecl()->getAttr<UuidAttr>()) {
695
153
    UuidAttrs.insert(Uuid);
696
153
    return;
697
153
  }
698
699
  // __uuidof can grab UUIDs from template arguments.
700
15
  if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(TD)) {
701
6
    const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
702
9
    for (const TemplateArgument &TA : TAL.asArray()) {
703
9
      const UuidAttr *UuidForTA = nullptr;
704
9
      if (TA.getKind() == TemplateArgument::Type)
705
9
        getUuidAttrOfType(SemaRef, TA.getAsType(), UuidAttrs);
706
0
      else if (TA.getKind() == TemplateArgument::Declaration)
707
0
        getUuidAttrOfType(SemaRef, TA.getAsDecl()->getType(), UuidAttrs);
708
709
9
      if (UuidForTA)
710
0
        UuidAttrs.insert(UuidForTA);
711
9
    }
712
6
  }
713
15
}
714
715
/// Build a Microsoft __uuidof expression with a type operand.
716
ExprResult Sema::BuildCXXUuidof(QualType Type,
717
                                SourceLocation TypeidLoc,
718
                                TypeSourceInfo *Operand,
719
167
                                SourceLocation RParenLoc) {
720
167
  MSGuidDecl *Guid = nullptr;
721
167
  if (!Operand->getType()->isDependentType()) {
722
151
    llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
723
151
    getUuidAttrOfType(*this, Operand->getType(), UuidAttrs);
724
151
    if (UuidAttrs.empty())
725
9
      return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
726
142
    if (UuidAttrs.size() > 1)
727
1
      return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
728
141
    Guid = UuidAttrs.back()->getGuidDecl();
729
141
  }
730
731
157
  return new (Context)
732
157
      CXXUuidofExpr(Type, Operand, Guid, SourceRange(TypeidLoc, RParenLoc));
733
167
}
734
735
/// Build a Microsoft __uuidof expression with an expression operand.
736
ExprResult Sema::BuildCXXUuidof(QualType Type, SourceLocation TypeidLoc,
737
27
                                Expr *E, SourceLocation RParenLoc) {
738
27
  MSGuidDecl *Guid = nullptr;
739
27
  if (!E->getType()->isDependentType()) {
740
26
    if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
741
      // A null pointer results in {00000000-0000-0000-0000-000000000000}.
742
13
      Guid = Context.getMSGuidDecl(MSGuidDecl::Parts{});
743
13
    } else {
744
13
      llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
745
13
      getUuidAttrOfType(*this, E->getType(), UuidAttrs);
746
13
      if (UuidAttrs.empty())
747
4
        return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
748
9
      if (UuidAttrs.size() > 1)
749
1
        return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
750
8
      Guid = UuidAttrs.back()->getGuidDecl();
751
8
    }
752
26
  }
753
754
22
  return new (Context)
755
22
      CXXUuidofExpr(Type, E, Guid, SourceRange(TypeidLoc, RParenLoc));
756
27
}
757
758
/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
759
ExprResult
760
Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
761
174
                     bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
762
174
  QualType GuidType = Context.getMSGuidType();
763
174
  GuidType.addConst();
764
765
174
  if (isType) {
766
    // The operand is a type; handle it as such.
767
147
    TypeSourceInfo *TInfo = nullptr;
768
147
    QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
769
147
                                   &TInfo);
770
147
    if (T.isNull())
771
0
      return ExprError();
772
773
147
    if (!TInfo)
774
0
      TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
775
776
147
    return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
777
147
  }
778
779
  // The operand is an expression.
780
27
  return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
781
27
}
782
783
/// ActOnCXXBoolLiteral - Parse {true,false} literals.
784
ExprResult
785
289k
Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
786
289k
  assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
787
289k
         "Unknown C++ Boolean value!");
788
289k
  return new (Context)
789
289k
      CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
790
289k
}
791
792
/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
793
ExprResult
794
82.4k
Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
795
82.4k
  return new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
796
82.4k
}
797
798
/// ActOnCXXThrow - Parse throw expressions.
799
ExprResult
800
13.5k
Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) {
801
13.5k
  bool IsThrownVarInScope = false;
802
13.5k
  if (Ex) {
803
    // C++0x [class.copymove]p31:
804
    //   When certain criteria are met, an implementation is allowed to omit the
805
    //   copy/move construction of a class object [...]
806
    //
807
    //     - in a throw-expression, when the operand is the name of a
808
    //       non-volatile automatic object (other than a function or catch-
809
    //       clause parameter) whose scope does not extend beyond the end of the
810
    //       innermost enclosing try-block (if there is one), the copy/move
811
    //       operation from the operand to the exception object (15.1) can be
812
    //       omitted by constructing the automatic object directly into the
813
    //       exception object
814
7.17k
    if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
815
530
      if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
816
524
        if (Var->hasLocalStorage() && 
!Var->getType().isVolatileQualified()501
) {
817
538
          for( ; S; 
S = S->getParent()37
) {
818
538
            if (S->isDeclScope(Var)) {
819
74
              IsThrownVarInScope = true;
820
74
              break;
821
74
            }
822
823
464
            if (S->getFlags() &
824
464
                (Scope::FnScope | Scope::ClassScope | Scope::BlockScope |
825
464
                 Scope::FunctionPrototypeScope | Scope::ObjCMethodScope |
826
464
                 Scope::TryScope))
827
427
              break;
828
464
          }
829
501
        }
830
524
      }
831
7.17k
  }
832
833
13.5k
  return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
834
13.5k
}
835
836
ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
837
13.6k
                               bool IsThrownVarInScope) {
838
  // Don't report an error if 'throw' is used in system headers.
839
13.6k
  if (!getLangOpts().CXXExceptions &&
840
13
      !getSourceManager().isInSystemHeader(OpLoc) && !getLangOpts().CUDA) {
841
    // Delay error emission for the OpenMP device code.
842
10
    targetDiag(OpLoc, diag::err_exceptions_disabled) << "throw";
843
10
  }
844
845
  // Exceptions aren't allowed in CUDA device code.
846
13.6k
  if (getLangOpts().CUDA)
847
17
    CUDADiagIfDeviceCode(OpLoc, diag::err_cuda_device_exceptions)
848
17
        << "throw" << CurrentCUDATarget();
849
850
13.6k
  if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
851
232
    Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw";
852
853
13.6k
  if (Ex && 
!Ex->isTypeDependent()7.24k
) {
854
5.96k
    QualType ExceptionObjectTy = Context.getExceptionObjectType(Ex->getType());
855
5.96k
    if (CheckCXXThrowOperand(OpLoc, ExceptionObjectTy, Ex))
856
42
      return ExprError();
857
858
    // Initialize the exception result.  This implicitly weeds out
859
    // abstract types or types with inaccessible copy constructors.
860
861
    // C++0x [class.copymove]p31:
862
    //   When certain criteria are met, an implementation is allowed to omit the
863
    //   copy/move construction of a class object [...]
864
    //
865
    //     - in a throw-expression, when the operand is the name of a
866
    //       non-volatile automatic object (other than a function or
867
    //       catch-clause
868
    //       parameter) whose scope does not extend beyond the end of the
869
    //       innermost enclosing try-block (if there is one), the copy/move
870
    //       operation from the operand to the exception object (15.1) can be
871
    //       omitted by constructing the automatic object directly into the
872
    //       exception object
873
5.92k
    const VarDecl *NRVOVariable = nullptr;
874
5.92k
    if (IsThrownVarInScope)
875
75
      NRVOVariable = getCopyElisionCandidate(QualType(), Ex, CES_Strict);
876
877
5.92k
    InitializedEntity Entity = InitializedEntity::InitializeException(
878
5.92k
        OpLoc, ExceptionObjectTy,
879
5.92k
        /*NRVO=*/NRVOVariable != nullptr);
880
5.92k
    ExprResult Res = PerformMoveOrCopyInitialization(
881
5.92k
        Entity, NRVOVariable, QualType(), Ex, IsThrownVarInScope);
882
5.92k
    if (Res.isInvalid())
883
5
      return ExprError();
884
5.92k
    Ex = Res.get();
885
5.92k
  }
886
887
  // PPC MMA non-pointer types are not allowed as throw expr types.
888
13.5k
  if (Ex && 
Context.getTargetInfo().getTriple().isPPC64()7.19k
)
889
10
    CheckPPCMMAType(Ex->getType(), Ex->getBeginLoc());
890
891
13.5k
  return new (Context)
892
13.5k
      CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope);
893
13.6k
}
894
895
static void
896
collectPublicBases(CXXRecordDecl *RD,
897
                   llvm::DenseMap<CXXRecordDecl *, unsigned> &SubobjectsSeen,
898
                   llvm::SmallPtrSetImpl<CXXRecordDecl *> &VBases,
899
                   llvm::SetVector<CXXRecordDecl *> &PublicSubobjectsSeen,
900
47
                   bool ParentIsPublic) {
901
16
  for (const CXXBaseSpecifier &BS : RD->bases()) {
902
16
    CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
903
16
    bool NewSubobject;
904
    // Virtual bases constitute the same subobject.  Non-virtual bases are
905
    // always distinct subobjects.
906
16
    if (BS.isVirtual())
907
4
      NewSubobject = VBases.insert(BaseDecl).second;
908
12
    else
909
12
      NewSubobject = true;
910
911
16
    if (NewSubobject)
912
14
      ++SubobjectsSeen[BaseDecl];
913
914
    // Only add subobjects which have public access throughout the entire chain.
915
16
    bool PublicPath = ParentIsPublic && BS.getAccessSpecifier() == AS_public;
916
16
    if (PublicPath)
917
10
      PublicSubobjectsSeen.insert(BaseDecl);
918
919
    // Recurse on to each base subobject.
920
16
    collectPublicBases(BaseDecl, SubobjectsSeen, VBases, PublicSubobjectsSeen,
921
16
                       PublicPath);
922
16
  }
923
47
}
924
925
static void getUnambiguousPublicSubobjects(
926
31
    CXXRecordDecl *RD, llvm::SmallVectorImpl<CXXRecordDecl *> &Objects) {
927
31
  llvm::DenseMap<CXXRecordDecl *, unsigned> SubobjectsSeen;
928
31
  llvm::SmallSet<CXXRecordDecl *, 2> VBases;
929
31
  llvm::SetVector<CXXRecordDecl *> PublicSubobjectsSeen;
930
31
  SubobjectsSeen[RD] = 1;
931
31
  PublicSubobjectsSeen.insert(RD);
932
31
  collectPublicBases(RD, SubobjectsSeen, VBases, PublicSubobjectsSeen,
933
31
                     /*ParentIsPublic=*/true);
934
935
39
  for (CXXRecordDecl *PublicSubobject : PublicSubobjectsSeen) {
936
    // Skip ambiguous objects.
937
39
    if (SubobjectsSeen[PublicSubobject] > 1)
938
0
      continue;
939
940
39
    Objects.push_back(PublicSubobject);
941
39
  }
942
31
}
943
944
/// CheckCXXThrowOperand - Validate the operand of a throw.
945
bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc,
946
5.97k
                                QualType ExceptionObjectTy, Expr *E) {
947
  //   If the type of the exception would be an incomplete type or a pointer
948
  //   to an incomplete type other than (cv) void the program is ill-formed.
949
5.97k
  QualType Ty = ExceptionObjectTy;
950
5.97k
  bool isPointer = false;
951
5.97k
  if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
952
143
    Ty = Ptr->getPointeeType();
953
143
    isPointer = true;
954
143
  }
955
5.97k
  if (!isPointer || 
!Ty->isVoidType()143
) {
956
5.96k
    if (RequireCompleteType(ThrowLoc, Ty,
957
135
                            isPointer ? diag::err_throw_incomplete_ptr
958
5.83k
                                      : diag::err_throw_incomplete,
959
5.96k
                            E->getSourceRange()))
960
33
      return true;
961
962
5.93k
    if (!isPointer && 
Ty->isSizelessType()5.81k
) {
963
4
      Diag(ThrowLoc, diag::err_throw_sizeless) << Ty << E->getSourceRange();
964
4
      return true;
965
4
    }
966
967
5.93k
    if (RequireNonAbstractType(ThrowLoc, ExceptionObjectTy,
968
5.93k
                               diag::err_throw_abstract_type, E))
969
3
      return true;
970
5.93k
  }
971
972
  // If the exception has class type, we need additional handling.
973
5.93k
  CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
974
5.93k
  if (!RD)
975
1.11k
    return false;
976
977
  // If we are throwing a polymorphic class type or pointer thereof,
978
  // exception handling will make use of the vtable.
979
4.82k
  MarkVTableUsed(ThrowLoc, RD);
980
981
  // If a pointer is thrown, the referenced object will not be destroyed.
982
4.82k
  if (isPointer)
983
16
    return false;
984
985
  // If the class has a destructor, we must be able to call it.
986
4.80k
  if (!RD->hasIrrelevantDestructor()) {
987
4.64k
    if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
988
4.64k
      MarkFunctionReferenced(E->getExprLoc(), Destructor);
989
4.64k
      CheckDestructorAccess(E->getExprLoc(), Destructor,
990
4.64k
                            PDiag(diag::err_access_dtor_exception) << Ty);
991
4.64k
      if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
992
1
        return true;
993
4.80k
    }
994
4.64k
  }
995
996
  // The MSVC ABI creates a list of all types which can catch the exception
997
  // object.  This list also references the appropriate copy constructor to call
998
  // if the object is caught by value and has a non-trivial copy constructor.
999
4.80k
  if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1000
    // We are only interested in the public, unambiguous bases contained within
1001
    // the exception object.  Bases which are ambiguous or otherwise
1002
    // inaccessible are not catchable types.
1003
31
    llvm::SmallVector<CXXRecordDecl *, 2> UnambiguousPublicSubobjects;
1004
31
    getUnambiguousPublicSubobjects(RD, UnambiguousPublicSubobjects);
1005
1006
39
    for (CXXRecordDecl *Subobject : UnambiguousPublicSubobjects) {
1007
      // Attempt to lookup the copy constructor.  Various pieces of machinery
1008
      // will spring into action, like template instantiation, which means this
1009
      // cannot be a simple walk of the class's decls.  Instead, we must perform
1010
      // lookup and overload resolution.
1011
39
      CXXConstructorDecl *CD = LookupCopyingConstructor(Subobject, 0);
1012
39
      if (!CD || CD->isDeleted())
1013
4
        continue;
1014
1015
      // Mark the constructor referenced as it is used by this throw expression.
1016
35
      MarkFunctionReferenced(E->getExprLoc(), CD);
1017
1018
      // Skip this copy constructor if it is trivial, we don't need to record it
1019
      // in the catchable type data.
1020
35
      if (CD->isTrivial())
1021
15
        continue;
1022
1023
      // The copy constructor is non-trivial, create a mapping from this class
1024
      // type to this constructor.
1025
      // N.B.  The selection of copy constructor is not sensitive to this
1026
      // particular throw-site.  Lookup will be performed at the catch-site to
1027
      // ensure that the copy constructor is, in fact, accessible (via
1028
      // friendship or any other means).
1029
20
      Context.addCopyConstructorForExceptionObject(Subobject, CD);
1030
1031
      // We don't keep the instantiated default argument expressions around so
1032
      // we must rebuild them here.
1033
26
      for (unsigned I = 1, E = CD->getNumParams(); I != E; 
++I6
) {
1034
7
        if (CheckCXXDefaultArgExpr(ThrowLoc, CD, CD->getParamDecl(I)))
1035
1
          return true;
1036
7
      }
1037
20
    }
1038
31
  }
1039
1040
  // Under the Itanium C++ ABI, memory for the exception object is allocated by
1041
  // the runtime with no ability for the compiler to request additional
1042
  // alignment. Warn if the exception type requires alignment beyond the minimum
1043
  // guaranteed by the target C++ runtime.
1044
4.80k
  if (Context.getTargetInfo().getCXXABI().isItaniumFamily()) {
1045
4.77k
    CharUnits TypeAlign = Context.getTypeAlignInChars(Ty);
1046
4.77k
    CharUnits ExnObjAlign = Context.getExnObjectAlignment();
1047
4.77k
    if (ExnObjAlign < TypeAlign) {
1048
29
      Diag(ThrowLoc, diag::warn_throw_underaligned_obj);
1049
29
      Diag(ThrowLoc, diag::note_throw_underaligned_obj)
1050
29
          << Ty << (unsigned)TypeAlign.getQuantity()
1051
29
          << (unsigned)ExnObjAlign.getQuantity();
1052
29
    }
1053
4.77k
  }
1054
1055
4.80k
  return false;
1056
4.80k
}
1057
1058
static QualType adjustCVQualifiersForCXXThisWithinLambda(
1059
    ArrayRef<FunctionScopeInfo *> FunctionScopes, QualType ThisTy,
1060
3.05k
    DeclContext *CurSemaContext, ASTContext &ASTCtx) {
1061
1062
3.05k
  QualType ClassType = ThisTy->getPointeeType();
1063
3.05k
  LambdaScopeInfo *CurLSI = nullptr;
1064
3.05k
  DeclContext *CurDC = CurSemaContext;
1065
1066
  // Iterate through the stack of lambdas starting from the innermost lambda to
1067
  // the outermost lambda, checking if '*this' is ever captured by copy - since
1068
  // that could change the cv-qualifiers of the '*this' object.
1069
  // The object referred to by '*this' starts out with the cv-qualifiers of its
1070
  // member function.  We then start with the innermost lambda and iterate
1071
  // outward checking to see if any lambda performs a by-copy capture of '*this'
1072
  // - and if so, any nested lambda must respect the 'constness' of that
1073
  // capturing lamdbda's call operator.
1074
  //
1075
1076
  // Since the FunctionScopeInfo stack is representative of the lexical
1077
  // nesting of the lambda expressions during initial parsing (and is the best
1078
  // place for querying information about captures about lambdas that are
1079
  // partially processed) and perhaps during instantiation of function templates
1080
  // that contain lambda expressions that need to be transformed BUT not
1081
  // necessarily during instantiation of a nested generic lambda's function call
1082
  // operator (which might even be instantiated at the end of the TU) - at which
1083
  // time the DeclContext tree is mature enough to query capture information
1084
  // reliably - we use a two pronged approach to walk through all the lexically
1085
  // enclosing lambda expressions:
1086
  //
1087
  //  1) Climb down the FunctionScopeInfo stack as long as each item represents
1088
  //  a Lambda (i.e. LambdaScopeInfo) AND each LSI's 'closure-type' is lexically
1089
  //  enclosed by the call-operator of the LSI below it on the stack (while
1090
  //  tracking the enclosing DC for step 2 if needed).  Note the topmost LSI on
1091
  //  the stack represents the innermost lambda.
1092
  //
1093
  //  2) If we run out of enclosing LSI's, check if the enclosing DeclContext
1094
  //  represents a lambda's call operator.  If it does, we must be instantiating
1095
  //  a generic lambda's call operator (represented by the Current LSI, and
1096
  //  should be the only scenario where an inconsistency between the LSI and the
1097
  //  DeclContext should occur), so climb out the DeclContexts if they
1098
  //  represent lambdas, while querying the corresponding closure types
1099
  //  regarding capture information.
1100
1101
  // 1) Climb down the function scope info stack.
1102
3.05k
  for (int I = FunctionScopes.size();
1103
6.77k
       I-- && isa<LambdaScopeInfo>(FunctionScopes[I]) &&
1104
4.35k
       (!CurLSI || 
!CurLSI->Lambda1.30k
|| CurLSI->Lambda->getDeclContext() ==
1105
1.29k
                       cast<LambdaScopeInfo>(FunctionScopes[I])->CallOperator);
1106
4.28k
       
CurDC = getLambdaAwareParentOfDeclContext(CurDC)3.72k
) {
1107
4.28k
    CurLSI = cast<LambdaScopeInfo>(FunctionScopes[I]);
1108
1109
4.28k
    if (!CurLSI->isCXXThisCaptured())
1110
1.76k
        continue;
1111
1112
2.51k
    auto C = CurLSI->getCXXThisCapture();
1113
1114
2.51k
    if (C.isCopyCapture()) {
1115
560
      ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1116
560
      if (CurLSI->CallOperator->isConst())
1117
240
        ClassType.addConst();
1118
560
      return ASTCtx.getPointerType(ClassType);
1119
560
    }
1120
2.51k
  }
1121
1122
  // 2) We've run out of ScopeInfos but check if CurDC is a lambda (which can
1123
  // happen during instantiation of its nested generic lambda call operator)
1124
2.49k
  if (isLambdaCallOperator(CurDC)) {
1125
148
    assert(CurLSI && "While computing 'this' capture-type for a generic "
1126
148
                     "lambda, we must have a corresponding LambdaScopeInfo");
1127
148
    assert(isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) &&
1128
148
           "While computing 'this' capture-type for a generic lambda, when we "
1129
148
           "run out of enclosing LSI's, yet the enclosing DC is a "
1130
148
           "lambda-call-operator we must be (i.e. Current LSI) in a generic "
1131
148
           "lambda call oeprator");
1132
148
    assert(CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator));
1133
1134
148
    auto IsThisCaptured =
1135
232
        [](CXXRecordDecl *Closure, bool &IsByCopy, bool &IsConst) {
1136
232
      IsConst = false;
1137
232
      IsByCopy = false;
1138
232
      for (auto &&C : Closure->captures()) {
1139
232
        if (C.capturesThis()) {
1140
232
          if (C.getCaptureKind() == LCK_StarThis)
1141
36
            IsByCopy = true;
1142
232
          if (Closure->getLambdaCallOperator()->isConst())
1143
196
            IsConst = true;
1144
232
          return true;
1145
232
        }
1146
232
      }
1147
0
      return false;
1148
232
    };
1149
1150
148
    bool IsByCopyCapture = false;
1151
148
    bool IsConstCapture = false;
1152
148
    CXXRecordDecl *Closure = cast<CXXRecordDecl>(CurDC->getParent());
1153
344
    while (Closure &&
1154
232
           IsThisCaptured(Closure, IsByCopyCapture, IsConstCapture)) {
1155
232
      if (IsByCopyCapture) {
1156
36
        ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1157
36
        if (IsConstCapture)
1158
0
          ClassType.addConst();
1159
36
        return ASTCtx.getPointerType(ClassType);
1160
36
      }
1161
196
      Closure = isLambdaCallOperator(Closure->getParent())
1162
84
                    ? cast<CXXRecordDecl>(Closure->getParent()->getParent())
1163
112
                    : nullptr;
1164
196
    }
1165
148
  }
1166
2.45k
  return ASTCtx.getPointerType(ClassType);
1167
2.49k
}
1168
1169
2.08M
QualType Sema::getCurrentThisType() {
1170
2.08M
  DeclContext *DC = getFunctionLevelDeclContext();
1171
2.08M
  QualType ThisTy = CXXThisTypeOverride;
1172
1173
2.08M
  if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
1174
2.07M
    if (method && method->isInstance())
1175
2.07M
      ThisTy = method->getThisType();
1176
2.07M
  }
1177
1178
2.08M
  if (ThisTy.isNull() && 
isLambdaCallOperator(CurContext)9.33k
&&
1179
60
      inTemplateInstantiation()) {
1180
1181
40
    assert(isa<CXXRecordDecl>(DC) &&
1182
40
           "Trying to get 'this' type from static method?");
1183
1184
    // This is a lambda call operator that is being instantiated as a default
1185
    // initializer. DC must point to the enclosing class type, so we can recover
1186
    // the 'this' type from it.
1187
1188
40
    QualType ClassTy = Context.getTypeDeclType(cast<CXXRecordDecl>(DC));
1189
    // There are no cv-qualifiers for 'this' within default initializers,
1190
    // per [expr.prim.general]p4.
1191
40
    ThisTy = Context.getPointerType(ClassTy);
1192
40
  }
1193
1194
  // If we are within a lambda's call operator, the cv-qualifiers of 'this'
1195
  // might need to be adjusted if the lambda or any of its enclosing lambda's
1196
  // captures '*this' by copy.
1197
2.08M
  if (!ThisTy.isNull() && 
isLambdaCallOperator(CurContext)2.07M
)
1198
3.05k
    return adjustCVQualifiersForCXXThisWithinLambda(FunctionScopes, ThisTy,
1199
3.05k
                                                    CurContext, Context);
1200
2.08M
  return ThisTy;
1201
2.08M
}
1202
1203
Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S,
1204
                                         Decl *ContextDecl,
1205
                                         Qualifiers CXXThisTypeQuals,
1206
                                         bool Enabled)
1207
  : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
1208
4.16M
{
1209
4.16M
  if (!Enabled || 
!ContextDecl2.72M
)
1210
1.59M
    return;
1211
1212
2.56M
  CXXRecordDecl *Record = nullptr;
1213
2.56M
  if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))
1214
55.8k
    Record = Template->getTemplatedDecl();
1215
2.50M
  else
1216
2.50M
    Record = cast<CXXRecordDecl>(ContextDecl);
1217
1218
2.56M
  QualType T = S.Context.getRecordType(Record);
1219
2.56M
  T = S.getASTContext().getQualifiedType(T, CXXThisTypeQuals);
1220
1221
2.56M
  S.CXXThisTypeOverride = S.Context.getPointerType(T);
1222
1223
2.56M
  this->Enabled = true;
1224
2.56M
}
1225
1226
1227
4.16M
Sema::CXXThisScopeRAII::~CXXThisScopeRAII() {
1228
4.16M
  if (Enabled) {
1229
2.56M
    S.CXXThisTypeOverride = OldCXXThisTypeOverride;
1230
2.56M
  }
1231
4.16M
}
1232
1233
bool Sema::CheckCXXThisCapture(SourceLocation Loc, const bool Explicit,
1234
    bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt,
1235
1.04M
    const bool ByCopy) {
1236
  // We don't need to capture this in an unevaluated context.
1237
1.04M
  if (isUnevaluatedContext() && 
!Explicit3.54k
)
1238
3.54k
    return true;
1239
1240
1.04M
  assert((!ByCopy || Explicit) && "cannot implicitly capture *this by value");
1241
1242
1.04M
  const int MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
1243
36
                                         ? *FunctionScopeIndexToStopAt
1244
1.04M
                                         : FunctionScopes.size() - 1;
1245
1246
  // Check that we can capture the *enclosing object* (referred to by '*this')
1247
  // by the capturing-entity/closure (lambda/block/etc) at
1248
  // MaxFunctionScopesIndex-deep on the FunctionScopes stack.
1249
1250
  // Note: The *enclosing object* can only be captured by-value by a
1251
  // closure that is a lambda, using the explicit notation:
1252
  //    [*this] { ... }.
1253
  // Every other capture of the *enclosing object* results in its by-reference
1254
  // capture.
1255
1256
  // For a closure 'L' (at MaxFunctionScopesIndex in the FunctionScopes
1257
  // stack), we can capture the *enclosing object* only if:
1258
  // - 'L' has an explicit byref or byval capture of the *enclosing object*
1259
  // -  or, 'L' has an implicit capture.
1260
  // AND
1261
  //   -- there is no enclosing closure
1262
  //   -- or, there is some enclosing closure 'E' that has already captured the
1263
  //      *enclosing object*, and every intervening closure (if any) between 'E'
1264
  //      and 'L' can implicitly capture the *enclosing object*.
1265
  //   -- or, every enclosing closure can implicitly capture the
1266
  //      *enclosing object*
1267
1268
1269
1.04M
  unsigned NumCapturingClosures = 0;
1270
1.05M
  for (int idx = MaxFunctionScopesIndex; idx >= 0; 
idx--11.3k
) {
1271
1.05M
    if (CapturingScopeInfo *CSI =
1272
23.0k
            dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
1273
23.0k
      if (CSI->CXXThisCaptureIndex != 0) {
1274
        // 'this' is already being captured; there isn't anything more to do.
1275
11.5k
        CSI->Captures[CSI->CXXThisCaptureIndex - 1].markUsed(BuildAndDiagnose);
1276
11.5k
        break;
1277
11.5k
      }
1278
11.4k
      LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI);
1279
11.4k
      if (LSI && 
isGenericLambdaCallOperatorSpecialization(LSI->CallOperator)978
) {
1280
        // This context can't implicitly capture 'this'; fail out.
1281
40
        if (BuildAndDiagnose)
1282
32
          Diag(Loc, diag::err_this_capture)
1283
32
              << (Explicit && 
idx == MaxFunctionScopesIndex0
);
1284
40
        return true;
1285
40
      }
1286
11.4k
      if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
1287
11.1k
          CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
1288
10.9k
          CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
1289
10.8k
          CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion ||
1290
11.3k
          
(424
Explicit424
&&
idx == MaxFunctionScopesIndex374
)) {
1291
        // Regarding (Explicit && idx == MaxFunctionScopesIndex): only the first
1292
        // iteration through can be an explicit capture, all enclosing closures,
1293
        // if any, must perform implicit captures.
1294
1295
        // This closure can capture 'this'; continue looking upwards.
1296
11.3k
        NumCapturingClosures++;
1297
11.3k
        continue;
1298
11.3k
      }
1299
      // This context can't implicitly capture 'this'; fail out.
1300
52
      if (BuildAndDiagnose)
1301
40
        Diag(Loc, diag::err_this_capture)
1302
40
            << (Explicit && 
idx == MaxFunctionScopesIndex2
);
1303
52
      return true;
1304
52
    }
1305
1.02M
    break;
1306
1.02M
  }
1307
1.04M
  if (!BuildAndDiagnose) 
return false77
;
1308
1309
  // If we got here, then the closure at MaxFunctionScopesIndex on the
1310
  // FunctionScopes stack, can capture the *enclosing object*, so capture it
1311
  // (including implicit by-reference captures in any enclosing closures).
1312
1313
  // In the loop below, respect the ByCopy flag only for the closure requesting
1314
  // the capture (i.e. first iteration through the loop below).  Ignore it for
1315
  // all enclosing closure's up to NumCapturingClosures (since they must be
1316
  // implicitly capturing the *enclosing  object* by reference (see loop
1317
  // above)).
1318
1.04M
  assert((!ByCopy ||
1319
1.04M
          dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) &&
1320
1.04M
         "Only a lambda can capture the enclosing object (referred to by "
1321
1.04M
         "*this) by copy");
1322
1.04M
  QualType ThisTy = getCurrentThisType();
1323
1.05M
  for (int idx = MaxFunctionScopesIndex; NumCapturingClosures;
1324
11.2k
       --idx, --NumCapturingClosures) {
1325
11.2k
    CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
1326
1327
    // The type of the corresponding data member (not a 'this' pointer if 'by
1328
    // copy').
1329
11.2k
    QualType CaptureType = ThisTy;
1330
11.2k
    if (ByCopy) {
1331
      // If we are capturing the object referred to by '*this' by copy, ignore
1332
      // any cv qualifiers inherited from the type of the member function for
1333
      // the type of the closure-type's corresponding data member and any use
1334
      // of 'this'.
1335
128
      CaptureType = ThisTy->getPointeeType();
1336
128
      CaptureType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1337
128
    }
1338
1339
11.2k
    bool isNested = NumCapturingClosures > 1;
1340
11.2k
    CSI->addThisCapture(isNested, Loc, CaptureType, ByCopy);
1341
11.2k
  }
1342
1.04M
  return false;
1343
1.04M
}
1344
1345
207k
ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
1346
  /// C++ 9.3.2: In the body of a non-static member function, the keyword this
1347
  /// is a non-lvalue expression whose value is the address of the object for
1348
  /// which the function is called.
1349
1350
207k
  QualType ThisTy = getCurrentThisType();
1351
207k
  if (ThisTy.isNull())
1352
49
    return Diag(Loc, diag::err_invalid_this_use);
1353
207k
  return BuildCXXThisExpr(Loc, ThisTy, /*IsImplicit=*/false);
1354
207k
}
1355
1356
Expr *Sema::BuildCXXThisExpr(SourceLocation Loc, QualType Type,
1357
1.04M
                             bool IsImplicit) {
1358
1.04M
  auto *This = new (Context) CXXThisExpr(Loc, Type, IsImplicit);
1359
1.04M
  MarkThisReferenced(This);
1360
1.04M
  return This;
1361
1.04M
}
1362
1363
1.04M
void Sema::MarkThisReferenced(CXXThisExpr *This) {
1364
1.04M
  CheckCXXThisCapture(This->getExprLoc());
1365
1.04M
}
1366
1367
788k
bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) {
1368
  // If we're outside the body of a member function, then we'll have a specified
1369
  // type for 'this'.
1370
788k
  if (CXXThisTypeOverride.isNull())
1371
787k
    return false;
1372
1373
  // Determine whether we're looking into a class that's currently being
1374
  // defined.
1375
558
  CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
1376
558
  return Class && Class->isBeingDefined();
1377
558
}
1378
1379
/// Parse construction of a specified type.
1380
/// Can be interpreted either as function-style casting ("int(x)")
1381
/// or class type construction ("ClassType(x,y,z)")
1382
/// or creation of a value-initialized type ("int()").
1383
ExprResult
1384
Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
1385
                                SourceLocation LParenOrBraceLoc,
1386
                                MultiExprArg exprs,
1387
                                SourceLocation RParenOrBraceLoc,
1388
304k
                                bool ListInitialization) {
1389
304k
  if (!TypeRep)
1390
5
    return ExprError();
1391
1392
304k
  TypeSourceInfo *TInfo;
1393
304k
  QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
1394
304k
  if (!TInfo)
1395
0
    TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
1396
1397
304k
  auto Result = BuildCXXTypeConstructExpr(TInfo, LParenOrBraceLoc, exprs,
1398
304k
                                          RParenOrBraceLoc, ListInitialization);
1399
  // Avoid creating a non-type-dependent expression that contains typos.
1400
  // Non-type-dependent expressions are liable to be discarded without
1401
  // checking for embedded typos.
1402
304k
  if (!Result.isInvalid() && 
Result.get()->isInstantiationDependent()304k
&&
1403
232k
      !Result.get()->isTypeDependent())
1404
4.98k
    Result = CorrectDelayedTyposInExpr(Result.get());
1405
299k
  else if (Result.isInvalid())
1406
194
    Result = CreateRecoveryExpr(TInfo->getTypeLoc().getBeginLoc(),
1407
194
                                RParenOrBraceLoc, exprs, Ty);
1408
304k
  return Result;
1409
304k
}
1410
1411
ExprResult
1412
Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
1413
                                SourceLocation LParenOrBraceLoc,
1414
                                MultiExprArg Exprs,
1415
                                SourceLocation RParenOrBraceLoc,
1416
366k
                                bool ListInitialization) {
1417
366k
  QualType Ty = TInfo->getType();
1418
366k
  SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
1419
1420
366k
  assert((!ListInitialization ||
1421
366k
          (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0]))) &&
1422
366k
         "List initialization must have initializer list as expression.");
1423
366k
  SourceRange FullRange = SourceRange(TyBeginLoc, RParenOrBraceLoc);
1424
1425
366k
  InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
1426
366k
  InitializationKind Kind =
1427
366k
      Exprs.size()
1428
211k
          ? ListInitialization
1429
15.0k
                ? InitializationKind::CreateDirectList(
1430
15.0k
                      TyBeginLoc, LParenOrBraceLoc, RParenOrBraceLoc)
1431
196k
                : InitializationKind::CreateDirect(TyBeginLoc, LParenOrBraceLoc,
1432
196k
                                                   RParenOrBraceLoc)
1433
154k
          : InitializationKind::CreateValue(TyBeginLoc, LParenOrBraceLoc,
1434
154k
                                            RParenOrBraceLoc);
1435
1436
  // C++1z [expr.type.conv]p1:
1437
  //   If the type is a placeholder for a deduced class type, [...perform class
1438
  //   template argument deduction...]
1439
366k
  DeducedType *Deduced = Ty->getContainedDeducedType();
1440
366k
  if (Deduced && 
isa<DeducedTemplateSpecializationType>(Deduced)92
) {
1441
92
    Ty = DeduceTemplateSpecializationFromInitializer(TInfo, Entity,
1442
92
                                                     Kind, Exprs);
1443
92
    if (Ty.isNull())
1444
5
      return ExprError();
1445
87
    Entity = InitializedEntity::InitializeTemporary(TInfo, Ty);
1446
87
  }
1447
1448
366k
  if (Ty->isDependentType() || 
CallExpr::hasAnyTypeDependentArguments(Exprs)135k
) {
1449
    // FIXME: CXXUnresolvedConstructExpr does not model list-initialization
1450
    // directly. We work around this by dropping the locations of the braces.
1451
234k
    SourceRange Locs = ListInitialization
1452
7.44k
                           ? SourceRange()
1453
227k
                           : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc);
1454
234k
    return CXXUnresolvedConstructExpr::Create(Context, Ty.getNonReferenceType(),
1455
234k
                                              TInfo, Locs.getBegin(), Exprs,
1456
234k
                                              Locs.getEnd());
1457
234k
  }
1458
1459
  // C++ [expr.type.conv]p1:
1460
  // If the expression list is a parenthesized single expression, the type
1461
  // conversion expression is equivalent (in definedness, and if defined in
1462
  // meaning) to the corresponding cast expression.
1463
131k
  if (Exprs.size() == 1 && 
!ListInitialization68.6k
&&
1464
61.1k
      !isa<InitListExpr>(Exprs[0])) {
1465
61.0k
    Expr *Arg = Exprs[0];
1466
61.0k
    return BuildCXXFunctionalCastExpr(TInfo, Ty, LParenOrBraceLoc, Arg,
1467
61.0k
                                      RParenOrBraceLoc);
1468
61.0k
  }
1469
1470
  //   For an expression of the form T(), T shall not be an array type.
1471
70.1k
  QualType ElemTy = Ty;
1472
70.1k
  if (Ty->isArrayType()) {
1473
69
    if (!ListInitialization)
1474
5
      return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_array_type)
1475
5
                         << FullRange);
1476
64
    ElemTy = Context.getBaseElementType(Ty);
1477
64
  }
1478
1479
  // There doesn't seem to be an explicit rule against this but sanity demands
1480
  // we only construct objects with object types.
1481
70.1k
  if (Ty->isFunctionType())
1482
16
    return ExprError(Diag(TyBeginLoc, diag::err_init_for_function_type)
1483
16
                       << Ty << FullRange);
1484
1485
  // C++17 [expr.type.conv]p2:
1486
  //   If the type is cv void and the initializer is (), the expression is a
1487
  //   prvalue of the specified type that performs no initialization.
1488
70.1k
  if (!Ty->isVoidType() &&
1489
69.9k
      RequireCompleteType(TyBeginLoc, ElemTy,
1490
69.9k
                          diag::err_invalid_incomplete_type_use, FullRange))
1491
40
    return ExprError();
1492
1493
  //   Otherwise, the expression is a prvalue of the specified type whose
1494
  //   result object is direct-initialized (11.6) with the initializer.
1495
70.1k
  InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
1496
70.1k
  ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs);
1497
1498
70.1k
  if (Result.isInvalid())
1499
169
    return Result;
1500
1501
69.9k
  Expr *Inner = Result.get();
1502
69.9k
  if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner))
1503
5.04k
    Inner = BTE->getSubExpr();
1504
69.9k
  if (!isa<CXXTemporaryObjectExpr>(Inner) &&
1505
17.2k
      !isa<CXXScalarValueInitExpr>(Inner)) {
1506
    // If we created a CXXTemporaryObjectExpr, that node also represents the
1507
    // functional cast. Otherwise, create an explicit cast to represent
1508
    // the syntactic form of a functional-style cast that was used here.
1509
    //
1510
    // FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr
1511
    // would give a more consistent AST representation than using a
1512
    // CXXTemporaryObjectExpr. It's also weird that the functional cast
1513
    // is sometimes handled by initialization and sometimes not.
1514
6.95k
    QualType ResultType = Result.get()->getType();
1515
6.95k
    SourceRange Locs = ListInitialization
1516
6.90k
                           ? SourceRange()
1517
52
                           : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc);
1518
6.95k
    Result = CXXFunctionalCastExpr::Create(
1519
6.95k
        Context, ResultType, Expr::getValueKindForType(Ty), TInfo, CK_NoOp,
1520
6.95k
        Result.get(), /*Path=*/nullptr, CurFPFeatureOverrides(),
1521
6.95k
        Locs.getBegin(), Locs.getEnd());
1522
6.95k
  }
1523
1524
69.9k
  return Result;
1525
69.9k
}
1526
1527
983
bool Sema::isUsualDeallocationFunction(const CXXMethodDecl *Method) {
1528
  // [CUDA] Ignore this function, if we can't call it.
1529
983
  const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext);
1530
983
  if (getLangOpts().CUDA &&
1531
192
      IdentifyCUDAPreference(Caller, Method) <= CFP_WrongSide)
1532
95
    return false;
1533
1534
888
  SmallVector<const FunctionDecl*, 4> PreventedBy;
1535
888
  bool Result = Method->isUsualDeallocationFunction(PreventedBy);
1536
1537
888
  if (Result || 
!getLangOpts().CUDA150
||
PreventedBy.empty()18
)
1538
870
    return Result;
1539
1540
  // In case of CUDA, return true if none of the 1-argument deallocator
1541
  // functions are actually callable.
1542
22
  
return llvm::none_of(PreventedBy, [&](const FunctionDecl *FD) 18
{
1543
22
    assert(FD->getNumParams() == 1 &&
1544
22
           "Only single-operand functions should be in PreventedBy");
1545
22
    return IdentifyCUDAPreference(Caller, FD) >= CFP_HostDevice;
1546
22
  });
1547
18
}
1548
1549
/// Determine whether the given function is a non-placement
1550
/// deallocation function.
1551
18.7k
static bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD) {
1552
18.7k
  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1553
862
    return S.isUsualDeallocationFunction(Method);
1554
1555
17.8k
  if (FD->getOverloadedOperator() != OO_Delete &&
1556
4.22k
      FD->getOverloadedOperator() != OO_Array_Delete)
1557
0
    return false;
1558
1559
17.8k
  unsigned UsualParams = 1;
1560
1561
17.8k
  if (S.getLangOpts().SizedDeallocation && 
UsualParams < FD->getNumParams()182
&&
1562
122
      S.Context.hasSameUnqualifiedType(
1563
122
          FD->getParamDecl(UsualParams)->getType(),
1564
122
          S.Context.getSizeType()))
1565
75
    ++UsualParams;
1566
1567
17.8k
  if (S.getLangOpts().AlignedAllocation && 
UsualParams < FD->getNumParams()1.47k
&&
1568
1.05k
      S.Context.hasSameUnqualifiedType(
1569
1.05k
          FD->getParamDecl(UsualParams)->getType(),
1570
1.05k
          S.Context.getTypeDeclType(S.getStdAlignValT())))
1571
712
    ++UsualParams;
1572
1573
17.8k
  return UsualParams == FD->getNumParams();
1574
17.8k
}
1575
1576
namespace {
1577
  struct UsualDeallocFnInfo {
1578
10.5k
    UsualDeallocFnInfo() : Found(), FD(nullptr) {}
1579
    UsualDeallocFnInfo(Sema &S, DeclAccessPair Found)
1580
        : Found(Found), FD(dyn_cast<FunctionDecl>(Found->getUnderlyingDecl())),
1581
          Destroying(false), HasSizeT(false), HasAlignValT(false),
1582
17.8k
          CUDAPref(Sema::CFP_Native) {
1583
      // A function template declaration is never a usual deallocation function.
1584
17.8k
      if (!FD)
1585
4
        return;
1586
17.8k
      unsigned NumBaseParams = 1;
1587
17.8k
      if (FD->isDestroyingOperatorDelete()) {
1588
139
        Destroying = true;
1589
139
        ++NumBaseParams;
1590
139
      }
1591
1592
17.8k
      if (NumBaseParams < FD->getNumParams() &&
1593
11.9k
          S.Context.hasSameUnqualifiedType(
1594
11.9k
              FD->getParamDecl(NumBaseParams)->getType(),
1595
1.19k
              S.Context.getSizeType())) {
1596
1.19k
        ++NumBaseParams;
1597
1.19k
        HasSizeT = true;
1598
1.19k
      }
1599
1600
17.8k
      if (NumBaseParams < FD->getNumParams() &&
1601
11.3k
          FD->getParamDecl(NumBaseParams)->getType()->isAlignValT()) {
1602
6.05k
        ++NumBaseParams;
1603
6.05k
        HasAlignValT = true;
1604
6.05k
      }
1605
1606
      // In CUDA, determine how much we'd like / dislike to call this.
1607
17.8k
      if (S.getLangOpts().CUDA)
1608
238
        if (auto *Caller = dyn_cast<FunctionDecl>(S.CurContext))
1609
238
          CUDAPref = S.IdentifyCUDAPreference(Caller, FD);
1610
17.8k
    }
1611
1612
25.6k
    explicit operator bool() const { return FD; }
1613
1614
    bool isBetterThan(const UsualDeallocFnInfo &Other, bool WantSize,
1615
654
                      bool WantAlign) const {
1616
      // C++ P0722:
1617
      //   A destroying operator delete is preferred over a non-destroying
1618
      //   operator delete.
1619
654
      if (Destroying != Other.Destroying)
1620
30
        return Destroying;
1621
1622
      // C++17 [expr.delete]p10:
1623
      //   If the type has new-extended alignment, a function with a parameter
1624
      //   of type std::align_val_t is preferred; otherwise a function without
1625
      //   such a parameter is preferred
1626
624
      if (HasAlignValT != Other.HasAlignValT)
1627
504
        return HasAlignValT == WantAlign;
1628
1629
120
      if (HasSizeT != Other.HasSizeT)
1630
106
        return HasSizeT == WantSize;
1631
1632
      // Use CUDA call preference as a tiebreaker.
1633
14
      return CUDAPref > Other.CUDAPref;
1634
14
    }
1635
1636
    DeclAccessPair Found;
1637
    FunctionDecl *FD;
1638
    bool Destroying, HasSizeT, HasAlignValT;
1639
    Sema::CUDAFunctionPreference CUDAPref;
1640
  };
1641
}
1642
1643
/// Determine whether a type has new-extended alignment. This may be called when
1644
/// the type is incomplete (for a delete-expression with an incomplete pointee
1645
/// type), in which case it will conservatively return false if the alignment is
1646
/// not known.
1647
10.3k
static bool hasNewExtendedAlignment(Sema &S, QualType AllocType) {
1648
10.3k
  return S.getLangOpts().AlignedAllocation &&
1649
909
         S.getASTContext().getTypeAlignIfKnown(AllocType) >
1650
909
             S.getASTContext().getTargetInfo().getNewAlign();
1651
10.3k
}
1652
1653
/// Select the correct "usual" deallocation function to use from a selection of
1654
/// deallocation functions (either global or class-scope).
1655
static UsualDeallocFnInfo resolveDeallocationOverload(
1656
    Sema &S, LookupResult &R, bool WantSize, bool WantAlign,
1657
10.5k
    llvm::SmallVectorImpl<UsualDeallocFnInfo> *BestFns = nullptr) {
1658
10.5k
  UsualDeallocFnInfo Best;
1659
1660
28.1k
  for (auto I = R.begin(), E = R.end(); I != E; 
++I17.6k
) {
1661
17.6k
    UsualDeallocFnInfo Info(S, I.getPair());
1662
17.6k
    if (!Info || 
!isNonPlacementDeallocationFunction(S, Info.FD)17.6k
||
1663
6.47k
        Info.CUDAPref == Sema::CFP_Never)
1664
11.1k
      continue;
1665
1666
6.45k
    if (!Best) {
1667
5.84k
      Best = Info;
1668
5.84k
      if (BestFns)
1669
1.81k
        BestFns->push_back(Info);
1670
5.84k
      continue;
1671
5.84k
    }
1672
1673
612
    if (Best.isBetterThan(Info, WantSize, WantAlign))
1674
458
      continue;
1675
1676
    //   If more than one preferred function is found, all non-preferred
1677
    //   functions are eliminated from further consideration.
1678
154
    if (BestFns && 
Info.isBetterThan(Best, WantSize, WantAlign)42
)
1679
38
      BestFns->clear();
1680
1681
154
    Best = Info;
1682
154
    if (BestFns)
1683
42
      BestFns->push_back(Info);
1684
154
  }
1685
1686
10.5k
  return Best;
1687
10.5k
}
1688
1689
/// Determine whether a given type is a class for which 'delete[]' would call
1690
/// a member 'operator delete[]' with a 'size_t' parameter. This implies that
1691
/// we need to store the array size (even if the type is
1692
/// trivially-destructible).
1693
static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
1694
1.07k
                                         QualType allocType) {
1695
1.07k
  const RecordType *record =
1696
1.07k
    allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
1697
1.07k
  if (!record) 
return false695
;
1698
1699
  // Try to find an operator delete[] in class scope.
1700
1701
384
  DeclarationName deleteName =
1702
384
    S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
1703
384
  LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
1704
384
  S.LookupQualifiedName(ops, record->getDecl());
1705
1706
  // We're just doing this for information.
1707
384
  ops.suppressDiagnostics();
1708
1709
  // Very likely: there's no operator delete[].
1710
384
  if (ops.empty()) 
return false340
;
1711
1712
  // If it's ambiguous, it should be illegal to call operator delete[]
1713
  // on this thing, so it doesn't matter if we allocate extra space or not.
1714
44
  if (ops.isAmbiguous()) 
return false0
;
1715
1716
  // C++17 [expr.delete]p10:
1717
  //   If the deallocation functions have class scope, the one without a
1718
  //   parameter of type std::size_t is selected.
1719
44
  auto Best = resolveDeallocationOverload(
1720
44
      S, ops, /*WantSize*/false,
1721
44
      /*WantAlign*/hasNewExtendedAlignment(S, allocType));
1722
44
  return Best && Best.HasSizeT;
1723
44
}
1724
1725
/// Parsed a C++ 'new' expression (C++ 5.3.4).
1726
///
1727
/// E.g.:
1728
/// @code new (memory) int[size][4] @endcode
1729
/// or
1730
/// @code ::new Foo(23, "hello") @endcode
1731
///
1732
/// \param StartLoc The first location of the expression.
1733
/// \param UseGlobal True if 'new' was prefixed with '::'.
1734
/// \param PlacementLParen Opening paren of the placement arguments.
1735
/// \param PlacementArgs Placement new arguments.
1736
/// \param PlacementRParen Closing paren of the placement arguments.
1737
/// \param TypeIdParens If the type is in parens, the source range.
1738
/// \param D The type to be allocated, as well as array dimensions.
1739
/// \param Initializer The initializing expression or initializer-list, or null
1740
///   if there is none.
1741
ExprResult
1742
Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
1743
                  SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
1744
                  SourceLocation PlacementRParen, SourceRange TypeIdParens,
1745
24.7k
                  Declarator &D, Expr *Initializer) {
1746
24.7k
  Optional<Expr *> ArraySize;
1747
  // If the specified type is an array, unwrap it and save the expression.
1748
24.7k
  if (D.getNumTypeObjects() > 0 &&
1749
1.23k
      D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
1750
1.19k
    DeclaratorChunk &Chunk = D.getTypeObject(0);
1751
1.19k
    if (D.getDeclSpec().hasAutoTypeSpec())
1752
0
      return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
1753
0
        << D.getSourceRange());
1754
1.19k
    if (Chunk.Arr.hasStatic)
1755
0
      return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
1756
0
        << D.getSourceRange());
1757
1.19k
    if (!Chunk.Arr.NumElts && 
!Initializer32
)
1758
9
      return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
1759
9
        << D.getSourceRange());
1760
1761
1.19k
    ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
1762
1.19k
    D.DropFirstTypeObject();
1763
1.19k
  }
1764
1765
  // Every dimension shall be of constant size.
1766
24.7k
  if (ArraySize) {
1767
1.24k
    for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; 
++I51
) {
1768
137
      if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
1769
72
        break;
1770
1771
65
      DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
1772
65
      if (Expr *NumElts = (Expr *)Array.NumElts) {
1773
65
        if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
1774
          // FIXME: GCC permits constant folding here. We should either do so consistently
1775
          // or not do so at all, rather than changing behavior in C++14 onwards.
1776
65
          if (getLangOpts().CPlusPlus14) {
1777
            // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator
1778
            //   shall be a converted constant expression (5.19) of type std::size_t
1779
            //   and shall evaluate to a strictly positive value.
1780
24
            llvm::APSInt Value(Context.getIntWidth(Context.getSizeType()));
1781
24
            Array.NumElts
1782
24
             = CheckConvertedConstantExpression(NumElts, Context.getSizeType(), Value,
1783
24
                                                CCEK_ArrayBound)
1784
24
                 .get();
1785
41
          } else {
1786
41
            Array.NumElts =
1787
41
                VerifyIntegerConstantExpression(
1788
41
                    NumElts, nullptr, diag::err_new_array_nonconst, AllowFold)
1789
41
                    .get();
1790
41
          }
1791
65
          if (!Array.NumElts)
1792
14
            return ExprError();
1793
65
        }
1794
65
      }
1795
65
    }
1796
1.19k
  }
1797
1798
24.7k
  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/nullptr);
1799
24.7k
  QualType AllocType = TInfo->getType();
1800
24.7k
  if (D.isInvalidType())
1801
11
    return ExprError();
1802
1803
24.7k
  SourceRange DirectInitRange;
1804
24.7k
  if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer))
1805
21.7k
    DirectInitRange = List->getSourceRange();
1806
1807
24.7k
  return BuildCXXNew(SourceRange(StartLoc, D.getEndLoc()), UseGlobal,
1808
24.7k
                     PlacementLParen, PlacementArgs, PlacementRParen,
1809
24.7k
                     TypeIdParens, AllocType, TInfo, ArraySize, DirectInitRange,
1810
24.7k
                     Initializer);
1811
24.7k
}
1812
1813
static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style,
1814
1.22k
                                       Expr *Init) {
1815
1.22k
  if (!Init)
1816
1.08k
    return true;
1817
142
  if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
1818
57
    return PLE->getNumExprs() == 0;
1819
85
  if (isa<ImplicitValueInitExpr>(Init))
1820
0
    return true;
1821
85
  else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
1822
0
    return !CCE->isListInitialization() &&
1823
0
           CCE->getConstructor()->isDefaultConstructor();
1824
85
  else if (Style == CXXNewExpr::ListInit) {
1825
85
    assert(isa<InitListExpr>(Init) &&
1826
85
           "Shouldn't create list CXXConstructExprs for arrays.");
1827
85
    return true;
1828
85
  }
1829
0
  return false;
1830
0
}
1831
1832
bool
1833
1.91M
Sema::isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const {
1834
1.91M
  if (!getLangOpts().AlignedAllocationUnavailable)
1835
1.91M
    return false;
1836
479
  if (FD.isDefined())
1837
180
    return false;
1838
299
  Optional<unsigned> AlignmentParam;
1839
299
  if (FD.isReplaceableGlobalAllocationFunction(&AlignmentParam) &&
1840
259
      AlignmentParam.hasValue())
1841
161
    return true;
1842
138
  return false;
1843
138
}
1844
1845
// Emit a diagnostic if an aligned allocation/deallocation function that is not
1846
// implemented in the standard library is selected.
1847
void Sema::diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD,
1848
1.91M
                                                SourceLocation Loc) {
1849
1.91M
  if (isUnavailableAlignedAllocationFunction(FD)) {
1850
161
    const llvm::Triple &T = getASTContext().getTargetInfo().getTriple();
1851
161
    StringRef OSName = AvailabilityAttr::getPlatformNameSourceSpelling(
1852
161
        getASTContext().getTargetInfo().getPlatformName());
1853
161
    VersionTuple OSVersion = alignedAllocMinVersion(T.getOS());
1854
1855
161
    OverloadedOperatorKind Kind = FD.getDeclName().getCXXOverloadedOperator();
1856
161
    bool IsDelete = Kind == OO_Delete || 
Kind == OO_Array_Delete105
;
1857
161
    Diag(Loc, diag::err_aligned_allocation_unavailable)
1858
161
        << IsDelete << FD.getType().getAsString() << OSName
1859
161
        << OSVersion.getAsString() << OSVersion.empty();
1860
161
    Diag(Loc, diag::note_silence_aligned_allocation_unavailable);
1861
161
  }
1862
1.91M
}
1863
1864
ExprResult
1865
Sema::BuildCXXNew(SourceRange Range, bool UseGlobal,
1866
                  SourceLocation PlacementLParen,
1867
                  MultiExprArg PlacementArgs,
1868
                  SourceLocation PlacementRParen,
1869
                  SourceRange TypeIdParens,
1870
                  QualType AllocType,
1871
                  TypeSourceInfo *AllocTypeInfo,
1872
                  Optional<Expr *> ArraySize,
1873
                  SourceRange DirectInitRange,
1874
26.3k
                  Expr *Initializer) {
1875
26.3k
  SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
1876
26.3k
  SourceLocation StartLoc = Range.getBegin();
1877
1878
26.3k
  CXXNewExpr::InitializationStyle initStyle;
1879
26.3k
  if (DirectInitRange.isValid()) {
1880
23.0k
    assert(Initializer && "Have parens but no initializer.");
1881
23.0k
    initStyle = CXXNewExpr::CallInit;
1882
3.28k
  } else if (Initializer && 
isa<InitListExpr>(Initializer)177
)
1883
177
    initStyle = CXXNewExpr::ListInit;
1884
3.11k
  else {
1885
3.11k
    assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||
1886
3.11k
            isa<CXXConstructExpr>(Initializer)) &&
1887
3.11k
           "Initializer expression that cannot have been implicitly created.");
1888
3.11k
    initStyle = CXXNewExpr::NoInit;
1889
3.11k
  }
1890
1891
26.3k
  Expr **Inits = &Initializer;
1892
23.2k
  unsigned NumInits = Initializer ? 1 : 
03.11k
;
1893
26.3k
  if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {
1894
23.0k
    assert(initStyle == CXXNewExpr::CallInit && "paren init for non-call init");
1895
23.0k
    Inits = List->getExprs();
1896
23.0k
    NumInits = List->getNumExprs();
1897
23.0k
  }
1898
1899
  // C++11 [expr.new]p15:
1900
  //   A new-expression that creates an object of type T initializes that
1901
  //   object as follows:
1902
26.3k
  InitializationKind Kind
1903
      //     - If the new-initializer is omitted, the object is default-
1904
      //       initialized (8.5); if no initialization is performed,
1905
      //       the object has indeterminate value
1906
26.3k
      = initStyle == CXXNewExpr::NoInit
1907
3.11k
            ? InitializationKind::CreateDefault(TypeRange.getBegin())
1908
            //     - Otherwise, the new-initializer is interpreted according to
1909
            //     the
1910
            //       initialization rules of 8.5 for direct-initialization.
1911
23.2k
            : initStyle == CXXNewExpr::ListInit
1912
177
                  ? InitializationKind::CreateDirectList(
1913
177
                        TypeRange.getBegin(), Initializer->getBeginLoc(),
1914
177
                        Initializer->getEndLoc())
1915
23.0k
                  : InitializationKind::CreateDirect(TypeRange.getBegin(),
1916
23.0k
                                                     DirectInitRange.getBegin(),
1917
23.0k
                                                     DirectInitRange.getEnd());
1918
1919
  // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
1920
26.3k
  auto *Deduced = AllocType->getContainedDeducedType();
1921
26.3k
  if (Deduced && 
isa<DeducedTemplateSpecializationType>(Deduced)70
) {
1922
18
    if (ArraySize)
1923
0
      return ExprError(
1924
0
          Diag(ArraySize ? (*ArraySize)->getExprLoc() : TypeRange.getBegin(),
1925
0
               diag::err_deduced_class_template_compound_type)
1926
0
          << /*array*/ 2
1927
0
          << (ArraySize ? (*ArraySize)->getSourceRange() : TypeRange));
1928
1929
18
    InitializedEntity Entity
1930
18
      = InitializedEntity::InitializeNew(StartLoc, AllocType);
1931
18
    AllocType = DeduceTemplateSpecializationFromInitializer(
1932
18
        AllocTypeInfo, Entity, Kind, MultiExprArg(Inits, NumInits));
1933
18
    if (AllocType.isNull())
1934
0
      return ExprError();
1935
26.3k
  } else if (Deduced) {
1936
52
    bool Braced = (initStyle == CXXNewExpr::ListInit);
1937
52
    if (NumInits == 1) {
1938
49
      if (auto p = dyn_cast_or_null<InitListExpr>(Inits[0])) {
1939
20
        Inits = p->getInits();
1940
20
        NumInits = p->getNumInits();
1941
20
        Braced = true;
1942
20
      }
1943
49
    }
1944
1945
52
    if (initStyle == CXXNewExpr::NoInit || 
NumInits == 051
)
1946
6
      return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
1947
6
                       << AllocType << TypeRange);
1948
46
    if (NumInits > 1) {
1949
10
      Expr *FirstBad = Inits[1];
1950
10
      return ExprError(Diag(FirstBad->getBeginLoc(),
1951
10
                            diag::err_auto_new_ctor_multiple_expressions)
1952
10
                       << AllocType << TypeRange);
1953
10
    }
1954
36
    if (Braced && 
!getLangOpts().CPlusPlus177
)
1955
5
      Diag(Initializer->getBeginLoc(), diag::ext_auto_new_list_init)
1956
5
          << AllocType << TypeRange;
1957
36
    Expr *Deduce = Inits[0];
1958
36
    QualType DeducedType;
1959
36
    if (DeduceAutoType(AllocTypeInfo, Deduce, DeducedType) == DAR_Failed)
1960
1
      return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
1961
1
                       << AllocType << Deduce->getType()
1962
1
                       << TypeRange << Deduce->getSourceRange());
1963
35
    if (DeducedType.isNull())
1964
1
      return ExprError();
1965
34
    AllocType = DeducedType;
1966
34
  }
1967
1968
  // Per C++0x [expr.new]p5, the type being constructed may be a
1969
  // typedef of an array type.
1970
26.3k
  if (!ArraySize) {
1971
25.0k
    if (const ConstantArrayType *Array
1972
8
                              = Context.getAsConstantArrayType(AllocType)) {
1973
8
      ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
1974
8
                                         Context.getSizeType(),
1975
8
                                         TypeRange.getEnd());
1976
8
      AllocType = Array->getElementType();
1977
8
    }
1978
25.0k
  }
1979
1980
26.3k
  if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
1981
59
    return ExprError();
1982
1983
  // In ARC, infer 'retaining' for the allocated
1984
26.2k
  if (getLangOpts().ObjCAutoRefCount &&
1985
31
      AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1986
14
      AllocType->isObjCLifetimeType()) {
1987
0
    AllocType = Context.getLifetimeQualifiedType(AllocType,
1988
0
                                    AllocType->getObjCARCImplicitLifetime());
1989
0
  }
1990
1991
26.2k
  QualType ResultType = Context.getPointerType(AllocType);
1992
1993
26.2k
  if (ArraySize && 
*ArraySize1.26k
&&
1994
1.22k
      (*ArraySize)->getType()->isNonOverloadPlaceholderType()) {
1995
4
    ExprResult result = CheckPlaceholderExpr(*ArraySize);
1996
4
    if (result.isInvalid()) 
return ExprError()0
;
1997
4
    ArraySize = result.get();
1998
4
  }
1999
  // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
2000
  //   integral or enumeration type with a non-negative value."
2001
  // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
2002
  //   enumeration type, or a class type for which a single non-explicit
2003
  //   conversion function to integral or unscoped enumeration type exists.
2004
  // C++1y [expr.new]p6: The expression [...] is implicitly converted to
2005
  //   std::size_t.
2006
26.2k
  llvm::Optional<uint64_t> KnownArraySize;
2007
26.2k
  if (ArraySize && 
*ArraySize1.26k
&&
!(*ArraySize)->isTypeDependent()1.22k
) {
2008
1.21k
    ExprResult ConvertedSize;
2009
1.21k
    if (getLangOpts().CPlusPlus14) {
2010
440
      assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?");
2011
2012
440
      ConvertedSize = PerformImplicitConversion(*ArraySize, Context.getSizeType(),
2013
440
                                                AA_Converting);
2014
2015
440
      if (!ConvertedSize.isInvalid() &&
2016
434
          (*ArraySize)->getType()->getAs<RecordType>())
2017
        // Diagnose the compatibility of this conversion.
2018
12
        Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion)
2019
12
          << (*ArraySize)->getType() << 0 << "'size_t'";
2020
777
    } else {
2021
777
      class SizeConvertDiagnoser : public ICEConvertDiagnoser {
2022
777
      protected:
2023
777
        Expr *ArraySize;
2024
2025
777
      public:
2026
777
        SizeConvertDiagnoser(Expr *ArraySize)
2027
777
            : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false),
2028
777
              ArraySize(ArraySize) {}
2029
2030
777
        SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
2031
5
                                             QualType T) override {
2032
5
          return S.Diag(Loc, diag::err_array_size_not_integral)
2033
5
                   << S.getLangOpts().CPlusPlus11 << T;
2034
5
        }
2035
2036
777
        SemaDiagnosticBuilder diagnoseIncomplete(
2037
0
            Sema &S, SourceLocation Loc, QualType T) override {
2038
0
          return S.Diag(Loc, diag::err_array_size_incomplete_type)
2039
0
                   << T << ArraySize->getSourceRange();
2040
0
        }
2041
2042
777
        SemaDiagnosticBuilder diagnoseExplicitConv(
2043
1
            Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
2044
1
          return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;
2045
1
        }
2046
2047
777
        SemaDiagnosticBuilder noteExplicitConv(
2048
1
            Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
2049
1
          return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
2050
1
                   << ConvTy->isEnumeralType() << ConvTy;
2051
1
        }
2052
2053
777
        SemaDiagnosticBuilder diagnoseAmbiguous(
2054
9
            Sema &S, SourceLocation Loc, QualType T) override {
2055
9
          return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;
2056
9
        }
2057
2058
777
        SemaDiagnosticBuilder noteAmbiguous(
2059
18
            Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
2060
18
          return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
2061
18
                   << ConvTy->isEnumeralType() << ConvTy;
2062
18
        }
2063
2064
777
        SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
2065
777
                                                 QualType T,
2066
15
                                                 QualType ConvTy) override {
2067
15
          return S.Diag(Loc,
2068
15
                        S.getLangOpts().CPlusPlus11
2069
8
                          ? diag::warn_cxx98_compat_array_size_conversion
2070
7
                          : diag::ext_array_size_conversion)
2071
15
                   << T << ConvTy->isEnumeralType() << ConvTy;
2072
15
        }
2073
777
      } SizeDiagnoser(*ArraySize);
2074
2075
777
      ConvertedSize = PerformContextualImplicitConversion(StartLoc, *ArraySize,
2076
777
                                                          SizeDiagnoser);
2077
777
    }
2078
1.21k
    if (ConvertedSize.isInvalid())
2079
6
      return ExprError();
2080
2081
1.21k
    ArraySize = ConvertedSize.get();
2082
1.21k
    QualType SizeType = (*ArraySize)->getType();
2083
2084
1.21k
    if (!SizeType->isIntegralOrUnscopedEnumerationType())
2085
14
      return ExprError();
2086
2087
    // C++98 [expr.new]p7:
2088
    //   The expression in a direct-new-declarator shall have integral type
2089
    //   with a non-negative value.
2090
    //
2091
    // Let's see if this is a constant < 0. If so, we reject it out of hand,
2092
    // per CWG1464. Otherwise, if it's not a constant, we must have an
2093
    // unparenthesized array type.
2094
1.19k
    if (!(*ArraySize)->isValueDependent()) {
2095
      // We've already performed any required implicit conversion to integer or
2096
      // unscoped enumeration type.
2097
      // FIXME: Per CWG1464, we are required to check the value prior to
2098
      // converting to size_t. This will never find a negative array size in
2099
      // C++14 onwards, because Value is always unsigned here!
2100
927
      if (Optional<llvm::APSInt> Value =
2101
649
              (*ArraySize)->getIntegerConstantExpr(Context)) {
2102
649
        if (Value->isSigned() && 
Value->isNegative()365
) {
2103
4
          return ExprError(Diag((*ArraySize)->getBeginLoc(),
2104
4
                                diag::err_typecheck_negative_array_size)
2105
4
                           << (*ArraySize)->getSourceRange());
2106
4
        }
2107
2108
645
        if (!AllocType->isDependentType()) {
2109
627
          unsigned ActiveSizeBits = ConstantArrayType::getNumAddressingBits(
2110
627
              Context, AllocType, *Value);
2111
627
          if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
2112
9
            return ExprError(
2113
9
                Diag((*ArraySize)->getBeginLoc(), diag::err_array_too_large)
2114
9
                << Value->toString(10) << (*ArraySize)->getSourceRange());
2115
636
        }
2116
2117
636
        KnownArraySize = Value->getZExtValue();
2118
278
      } else if (TypeIdParens.isValid()) {
2119
        // Can't have dynamic array size when the type-id is in parentheses.
2120
8
        Diag((*ArraySize)->getBeginLoc(), diag::ext_new_paren_array_nonconst)
2121
8
            << (*ArraySize)->getSourceRange()
2122
8
            << FixItHint::CreateRemoval(TypeIdParens.getBegin())
2123
8
            << FixItHint::CreateRemoval(TypeIdParens.getEnd());
2124
2125
8
        TypeIdParens = SourceRange();
2126
8
      }
2127
927
    }
2128
2129
    // Note that we do *not* convert the argument in any way.  It can
2130
    // be signed, larger than size_t, whatever.
2131
1.19k
  }
2132
2133
26.2k
  FunctionDecl *OperatorNew = nullptr;
2134
26.2k
  FunctionDecl *OperatorDelete = nullptr;
2135
26.2k
  unsigned Alignment =
2136
21.2k
      AllocType->isDependentType() ? 0 : 
Context.getTypeAlign(AllocType)5.03k
;
2137
26.2k
  unsigned NewAlignment = Context.getTargetInfo().getNewAlign();
2138
26.2k
  bool PassAlignment = getLangOpts().AlignedAllocation &&
2139
1.20k
                       Alignment > NewAlignment;
2140
2141
17.6k
  AllocationFunctionScope Scope = UseGlobal ? AFS_Global : 
AFS_Both8.61k
;
2142
26.2k
  if (!AllocType->isDependentType() &&
2143
5.03k
      !Expr::hasAnyTypeDependentArguments(PlacementArgs) &&
2144
5.02k
      FindAllocationFunctions(
2145
5.02k
          StartLoc, SourceRange(PlacementLParen, PlacementRParen), Scope, Scope,
2146
5.02k
          AllocType, ArraySize.hasValue(), PassAlignment, PlacementArgs,
2147
5.02k
          OperatorNew, OperatorDelete))
2148
46
    return ExprError();
2149
2150
  // If this is an array allocation, compute whether the usual array
2151
  // deallocation function for the type has a size_t parameter.
2152
26.2k
  bool UsualArrayDeleteWantsSize = false;
2153
26.2k
  if (ArraySize && 
!AllocType->isDependentType()1.22k
)
2154
1.05k
    UsualArrayDeleteWantsSize =
2155
1.05k
        doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
2156
2157
26.2k
  SmallVector<Expr *, 8> AllPlaceArgs;
2158
26.2k
  if (OperatorNew) {
2159
4.98k
    auto *Proto = OperatorNew->getType()->castAs<FunctionProtoType>();
2160
24
    VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction
2161
4.95k
                                                    : VariadicDoesNotApply;
2162
2163
    // We've already converted the placement args, just fill in any default
2164
    // arguments. Skip the first parameter because we don't have a corresponding
2165
    // argument. Skip the second parameter too if we're passing in the
2166
    // alignment; we've already filled it in.
2167
4.86k
    unsigned NumImplicitArgs = PassAlignment ? 
2119
: 1;
2168
4.98k
    if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto,
2169
4.98k
                               NumImplicitArgs, PlacementArgs, AllPlaceArgs,
2170
4.98k
                               CallType))
2171
1
      return ExprError();
2172
2173
4.97k
    if (!AllPlaceArgs.empty())
2174
1.58k
      PlacementArgs = AllPlaceArgs;
2175
2176
    // We would like to perform some checking on the given `operator new` call,
2177
    // but the PlacementArgs does not contain the implicit arguments,
2178
    // namely allocation size and maybe allocation alignment,
2179
    // so we need to conjure them.
2180
2181
4.97k
    QualType SizeTy = Context.getSizeType();
2182
4.97k
    unsigned SizeTyWidth = Context.getTypeSize(SizeTy);
2183
2184
4.97k
    llvm::APInt SingleEltSize(
2185
4.97k
        SizeTyWidth, Context.getTypeSizeInChars(AllocType).getQuantity());
2186
2187
    // How many bytes do we want to allocate here?
2188
4.97k
    llvm::Optional<llvm::APInt> AllocationSize;
2189
4.97k
    if (!ArraySize.hasValue() && 
!AllocType->isDependentType()3.92k
) {
2190
      // For non-array operator new, we only want to allocate one element.
2191
3.92k
      AllocationSize = SingleEltSize;
2192
1.05k
    } else if (KnownArraySize.hasValue() && 
!AllocType->isDependentType()616
) {
2193
      // For array operator new, only deal with static array size case.
2194
616
      bool Overflow;
2195
616
      AllocationSize = llvm::APInt(SizeTyWidth, *KnownArraySize)
2196
616
                           .umul_ov(SingleEltSize, Overflow);
2197
616
      (void)Overflow;
2198
616
      assert(
2199
616
          !Overflow &&
2200
616
          "Expected that all the overflows would have been handled already.");
2201
616
    }
2202
2203
4.97k
    IntegerLiteral AllocationSizeLiteral(
2204
4.97k
        Context,
2205
4.97k
        AllocationSize.getValueOr(llvm::APInt::getNullValue(SizeTyWidth)),
2206
4.97k
        SizeTy, SourceLocation());
2207
    // Otherwise, if we failed to constant-fold the allocation size, we'll
2208
    // just give up and pass-in something opaque, that isn't a null pointer.
2209
4.97k
    OpaqueValueExpr OpaqueAllocationSize(SourceLocation(), SizeTy, VK_RValue,
2210
4.97k
                                         OK_Ordinary, /*SourceExpr=*/nullptr);
2211
2212
    // Let's synthesize the alignment argument in case we will need it.
2213
    // Since we *really* want to allocate these on stack, this is slightly ugly
2214
    // because there might not be a `std::align_val_t` type.
2215
4.97k
    EnumDecl *StdAlignValT = getStdAlignValT();
2216
4.97k
    QualType AlignValT =
2217
2.96k
        StdAlignValT ? Context.getTypeDeclType(StdAlignValT) : 
SizeTy2.01k
;
2218
4.97k
    IntegerLiteral AlignmentLiteral(
2219
4.97k
        Context,
2220
4.97k
        llvm::APInt(Context.getTypeSize(SizeTy),
2221
4.97k
                    Alignment / Context.getCharWidth()),
2222
4.97k
        SizeTy, SourceLocation());
2223
4.97k
    ImplicitCastExpr DesiredAlignment(ImplicitCastExpr::OnStack, AlignValT,
2224
4.97k
                                      CK_IntegralCast, &AlignmentLiteral,
2225
4.97k
                                      VK_RValue, FPOptionsOverride());
2226
2227
    // Adjust placement args by prepending conjured size and alignment exprs.
2228
4.97k
    llvm::SmallVector<Expr *, 8> CallArgs;
2229
4.97k
    CallArgs.reserve(NumImplicitArgs + PlacementArgs.size());
2230
4.97k
    CallArgs.emplace_back(AllocationSize.hasValue()
2231
4.54k
                              ? static_cast<Expr *>(&AllocationSizeLiteral)
2232
438
                              : &OpaqueAllocationSize);
2233
4.97k
    if (PassAlignment)
2234
119
      CallArgs.emplace_back(&DesiredAlignment);
2235
4.97k
    CallArgs.insert(CallArgs.end(), PlacementArgs.begin(), PlacementArgs.end());
2236
2237
4.97k
    DiagnoseSentinelCalls(OperatorNew, PlacementLParen, CallArgs);
2238
2239
4.97k
    checkCall(OperatorNew, Proto, /*ThisArg=*/nullptr, CallArgs,
2240
4.97k
              /*IsMemberFunction=*/false, StartLoc, Range, CallType);
2241
2242
    // Warn if the type is over-aligned and is being allocated by (unaligned)
2243
    // global operator new.
2244
4.97k
    if (PlacementArgs.empty() && 
!PassAlignment3.39k
&&
2245
3.31k
        (OperatorNew->isImplicit() ||
2246
1.38k
         (OperatorNew->getBeginLoc().isValid() &&
2247
3.07k
          
getSourceManager().isInSystemHeader(OperatorNew->getBeginLoc())1.37k
))) {
2248
3.07k
      if (Alignment > NewAlignment)
2249
37
        Diag(StartLoc, diag::warn_overaligned_type)
2250
37
            << AllocType
2251
37
            << unsigned(Alignment / Context.getCharWidth())
2252
37
            << unsigned(NewAlignment / Context.getCharWidth());
2253
3.07k
    }
2254
4.97k
  }
2255
2256
  // Array 'new' can't have any initializers except empty parentheses.
2257
  // Initializer lists are also allowed, in C++11. Rely on the parser for the
2258
  // dialect distinction.
2259
26.2k
  if (ArraySize && 
!isLegalArrayNewInitializer(initStyle, Initializer)1.22k
) {
2260
20
    SourceRange InitRange(Inits[0]->getBeginLoc(),
2261
20
                          Inits[NumInits - 1]->getEndLoc());
2262
20
    Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
2263
20
    return ExprError();
2264
20
  }
2265
2266
  // If we can perform the initialization, and we've not already done so,
2267
  // do it now.
2268
26.1k
  if (!AllocType->isDependentType() &&
2269
4.96k
      !Expr::hasAnyTypeDependentArguments(
2270
4.94k
          llvm::makeArrayRef(Inits, NumInits))) {
2271
    // The type we initialize is the complete type, including the array bound.
2272
4.94k
    QualType InitType;
2273
4.94k
    if (KnownArraySize)
2274
600
      InitType = Context.getConstantArrayType(
2275
600
          AllocType,
2276
600
          llvm::APInt(Context.getTypeSize(Context.getSizeType()),
2277
600
                      *KnownArraySize),
2278
600
          *ArraySize, ArrayType::Normal, 0);
2279
4.34k
    else if (ArraySize)
2280
432
      InitType =
2281
432
          Context.getIncompleteArrayType(AllocType, ArrayType::Normal, 0);
2282
3.91k
    else
2283
3.91k
      InitType = AllocType;
2284
2285
4.94k
    InitializedEntity Entity
2286
4.94k
      = InitializedEntity::InitializeNew(StartLoc, InitType);
2287
4.94k
    InitializationSequence InitSeq(*this, Entity, Kind,
2288
4.94k
                                   MultiExprArg(Inits, NumInits));
2289
4.94k
    ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
2290
4.94k
                                          MultiExprArg(Inits, NumInits));
2291
4.94k
    if (FullInit.isInvalid())
2292
66
      return ExprError();
2293
2294
    // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
2295
    // we don't want the initialized object to be destructed.
2296
    // FIXME: We should not create these in the first place.
2297
4.87k
    if (CXXBindTemporaryExpr *Binder =
2298
0
            dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
2299
0
      FullInit = Binder->getSubExpr();
2300
2301
4.87k
    Initializer = FullInit.get();
2302
2303
    // FIXME: If we have a KnownArraySize, check that the array bound of the
2304
    // initializer is no greater than that constant value.
2305
2306
4.87k
    if (ArraySize && 
!*ArraySize1.01k
) {
2307
26
      auto *CAT = Context.getAsConstantArrayType(Initializer->getType());
2308
26
      if (CAT) {
2309
        // FIXME: Track that the array size was inferred rather than explicitly
2310
        // specified.
2311
22
        ArraySize = IntegerLiteral::Create(
2312
22
            Context, CAT->getSize(), Context.getSizeType(), TypeRange.getEnd());
2313
4
      } else {
2314
4
        Diag(TypeRange.getEnd(), diag::err_new_array_size_unknown_from_init)
2315
4
            << Initializer->getSourceRange();
2316
4
      }
2317
26
    }
2318
4.87k
  }
2319
2320
  // Mark the new and delete operators as referenced.
2321
26.1k
  if (OperatorNew) {
2322
4.89k
    if (DiagnoseUseOfDecl(OperatorNew, StartLoc))
2323
0
      return ExprError();
2324
4.89k
    MarkFunctionReferenced(StartLoc, OperatorNew);
2325
4.89k
  }
2326
26.1k
  if (OperatorDelete) {
2327
2.44k
    if (DiagnoseUseOfDecl(OperatorDelete, StartLoc))
2328
38
      return ExprError();
2329
2.41k
    MarkFunctionReferenced(StartLoc, OperatorDelete);
2330
2.41k
  }
2331
2332
26.0k
  return CXXNewExpr::Create(Context, UseGlobal, OperatorNew, OperatorDelete,
2333
26.0k
                            PassAlignment, UsualArrayDeleteWantsSize,
2334
26.0k
                            PlacementArgs, TypeIdParens, ArraySize, initStyle,
2335
26.0k
                            Initializer, ResultType, AllocTypeInfo, Range,
2336
26.0k
                            DirectInitRange);
2337
26.1k
}
2338
2339
/// Checks that a type is suitable as the allocated type
2340
/// in a new-expression.
2341
bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
2342
26.3k
                              SourceRange R) {
2343
  // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
2344
  //   abstract class type or array thereof.
2345
26.3k
  if (AllocType->isFunctionType())
2346
0
    return Diag(Loc, diag::err_bad_new_type)
2347
0
      << AllocType << 0 << R;
2348
26.3k
  else if (AllocType->isReferenceType())
2349
4
    return Diag(Loc, diag::err_bad_new_type)
2350
4
      << AllocType << 1 << R;
2351
26.3k
  else if (!AllocType->isDependentType() &&
2352
5.11k
           RequireCompleteSizedType(
2353
5.11k
               Loc, AllocType, diag::err_new_incomplete_or_sizeless_type, R))
2354
36
    return true;
2355
26.3k
  else if (RequireNonAbstractType(Loc, AllocType,
2356
26.3k
                                  diag::err_allocation_of_abstract_type))
2357
8
    return true;
2358
26.2k
  else if (AllocType->isVariablyModifiedType())
2359
3
    return Diag(Loc, diag::err_variably_modified_new_type)
2360
3
             << AllocType;
2361
26.2k
  else if (AllocType.getAddressSpace() != LangAS::Default &&
2362
8
           !getLangOpts().OpenCLCPlusPlus)
2363
8
    return Diag(Loc, diag::err_address_space_qualified_new)
2364
8
      << AllocType.getUnqualifiedType()
2365
8
      << AllocType.getQualifiers().getAddressSpaceAttributePrintValue();
2366
26.2k
  else if (getLangOpts().ObjCAutoRefCount) {
2367
31
    if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
2368
0
      QualType BaseAllocType = Context.getBaseElementType(AT);
2369
0
      if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
2370
0
          BaseAllocType->isObjCLifetimeType())
2371
0
        return Diag(Loc, diag::err_arc_new_array_without_ownership)
2372
0
          << BaseAllocType;
2373
26.2k
    }
2374
31
  }
2375
2376
26.2k
  return false;
2377
26.2k
}
2378
2379
static bool resolveAllocationOverload(
2380
    Sema &S, LookupResult &R, SourceRange Range, SmallVectorImpl<Expr *> &Args,
2381
    bool &PassAlignment, FunctionDecl *&Operator,
2382
5.30k
    OverloadCandidateSet *AlignedCandidates, Expr *AlignArg, bool Diagnose) {
2383
5.30k
  OverloadCandidateSet Candidates(R.getNameLoc(),
2384
5.30k
                                  OverloadCandidateSet::CSK_Normal);
2385
5.30k
  for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
2386
22.2k
       Alloc != AllocEnd; 
++Alloc16.9k
) {
2387
    // Even member operator new/delete are implicitly treated as
2388
    // static, so don't use AddMemberCandidate.
2389
16.9k
    NamedDecl *D = (*Alloc)->getUnderlyingDecl();
2390
2391
16.9k
    if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
2392
60
      S.AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
2393
60
                                     /*ExplicitTemplateArgs=*/nullptr, Args,
2394
60
                                     Candidates,
2395
60
                                     /*SuppressUserConversions=*/false);
2396
60
      continue;
2397
60
    }
2398
2399
16.8k
    FunctionDecl *Fn = cast<FunctionDecl>(D);
2400
16.8k
    S.AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates,
2401
16.8k
                           /*SuppressUserConversions=*/false);
2402
16.8k
  }
2403
2404
  // Do the resolution.
2405
5.30k
  OverloadCandidateSet::iterator Best;
2406
5.30k
  switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
2407
5.17k
  case OR_Success: {
2408
    // Got one!
2409
5.17k
    FunctionDecl *FnDecl = Best->Function;
2410
5.17k
    if (S.CheckAllocationAccess(R.getNameLoc(), Range, R.getNamingClass(),
2411
5.17k
                                Best->FoundDecl) == Sema::AR_inaccessible)
2412
8
      return true;
2413
2414
5.16k
    Operator = FnDecl;
2415
5.16k
    return false;
2416
5.16k
  }
2417
2418
112
  case OR_No_Viable_Function:
2419
    // C++17 [expr.new]p13:
2420
    //   If no matching function is found and the allocated object type has
2421
    //   new-extended alignment, the alignment argument is removed from the
2422
    //   argument list, and overload resolution is performed again.
2423
112
    if (PassAlignment) {
2424
86
      PassAlignment = false;
2425
86
      AlignArg = Args[1];
2426
86
      Args.erase(Args.begin() + 1);
2427
86
      return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2428
86
                                       Operator, &Candidates, AlignArg,
2429
86
                                       Diagnose);
2430
86
    }
2431
2432
    // MSVC will fall back on trying to find a matching global operator new
2433
    // if operator new[] cannot be found.  Also, MSVC will leak by not
2434
    // generating a call to operator delete or operator delete[], but we
2435
    // will not replicate that bug.
2436
    // FIXME: Find out how this interacts with the std::align_val_t fallback
2437
    // once MSVC implements it.
2438
26
    if (R.getLookupName().getCXXOverloadedOperator() == OO_Array_New &&
2439
5
        S.Context.getLangOpts().MSVCCompat) {
2440
4
      R.clear();
2441
4
      R.setLookupName(S.Context.DeclarationNames.getCXXOperatorName(OO_New));
2442
4
      S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl());
2443
      // FIXME: This will give bad diagnostics pointing at the wrong functions.
2444
4
      return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2445
4
                                       Operator, /*Candidates=*/nullptr,
2446
4
                                       /*AlignArg=*/nullptr, Diagnose);
2447
4
    }
2448
2449
22
    if (Diagnose) {
2450
20
      PartialDiagnosticAt PD(R.getNameLoc(), S.PDiag(diag::err_ovl_no_viable_function_in_call)
2451
20
          << R.getLookupName() << Range);
2452
2453
      // If we have aligned candidates, only note the align_val_t candidates
2454
      // from AlignedCandidates and the non-align_val_t candidates from
2455
      // Candidates.
2456
20
      if (AlignedCandidates) {
2457
0
        auto IsAligned = [](OverloadCandidate &C) {
2458
0
          return C.Function->getNumParams() > 1 &&
2459
0
                 C.Function->getParamDecl(1)->getType()->isAlignValT();
2460
0
        };
2461
0
        auto IsUnaligned = [&](OverloadCandidate &C) { return !IsAligned(C); };
2462
2463
        // This was an overaligned allocation, so list the aligned candidates
2464
        // first.
2465
0
        Args.insert(Args.begin() + 1, AlignArg);
2466
0
        AlignedCandidates->NoteCandidates(PD, S, OCD_AllCandidates, Args, "",
2467
0
                                          R.getNameLoc(), IsAligned);
2468
0
        Args.erase(Args.begin() + 1);
2469
0
        Candidates.NoteCandidates(PD, S, OCD_AllCandidates, Args, "", R.getNameLoc(),
2470
0
                                  IsUnaligned);
2471
20
      } else {
2472
20
        Candidates.NoteCandidates(PD, S, OCD_AllCandidates, Args);
2473
20
      }
2474
20
    }
2475
22
    return true;
2476
2477
4
  case OR_Ambiguous:
2478
4
    if (Diagnose) {
2479
4
      Candidates.NoteCandidates(
2480
4
          PartialDiagnosticAt(R.getNameLoc(),
2481
4
                              S.PDiag(diag::err_ovl_ambiguous_call)
2482
4
                                  << R.getLookupName() << Range),
2483
4
          S, OCD_AmbiguousCandidates, Args);
2484
4
    }
2485
4
    return true;
2486
2487
12
  case OR_Deleted: {
2488
12
    if (Diagnose) {
2489
12
      Candidates.NoteCandidates(
2490
12
          PartialDiagnosticAt(R.getNameLoc(),
2491
12
                              S.PDiag(diag::err_ovl_deleted_call)
2492
12
                                  << R.getLookupName() << Range),
2493
12
          S, OCD_AllCandidates, Args);
2494
12
    }
2495
12
    return true;
2496
0
  }
2497
0
  }
2498
0
  llvm_unreachable("Unreachable, bad result from BestViableFunction");
2499
0
}
2500
2501
bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
2502
                                   AllocationFunctionScope NewScope,
2503
                                   AllocationFunctionScope DeleteScope,
2504
                                   QualType AllocType, bool IsArray,
2505
                                   bool &PassAlignment, MultiExprArg PlaceArgs,
2506
                                   FunctionDecl *&OperatorNew,
2507
                                   FunctionDecl *&OperatorDelete,
2508
5.48k
                                   bool Diagnose) {
2509
  // --- Choosing an allocation function ---
2510
  // C++ 5.3.4p8 - 14 & 18
2511
  // 1) If looking in AFS_Global scope for allocation functions, only look in
2512
  //    the global scope. Else, if AFS_Class, only look in the scope of the
2513
  //    allocated class. If AFS_Both, look in both.
2514
  // 2) If an array size is given, look for operator new[], else look for
2515
  //   operator new.
2516
  // 3) The first argument is always size_t. Append the arguments from the
2517
  //   placement form.
2518
2519
5.48k
  SmallVector<Expr*, 8> AllocArgs;
2520
5.27k
  AllocArgs.reserve((PassAlignment ? 
2211
: 1) + PlaceArgs.size());
2521
2522
  // We don't care about the actual value of these arguments.
2523
  // FIXME: Should the Sema create the expression and embed it in the syntax
2524
  // tree? Or should the consumer just recalculate the value?
2525
  // FIXME: Using a dummy value will interact poorly with attribute enable_if.
2526
5.48k
  IntegerLiteral Size(Context, llvm::APInt::getNullValue(
2527
5.48k
                      Context.getTargetInfo().getPointerWidth(0)),
2528
5.48k
                      Context.getSizeType(),
2529
5.48k
                      SourceLocation());
2530
5.48k
  AllocArgs.push_back(&Size);
2531
2532
5.48k
  QualType AlignValT = Context.VoidTy;
2533
5.48k
  if (PassAlignment) {
2534
211
    DeclareGlobalNewDelete();
2535
211
    AlignValT = Context.getTypeDeclType(getStdAlignValT());
2536
211
  }
2537
5.48k
  CXXScalarValueInitExpr Align(AlignValT, nullptr, SourceLocation());
2538
5.48k
  if (PassAlignment)
2539
211
    AllocArgs.push_back(&Align);
2540
2541
5.48k
  AllocArgs.insert(AllocArgs.end(), PlaceArgs.begin(), PlaceArgs.end());
2542
2543
  // C++ [expr.new]p8:
2544
  //   If the allocated type is a non-array type, the allocation
2545
  //   function's name is operator new and the deallocation function's
2546
  //   name is operator delete. If the allocated type is an array
2547
  //   type, the allocation function's name is operator new[] and the
2548
  //   deallocation function's name is operator delete[].
2549
5.48k
  DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
2550
4.42k
      IsArray ? 
OO_Array_New1.05k
: OO_New);
2551
2552
5.48k
  QualType AllocElemType = Context.getBaseElementType(AllocType);
2553
2554
  // Find the allocation function.
2555
5.48k
  {
2556
5.48k
    LookupResult R(*this, NewName, StartLoc, LookupOrdinaryName);
2557
2558
    // C++1z [expr.new]p9:
2559
    //   If the new-expression begins with a unary :: operator, the allocation
2560
    //   function's name is looked up in the global scope. Otherwise, if the
2561
    //   allocated type is a class type T or array thereof, the allocation
2562
    //   function's name is looked up in the scope of T.
2563
5.48k
    if (AllocElemType->isRecordType() && 
NewScope != AFS_Global3.83k
)
2564
2.85k
      LookupQualifiedName(R, AllocElemType->getAsCXXRecordDecl());
2565
2566
    // We can see ambiguity here if the allocation function is found in
2567
    // multiple base classes.
2568
5.48k
    if (R.isAmbiguous())
2569
0
      return true;
2570
2571
    //   If this lookup fails to find the name, or if the allocated type is not
2572
    //   a class type, the allocation function's name is looked up in the
2573
    //   global scope.
2574
5.48k
    if (R.empty()) {
2575
5.23k
      if (NewScope == AFS_Class)
2576
268
        return true;
2577
2578
4.96k
      LookupQualifiedName(R, Context.getTranslationUnitDecl());
2579
4.96k
    }
2580
2581
5.21k
    if (getLangOpts().OpenCLCPlusPlus && 
R.empty()7
) {
2582
2
      if (PlaceArgs.empty()) {
2583
1
        Diag(StartLoc, diag::err_openclcxx_not_supported) << "default new";
2584
1
      } else {
2585
1
        Diag(StartLoc, diag::err_openclcxx_placement_new);
2586
1
      }
2587
2
      return true;
2588
2
    }
2589
2590
5.21k
    assert(!R.empty() && "implicitly declared allocation functions not found");
2591
5.21k
    assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
2592
2593
    // We do our own custom access checks below.
2594
5.21k
    R.suppressDiagnostics();
2595
2596
5.21k
    if (resolveAllocationOverload(*this, R, Range, AllocArgs, PassAlignment,
2597
5.21k
                                  OperatorNew, /*Candidates=*/nullptr,
2598
5.21k
                                  /*AlignArg=*/nullptr, Diagnose))
2599
46
      return true;
2600
5.16k
  }
2601
2602
  // We don't need an operator delete if we're running under -fno-exceptions.
2603
5.16k
  if (!getLangOpts().Exceptions) {
2604
2.52k
    OperatorDelete = nullptr;
2605
2.52k
    return false;
2606
2.52k
  }
2607
2608
  // Note, the name of OperatorNew might have been changed from array to
2609
  // non-array by resolveAllocationOverload.
2610
2.64k
  DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
2611
2.64k
      OperatorNew->getDeclName().getCXXOverloadedOperator() == OO_Array_New
2612
433
          ? OO_Array_Delete
2613
2.21k
          : OO_Delete);
2614
2615
  // C++ [expr.new]p19:
2616
  //
2617
  //   If the new-expression begins with a unary :: operator, the
2618
  //   deallocation function's name is looked up in the global
2619
  //   scope. Otherwise, if the allocated type is a class type T or an
2620
  //   array thereof, the deallocation function's name is looked up in
2621
  //   the scope of T. If this lookup fails to find the name, or if
2622
  //   the allocated type is not a class type or array thereof, the
2623
  //   deallocation function's name is looked up in the global scope.
2624
2.64k
  LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
2625
2.64k
  if (AllocElemType->isRecordType() && 
DeleteScope != AFS_Global2.11k
) {
2626
1.40k
    auto *RD =
2627
1.40k
        cast<CXXRecordDecl>(AllocElemType->castAs<RecordType>()->getDecl());
2628
1.40k
    LookupQualifiedName(FoundDelete, RD);
2629
1.40k
  }
2630
2.64k
  if (FoundDelete.isAmbiguous())
2631
0
    return true; // FIXME: clean up expressions?
2632
2633
  // Filter out any destroying operator deletes. We can't possibly call such a
2634
  // function in this context, because we're handling the case where the object
2635
  // was not successfully constructed.
2636
  // FIXME: This is not covered by the language rules yet.
2637
2.64k
  {
2638
2.64k
    LookupResult::Filter Filter = FoundDelete.makeFilter();
2639
2.83k
    while (Filter.hasNext()) {
2640
194
      auto *FD = dyn_cast<FunctionDecl>(Filter.next()->getUnderlyingDecl());
2641
194
      if (FD && 
FD->isDestroyingOperatorDelete()193
)
2642
16
        Filter.erase();
2643
194
    }
2644
2.64k
    Filter.done();
2645
2.64k
  }
2646
2647
2.64k
  bool FoundGlobalDelete = FoundDelete.empty();
2648
2.64k
  if (FoundDelete.empty()) {
2649
2.51k
    FoundDelete.clear(LookupOrdinaryName);
2650
2651
2.51k
    if (DeleteScope == AFS_Class)
2652
0
      return true;
2653
2654
2.51k
    DeclareGlobalNewDelete();
2655
2.51k
    LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2656
2.51k
  }
2657
2658
2.64k
  FoundDelete.suppressDiagnostics();
2659
2660
2.64k
  SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
2661
2662
  // Whether we're looking for a placement operator delete is dictated
2663
  // by whether we selected a placement operator new, not by whether
2664
  // we had explicit placement arguments.  This matters for things like
2665
  //   struct A { void *operator new(size_t, int = 0); ... };
2666
  //   A *a = new A()
2667
  //
2668
  // We don't have any definition for what a "placement allocation function"
2669
  // is, but we assume it's any allocation function whose
2670
  // parameter-declaration-clause is anything other than (size_t).
2671
  //
2672
  // FIXME: Should (size_t, std::align_val_t) also be considered non-placement?
2673
  // This affects whether an exception from the constructor of an overaligned
2674
  // type uses the sized or non-sized form of aligned operator delete.
2675
2.64k
  bool isPlacementNew = !PlaceArgs.empty() || 
OperatorNew->param_size() != 11.53k
||
2676
1.47k
                        OperatorNew->isVariadic();
2677
2678
2.64k
  if (isPlacementNew) {
2679
    // C++ [expr.new]p20:
2680
    //   A declaration of a placement deallocation function matches the
2681
    //   declaration of a placement allocation function if it has the
2682
    //   same number of parameters and, after parameter transformations
2683
    //   (8.3.5), all parameter types except the first are
2684
    //   identical. [...]
2685
    //
2686
    // To perform this comparison, we compute the function type that
2687
    // the deallocation function should have, and use that type both
2688
    // for template argument deduction and for comparison purposes.
2689
1.17k
    QualType ExpectedFunctionType;
2690
1.17k
    {
2691
1.17k
      auto *Proto = OperatorNew->getType()->castAs<FunctionProtoType>();
2692
2693
1.17k
      SmallVector<QualType, 4> ArgTypes;
2694
1.17k
      ArgTypes.push_back(Context.VoidPtrTy);
2695
2.41k
      for (unsigned I = 1, N = Proto->getNumParams(); I < N; 
++I1.23k
)
2696
1.23k
        ArgTypes.push_back(Proto->getParamType(I));
2697
2698
1.17k
      FunctionProtoType::ExtProtoInfo EPI;
2699
      // FIXME: This is not part of the standard's rule.
2700
1.17k
      EPI.Variadic = Proto->isVariadic();
2701
2702
1.17k
      ExpectedFunctionType
2703
1.17k
        = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
2704
1.17k
    }
2705
2706
1.17k
    for (LookupResult::iterator D = FoundDelete.begin(),
2707
1.17k
                             DEnd = FoundDelete.end();
2708
6.67k
         D != DEnd; 
++D5.50k
) {
2709
5.50k
      FunctionDecl *Fn = nullptr;
2710
5.50k
      if (FunctionTemplateDecl *FnTmpl =
2711
36
              dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
2712
        // Perform template argument deduction to try to match the
2713
        // expected function type.
2714
36
        TemplateDeductionInfo Info(StartLoc);
2715
36
        if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn,
2716
36
                                    Info))
2717
17
          continue;
2718
5.46k
      } else
2719
5.46k
        Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
2720
2721
5.48k
      if (Context.hasSameType(adjustCCAndNoReturn(Fn->getType(),
2722
5.48k
                                                  ExpectedFunctionType,
2723
5.48k
                                                  /*AdjustExcpetionSpec*/true),
2724
5.48k
                              ExpectedFunctionType))
2725
1.10k
        Matches.push_back(std::make_pair(D.getPair(), Fn));
2726
5.48k
    }
2727
2728
1.17k
    if (getLangOpts().CUDA)
2729
0
      EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(CurContext), Matches);
2730
1.46k
  } else {
2731
    // C++1y [expr.new]p22:
2732
    //   For a non-placement allocation function, the normal deallocation
2733
    //   function lookup is used
2734
    //
2735
    // Per [expr.delete]p10, this lookup prefers a member operator delete
2736
    // without a size_t argument, but prefers a non-member operator delete
2737
    // with a size_t where possible (which it always is in this case).
2738
1.46k
    llvm::SmallVector<UsualDeallocFnInfo, 4> BestDeallocFns;
2739
1.46k
    UsualDeallocFnInfo Selected = resolveDeallocationOverload(
2740
1.46k
        *this, FoundDelete, /*WantSize*/ FoundGlobalDelete,
2741
1.46k
        /*WantAlign*/ hasNewExtendedAlignment(*this, AllocElemType),
2742
1.46k
        &BestDeallocFns);
2743
1.46k
    if (Selected)
2744
1.46k
      Matches.push_back(std::make_pair(Selected.Found, Selected.FD));
2745
1
    else {
2746
      // If we failed to select an operator, all remaining functions are viable
2747
      // but ambiguous.
2748
1
      for (auto Fn : BestDeallocFns)
2749
0
        Matches.push_back(std::make_pair(Fn.Found, Fn.FD));
2750
1
    }
2751
1.46k
  }
2752
2753
  // C++ [expr.new]p20:
2754
  //   [...] If the lookup finds a single matching deallocation
2755
  //   function, that function will be called; otherwise, no
2756
  //   deallocation function will be called.
2757
2.64k
  if (Matches.size() == 1) {
2758
2.57k
    OperatorDelete = Matches[0].second;
2759
2760
    // C++1z [expr.new]p23:
2761
    //   If the lookup finds a usual deallocation function (3.7.4.2)
2762
    //   with a parameter of type std::size_t and that function, considered
2763
    //   as a placement deallocation function, would have been
2764
    //   selected as a match for the allocation function, the program
2765
    //   is ill-formed.
2766
2.57k
    if (getLangOpts().CPlusPlus11 && 
isPlacementNew2.48k
&&
2767
1.09k
        isNonPlacementDeallocationFunction(*this, OperatorDelete)) {
2768
132
      UsualDeallocFnInfo Info(*this,
2769
132
                              DeclAccessPair::make(OperatorDelete, AS_public));
2770
      // Core issue, per mail to core reflector, 2016-10-09:
2771
      //   If this is a member operator delete, and there is a corresponding
2772
      //   non-sized member operator delete, this isn't /really/ a sized
2773
      //   deallocation function, it just happens to have a size_t parameter.
2774
132
      bool IsSizedDelete = Info.HasSizeT;
2775
132
      if (IsSizedDelete && 
!FoundGlobalDelete12
) {
2776
11
        auto NonSizedDelete =
2777
11
            resolveDeallocationOverload(*this, FoundDelete, /*WantSize*/false,
2778
11
                                        /*WantAlign*/Info.HasAlignValT);
2779
11
        if (NonSizedDelete && !NonSizedDelete.HasSizeT &&
2780
3
            NonSizedDelete.HasAlignValT == Info.HasAlignValT)
2781
3
          IsSizedDelete = false;
2782
11
      }
2783
2784
132
      if (IsSizedDelete) {
2785
9
        SourceRange R = PlaceArgs.empty()
2786
0
                            ? SourceRange()
2787
9
                            : SourceRange(PlaceArgs.front()->getBeginLoc(),
2788
9
                                          PlaceArgs.back()->getEndLoc());
2789
9
        Diag(StartLoc, diag::err_placement_new_non_placement_delete) << R;
2790
9
        if (!OperatorDelete->isImplicit())
2791
9
          Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
2792
9
              << DeleteName;
2793
9
      }
2794
132
    }
2795
2796
2.57k
    CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
2797
2.57k
                          Matches[0].first);
2798
72
  } else if (!Matches.empty()) {
2799
    // We found multiple suitable operators. Per [expr.new]p20, that means we
2800
    // call no 'operator delete' function, but we should at least warn the user.
2801
    // FIXME: Suppress this warning if the construction cannot throw.
2802
0
    Diag(StartLoc, diag::warn_ambiguous_suitable_delete_function_found)
2803
0
      << DeleteName << AllocElemType;
2804
2805
0
    for (auto &Match : Matches)
2806
0
      Diag(Match.second->getLocation(),
2807
0
           diag::note_member_declared_here) << DeleteName;
2808
0
  }
2809
2810
2.64k
  return false;
2811
2.64k
}
2812
2813
/// DeclareGlobalNewDelete - Declare the global forms of operator new and
2814
/// delete. These are:
2815
/// @code
2816
///   // C++03:
2817
///   void* operator new(std::size_t) throw(std::bad_alloc);
2818
///   void* operator new[](std::size_t) throw(std::bad_alloc);
2819
///   void operator delete(void *) throw();
2820
///   void operator delete[](void *) throw();
2821
///   // C++11:
2822
///   void* operator new(std::size_t);
2823
///   void* operator new[](std::size_t);
2824
///   void operator delete(void *) noexcept;
2825
///   void operator delete[](void *) noexcept;
2826
///   // C++1y:
2827
///   void* operator new(std::size_t);
2828
///   void* operator new[](std::size_t);
2829
///   void operator delete(void *) noexcept;
2830
///   void operator delete[](void *) noexcept;
2831
///   void operator delete(void *, std::size_t) noexcept;
2832
///   void operator delete[](void *, std::size_t) noexcept;
2833
/// @endcode
2834
/// Note that the placement and nothrow forms of new are *not* implicitly
2835
/// declared. Their use requires including \<new\>.
2836
45.3k
void Sema::DeclareGlobalNewDelete() {
2837
45.3k
  if (GlobalNewDeleteDeclared)
2838
43.0k
    return;
2839
2840
  // The implicitly declared new and delete operators
2841
  // are not supported in OpenCL.
2842
2.27k
  if (getLangOpts().OpenCLCPlusPlus)
2843
15
    return;
2844
2845
  // C++ [basic.std.dynamic]p2:
2846
  //   [...] The following allocation and deallocation functions (18.4) are
2847
  //   implicitly declared in global scope in each translation unit of a
2848
  //   program
2849
  //
2850
  //     C++03:
2851
  //     void* operator new(std::size_t) throw(std::bad_alloc);
2852
  //     void* operator new[](std::size_t) throw(std::bad_alloc);
2853
  //     void  operator delete(void*) throw();
2854
  //     void  operator delete[](void*) throw();
2855
  //     C++11:
2856
  //     void* operator new(std::size_t);
2857
  //     void* operator new[](std::size_t);
2858
  //     void  operator delete(void*) noexcept;
2859
  //     void  operator delete[](void*) noexcept;
2860
  //     C++1y:
2861
  //     void* operator new(std::size_t);
2862
  //     void* operator new[](std::size_t);
2863
  //     void  operator delete(void*) noexcept;
2864
  //     void  operator delete[](void*) noexcept;
2865
  //     void  operator delete(void*, std::size_t) noexcept;
2866
  //     void  operator delete[](void*, std::size_t) noexcept;
2867
  //
2868
  //   These implicit declarations introduce only the function names operator
2869
  //   new, operator new[], operator delete, operator delete[].
2870
  //
2871
  // Here, we need to refer to std::bad_alloc, so we will implicitly declare
2872
  // "std" or "bad_alloc" as necessary to form the exception specification.
2873
  // However, we do not make these implicit declarations visible to name
2874
  // lookup.
2875
2.26k
  if (!StdBadAlloc && 
!getLangOpts().CPlusPlus111.58k
) {
2876
    // The "std::bad_alloc" class has not yet been declared, so build it
2877
    // implicitly.
2878
177
    StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
2879
177
                                        getOrCreateStdNamespace(),
2880
177
                                        SourceLocation(), SourceLocation(),
2881
177
                                      &PP.getIdentifierTable().get("bad_alloc"),
2882
177
                                        nullptr);
2883
177
    getStdBadAlloc()->setImplicit(true);
2884
177
  }
2885
2.26k
  if (!StdAlignValT && 
getLangOpts().AlignedAllocation1.65k
) {
2886
    // The "std::align_val_t" enum class has not yet been declared, so build it
2887
    // implicitly.
2888
184
    auto *AlignValT = EnumDecl::Create(
2889
184
        Context, getOrCreateStdNamespace(), SourceLocation(), SourceLocation(),
2890
184
        &PP.getIdentifierTable().get("align_val_t"), nullptr, true, true, true);
2891
184
    AlignValT->setIntegerType(Context.getSizeType());
2892
184
    AlignValT->setPromotionType(Context.getSizeType());
2893
184
    AlignValT->setImplicit(true);
2894
184
    StdAlignValT = AlignValT;
2895
184
  }
2896
2897
2.26k
  GlobalNewDeleteDeclared = true;
2898
2899
2.26k
  QualType VoidPtr = Context.getPointerType(Context.VoidTy);
2900
2.26k
  QualType SizeT = Context.getSizeType();
2901
2902
2.26k
  auto DeclareGlobalAllocationFunctions = [&](OverloadedOperatorKind Kind,
2903
9.04k
                                              QualType Return, QualType Param) {
2904
9.04k
    llvm::SmallVector<QualType, 3> Params;
2905
9.04k
    Params.push_back(Param);
2906
2907
    // Create up to four variants of the function (sized/aligned).
2908
9.04k
    bool HasSizedVariant = getLangOpts().SizedDeallocation &&
2909
116
                           (Kind == OO_Delete || 
Kind == OO_Array_Delete87
);
2910
9.04k
    bool HasAlignedVariant = getLangOpts().AlignedAllocation;
2911
2912
8.98k
    int NumSizeVariants = (HasSizedVariant ? 
258
: 1);
2913
8.11k
    int NumAlignVariants = (HasAlignedVariant ? 
2932
: 1);
2914
18.1k
    for (int Sized = 0; Sized < NumSizeVariants; 
++Sized9.10k
) {
2915
9.10k
      if (Sized)
2916
58
        Params.push_back(SizeT);
2917
2918
19.1k
      for (int Aligned = 0; Aligned < NumAlignVariants; 
++Aligned10.0k
) {
2919
10.0k
        if (Aligned)
2920
966
          Params.push_back(Context.getTypeDeclType(getStdAlignValT()));
2921
2922
10.0k
        DeclareGlobalAllocationFunction(
2923
10.0k
            Context.DeclarationNames.getCXXOperatorName(Kind), Return, Params);
2924
2925
10.0k
        if (Aligned)
2926
966
          Params.pop_back();
2927
10.0k
      }
2928
9.10k
    }
2929
9.04k
  };
2930
2931
2.26k
  DeclareGlobalAllocationFunctions(OO_New, VoidPtr, SizeT);
2932
2.26k
  DeclareGlobalAllocationFunctions(OO_Array_New, VoidPtr, SizeT);
2933
2.26k
  DeclareGlobalAllocationFunctions(OO_Delete, Context.VoidTy, VoidPtr);
2934
2.26k
  DeclareGlobalAllocationFunctions(OO_Array_Delete, Context.VoidTy, VoidPtr);
2935
2.26k
}
2936
2937
/// DeclareGlobalAllocationFunction - Declares a single implicit global
2938
/// allocation function if it doesn't already exist.
2939
void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
2940
                                           QualType Return,
2941
10.0k
                                           ArrayRef<QualType> Params) {
2942
10.0k
  DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
2943
2944
  // Check if this function is already declared.
2945
10.0k
  DeclContext::lookup_result R = GlobalCtx->lookup(Name);
2946
10.0k
  for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end();
2947
11.3k
       Alloc != AllocEnd; 
++Alloc1.23k
) {
2948
    // Only look at non-template functions, as it is the predefined,
2949
    // non-templated allocation function we are trying to declare here.
2950
1.88k
    if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
2951
1.88k
      if (Func->getNumParams() == Params.size()) {
2952
684
        llvm::SmallVector<QualType, 3> FuncParams;
2953
684
        for (auto *P : Func->parameters())
2954
750
          FuncParams.push_back(
2955
750
              Context.getCanonicalType(P->getType().getUnqualifiedType()));
2956
684
        if (llvm::makeArrayRef(FuncParams) == Params) {
2957
          // Make the function visible to name lookup, even if we found it in
2958
          // an unimported module. It either is an implicitly-declared global
2959
          // allocation function, or is suppressing that function.
2960
650
          Func->setVisibleDespiteOwningModule();
2961
650
          return;
2962
650
        }
2963
684
      }
2964
1.88k
    }
2965
1.88k
  }
2966
2967
9.41k
  FunctionProtoType::ExtProtoInfo EPI(Context.getDefaultCallingConvention(
2968
9.41k
      /*IsVariadic=*/false, /*IsCXXMethod=*/false, /*IsBuiltin=*/true));
2969
2970
9.41k
  QualType BadAllocType;
2971
9.41k
  bool HasBadAllocExceptionSpec
2972
9.41k
    = (Name.getCXXOverloadedOperator() == OO_New ||
2973
7.08k
       Name.getCXXOverloadedOperator() == OO_Array_New);
2974
9.41k
  if (HasBadAllocExceptionSpec) {
2975
4.66k
    if (!getLangOpts().CPlusPlus11) {
2976
364
      BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
2977
364
      assert(StdBadAlloc && "Must have std::bad_alloc declared");
2978
364
      EPI.ExceptionSpec.Type = EST_Dynamic;
2979
364
      EPI.ExceptionSpec.Exceptions = llvm::makeArrayRef(BadAllocType);
2980
364
    }
2981
4.75k
  } else {
2982
4.75k
    EPI.ExceptionSpec =
2983
4.39k
        getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : 
EST_DynamicNone364
;
2984
4.75k
  }
2985
2986
9.87k
  auto CreateAllocationFunctionDecl = [&](Attr *ExtraAttr) {
2987
9.87k
    QualType FnType = Context.getFunctionType(Return, Params, EPI);
2988
9.87k
    FunctionDecl *Alloc = FunctionDecl::Create(
2989
9.87k
        Context, GlobalCtx, SourceLocation(), SourceLocation(), Name,
2990
9.87k
        FnType, /*TInfo=*/nullptr, SC_None, false, true);
2991
9.87k
    Alloc->setImplicit();
2992
    // Global allocation functions should always be visible.
2993
9.87k
    Alloc->setVisibleDespiteOwningModule();
2994
2995
9.87k
    Alloc->addAttr(VisibilityAttr::CreateImplicit(
2996
9.87k
        Context, LangOpts.GlobalAllocationFunctionVisibilityHidden
2997
0
                     ? VisibilityAttr::Hidden
2998
9.87k
                     : VisibilityAttr::Default));
2999
3000
9.87k
    llvm::SmallVector<ParmVarDecl *, 3> ParamDecls;
3001
10.9k
    for (QualType T : Params) {
3002
10.9k
      ParamDecls.push_back(ParmVarDecl::Create(
3003
10.9k
          Context, Alloc, SourceLocation(), SourceLocation(), nullptr, T,
3004
10.9k
          /*TInfo=*/nullptr, SC_None, nullptr));
3005
10.9k
      ParamDecls.back()->setImplicit();
3006
10.9k
    }
3007
9.87k
    Alloc->setParams(ParamDecls);
3008
9.87k
    if (ExtraAttr)
3009
904
      Alloc->addAttr(ExtraAttr);
3010
9.87k
    AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(Alloc);
3011
9.87k
    Context.getTranslationUnitDecl()->addDecl(Alloc);
3012
9.87k
    IdResolver.tryAddTopLevelDecl(Alloc, Name);
3013
9.87k
  };
3014
3015
9.41k
  if (!LangOpts.CUDA)
3016
8.96k
    CreateAllocationFunctionDecl(nullptr);
3017
452
  else {
3018
    // Host and device get their own declaration so each can be
3019
    // defined or re-declared independently.
3020
452
    CreateAllocationFunctionDecl(CUDAHostAttr::CreateImplicit(Context));
3021
452
    CreateAllocationFunctionDecl(CUDADeviceAttr::CreateImplicit(Context));
3022
452
  }
3023
9.41k
}
3024
3025
FunctionDecl *Sema::FindUsualDeallocationFunction(SourceLocation StartLoc,
3026
                                                  bool CanProvideSize,
3027
                                                  bool Overaligned,
3028
3.97k
                                                  DeclarationName Name) {
3029
3.97k
  DeclareGlobalNewDelete();
3030
3031
3.97k
  LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName);
3032
3.97k
  LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
3033
3034
  // FIXME: It's possible for this to result in ambiguity, through a
3035
  // user-declared variadic operator delete or the enable_if attribute. We
3036
  // should probably not consider those cases to be usual deallocation
3037
  // functions. But for now we just make an arbitrary choice in that case.
3038
3.97k
  auto Result = resolveDeallocationOverload(*this, FoundDelete, CanProvideSize,
3039
3.97k
                                            Overaligned);
3040
3.97k
  assert(Result.FD && "operator delete missing from global scope?");
3041
3.97k
  return Result.FD;
3042
3.97k
}
3043
3044
FunctionDecl *Sema::FindDeallocationFunctionForDestructor(SourceLocation Loc,
3045
1.89k
                                                          CXXRecordDecl *RD) {
3046
1.89k
  DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Delete);
3047
3048
1.89k
  FunctionDecl *OperatorDelete = nullptr;
3049
1.89k
  if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
3050
49
    return nullptr;
3051
1.85k
  if (OperatorDelete)
3052
58
    return OperatorDelete;
3053
3054
  // If there's no class-specific operator delete, look up the global
3055
  // non-array delete.
3056
1.79k
  return FindUsualDeallocationFunction(
3057
1.79k
      Loc, true, hasNewExtendedAlignment(*this, Context.getRecordType(RD)),
3058
1.79k
      Name);
3059
1.79k
}
3060
3061
bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
3062
                                    DeclarationName Name,
3063
5.05k
                                    FunctionDecl *&Operator, bool Diagnose) {
3064
5.05k
  LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
3065
  // Try to find operator delete/operator delete[] in class scope.
3066
5.05k
  LookupQualifiedName(Found, RD);
3067
3068
5.05k
  if (Found.isAmbiguous())
3069
10
    return true;
3070
3071
5.04k
  Found.suppressDiagnostics();
3072
3073
5.04k
  bool Overaligned = hasNewExtendedAlignment(*this, Context.getRecordType(RD));
3074
3075
  // C++17 [expr.delete]p10:
3076
  //   If the deallocation functions have class scope, the one without a
3077
  //   parameter of type std::size_t is selected.
3078
5.04k
  llvm::SmallVector<UsualDeallocFnInfo, 4> Matches;
3079
5.04k
  resolveDeallocationOverload(*this, Found, /*WantSize*/ false,
3080
5.04k
                              /*WantAlign*/ Overaligned, &Matches);
3081
3082
  // If we could find an overload, use it.
3083
5.04k
  if (Matches.size() == 1) {
3084
350
    Operator = cast<CXXMethodDecl>(Matches[0].FD);
3085
3086
    // FIXME: DiagnoseUseOfDecl?
3087
350
    if (Operator->isDeleted()) {
3088
69
      if (Diagnose) {
3089
66
        Diag(StartLoc, diag::err_deleted_function_use);
3090
66
        NoteDeletedFunction(Operator);
3091
66
      }
3092
69
      return true;
3093
69
    }
3094
3095
281
    if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
3096
281
                              Matches[0].Found, Diagnose) == AR_inaccessible)
3097
8
      return true;
3098
3099
273
    return false;
3100
273
  }
3101
3102
  // We found multiple suitable operators; complain about the ambiguity.
3103
  // FIXME: The standard doesn't say to do this; it appears that the intent
3104
  // is that this should never happen.
3105
4.69k
  if (!Matches.empty()) {
3106
4
    if (Diagnose) {
3107
4
      Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
3108
4
        << Name << RD;
3109
4
      for (auto &Match : Matches)
3110
8
        Diag(Match.FD->getLocation(), diag::note_member_declared_here) << Name;
3111
4
    }
3112
4
    return true;
3113
4
  }
3114
3115
  // We did find operator delete/operator delete[] declarations, but
3116
  // none of them were suitable.
3117
4.68k
  if (!Found.empty()) {
3118
81
    if (Diagnose) {
3119
26
      Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
3120
26
        << Name << RD;
3121
3122
26
      for (NamedDecl *D : Found)
3123
30
        Diag(D->getUnderlyingDecl()->getLocation(),
3124
30
             diag::note_member_declared_here) << Name;
3125
26
    }
3126
81
    return true;
3127
81
  }
3128
3129
4.60k
  Operator = nullptr;
3130
4.60k
  return false;
3131
4.60k
}
3132
3133
namespace {
3134
/// Checks whether delete-expression, and new-expression used for
3135
///  initializing deletee have the same array form.
3136
class MismatchingNewDeleteDetector {
3137
public:
3138
  enum MismatchResult {
3139
    /// Indicates that there is no mismatch or a mismatch cannot be proven.
3140
    NoMismatch,
3141
    /// Indicates that variable is initialized with mismatching form of \a new.
3142
    VarInitMismatches,
3143
    /// Indicates that member is initialized with mismatching form of \a new.
3144
    MemberInitMismatches,
3145
    /// Indicates that 1 or more constructors' definitions could not been
3146
    /// analyzed, and they will be checked again at the end of translation unit.
3147
    AnalyzeLater
3148
  };
3149
3150
  /// \param EndOfTU True, if this is the final analysis at the end of
3151
  /// translation unit. False, if this is the initial analysis at the point
3152
  /// delete-expression was encountered.
3153
  explicit MismatchingNewDeleteDetector(bool EndOfTU)
3154
      : Field(nullptr), IsArrayForm(false), EndOfTU(EndOfTU),
3155
4.69k
        HasUndefinedConstructors(false) {}
3156
3157
  /// Checks whether pointee of a delete-expression is initialized with
3158
  /// matching form of new-expression.
3159
  ///
3160
  /// If return value is \c VarInitMismatches or \c MemberInitMismatches at the
3161
  /// point where delete-expression is encountered, then a warning will be
3162
  /// issued immediately. If return value is \c AnalyzeLater at the point where
3163
  /// delete-expression is seen, then member will be analyzed at the end of
3164
  /// translation unit. \c AnalyzeLater is returned iff at least one constructor
3165
  /// couldn't be analyzed. If at least one constructor initializes the member
3166
  /// with matching type of new, the return value is \c NoMismatch.
3167
  MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE);
3168
  /// Analyzes a class member.
3169
  /// \param Field Class member to analyze.
3170
  /// \param DeleteWasArrayForm Array form-ness of the delete-expression used
3171
  /// for deleting the \p Field.
3172
  MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm);
3173
  FieldDecl *Field;
3174
  /// List of mismatching new-expressions used for initialization of the pointee
3175
  llvm::SmallVector<const CXXNewExpr *, 4> NewExprs;
3176
  /// Indicates whether delete-expression was in array form.
3177
  bool IsArrayForm;
3178
3179
private:
3180
  const bool EndOfTU;
3181
  /// Indicates that there is at least one constructor without body.
3182
  bool HasUndefinedConstructors;
3183
  /// Returns \c CXXNewExpr from given initialization expression.
3184
  /// \param E Expression used for initializing pointee in delete-expression.
3185
  /// E can be a single-element \c InitListExpr consisting of new-expression.
3186
  const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E);
3187
  /// Returns whether member is initialized with mismatching form of
3188
  /// \c new either by the member initializer or in-class initialization.
3189
  ///
3190
  /// If bodies of all constructors are not visible at the end of translation
3191
  /// unit or at least one constructor initializes member with the matching
3192
  /// form of \c new, mismatch cannot be proven, and this function will return
3193
  /// \c NoMismatch.
3194
  MismatchResult analyzeMemberExpr(const MemberExpr *ME);
3195
  /// Returns whether variable is initialized with mismatching form of
3196
  /// \c new.
3197
  ///
3198
  /// If variable is initialized with matching form of \c new or variable is not
3199
  /// initialized with a \c new expression, this function will return true.
3200
  /// If variable is initialized with mismatching form of \c new, returns false.
3201
  /// \param D Variable to analyze.
3202
  bool hasMatchingVarInit(const DeclRefExpr *D);
3203
  /// Checks whether the constructor initializes pointee with mismatching
3204
  /// form of \c new.
3205
  ///
3206
  /// Returns true, if member is initialized with matching form of \c new in
3207
  /// member initializer list. Returns false, if member is initialized with the
3208
  /// matching form of \c new in this constructor's initializer or given
3209
  /// constructor isn't defined at the point where delete-expression is seen, or
3210
  /// member isn't initialized by the constructor.
3211
  bool hasMatchingNewInCtor(const CXXConstructorDecl *CD);
3212
  /// Checks whether member is initialized with matching form of
3213
  /// \c new in member initializer list.
3214
  bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI);
3215
  /// Checks whether member is initialized with mismatching form of \c new by
3216
  /// in-class initializer.
3217
  MismatchResult analyzeInClassInitializer();
3218
};
3219
}
3220
3221
MismatchingNewDeleteDetector::MismatchResult
3222
4.16k
MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) {
3223
4.16k
  NewExprs.clear();
3224
4.16k
  assert(DE && "Expected delete-expression");
3225
4.16k
  IsArrayForm = DE->isArrayForm();
3226
4.16k
  const Expr *E = DE->getArgument()->IgnoreParenImpCasts();
3227
4.16k
  if (const MemberExpr *ME = dyn_cast<const MemberExpr>(E)) {
3228
1.54k
    return analyzeMemberExpr(ME);
3229
2.62k
  } else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(E)) {
3230
2.14k
    if (!hasMatchingVarInit(D))
3231
16
      return VarInitMismatches;
3232
2.61k
  }
3233
2.61k
  return NoMismatch;
3234
2.61k
}
3235
3236
const CXXNewExpr *
3237
3.06k
MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) {
3238
3.06k
  assert(E != nullptr && "Expected a valid initializer expression");
3239
3.06k
  E = E->IgnoreParenImpCasts();
3240
3.06k
  if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(E)) {
3241
18
    if (ILE->getNumInits() == 1)
3242
18
      E = dyn_cast<const CXXNewExpr>(ILE->getInit(0)->IgnoreParenImpCasts());
3243
18
  }
3244
3245
3.06k
  return dyn_cast_or_null<const CXXNewExpr>(E);
3246
3.06k
}
3247
3248
bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit(
3249
11.0k
    const CXXCtorInitializer *CI) {
3250
11.0k
  const CXXNewExpr *NE = nullptr;
3251
11.0k
  if (Field == CI->getMember() &&
3252
2.50k
      (NE = getNewExprFromInitListOrExpr(CI->getInit()))) {
3253
58
    if (NE->isArray() == IsArrayForm)
3254
26
      return true;
3255
32
    else
3256
32
      NewExprs.push_back(NE);
3257
58
  }
3258
11.0k
  return false;
3259
11.0k
}
3260
3261
bool MismatchingNewDeleteDetector::hasMatchingNewInCtor(
3262
5.10k
    const CXXConstructorDecl *CD) {
3263
5.10k
  if (CD->isImplicit())
3264
101
    return false;
3265
4.99k
  const FunctionDecl *Definition = CD;
3266
4.99k
  if (!CD->isThisDeclarationADefinition() && 
!CD->isDefined(Definition)1.91k
) {
3267
1.05k
    HasUndefinedConstructors = true;
3268
1.05k
    return EndOfTU;
3269
1.05k
  }
3270
11.0k
  
for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits())3.94k
{
3271
11.0k
    if (hasMatchingNewInCtorInit(CI))
3272
26
      return true;
3273
11.0k
  }
3274
3.92k
  return false;
3275
3.94k
}
3276
3277
MismatchingNewDeleteDetector::MismatchResult
3278
24
MismatchingNewDeleteDetector::analyzeInClassInitializer() {
3279
24
  assert(Field != nullptr && "This should be called only for members");
3280
24
  const Expr *InitExpr = Field->getInClassInitializer();
3281
24
  if (!InitExpr)
3282
8
    return EndOfTU ? 
NoMismatch4
:
AnalyzeLater4
;
3283
16
  if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(InitExpr)) {
3284
10
    if (NE->isArray() != IsArrayForm) {
3285
8
      NewExprs.push_back(NE);
3286
8
      return MemberInitMismatches;
3287
8
    }
3288
8
  }
3289
8
  return NoMismatch;
3290
8
}
3291
3292
MismatchingNewDeleteDetector::MismatchResult
3293
MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field,
3294
2.06k
                                           bool DeleteWasArrayForm) {
3295
2.06k
  assert(Field != nullptr && "Analysis requires a valid class member.");
3296
2.06k
  this->Field = Field;
3297
2.06k
  IsArrayForm = DeleteWasArrayForm;
3298
2.06k
  const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Field->getParent());
3299
5.10k
  for (const auto *CD : RD->ctors()) {
3300
5.10k
    if (hasMatchingNewInCtor(CD))
3301
528
      return NoMismatch;
3302
5.10k
  }
3303
1.53k
  if (HasUndefinedConstructors)
3304
521
    return EndOfTU ? 
NoMismatch0
: AnalyzeLater;
3305
1.01k
  if (!NewExprs.empty())
3306
12
    return MemberInitMismatches;
3307
1.00k
  return Field->hasInClassInitializer() ? 
analyzeInClassInitializer()24
3308
981
                                        : NoMismatch;
3309
1.00k
}
3310
3311
MismatchingNewDeleteDetector::MismatchResult
3312
1.54k
MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) {
3313
1.54k
  assert(ME != nullptr && "Expected a member expression");
3314
1.54k
  if (FieldDecl *F = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3315
1.54k
    return analyzeField(F, IsArrayForm);
3316
2
  return NoMismatch;
3317
2
}
3318
3319
2.14k
bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) {
3320
2.14k
  const CXXNewExpr *NE = nullptr;
3321
2.14k
  if (const VarDecl *VD = dyn_cast<const VarDecl>(D->getDecl())) {
3322
2.14k
    if (VD->hasInit() && 
(NE = getNewExprFromInitListOrExpr(VD->getInit()))536
&&
3323
372
        NE->isArray() != IsArrayForm) {
3324
16
      NewExprs.push_back(NE);
3325
16
    }
3326
2.14k
  }
3327
2.14k
  return NewExprs.empty();
3328
2.14k
}
3329
3330
static void
3331
DiagnoseMismatchedNewDelete(Sema &SemaRef, SourceLocation DeleteLoc,
3332
36
                            const MismatchingNewDeleteDetector &Detector) {
3333
36
  SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(DeleteLoc);
3334
36
  FixItHint H;
3335
36
  if (!Detector.IsArrayForm)
3336
27
    H = FixItHint::CreateInsertion(EndOfDelete, "[]");
3337
9
  else {
3338
9
    SourceLocation RSquare = Lexer::findLocationAfterToken(
3339
9
        DeleteLoc, tok::l_square, SemaRef.getSourceManager(),
3340
9
        SemaRef.getLangOpts(), true);
3341
9
    if (RSquare.isValid())
3342
7
      H = FixItHint::CreateRemoval(SourceRange(EndOfDelete, RSquare));
3343
9
  }
3344
36
  SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new)
3345
36
      << Detector.IsArrayForm << H;
3346
3347
36
  for (const auto *NE : Detector.NewExprs)
3348
48
    SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here)
3349
48
        << Detector.IsArrayForm;
3350
36
}
3351
3352
4.45k
void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) {
3353
4.45k
  if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation()))
3354
288
    return;
3355
4.16k
  MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false);
3356
4.16k
  switch (Detector.analyzeDeleteExpr(DE)) {
3357
16
  case MismatchingNewDeleteDetector::VarInitMismatches:
3358
24
  case MismatchingNewDeleteDetector::MemberInitMismatches: {
3359
24
    DiagnoseMismatchedNewDelete(*this, DE->getBeginLoc(), Detector);
3360
24
    break;
3361
16
  }
3362
525
  case MismatchingNewDeleteDetector::AnalyzeLater: {
3363
525
    DeleteExprs[Detector.Field].push_back(
3364
525
        std::make_pair(DE->getBeginLoc(), DE->isArrayForm()));
3365
525
    break;
3366
16
  }
3367
3.62k
  case MismatchingNewDeleteDetector::NoMismatch:
3368
3.62k
    break;
3369
4.16k
  }
3370
4.16k
}
3371
3372
void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
3373
525
                                     bool DeleteWasArrayForm) {
3374
525
  MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true);
3375
525
  switch (Detector.analyzeField(Field, DeleteWasArrayForm)) {
3376
0
  case MismatchingNewDeleteDetector::VarInitMismatches:
3377
0
    llvm_unreachable("This analysis should have been done for class members.");
3378
0
  case MismatchingNewDeleteDetector::AnalyzeLater:
3379
0
    llvm_unreachable("Analysis cannot be postponed any point beyond end of "
3380
0
                     "translation unit.");
3381
12
  case MismatchingNewDeleteDetector::MemberInitMismatches:
3382
12
    DiagnoseMismatchedNewDelete(*this, DeleteLoc, Detector);
3383
12
    break;
3384
513
  case MismatchingNewDeleteDetector::NoMismatch:
3385
513
    break;
3386
525
  }
3387
525
}
3388
3389
/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
3390
/// @code ::delete ptr; @endcode
3391
/// or
3392
/// @code delete [] ptr; @endcode
3393
ExprResult
3394
Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
3395
4.58k
                     bool ArrayForm, Expr *ExE) {
3396
  // C++ [expr.delete]p1:
3397
  //   The operand shall have a pointer type, or a class type having a single
3398
  //   non-explicit conversion function to a pointer type. The result has type
3399
  //   void.
3400
  //
3401
  // DR599 amends "pointer type" to "pointer to object type" in both cases.
3402
3403
4.58k
  ExprResult Ex = ExE;
3404
4.58k
  FunctionDecl *OperatorDelete = nullptr;
3405
4.58k
  bool ArrayFormAsWritten = ArrayForm;
3406
4.58k
  bool UsualArrayDeleteWantsSize = false;
3407
3408
4.58k
  if (!Ex.get()->isTypeDependent()) {
3409
    // Perform lvalue-to-rvalue cast, if needed.
3410
2.32k
    Ex = DefaultLvalueConversion(Ex.get());
3411
2.32k
    if (Ex.isInvalid())
3412
4
      return ExprError();
3413
3414
2.32k
    QualType Type = Ex.get()->getType();
3415
3416
2.32k
    class DeleteConverter : public ContextualImplicitConverter {
3417
2.32k
    public:
3418
2.32k
      DeleteConverter() : ContextualImplicitConverter(false, true) {}
3419
3420
4.77k
      bool match(QualType ConvType) override {
3421
        // FIXME: If we have an operator T* and an operator void*, we must pick
3422
        // the operator T*.
3423
4.77k
        if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
3424
4.64k
          if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
3425
4.63k
            return true;
3426
143
        return false;
3427
143
      }
3428
3429
2.32k
      SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
3430
24
                                            QualType T) override {
3431
24
        return S.Diag(Loc, diag::err_delete_operand) << T;
3432
24
      }
3433
3434
2.32k
      SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
3435
4
                                               QualType T) override {
3436
4
        return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T;
3437
4
      }
3438
3439
2.32k
      SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
3440
2.32k
                                                 QualType T,
3441
2
                                                 QualType ConvTy) override {
3442
2
        return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy;
3443
2
      }
3444
3445
2.32k
      SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
3446
2
                                             QualType ConvTy) override {
3447
2
        return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3448
2
          << ConvTy;
3449
2
      }
3450
3451
2.32k
      SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
3452
12
                                              QualType T) override {
3453
12
        return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T;
3454
12
      }
3455
3456
2.32k
      SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
3457
24
                                          QualType ConvTy) override {
3458
24
        return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3459
24
          << ConvTy;
3460
24
      }
3461
3462
2.32k
      SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
3463
2.32k
                                               QualType T,
3464
0
                                               QualType ConvTy) override {
3465
0
        llvm_unreachable("conversion functions are permitted");
3466
0
      }
3467
2.32k
    } Converter;
3468
3469
2.32k
    Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter);
3470
2.32k
    if (Ex.isInvalid())
3471
0
      return ExprError();
3472
2.32k
    Type = Ex.get()->getType();
3473
2.32k
    if (!Converter.match(Type))
3474
      // FIXME: PerformContextualImplicitConversion should return ExprError
3475
      //        itself in this case.
3476
40
      return ExprError();
3477
3478
2.28k
    QualType Pointee = Type->castAs<PointerType>()->getPointeeType();
3479
2.28k
    QualType PointeeElem = Context.getBaseElementType(Pointee);
3480
3481
2.28k
    if (Pointee.getAddressSpace() != LangAS::Default &&
3482
6
        !getLangOpts().OpenCLCPlusPlus)
3483
2
      return Diag(Ex.get()->getBeginLoc(),
3484
2
                  diag::err_address_space_qualified_delete)
3485
2
             << Pointee.getUnqualifiedType()
3486
2
             << Pointee.getQualifiers().getAddressSpaceAttributePrintValue();
3487
3488
2.28k
    CXXRecordDecl *PointeeRD = nullptr;
3489
2.28k
    if (Pointee->isVoidType() && 
!isSFINAEContext()24
) {
3490
      // The C++ standard bans deleting a pointer to a non-object type, which
3491
      // effectively bans deletion of "void*". However, most compilers support
3492
      // this, so we treat it as a warning unless we're in a SFINAE context.
3493
24
      Diag(StartLoc, diag::ext_delete_void_ptr_operand)
3494
24
        << Type << Ex.get()->getSourceRange();
3495
2.25k
    } else if (Pointee->isFunctionType() || Pointee->isVoidType() ||
3496
2.25k
               Pointee->isSizelessType()) {
3497
8
      return ExprError(Diag(StartLoc, diag::err_delete_operand)
3498
8
        << Type << Ex.get()->getSourceRange());
3499
2.24k
    } else if (!Pointee->isDependentType()) {
3500
      // FIXME: This can result in errors if the definition was imported from a
3501
      // module but is hidden.
3502
2.24k
      if (!RequireCompleteType(StartLoc, Pointee,
3503
2.22k
                               diag::warn_delete_incomplete, Ex.get())) {
3504
2.22k
        if (const RecordType *RT = PointeeElem->getAs<RecordType>())
3505
1.19k
          PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
3506
2.22k
      }
3507
2.24k
    }
3508
3509
2.27k
    if (Pointee->isArrayType() && 
!ArrayForm17
) {
3510
4
      Diag(StartLoc, diag::warn_delete_array_type)
3511
4
          << Type << Ex.get()->getSourceRange()
3512
4
          << FixItHint::CreateInsertion(getLocForEndOfToken(StartLoc), "[]");
3513
4
      ArrayForm = true;
3514
4
    }
3515
3516
2.27k
    DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
3517
1.52k
                                      ArrayForm ? 
OO_Array_Delete748
: OO_Delete);
3518
3519
2.27k
    if (PointeeRD) {
3520
1.19k
      if (!UseGlobal &&
3521
1.14k
          FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
3522
1.14k
                                   OperatorDelete))
3523
62
        return ExprError();
3524
3525
      // If we're allocating an array of records, check whether the
3526
      // usual operator delete[] has a size_t parameter.
3527
1.12k
      if (ArrayForm) {
3528
        // If the user specifically asked to use the global allocator,
3529
        // we'll need to do the lookup into the class.
3530
173
        if (UseGlobal)
3531
24
          UsualArrayDeleteWantsSize =
3532
24
            doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
3533
3534
        // Otherwise, the usual operator delete[] should be the
3535
        // function we just found.
3536
149
        else if (OperatorDelete && 
isa<CXXMethodDecl>(OperatorDelete)38
)
3537
38
          UsualArrayDeleteWantsSize =
3538
38
            UsualDeallocFnInfo(*this,
3539
38
                               DeclAccessPair::make(OperatorDelete, AS_public))
3540
38
              .HasSizeT;
3541
173
      }
3542
3543
1.12k
      if (!PointeeRD->hasIrrelevantDestructor())
3544
666
        if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
3545
666
          MarkFunctionReferenced(StartLoc,
3546
666
                                    const_cast<CXXDestructorDecl*>(Dtor));
3547
666
          if (DiagnoseUseOfDecl(Dtor, StartLoc))
3548
6
            return ExprError();
3549
1.12k
        }
3550
3551
1.12k
      CheckVirtualDtorCall(PointeeRD->getDestructor(), StartLoc,
3552
1.12k
                           /*IsDelete=*/true, /*CallCanBeVirtual=*/true,
3553
1.12k
                           /*WarnOnNonAbstractTypes=*/!ArrayForm,
3554
1.12k
                           SourceLocation());
3555
1.12k
    }
3556
3557
2.20k
    if (!OperatorDelete) {
3558
2.00k
      if (getLangOpts().OpenCLCPlusPlus) {
3559
3
        Diag(StartLoc, diag::err_openclcxx_not_supported) << "default delete";
3560
3
        return ExprError();
3561
3
      }
3562
3563
2.00k
      bool IsComplete = isCompleteType(StartLoc, Pointee);
3564
2.00k
      bool CanProvideSize =
3565
2.00k
          IsComplete && 
(1.96k
!ArrayForm1.96k
||
UsualArrayDeleteWantsSize706
||
3566
701
                         Pointee.isDestructedType());
3567
2.00k
      bool Overaligned = hasNewExtendedAlignment(*this, Pointee);
3568
3569
      // Look for a global declaration.
3570
2.00k
      OperatorDelete = FindUsualDeallocationFunction(StartLoc, CanProvideSize,
3571
2.00k
                                                     Overaligned, DeleteName);
3572
2.00k
    }
3573
3574
2.20k
    MarkFunctionReferenced(StartLoc, OperatorDelete);
3575
3576
    // Check access and ambiguity of destructor if we're going to call it.
3577
    // Note that this is required even for a virtual delete.
3578
2.20k
    bool IsVirtualDelete = false;
3579
2.20k
    if (PointeeRD) {
3580
1.12k
      if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
3581
1.12k
        CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
3582
1.12k
                              PDiag(diag::err_access_dtor) << PointeeElem);
3583
1.12k
        IsVirtualDelete = Dtor->isVirtual();
3584
1.12k
      }
3585
1.12k
    }
3586
3587
2.20k
    DiagnoseUseOfDecl(OperatorDelete, StartLoc);
3588
3589
    // Convert the operand to the type of the first parameter of operator
3590
    // delete. This is only necessary if we selected a destroying operator
3591
    // delete that we are going to call (non-virtually); converting to void*
3592
    // is trivial and left to AST consumers to handle.
3593
2.20k
    QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
3594
2.20k
    if (!IsVirtualDelete && 
!ParamType->getPointeeType()->isVoidType()2.07k
) {
3595
29
      Qualifiers Qs = Pointee.getQualifiers();
3596
29
      if (Qs.hasCVRQualifiers()) {
3597
        // Qualifiers are irrelevant to this conversion; we're only looking
3598
        // for access and ambiguity.
3599
2
        Qs.removeCVRQualifiers();
3600
2
        QualType Unqual = Context.getPointerType(
3601
2
            Context.getQualifiedType(Pointee.getUnqualifiedType(), Qs));
3602
2
        Ex = ImpCastExprToType(Ex.get(), Unqual, CK_NoOp);
3603
2
      }
3604
29
      Ex = PerformImplicitConversion(Ex.get(), ParamType, AA_Passing);
3605
29
      if (Ex.isInvalid())
3606
4
        return ExprError();
3607
4.45k
    }
3608
2.20k
  }
3609
3610
4.45k
  CXXDeleteExpr *Result = new (Context) CXXDeleteExpr(
3611
4.45k
      Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten,
3612
4.45k
      UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc);
3613
4.45k
  AnalyzeDeleteExprMismatch(Result);
3614
4.45k
  return Result;
3615
4.45k
}
3616
3617
static bool resolveBuiltinNewDeleteOverload(Sema &S, CallExpr *TheCall,
3618
                                            bool IsDelete,
3619
983
                                            FunctionDecl *&Operator) {
3620
3621
983
  DeclarationName NewName = S.Context.DeclarationNames.getCXXOperatorName(
3622
499
      IsDelete ? 
OO_Delete484
: OO_New);
3623
3624
983
  LookupResult R(S, NewName, TheCall->getBeginLoc(), Sema::LookupOrdinaryName);
3625
983
  S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl());
3626
983
  assert(!R.empty() && "implicitly declared allocation functions not found");
3627
983
  assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
3628
3629
  // We do our own custom access checks below.
3630
983
  R.suppressDiagnostics();
3631
3632
983
  SmallVector<Expr *, 8> Args(TheCall->arg_begin(), TheCall->arg_end());
3633
983
  OverloadCandidateSet Candidates(R.getNameLoc(),
3634
983
                                  OverloadCandidateSet::CSK_Normal);
3635
983
  for (LookupResult::iterator FnOvl = R.begin(), FnOvlEnd = R.end();
3636
5.98k
       FnOvl != FnOvlEnd; 
++FnOvl4.99k
) {
3637
    // Even member operator new/delete are implicitly treated as
3638
    // static, so don't use AddMemberCandidate.
3639
4.99k
    NamedDecl *D = (*FnOvl)->getUnderlyingDecl();
3640
3641
4.99k
    if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
3642
4
      S.AddTemplateOverloadCandidate(FnTemplate, FnOvl.getPair(),
3643
4
                                     /*ExplicitTemplateArgs=*/nullptr, Args,
3644
4
                                     Candidates,
3645
4
                                     /*SuppressUserConversions=*/false);
3646
4
      continue;
3647
4
    }
3648
3649
4.99k
    FunctionDecl *Fn = cast<FunctionDecl>(D);
3650
4.99k
    S.AddOverloadCandidate(Fn, FnOvl.getPair(), Args, Candidates,
3651
4.99k
                           /*SuppressUserConversions=*/false);
3652
4.99k
  }
3653
3654
983
  SourceRange Range = TheCall->getSourceRange();
3655
3656
  // Do the resolution.
3657
983
  OverloadCandidateSet::iterator Best;
3658
983
  switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
3659
949
  case OR_Success: {
3660
    // Got one!
3661
949
    FunctionDecl *FnDecl = Best->Function;
3662
949
    assert(R.getNamingClass() == nullptr &&
3663
949
           "class members should not be considered");
3664
3665
949
    if (!FnDecl->isReplaceableGlobalAllocationFunction()) {
3666
20
      S.Diag(R.getNameLoc(), diag::err_builtin_operator_new_delete_not_usual)
3667
12
          << (IsDelete ? 1 : 
08
) << Range;
3668
20
      S.Diag(FnDecl->getLocation(), diag::note_non_usual_function_declared_here)
3669
20
          << R.getLookupName() << FnDecl->getSourceRange();
3670
20
      return true;
3671
20
    }
3672
3673
929
    Operator = FnDecl;
3674
929
    return false;
3675
929
  }
3676
3677
30
  case OR_No_Viable_Function:
3678
30
    Candidates.NoteCandidates(
3679
30
        PartialDiagnosticAt(R.getNameLoc(),
3680
30
                            S.PDiag(diag::err_ovl_no_viable_function_in_call)
3681
30
                                << R.getLookupName() << Range),
3682
30
        S, OCD_AllCandidates, Args);
3683
30
    return true;
3684
3685
4
  case OR_Ambiguous:
3686
4
    Candidates.NoteCandidates(
3687
4
        PartialDiagnosticAt(R.getNameLoc(),
3688
4
                            S.PDiag(diag::err_ovl_ambiguous_call)
3689
4
                                << R.getLookupName() << Range),
3690
4
        S, OCD_AmbiguousCandidates, Args);
3691
4
    return true;
3692
3693
0
  case OR_Deleted: {
3694
0
    Candidates.NoteCandidates(
3695
0
        PartialDiagnosticAt(R.getNameLoc(), S.PDiag(diag::err_ovl_deleted_call)
3696
0
                                                << R.getLookupName() << Range),
3697
0
        S, OCD_AllCandidates, Args);
3698
0
    return true;
3699
0
  }
3700
0
  }
3701
0
  llvm_unreachable("Unreachable, bad result from BestViableFunction");
3702
0
}
3703
3704
ExprResult
3705
Sema::SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
3706
985
                                             bool IsDelete) {
3707
985
  CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
3708
985
  if (!getLangOpts().CPlusPlus) {
3709
2
    Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
3710
1
        << (IsDelete ? "__builtin_operator_delete" : "__builtin_operator_new")
3711
2
        << "C++";
3712
2
    return ExprError();
3713
2
  }
3714
  // CodeGen assumes it can find the global new and delete to call,
3715
  // so ensure that they are declared.
3716
983
  DeclareGlobalNewDelete();
3717
3718
983
  FunctionDecl *OperatorNewOrDelete = nullptr;
3719
983
  if (resolveBuiltinNewDeleteOverload(*this, TheCall, IsDelete,
3720
983
                                      OperatorNewOrDelete))
3721
54
    return ExprError();
3722
929
  assert(OperatorNewOrDelete && "should be found");
3723
3724
929
  DiagnoseUseOfDecl(OperatorNewOrDelete, TheCall->getExprLoc());
3725
929
  MarkFunctionReferenced(TheCall->getExprLoc(), OperatorNewOrDelete);
3726
3727
929
  TheCall->setType(OperatorNewOrDelete->getReturnType());
3728
1.90k
  for (unsigned i = 0; i != TheCall->getNumArgs(); 
++i975
) {
3729
975
    QualType ParamTy = OperatorNewOrDelete->getParamDecl(i)->getType();
3730
975
    InitializedEntity Entity =
3731
975
        InitializedEntity::InitializeParameter(Context, ParamTy, false);
3732
975
    ExprResult Arg = PerformCopyInitialization(
3733
975
        Entity, TheCall->getArg(i)->getBeginLoc(), TheCall->getArg(i));
3734
975
    if (Arg.isInvalid())
3735
0
      return ExprError();
3736
975
    TheCall->setArg(i, Arg.get());
3737
975
  }
3738
929
  auto Callee = dyn_cast<ImplicitCastExpr>(TheCall->getCallee());
3739
929
  assert(Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr &&
3740
929
         "Callee expected to be implicit cast to a builtin function pointer");
3741
929
  Callee->setType(OperatorNewOrDelete->getType());
3742
3743
929
  return TheCallResult;
3744
929
}
3745
3746
void Sema::CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
3747
                                bool IsDelete, bool CallCanBeVirtual,
3748
                                bool WarnOnNonAbstractTypes,
3749
2.23k
                                SourceLocation DtorLoc) {
3750
2.23k
  if (!dtor || 
dtor->isVirtual()1.98k
||
!CallCanBeVirtual1.81k
||
isUnevaluatedContext()1.63k
)
3751
654
    return;
3752
3753
  // C++ [expr.delete]p3:
3754
  //   In the first alternative (delete object), if the static type of the
3755
  //   object to be deleted is different from its dynamic type, the static
3756
  //   type shall be a base class of the dynamic type of the object to be
3757
  //   deleted and the static type shall have a virtual destructor or the
3758
  //   behavior is undefined.
3759
  //
3760
1.58k
  const CXXRecordDecl *PointeeRD = dtor->getParent();
3761
  // Note: a final class cannot be derived from, no issue there
3762
1.58k
  if (!PointeeRD->isPolymorphic() || 
PointeeRD->hasAttr<FinalAttr>()74
)
3763
1.51k
    return;
3764
3765
  // If the superclass is in a system header, there's nothing that can be done.
3766
  // The `delete` (where we emit the warning) can be in a system header,
3767
  // what matters for this warning is where the deleted type is defined.
3768
65
  if (getSourceManager().isInSystemHeader(PointeeRD->getLocation()))
3769
2
    return;
3770
3771
63
  QualType ClassType = dtor->getThisType()->getPointeeType();
3772
63
  if (PointeeRD->isAbstract()) {
3773
    // If the class is abstract, we warn by default, because we're
3774
    // sure the code has undefined behavior.
3775
9
    Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 
10
)
3776
9
                                                           << ClassType;
3777
54
  } else if (WarnOnNonAbstractTypes) {
3778
    // Otherwise, if this is not an array delete, it's a bit suspect,
3779
    // but not necessarily wrong.
3780
42
    Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 
18
)
3781
50
                                                  << ClassType;
3782
50
  }
3783
63
  if (!IsDelete) {
3784
8
    std::string TypeStr;
3785
8
    ClassType.getAsStringInternal(TypeStr, getPrintingPolicy());
3786
8
    Diag(DtorLoc, diag::note_delete_non_virtual)
3787
8
        << FixItHint::CreateInsertion(DtorLoc, TypeStr + "::");
3788
8
  }
3789
63
}
3790
3791
Sema::ConditionResult Sema::ActOnConditionVariable(Decl *ConditionVar,
3792
                                                   SourceLocation StmtLoc,
3793
1.03k
                                                   ConditionKind CK) {
3794
1.03k
  ExprResult E =
3795
1.03k
      CheckConditionVariable(cast<VarDecl>(ConditionVar), StmtLoc, CK);
3796
1.03k
  if (E.isInvalid())
3797
77
    return ConditionError();
3798
954
  return ConditionResult(*this, ConditionVar, MakeFullExpr(E.get(), StmtLoc),
3799
954
                         CK == ConditionKind::ConstexprIf);
3800
954
}
3801
3802
/// Check the use of the given variable as a C++ condition in an if,
3803
/// while, do-while, or switch statement.
3804
ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
3805
                                        SourceLocation StmtLoc,
3806
1.03k
                                        ConditionKind CK) {
3807
1.03k
  if (ConditionVar->isInvalidDecl())
3808
56
    return ExprError();
3809
3810
975
  QualType T = ConditionVar->getType();
3811
3812
  // C++ [stmt.select]p2:
3813
  //   The declarator shall not specify a function or an array.
3814
975
  if (T->isFunctionType())
3815
0
    return ExprError(Diag(ConditionVar->getLocation(),
3816
0
                          diag::err_invalid_use_of_function_type)
3817
0
                       << ConditionVar->getSourceRange());
3818
975
  else if (T->isArrayType())
3819
2
    return ExprError(Diag(ConditionVar->getLocation(),
3820
2
                          diag::err_invalid_use_of_array_type)
3821
2
                     << ConditionVar->getSourceRange());
3822
3823
973
  ExprResult Condition = BuildDeclRefExpr(
3824
973
      ConditionVar, ConditionVar->getType().getNonReferenceType(), VK_LValue,
3825
973
      ConditionVar->getLocation());
3826
3827
973
  switch (CK) {
3828
912
  case ConditionKind::Boolean:
3829
912
    return CheckBooleanCondition(StmtLoc, Condition.get());
3830
3831
0
  case ConditionKind::ConstexprIf:
3832
0
    return CheckBooleanCondition(StmtLoc, Condition.get(), true);
3833
3834
61
  case ConditionKind::Switch:
3835
61
    return CheckSwitchCondition(StmtLoc, Condition.get());
3836
0
  }
3837
3838
0
  llvm_unreachable("unexpected condition kind");
3839
0
}
3840
3841
/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
3842
607k
ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) {
3843
  // C++ 6.4p4:
3844
  // The value of a condition that is an initialized declaration in a statement
3845
  // other than a switch statement is the value of the declared variable
3846
  // implicitly converted to type bool. If that conversion is ill-formed, the
3847
  // program is ill-formed.
3848
  // The value of a condition that is an expression is the value of the
3849
  // expression, implicitly converted to bool.
3850
  //
3851
  // FIXME: Return this value to the caller so they don't need to recompute it.
3852
607k
  llvm::APSInt Value(/*BitWidth*/1);
3853
607k
  return (IsConstexpr && 
!CondExpr->isValueDependent()212
)
3854
185
             ? CheckConvertedConstantExpression(CondExpr, Context.BoolTy, Value,
3855
185
                                                CCEK_ConstexprIf)
3856
606k
             : PerformContextuallyConvertToBool(CondExpr);
3857
607k
}
3858
3859
/// Helper function to determine whether this is the (deprecated) C++
3860
/// conversion from a string literal to a pointer to non-const char or
3861
/// non-const wchar_t (for narrow and wide string literals,
3862
/// respectively).
3863
bool
3864
151k
Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
3865
  // Look inside the implicit cast, if it exists.
3866
151k
  if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
3867
5
    From = Cast->getSubExpr();
3868
3869
  // A string literal (2.13.4) that is not a wide string literal can
3870
  // be converted to an rvalue of type "pointer to char"; a wide
3871
  // string literal can be converted to an rvalue of type "pointer
3872
  // to wchar_t" (C++ 4.2p2).
3873
151k
  if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
3874
130k
    if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
3875
127k
      if (const BuiltinType *ToPointeeType
3876
126k
          = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
3877
        // This conversion is considered only when there is an
3878
        // explicit appropriate pointer target type (C++ 4.2p2).
3879
126k
        if (!ToPtrType->getPointeeType().hasQualifiers()) {
3880
870
          switch (StrLit->getKind()) {
3881
2
            case StringLiteral::UTF8:
3882
4
            case StringLiteral::UTF16:
3883
6
            case StringLiteral::UTF32:
3884
              // We don't allow UTF literals to be implicitly converted
3885
6
              break;
3886
838
            case StringLiteral::Ascii:
3887
838
              return (ToPointeeType->getKind() == BuiltinType::Char_U ||
3888
838
                      ToPointeeType->getKind() == BuiltinType::Char_S);
3889
26
            case StringLiteral::Wide:
3890
26
              return Context.typesAreCompatible(Context.getWideCharType(),
3891
26
                                                QualType(ToPointeeType, 0));
3892
150k
          }
3893
150k
        }
3894
126k
      }
3895
3896
150k
  return false;
3897
150k
}
3898
3899
static ExprResult BuildCXXCastArgument(Sema &S,
3900
                                       SourceLocation CastLoc,
3901
                                       QualType Ty,
3902
                                       CastKind Kind,
3903
                                       CXXMethodDecl *Method,
3904
                                       DeclAccessPair FoundDecl,
3905
                                       bool HadMultipleCandidates,
3906
5.82k
                                       Expr *From) {
3907
5.82k
  switch (Kind) {
3908
0
  default: llvm_unreachable("Unhandled cast kind!");
3909
715
  case CK_ConstructorConversion: {
3910
715
    CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
3911
715
    SmallVector<Expr*, 8> ConstructorArgs;
3912
3913
715
    if (S.RequireNonAbstractType(CastLoc, Ty,
3914
715
                                 diag::err_allocation_of_abstract_type))
3915
4
      return ExprError();
3916
3917
711
    if (S.CompleteConstructorCall(Constructor, From, CastLoc, ConstructorArgs))
3918
0
      return ExprError();
3919
3920
711
    S.CheckConstructorAccess(CastLoc, Constructor, FoundDecl,
3921
711
                             InitializedEntity::InitializeTemporary(Ty));
3922
711
    if (S.DiagnoseUseOfDecl(Method, CastLoc))
3923
2
      return ExprError();
3924
3925
709
    ExprResult Result = S.BuildCXXConstructExpr(
3926
709
        CastLoc, Ty, FoundDecl, cast<CXXConstructorDecl>(Method),
3927
709
        ConstructorArgs, HadMultipleCandidates,
3928
709
        /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3929
709
        CXXConstructExpr::CK_Complete, SourceRange());
3930
709
    if (Result.isInvalid())
3931
0
      return ExprError();
3932
3933
709
    return S.MaybeBindToTemporary(Result.getAs<Expr>());
3934
709
  }
3935
3936
5.10k
  case CK_UserDefinedConversion: {
3937
5.10k
    assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
3938
3939
5.10k
    S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl);
3940
5.10k
    if (S.DiagnoseUseOfDecl(Method, CastLoc))
3941
0
      return ExprError();
3942
3943
    // Create an implicit call expr that calls it.
3944
5.10k
    CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
3945
5.10k
    ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
3946
5.10k
                                                 HadMultipleCandidates);
3947
5.10k
    if (Result.isInvalid())
3948
1
      return ExprError();
3949
    // Record usage of conversion in an implicit cast.
3950
5.10k
    Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(),
3951
5.10k
                                      CK_UserDefinedConversion, Result.get(),
3952
5.10k
                                      nullptr, Result.get()->getValueKind(),
3953
5.10k
                                      S.CurFPFeatureOverrides());
3954
3955
5.10k
    return S.MaybeBindToTemporary(Result.get());
3956
5.10k
  }
3957
5.82k
  }
3958
5.82k
}
3959
3960
/// PerformImplicitConversion - Perform an implicit conversion of the
3961
/// expression From to the type ToType using the pre-computed implicit
3962
/// conversion sequence ICS. Returns the converted
3963
/// expression. Action is the kind of conversion we're performing,
3964
/// used in the error message.
3965
ExprResult
3966
Sema::PerformImplicitConversion(Expr *From, QualType ToType,
3967
                                const ImplicitConversionSequence &ICS,
3968
                                AssignmentAction Action,
3969
10.0M
                                CheckedConversionKind CCK) {
3970
  // C++ [over.match.oper]p7: [...] operands of class type are converted [...]
3971
10.0M
  if (CCK == CCK_ForBuiltinOverloadedOp && 
!From->getType()->isRecordType()84.1k
)
3972
79.8k
    return From;
3973
3974
9.96M
  switch (ICS.getKind()) {
3975
9.95M
  case ImplicitConversionSequence::StandardConversion: {
3976
9.95M
    ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
3977
9.95M
                                               Action, CCK);
3978
9.95M
    if (Res.isInvalid())
3979
112
      return ExprError();
3980
9.95M
    From = Res.get();
3981
9.95M
    break;
3982
9.95M
  }
3983
3984
5.82k
  case ImplicitConversionSequence::UserDefinedConversion: {
3985
3986
5.82k
      FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
3987
5.82k
      CastKind CastKind;
3988
5.82k
      QualType BeforeToType;
3989
5.82k
      assert(FD && "no conversion function for user-defined conversion seq");
3990
5.82k
      if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
3991
5.10k
        CastKind = CK_UserDefinedConversion;
3992
3993
        // If the user-defined conversion is specified by a conversion function,
3994
        // the initial standard conversion sequence converts the source type to
3995
        // the implicit object parameter of the conversion function.
3996
5.10k
        BeforeToType = Context.getTagDeclType(Conv->getParent());
3997
715
      } else {
3998
715
        const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
3999
715
        CastKind = CK_ConstructorConversion;
4000
        // Do no conversion if dealing with ... for the first conversion.
4001
715
        if (!ICS.UserDefined.EllipsisConversion) {
4002
          // If the user-defined conversion is specified by a constructor, the
4003
          // initial standard conversion sequence converts the source type to
4004
          // the type required by the argument of the constructor
4005
712
          BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
4006
712
        }
4007
715
      }
4008
      // Watch out for ellipsis conversion.
4009
5.82k
      if (!ICS.UserDefined.EllipsisConversion) {
4010
5.81k
        ExprResult Res =
4011
5.81k
          PerformImplicitConversion(From, BeforeToType,
4012
5.81k
                                    ICS.UserDefined.Before, AA_Converting,
4013
5.81k
                                    CCK);
4014
5.81k
        if (Res.isInvalid())
4015
0
          return ExprError();
4016
5.81k
        From = Res.get();
4017
5.81k
      }
4018
4019
5.82k
      ExprResult CastArg = BuildCXXCastArgument(
4020
5.82k
          *this, From->getBeginLoc(), ToType.getNonReferenceType(), CastKind,
4021
5.82k
          cast<CXXMethodDecl>(FD), ICS.UserDefined.FoundConversionFunction,
4022
5.82k
          ICS.UserDefined.HadMultipleCandidates, From);
4023
4024
5.82k
      if (CastArg.isInvalid())
4025
7
        return ExprError();
4026
4027
5.81k
      From = CastArg.get();
4028
4029
      // C++ [over.match.oper]p7:
4030
      //   [...] the second standard conversion sequence of a user-defined
4031
      //   conversion sequence is not applied.
4032
5.81k
      if (CCK == CCK_ForBuiltinOverloadedOp)
4033
4.30k
        return From;
4034
4035
1.51k
      return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
4036
1.51k
                                       AA_Converting, CCK);
4037
1.51k
  }
4038
4039
10
  case ImplicitConversionSequence::AmbiguousConversion:
4040
10
    ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
4041
10
                          PDiag(diag::err_typecheck_ambiguous_condition)
4042
10
                            << From->getSourceRange());
4043
10
    return ExprError();
4044
4045
0
  case ImplicitConversionSequence::EllipsisConversion:
4046
0
    llvm_unreachable("Cannot perform an ellipsis conversion");
4047
4048
466
  case ImplicitConversionSequence::BadConversion:
4049
466
    Sema::AssignConvertType ConvTy =
4050
466
        CheckAssignmentConstraints(From->getExprLoc(), ToType, From->getType());
4051
466
    bool Diagnosed = DiagnoseAssignmentResult(
4052
461
        ConvTy == Compatible ? 
Incompatible5
: ConvTy, From->getExprLoc(),
4053
466
        ToType, From->getType(), From, Action);
4054
466
    assert(Diagnosed && "failed to diagnose bad conversion"); (void)Diagnosed;
4055
466
    return ExprError();
4056
9.95M
  }
4057
4058
  // Everything went well.
4059
9.95M
  return From;
4060
9.95M
}
4061
4062
/// PerformImplicitConversion - Perform an implicit conversion of the
4063
/// expression From to the type ToType by following the standard
4064
/// conversion sequence SCS. Returns the converted
4065
/// expression. Flavor is the context in which we're performing this
4066
/// conversion, for use in error messages.
4067
ExprResult
4068
Sema::PerformImplicitConversion(Expr *From, QualType ToType,
4069
                                const StandardConversionSequence& SCS,
4070
                                AssignmentAction Action,
4071
9.96M
                                CheckedConversionKind CCK) {
4072
9.96M
  bool CStyle = (CCK == CCK_CStyleCast || 
CCK == CCK_FunctionalCast9.54M
);
4073
4074
  // Overall FIXME: we are recomputing too many types here and doing far too
4075
  // much extra work. What this means is that we need to keep track of more
4076
  // information that is computed when we try the implicit conversion initially,
4077
  // so that we don't need to recompute anything here.
4078
9.96M
  QualType FromType = From->getType();
4079
4080
9.96M
  if (SCS.CopyConstructor) {
4081
    // FIXME: When can ToType be a reference type?
4082
0
    assert(!ToType->isReferenceType());
4083
0
    if (SCS.Second == ICK_Derived_To_Base) {
4084
0
      SmallVector<Expr*, 8> ConstructorArgs;
4085
0
      if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
4086
0
                                  From, /*FIXME:ConstructLoc*/SourceLocation(),
4087
0
                                  ConstructorArgs))
4088
0
        return ExprError();
4089
0
      return BuildCXXConstructExpr(
4090
0
          /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
4091
0
          SCS.FoundCopyConstructor, SCS.CopyConstructor,
4092
0
          ConstructorArgs, /*HadMultipleCandidates*/ false,
4093
0
          /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
4094
0
          CXXConstructExpr::CK_Complete, SourceRange());
4095
0
    }
4096
0
    return BuildCXXConstructExpr(
4097
0
        /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
4098
0
        SCS.FoundCopyConstructor, SCS.CopyConstructor,
4099
0
        From, /*HadMultipleCandidates*/ false,
4100
0
        /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
4101
0
        CXXConstructExpr::CK_Complete, SourceRange());
4102
0
  }
4103
4104
  // Resolve overloaded function references.
4105
9.96M
  if (Context.hasSameType(FromType, Context.OverloadTy)) {
4106
1.13k
    DeclAccessPair Found;
4107
1.13k
    FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
4108
1.13k
                                                          true, Found);
4109
1.13k
    if (!Fn)
4110
0
      return ExprError();
4111
4112
1.13k
    if (DiagnoseUseOfDecl(Fn, From->getBeginLoc()))
4113
20
      return ExprError();
4114
4115
1.11k
    From = FixOverloadedFunctionReference(From, Found, Fn);
4116
1.11k
    FromType = From->getType();
4117
1.11k
  }
4118
4119
  // If we're converting to an atomic type, first convert to the corresponding
4120
  // non-atomic type.
4121
9.96M
  QualType ToAtomicType;
4122
9.96M
  if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) {
4123
510
    ToAtomicType = ToType;
4124
510
    ToType = ToAtomic->getValueType();
4125
510
  }
4126
4127
9.96M
  QualType InitialFromType = FromType;
4128
  // Perform the first implicit conversion.
4129
9.96M
  switch (SCS.First) {
4130
8.33M
  case ICK_Identity:
4131
8.33M
    if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) {
4132
1
      FromType = FromAtomic->getValueType().getUnqualifiedType();
4133
1
      From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic,
4134
1
                                      From, /*BasePath=*/nullptr, VK_RValue,
4135
1
                                      FPOptionsOverride());
4136
1
    }
4137
8.33M
    break;
4138
4139
1.54M
  case ICK_Lvalue_To_Rvalue: {
4140
1.54M
    assert(From->getObjectKind() != OK_ObjCProperty);
4141
1.54M
    ExprResult FromRes = DefaultLvalueConversion(From);
4142
1.54M
    assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!");
4143
1.54M
    From = FromRes.get();
4144
1.54M
    FromType = From->getType();
4145
1.54M
    break;
4146
0
  }
4147
4148
80.8k
  case ICK_Array_To_Pointer:
4149
80.8k
    FromType = Context.getArrayDecayedType(FromType);
4150
80.8k
    From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
4151
80.8k
                             VK_RValue, /*BasePath=*/nullptr, CCK).get();
4152
80.8k
    break;
4153
4154
4.58k
  case ICK_Function_To_Pointer:
4155
4.58k
    FromType = Context.getPointerType(FromType);
4156
4.58k
    From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
4157
4.58k
                             VK_RValue, /*BasePath=*/nullptr, CCK).get();
4158
4.58k
    break;
4159
4160
0
  default:
4161
0
    llvm_unreachable("Improper first standard conversion");
4162
9.96M
  }
4163
4164
  // Perform the second implicit conversion
4165
9.96M
  switch (SCS.Second) {
4166
8.78M
  case ICK_Identity:
4167
    // C++ [except.spec]p5:
4168
    //   [For] assignment to and initialization of pointers to functions,
4169
    //   pointers to member functions, and references to functions: the
4170
    //   target entity shall allow at least the exceptions allowed by the
4171
    //   source value in the assignment or initialization.
4172
8.78M
    switch (Action) {
4173
1.06M
    case AA_Assigning:
4174
2.23M
    case AA_Initializing:
4175
      // Note, function argument passing and returning are initialization.
4176
3.22M
    case AA_Passing:
4177
3.73M
    case AA_Returning:
4178
3.73M
    case AA_Sending:
4179
3.73M
    case AA_Passing_CFAudited:
4180
3.73M
      if (CheckExceptionSpecCompatibility(From, ToType))
4181
55
        return ExprError();
4182
3.73M
      break;
4183
4184
260k
    case AA_Casting:
4185
5.05M
    case AA_Converting:
4186
      // Casts and implicit conversions are not initialization, so are not
4187
      // checked for exception specification mismatches.
4188
5.05M
      break;
4189
8.78M
    }
4190
    // Nothing else to do.
4191
8.78M
    break;
4192
4193
19.4k
  case ICK_Integral_Promotion:
4194
715k
  case ICK_Integral_Conversion:
4195
715k
    if (ToType->isBooleanType()) {
4196
4
      assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&
4197
4
             SCS.Second == ICK_Integral_Promotion &&
4198
4
             "only enums with fixed underlying type can promote to bool");
4199
4
      From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean,
4200
4
                               VK_RValue, /*BasePath=*/nullptr, CCK).get();
4201
715k
    } else {
4202
715k
      From = ImpCastExprToType(From, ToType, CK_IntegralCast,
4203
715k
                               VK_RValue, /*BasePath=*/nullptr, CCK).get();
4204
715k
    }
4205
715k
    break;
4206
4207
431
  case ICK_Floating_Promotion:
4208
4.27k
  case ICK_Floating_Conversion:
4209
4.27k
    From = ImpCastExprToType(From, ToType, CK_FloatingCast,
4210
4.27k
                             VK_RValue, /*BasePath=*/nullptr, CCK).get();
4211
4.27k
    break;
4212
4213
7
  case ICK_Complex_Promotion:
4214
55
  case ICK_Complex_Conversion: {
4215
55
    QualType FromEl = From->getType()->castAs<ComplexType>()->getElementType();
4216
55
    QualType ToEl = ToType->castAs<ComplexType>()->getElementType();
4217
55
    CastKind CK;
4218
55
    if (FromEl->isRealFloatingType()) {
4219
41
      if (ToEl->isRealFloatingType())
4220
33
        CK = CK_FloatingComplexCast;
4221
8
      else
4222
8
        CK = CK_FloatingComplexToIntegralComplex;
4223
14
    } else if (ToEl->isRealFloatingType()) {
4224
4
      CK = CK_IntegralComplexToFloatingComplex;
4225
10
    } else {
4226
10
      CK = CK_IntegralComplexCast;
4227
10
    }
4228
55
    From = ImpCastExprToType(From, ToType, CK,
4229
55
                             VK_RValue, /*BasePath=*/nullptr, CCK).get();
4230
55
    break;
4231
7
  }
4232
4233
21.1k
  case ICK_Floating_Integral:
4234
21.1k
    if (ToType->isRealFloatingType())
4235
15.5k
      From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
4236
15.5k
                               VK_RValue, /*BasePath=*/nullptr, CCK).get();
4237
5.53k
    else
4238
5.53k
      From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
4239
5.53k
                               VK_RValue, /*BasePath=*/nullptr, CCK).get();
4240
21.1k
    break;
4241
4242
0
  case ICK_Compatible_Conversion:
4243
0
    From = ImpCastExprToType(From, ToType, CK_NoOp, From->getValueKind(),
4244
0
                             /*BasePath=*/nullptr, CCK).get();
4245
0
    break;
4246
4247
0
  case ICK_Writeback_Conversion:
4248
96.5k
  case ICK_Pointer_Conversion: {
4249
96.5k
    if (SCS.IncompatibleObjC && 
Action != AA_Casting18
) {
4250
      // Diagnose incompatible Objective-C conversions
4251
13
      if (Action == AA_Initializing || 
Action == AA_Assigning9
)
4252
10
        Diag(From->getBeginLoc(),
4253
10
             diag::ext_typecheck_convert_incompatible_pointer)
4254
10
            << ToType << From->getType() << Action << From->getSourceRange()
4255
10
            << 0;
4256
3
      else
4257
3
        Diag(From->getBeginLoc(),
4258
3
             diag::ext_typecheck_convert_incompatible_pointer)
4259
3
            << From->getType() << ToType << Action << From->getSourceRange()
4260
3
            << 0;
4261
4262
13
      if (From->getType()->isObjCObjectPointerType() &&
4263
9
          ToType->isObjCObjectPointerType())
4264
9
        EmitRelatedResultTypeNote(From);
4265
96.5k
    } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
4266
679
               !CheckObjCARCUnavailableWeakConversion(ToType,
4267
10
                                                      From->getType())) {
4268
10
      if (Action == AA_Initializing)
4269
6
        Diag(From->getBeginLoc(), diag::err_arc_weak_unavailable_assign);
4270
4
      else
4271
4
        Diag(From->getBeginLoc(), diag::err_arc_convesion_of_weak_unavailable)
4272
4
            << (Action == AA_Casting) << From->getType() << ToType
4273
4
            << From->getSourceRange();
4274
10
    }
4275
4276
    // Defer address space conversion to the third conversion.
4277
96.5k
    QualType FromPteeType = From->getType()->getPointeeType();
4278
96.5k
    QualType ToPteeType = ToType->getPointeeType();
4279
96.5k
    QualType NewToType = ToType;
4280
96.5k
    if (!FromPteeType.isNull() && 
!ToPteeType.isNull()52.3k
&&
4281
52.3k
        FromPteeType.getAddressSpace() != ToPteeType.getAddressSpace()) {
4282
3
      NewToType = Context.removeAddrSpaceQualType(ToPteeType);
4283
3
      NewToType = Context.getAddrSpaceQualType(NewToType,
4284
3
                                               FromPteeType.getAddressSpace());
4285
3
      if (ToType->isObjCObjectPointerType())
4286
0
        NewToType = Context.getObjCObjectPointerType(NewToType);
4287
3
      else if (ToType->isBlockPointerType())
4288
0
        NewToType = Context.getBlockPointerType(NewToType);
4289
3
      else
4290
3
        NewToType = Context.getPointerType(NewToType);
4291
3
    }
4292
4293
96.5k
    CastKind Kind;
4294
96.5k
    CXXCastPath BasePath;
4295
96.5k
    if (CheckPointerConversion(From, NewToType, Kind, BasePath, CStyle))
4296
13
      return ExprError();
4297
4298
    // Make sure we extend blocks if necessary.
4299
    // FIXME: doing this here is really ugly.
4300
96.5k
    if (Kind == CK_BlockPointerToObjCPointerCast) {
4301
24
      ExprResult E = From;
4302
24
      (void) PrepareCastToObjCObjectPointer(E);
4303
24
      From = E.get();
4304
24
    }
4305
96.5k
    if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
4306
679
      CheckObjCConversion(SourceRange(), NewToType, From, CCK);
4307
96.5k
    From = ImpCastExprToType(From, NewToType, Kind, VK_RValue, &BasePath, CCK)
4308
96.5k
             .get();
4309
96.5k
    break;
4310
96.5k
  }
4311
4312
652
  case ICK_Pointer_Member: {
4313
652
    CastKind Kind;
4314
652
    CXXCastPath BasePath;
4315
652
    if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
4316
24
      return ExprError();
4317
628
    if (CheckExceptionSpecCompatibility(From, ToType))
4318
0
      return ExprError();
4319
4320
    // We may not have been able to figure out what this member pointer resolved
4321
    // to up until this exact point.  Attempt to lock-in it's inheritance model.
4322
628
    if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
4323
124
      (void)isCompleteType(From->getExprLoc(), From->getType());
4324
124
      (void)isCompleteType(From->getExprLoc(), ToType);
4325
124
    }
4326
4327
628
    From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
4328
628
             .get();
4329
628
    break;
4330
628
  }
4331
4332
101k
  case ICK_Boolean_Conversion:
4333
    // Perform half-to-boolean conversion via float.
4334
101k
    if (From->getType()->isHalfType()) {
4335
0
      From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get();
4336
0
      FromType = Context.FloatTy;
4337
0
    }
4338
4339
101k
    From = ImpCastExprToType(From, Context.BoolTy,
4340
101k
                             ScalarTypeToBooleanCastKind(FromType),
4341
101k
                             VK_RValue, /*BasePath=*/nullptr, CCK).get();
4342
101k
    break;
4343
4344
0
  case ICK_Derived_To_Base: {
4345
0
    CXXCastPath BasePath;
4346
0
    if (CheckDerivedToBaseConversion(
4347
0
            From->getType(), ToType.getNonReferenceType(), From->getBeginLoc(),
4348
0
            From->getSourceRange(), &BasePath, CStyle))
4349
0
      return ExprError();
4350
4351
0
    From = ImpCastExprToType(From, ToType.getNonReferenceType(),
4352
0
                      CK_DerivedToBase, From->getValueKind(),
4353
0
                      &BasePath, CCK).get();
4354
0
    break;
4355
0
  }
4356
4357
237k
  case ICK_Vector_Conversion:
4358
237k
    From = ImpCastExprToType(From, ToType, CK_BitCast,
4359
237k
                             VK_RValue, /*BasePath=*/nullptr, CCK).get();
4360
237k
    break;
4361
4362
56
  case ICK_SVE_Vector_Conversion:
4363
56
    From = ImpCastExprToType(From, ToType, CK_BitCast, VK_RValue,
4364
56
                             /*BasePath=*/nullptr, CCK)
4365
56
               .get();
4366
56
    break;
4367
4368
48
  case ICK_Vector_Splat: {
4369
    // Vector splat from any arithmetic type to a vector.
4370
48
    Expr *Elem = prepareVectorSplat(ToType, From).get();
4371
48
    From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_RValue,
4372
48
                             /*BasePath=*/nullptr, CCK).get();
4373
48
    break;
4374
0
  }
4375
4376
190
  case ICK_Complex_Real:
4377
    // Case 1.  x -> _Complex y
4378
190
    if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
4379
172
      QualType ElType = ToComplex->getElementType();
4380
172
      bool isFloatingComplex = ElType->isRealFloatingType();
4381
4382
      // x -> y
4383
172
      if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
4384
        // do nothing
4385
96
      } else if (From->getType()->isRealFloatingType()) {
4386
26
        From = ImpCastExprToType(From, ElType,
4387
26
                isFloatingComplex ? CK_FloatingCast : 
CK_FloatingToIntegral0
).get();
4388
70
      } else {
4389
70
        assert(From->getType()->isIntegerType());
4390
70
        From = ImpCastExprToType(From, ElType,
4391
68
                isFloatingComplex ? CK_IntegralToFloating : 
CK_IntegralCast2
).get();
4392
70
      }
4393
      // y -> _Complex y
4394
172
      From = ImpCastExprToType(From, ToType,
4395
163
                   isFloatingComplex ? CK_FloatingRealToComplex
4396
9
                                     : CK_IntegralRealToComplex).get();
4397
4398
    // Case 2.  _Complex x -> y
4399
18
    } else {
4400
18
      auto *FromComplex = From->getType()->castAs<ComplexType>();
4401
18
      QualType ElType = FromComplex->getElementType();
4402
18
      bool isFloatingComplex = ElType->isRealFloatingType();
4403
4404
      // _Complex x -> x
4405
18
      From = ImpCastExprToType(From, ElType,
4406
8
                   isFloatingComplex ? CK_FloatingComplexToReal
4407
10
                                     : CK_IntegralComplexToReal,
4408
18
                               VK_RValue, /*BasePath=*/nullptr, CCK).get();
4409
4410
      // x -> y
4411
18
      if (Context.hasSameUnqualifiedType(ElType, ToType)) {
4412
        // do nothing
4413
7
      } else if (ToType->isRealFloatingType()) {
4414
5
        From = ImpCastExprToType(From, ToType,
4415
4
                   isFloatingComplex ? 
CK_FloatingCast1
: CK_IntegralToFloating,
4416
5
                                 VK_RValue, /*BasePath=*/nullptr, CCK).get();
4417
2
      } else {
4418
2
        assert(ToType->isIntegerType());
4419
2
        From = ImpCastExprToType(From, ToType,
4420
2
                   isFloatingComplex ? 
CK_FloatingToIntegral0
: CK_IntegralCast,
4421
2
                                 VK_RValue, /*BasePath=*/nullptr, CCK).get();
4422
2
      }
4423
18
    }
4424
190
    break;
4425
4426
5
  case ICK_Block_Pointer_Conversion: {
4427
5
    LangAS AddrSpaceL =
4428
5
        ToType->castAs<BlockPointerType>()->getPointeeType().getAddressSpace();
4429
5
    LangAS AddrSpaceR =
4430
5
        FromType->castAs<BlockPointerType>()->getPointeeType().getAddressSpace();
4431
5
    assert(Qualifiers::isAddressSpaceSupersetOf(AddrSpaceL, AddrSpaceR) &&
4432
5
           "Invalid cast");
4433
5
    CastKind Kind =
4434
5
        AddrSpaceL != AddrSpaceR ? 
CK_AddressSpaceConversion0
: CK_BitCast;
4435
5
    From = ImpCastExprToType(From, ToType.getUnqualifiedType(), Kind,
4436
5
                             VK_RValue, /*BasePath=*/nullptr, CCK).get();
4437
5
    break;
4438
0
  }
4439
4440
0
  case ICK_TransparentUnionConversion: {
4441
0
    ExprResult FromRes = From;
4442
0
    Sema::AssignConvertType ConvTy =
4443
0
      CheckTransparentUnionArgumentConstraints(ToType, FromRes);
4444
0
    if (FromRes.isInvalid())
4445
0
      return ExprError();
4446
0
    From = FromRes.get();
4447
0
    assert ((ConvTy == Sema::Compatible) &&
4448
0
            "Improper transparent union conversion");
4449
0
    (void)ConvTy;
4450
0
    break;
4451
0
  }
4452
4453
0
  case ICK_Zero_Event_Conversion:
4454
0
  case ICK_Zero_Queue_Conversion:
4455
0
    From = ImpCastExprToType(From, ToType,
4456
0
                             CK_ZeroToOCLOpaqueType,
4457
0
                             From->getValueKind()).get();
4458
0
    break;
4459
4460
0
  case ICK_Lvalue_To_Rvalue:
4461
0
  case ICK_Array_To_Pointer:
4462
0
  case ICK_Function_To_Pointer:
4463
0
  case ICK_Function_Conversion:
4464
0
  case ICK_Qualification:
4465
0
  case ICK_Num_Conversion_Kinds:
4466
0
  case ICK_C_Only_Conversion:
4467
0
  case ICK_Incompatible_Pointer_Conversion:
4468
0
    llvm_unreachable("Improper second standard conversion");
4469
9.96M
  }
4470
4471
9.96M
  switch (SCS.Third) {
4472
9.92M
  case ICK_Identity:
4473
    // Nothing to do.
4474
9.92M
    break;
4475
4476
122
  case ICK_Function_Conversion:
4477
    // If both sides are functions (or pointers/references to them), there could
4478
    // be incompatible exception declarations.
4479
122
    if (CheckExceptionSpecCompatibility(From, ToType))
4480
0
      return ExprError();
4481
4482
122
    From = ImpCastExprToType(From, ToType, CK_NoOp,
4483
122
                             VK_RValue, /*BasePath=*/nullptr, CCK).get();
4484
122
    break;
4485
4486
38.8k
  case ICK_Qualification: {
4487
38.8k
    ExprValueKind VK = From->getValueKind();
4488
38.8k
    CastKind CK = CK_NoOp;
4489
4490
38.8k
    if (ToType->isReferenceType() &&
4491
0
        ToType->getPointeeType().getAddressSpace() !=
4492
0
            From->getType().getAddressSpace())
4493
0
      CK = CK_AddressSpaceConversion;
4494
4495
38.8k
    if (ToType->isPointerType() &&
4496
38.7k
        ToType->getPointeeType().getAddressSpace() !=
4497
38.7k
            From->getType()->getPointeeType().getAddressSpace())
4498
46
      CK = CK_AddressSpaceConversion;
4499
4500
38.8k
    From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context), CK, VK,
4501
38.8k
                             /*BasePath=*/nullptr, CCK)
4502
38.8k
               .get();
4503
4504
38.8k
    if (SCS.DeprecatedStringLiteralToCharPtr &&
4505
318
        !getLangOpts().WritableStrings) {
4506
317
      Diag(From->getBeginLoc(),
4507
317
           getLangOpts().CPlusPlus11
4508
154
               ? diag::ext_deprecated_string_literal_conversion
4509
163
               : diag::warn_deprecated_string_literal_conversion)
4510
317
          << ToType.getNonReferenceType();
4511
317
    }
4512
4513
38.8k
    break;
4514
122
  }
4515
4516
0
  default:
4517
0
    llvm_unreachable("Improper third standard conversion");
4518
9.96M
  }
4519
4520
  // If this conversion sequence involved a scalar -> atomic conversion, perform
4521
  // that conversion now.
4522
9.96M
  if (!ToAtomicType.isNull()) {
4523
510
    assert(Context.hasSameType(
4524
510
        ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()));
4525
510
    From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic,
4526
510
                             VK_RValue, nullptr, CCK).get();
4527
510
  }
4528
4529
  // Materialize a temporary if we're implicitly converting to a reference
4530
  // type. This is not required by the C++ rules but is necessary to maintain
4531
  // AST invariants.
4532
9.96M
  if (ToType->isReferenceType() && 
From->isRValue()229
) {
4533
2
    ExprResult Res = TemporaryMaterializationConversion(From);
4534
2
    if (Res.isInvalid())
4535
0
      return ExprError();
4536
2
    From = Res.get();
4537
2
  }
4538
4539
  // If this conversion sequence succeeded and involved implicitly converting a
4540
  // _Nullable type to a _Nonnull one, complain.
4541
9.96M
  if (!isCast(CCK))
4542
9.46M
    diagnoseNullableToNonnullConversion(ToType, InitialFromType,
4543
9.46M
                                        From->getBeginLoc());
4544
4545
9.96M
  return From;
4546
9.96M
}
4547
4548
/// Check the completeness of a type in a unary type trait.
4549
///
4550
/// If the particular type trait requires a complete type, tries to complete
4551
/// it. If completing the type fails, a diagnostic is emitted and false
4552
/// returned. If completing the type succeeds or no completion was required,
4553
/// returns true.
4554
static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, TypeTrait UTT,
4555
                                                SourceLocation Loc,
4556
91.0k
                                                QualType ArgTy) {
4557
  // C++0x [meta.unary.prop]p3:
4558
  //   For all of the class templates X declared in this Clause, instantiating
4559
  //   that template with a template argument that is a class template
4560
  //   specialization may result in the implicit instantiation of the template
4561
  //   argument if and only if the semantics of X require that the argument
4562
  //   must be a complete type.
4563
  // We apply this rule to all the type trait expressions used to implement
4564
  // these class templates. We also try to follow any GCC documented behavior
4565
  // in these expressions to ensure portability of standard libraries.
4566
91.0k
  switch (UTT) {
4567
0
  default: llvm_unreachable("not a UTT");
4568
    // is_complete_type somewhat obviously cannot require a complete type.
4569
50
  case UTT_IsCompleteType:
4570
    // Fall-through
4571
4572
    // These traits are modeled on the type predicates in C++0x
4573
    // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
4574
    // requiring a complete type, as whether or not they return true cannot be
4575
    // impacted by the completeness of the type.
4576
3.80k
  case UTT_IsVoid:
4577
6.68k
  case UTT_IsIntegral:
4578
6.75k
  case UTT_IsFloatingPoint:
4579
26.2k
  case UTT_IsArray:
4580
28.3k
  case UTT_IsPointer:
4581
29.6k
  case UTT_IsLvalueReference:
4582
31.7k
  case UTT_IsRvalueReference:
4583
32.4k
  case UTT_IsMemberFunctionPointer:
4584
33.1k
  case UTT_IsMemberObjectPointer:
4585
34.8k
  case UTT_IsEnum:
4586
35.3k
  case UTT_IsUnion:
4587
35.8k
  case UTT_IsClass:
4588
55.3k
  case UTT_IsFunction:
4589
57.6k
  case UTT_IsReference:
4590
57.6k
  case UTT_IsArithmetic:
4591
58.2k
  case UTT_IsFundamental:
4592
58.7k
  case UTT_IsObject:
4593
59.2k
  case UTT_IsScalar:
4594
59.8k
  case UTT_IsCompound:
4595
60.3k
  case UTT_IsMemberPointer:
4596
    // Fall-through
4597
4598
    // These traits are modeled on type predicates in C++0x [meta.unary.prop]
4599
    // which requires some of its traits to have the complete type. However,
4600
    // the completeness of the type cannot impact these traits' semantics, and
4601
    // so they don't require it. This matches the comments on these traits in
4602
    // Table 49.
4603
61.4k
  case UTT_IsConst:
4604
62.5k
  case UTT_IsVolatile:
4605
64.9k
  case UTT_IsSigned:
4606
65.4k
  case UTT_IsUnsigned:
4607
4608
  // This type trait always returns false, checking the type is moot.
4609
65.4k
  case UTT_IsInterfaceClass:
4610
65.4k
    return true;
4611
4612
  // C++14 [meta.unary.prop]:
4613
  //   If T is a non-union class type, T shall be a complete type.
4614
8.54k
  case UTT_IsEmpty:
4615
9.04k
  case UTT_IsPolymorphic:
4616
9.51k
  case UTT_IsAbstract:
4617
9.51k
    if (const auto *RD = ArgTy->getAsCXXRecordDecl())
4618
4.59k
      if (!RD->isUnion())
4619
4.58k
        return !S.RequireCompleteType(
4620
4.58k
            Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4621
4.93k
    return true;
4622
4623
  // C++14 [meta.unary.prop]:
4624
  //   If T is a class type, T shall be a complete type.
4625
8.53k
  case UTT_IsFinal:
4626
8.59k
  case UTT_IsSealed:
4627
8.59k
    if (ArgTy->getAsCXXRecordDecl())
4628
4.57k
      return !S.RequireCompleteType(
4629
4.57k
          Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4630
4.01k
    return true;
4631
4632
  // C++1z [meta.unary.prop]:
4633
  //   remove_all_extents_t<T> shall be a complete type or cv void.
4634
180
  case UTT_IsAggregate:
4635
1.56k
  case UTT_IsTrivial:
4636
2.30k
  case UTT_IsTriviallyCopyable:
4637
3.66k
  case UTT_IsStandardLayout:
4638
4.33k
  case UTT_IsPOD:
4639
4.87k
  case UTT_IsLiteral:
4640
  // Per the GCC type traits documentation, T shall be a complete type, cv void,
4641
  // or an array of unknown bound. But GCC actually imposes the same constraints
4642
  // as above.
4643
4.98k
  case UTT_HasNothrowAssign:
4644
5.05k
  case UTT_HasNothrowMoveAssign:
4645
5.16k
  case UTT_HasNothrowConstructor:
4646
5.27k
  case UTT_HasNothrowCopy:
4647
5.39k
  case UTT_HasTrivialAssign:
4648
5.42k
  case UTT_HasTrivialMoveAssign:
4649
5.59k
  case UTT_HasTrivialDefaultConstructor:
4650
5.63k
  case UTT_HasTrivialMoveConstructor:
4651
5.75k
  case UTT_HasTrivialCopy:
4652
5.87k
  case UTT_HasTrivialDestructor:
4653
6.41k
  case UTT_HasVirtualDestructor:
4654
6.41k
    ArgTy = QualType(ArgTy->getBaseElementTypeUnsafe(), 0);
4655
6.41k
    LLVM_FALLTHROUGH;
4656
4657
  // C++1z [meta.unary.prop]:
4658
  //   T shall be a complete type, cv void, or an array of unknown bound.
4659
6.47k
  case UTT_IsDestructible:
4660
6.53k
  case UTT_IsNothrowDestructible:
4661
7.11k
  case UTT_IsTriviallyDestructible:
4662
7.48k
  case UTT_HasUniqueObjectRepresentations:
4663
7.48k
    if (ArgTy->isIncompleteArrayType() || 
ArgTy->isVoidType()7.45k
)
4664
165
      return true;
4665
4666
7.31k
    return !S.RequireCompleteType(
4667
7.31k
        Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4668
91.0k
  }
4669
91.0k
}
4670
4671
static bool HasNoThrowOperator(const RecordType *RT, OverloadedOperatorKind Op,
4672
                               Sema &Self, SourceLocation KeyLoc, ASTContext &C,
4673
                               bool (CXXRecordDecl::*HasTrivial)() const,
4674
                               bool (CXXRecordDecl::*HasNonTrivial)() const,
4675
                               bool (CXXMethodDecl::*IsDesiredOp)() const)
4676
81
{
4677
81
  CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4678
81
  if ((RD->*HasTrivial)() && 
!(RD->*HasNonTrivial)()18
)
4679
18
    return true;
4680
4681
63
  DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op);
4682
63
  DeclarationNameInfo NameInfo(Name, KeyLoc);
4683
63
  LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName);
4684
63
  if (Self.LookupQualifiedName(Res, RD)) {
4685
63
    bool FoundOperator = false;
4686
63
    Res.suppressDiagnostics();
4687
63
    for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
4688
135
         Op != OpEnd; 
++Op72
) {
4689
93
      if (isa<FunctionTemplateDecl>(*Op))
4690
3
        continue;
4691
4692
90
      CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
4693
90
      if((Operator->*IsDesiredOp)()) {
4694
54
        FoundOperator = true;
4695
54
        auto *CPT = Operator->getType()->castAs<FunctionProtoType>();
4696
54
        CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4697
54
        if (!CPT || !CPT->isNothrow())
4698
21
          return false;
4699
54
      }
4700
90
    }
4701
42
    return FoundOperator;
4702
0
  }
4703
0
  return false;
4704
0
}
4705
4706
static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT,
4707
75.7k
                                   SourceLocation KeyLoc, QualType T) {
4708
75.7k
  assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
4709
4710
75.7k
  ASTContext &C = Self.Context;
4711
75.7k
  switch(UTT) {
4712
0
  default: llvm_unreachable("not a UTT");
4713
    // Type trait expressions corresponding to the primary type category
4714
    // predicates in C++0x [meta.unary.cat].
4715
3.29k
  case UTT_IsVoid:
4716
3.29k
    return T->isVoidType();
4717
2.41k
  case UTT_IsIntegral:
4718
2.41k
    return T->isIntegralType(C);
4719
72
  case UTT_IsFloatingPoint:
4720
72
    return T->isFloatingType();
4721
19.0k
  case UTT_IsArray:
4722
19.0k
    return T->isArrayType();
4723
1.62k
  case UTT_IsPointer:
4724
1.62k
    return T->isAnyPointerType();
4725
825
  case UTT_IsLvalueReference:
4726
825
    return T->isLValueReferenceType();
4727
1.64k
  case UTT_IsRvalueReference:
4728
1.64k
    return T->isRValueReferenceType();
4729
287
  case UTT_IsMemberFunctionPointer:
4730
287
    return T->isMemberFunctionPointerType();
4731
218
  case UTT_IsMemberObjectPointer:
4732
218
    return T->isMemberDataPointerType();
4733
1.23k
  case UTT_IsEnum:
4734
1.23k
    return T->isEnumeralType();
4735
32
  case UTT_IsUnion:
4736
32
    return T->isUnionType();
4737
42
  case UTT_IsClass:
4738
42
    return T->isClassType() || 
T->isStructureType()39
||
T->isInterfaceType()30
;
4739
19.0k
  case UTT_IsFunction:
4740
19.0k
    return T->isFunctionType();
4741
4742
    // Type trait expressions which correspond to the convenient composition
4743
    // predicates in C++0x [meta.unary.comp].
4744
1.82k
  case UTT_IsReference:
4745
1.82k
    return T->isReferenceType();
4746
72
  case UTT_IsArithmetic:
4747
72
    return T->isArithmeticType() && 
!T->isEnumeralType()47
;
4748
75
  case UTT_IsFundamental:
4749
75
    return T->isFundamentalType();
4750
49
  case UTT_IsObject:
4751
49
    return T->isObjectType();
4752
87
  case UTT_IsScalar:
4753
    // Note: semantic analysis depends on Objective-C lifetime types to be
4754
    // considered scalar types. However, such types do not actually behave
4755
    // like scalar types at run time (since they may require retain/release
4756
    // operations), so we report them as non-scalar.
4757
87
    if (T->isObjCLifetimeType()) {
4758
8
      switch (T.getObjCLifetime()) {
4759
3
      case Qualifiers::OCL_None:
4760
4
      case Qualifiers::OCL_ExplicitNone:
4761
4
        return true;
4762
4763
1
      case Qualifiers::OCL_Strong:
4764
3
      case Qualifiers::OCL_Weak:
4765
4
      case Qualifiers::OCL_Autoreleasing:
4766
4
        return false;
4767
79
      }
4768
79
    }
4769
4770
79
    return T->isScalarType();
4771
90
  case UTT_IsCompound:
4772
90
    return T->isCompoundType();
4773
93
  case UTT_IsMemberPointer:
4774
93
    return T->isMemberPointerType();
4775
4776
    // Type trait expressions which correspond to the type property predicates
4777
    // in C++0x [meta.unary.prop].
4778
659
  case UTT_IsConst:
4779
659
    return T.isConstQualified();
4780
572
  case UTT_IsVolatile:
4781
572
    return T.isVolatileQualified();
4782
916
  case UTT_IsTrivial:
4783
916
    return T.isTrivialType(C);
4784
285
  case UTT_IsTriviallyCopyable:
4785
285
    return T.isTriviallyCopyableType(C);
4786
891
  case UTT_IsStandardLayout:
4787
891
    return T->isStandardLayoutType();
4788
202
  case UTT_IsPOD:
4789
202
    return T.isPODType(C);
4790
85
  case UTT_IsLiteral:
4791
85
    return T->isLiteralType(C);
4792
8.08k
  case UTT_IsEmpty:
4793
8.08k
    if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4794
4.56k
      return !RD->isUnion() && 
RD->isEmpty()4.55k
;
4795
3.52k
    return false;
4796
46
  case UTT_IsPolymorphic:
4797
46
    if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4798
19
      return !RD->isUnion() && 
RD->isPolymorphic()13
;
4799
27
    return false;
4800
14
  case UTT_IsAbstract:
4801
14
    if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4802
8
      return !RD->isUnion() && 
RD->isAbstract()7
;
4803
6
    return false;
4804
153
  case UTT_IsAggregate:
4805
    // Report vector extensions and complex types as aggregates because they
4806
    // support aggregate initialization. GCC mirrors this behavior for vectors
4807
    // but not _Complex.
4808
153
    return T->isAggregateType() || 
T->isVectorType()71
||
T->isExtVectorType()65
||
4809
65
           T->isAnyComplexType();
4810
  // __is_interface_class only returns true when CL is invoked in /CLR mode and
4811
  // even then only when it is used with the 'interface struct ...' syntax
4812
  // Clang doesn't support /CLR which makes this type trait moot.
4813
10
  case UTT_IsInterfaceClass:
4814
10
    return false;
4815
8.06k
  case UTT_IsFinal:
4816
8.11k
  case UTT_IsSealed:
4817
8.11k
    if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4818
4.57k
      return RD->hasAttr<FinalAttr>();
4819
3.54k
    return false;
4820
1.94k
  case UTT_IsSigned:
4821
    // Enum types should always return false.
4822
    // Floating points should always return true.
4823
1.94k
    return !T->isEnumeralType() && 
(1.93k
T->isFloatingType()1.93k
||
T->isSignedIntegerType()1.92k
);
4824
90
  case UTT_IsUnsigned:
4825
90
    return T->isUnsignedIntegerType();
4826
4827
    // Type trait expressions which query classes regarding their construction,
4828
    // destruction, and copying. Rather than being based directly on the
4829
    // related type predicates in the standard, they are specified by both
4830
    // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
4831
    // specifications.
4832
    //
4833
    //   1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
4834
    //   2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
4835
    //
4836
    // Note that these builtins do not behave as documented in g++: if a class
4837
    // has both a trivial and a non-trivial special member of a particular kind,
4838
    // they return false! For now, we emulate this behavior.
4839
    // FIXME: This appears to be a g++ bug: more complex cases reveal that it
4840
    // does not correctly compute triviality in the presence of multiple special
4841
    // members of the same kind. Revisit this once the g++ bug is fixed.
4842
159
  case UTT_HasTrivialDefaultConstructor:
4843
    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4844
    //   If __is_pod (type) is true then the trait is true, else if type is
4845
    //   a cv class or union type (or array thereof) with a trivial default
4846
    //   constructor ([class.ctor]) then the trait is true, else it is false.
4847
159
    if (T.isPODType(C))
4848
64
      return true;
4849
95
    if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4850
82
      return RD->hasTrivialDefaultConstructor() &&
4851
21
             !RD->hasNonTrivialDefaultConstructor();
4852
13
    return false;
4853
37
  case UTT_HasTrivialMoveConstructor:
4854
    //  This trait is implemented by MSVC 2012 and needed to parse the
4855
    //  standard library headers. Specifically this is used as the logic
4856
    //  behind std::is_trivially_move_constructible (20.9.4.3).
4857
37
    if (T.isPODType(C))
4858
19
      return true;
4859
18
    if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4860
18
      return RD->hasTrivialMoveConstructor() && 
!RD->hasNonTrivialMoveConstructor()3
;
4861
0
    return false;
4862
119
  case UTT_HasTrivialCopy:
4863
    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4864
    //   If __is_pod (type) is true or type is a reference type then
4865
    //   the trait is true, else if type is a cv class or union type
4866
    //   with a trivial copy constructor ([class.copy]) then the trait
4867
    //   is true, else it is false.
4868
119
    if (T.isPODType(C) || 
T->isReferenceType()65
)
4869
57
      return true;
4870
62
    if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4871
49
      return RD->hasTrivialCopyConstructor() &&
4872
28
             !RD->hasNonTrivialCopyConstructor();
4873
13
    return false;
4874
31
  case UTT_HasTrivialMoveAssign:
4875
    //  This trait is implemented by MSVC 2012 and needed to parse the
4876
    //  standard library headers. Specifically it is used as the logic
4877
    //  behind std::is_trivially_move_assignable (20.9.4.3)
4878
31
    if (T.isPODType(C))
4879
16
      return true;
4880
15
    if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4881
15
      return RD->hasTrivialMoveAssignment() && 
!RD->hasNonTrivialMoveAssignment()0
;
4882
0
    return false;
4883
115
  case UTT_HasTrivialAssign:
4884
    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4885
    //   If type is const qualified or is a reference type then the
4886
    //   trait is false. Otherwise if __is_pod (type) is true then the
4887
    //   trait is true, else if type is a cv class or union type with
4888
    //   a trivial copy assignment ([class.copy]) then the trait is
4889
    //   true, else it is false.
4890
    // Note: the const and reference restrictions are interesting,
4891
    // given that const and reference members don't prevent a class
4892
    // from having a trivial copy assignment operator (but do cause
4893
    // errors if the copy assignment operator is actually used, q.v.
4894
    // [class.copy]p12).
4895
4896
115
    if (T.isConstQualified())
4897
12
      return false;
4898
103
    if (T.isPODType(C))
4899
50
      return true;
4900
53
    if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4901
40
      return RD->hasTrivialCopyAssignment() &&
4902
22
             !RD->hasNonTrivialCopyAssignment();
4903
13
    return false;
4904
50
  case UTT_IsDestructible:
4905
171
  case UTT_IsTriviallyDestructible:
4906
224
  case UTT_IsNothrowDestructible:
4907
    // C++14 [meta.unary.prop]:
4908
    //   For reference types, is_destructible<T>::value is true.
4909
224
    if (T->isReferenceType())
4910
9
      return true;
4911
4912
    // Objective-C++ ARC: autorelease types don't require destruction.
4913
215
    if (T->isObjCLifetimeType() &&
4914
0
        T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4915
0
      return true;
4916
4917
    // C++14 [meta.unary.prop]:
4918
    //   For incomplete types and function types, is_destructible<T>::value is
4919
    //   false.
4920
215
    if (T->isIncompleteType() || 
T->isFunctionType()170
)
4921
45
      return false;
4922
4923
    // A type that requires destruction (via a non-trivial destructor or ARC
4924
    // lifetime semantics) is not trivially-destructible.
4925
170
    if (UTT == UTT_IsTriviallyDestructible && 
T.isDestructedType()103
)
4926
21
      return false;
4927
4928
    // C++14 [meta.unary.prop]:
4929
    //   For object types and given U equal to remove_all_extents_t<T>, if the
4930
    //   expression std::declval<U&>().~U() is well-formed when treated as an
4931
    //   unevaluated operand (Clause 5), then is_destructible<T>::value is true
4932
149
    if (auto *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4933
67
      CXXDestructorDecl *Destructor = Self.LookupDestructor(RD);
4934
67
      if (!Destructor)
4935
0
        return false;
4936
      //  C++14 [dcl.fct.def.delete]p2:
4937
      //    A program that refers to a deleted function implicitly or
4938
      //    explicitly, other than to declare it, is ill-formed.
4939
67
      if (Destructor->isDeleted())
4940
13
        return false;
4941
54
      if (C.getLangOpts().AccessControl && Destructor->getAccess() != AS_public)
4942
6
        return false;
4943
48
      if (UTT == UTT_IsNothrowDestructible) {
4944
21
        auto *CPT = Destructor->getType()->castAs<FunctionProtoType>();
4945
21
        CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4946
21
        if (!CPT || !CPT->isNothrow())
4947
3
          return false;
4948
127
      }
4949
48
    }
4950
127
    return true;
4951
4952
117
  case UTT_HasTrivialDestructor:
4953
    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
4954
    //   If __is_pod (type) is true or type is a reference type
4955
    //   then the trait is true, else if type is a cv class or union
4956
    //   type (or array thereof) with a trivial destructor
4957
    //   ([class.dtor]) then the trait is true, else it is
4958
    //   false.
4959
117
    if (T.isPODType(C) || 
T->isReferenceType()61
)
4960
59
      return true;
4961
4962
    // Objective-C++ ARC: autorelease types don't require destruction.
4963
58
    if (T->isObjCLifetimeType() &&
4964
4
        T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4965
1
      return true;
4966
4967
57
    if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4968
48
      return RD->hasTrivialDestructor();
4969
9
    return false;
4970
  // TODO: Propagate nothrowness for implicitly declared special members.
4971
108
  case UTT_HasNothrowAssign:
4972
    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4973
    //   If type is const qualified or is a reference type then the
4974
    //   trait is false. Otherwise if __has_trivial_assign (type)
4975
    //   is true then the trait is true, else if type is a cv class
4976
    //   or union type with copy assignment operators that are known
4977
    //   not to throw an exception then the trait is true, else it is
4978
    //   false.
4979
108
    if (C.getBaseElementType(T).isConstQualified())
4980
12
      return false;
4981
96
    if (T->isReferenceType())
4982
3
      return false;
4983
93
    if (T.isPODType(C) || 
T->isObjCLifetimeType()52
)
4984
45
      return true;
4985
4986
48
    if (const RecordType *RT = T->getAs<RecordType>())
4987
42
      return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4988
42
                                &CXXRecordDecl::hasTrivialCopyAssignment,
4989
42
                                &CXXRecordDecl::hasNonTrivialCopyAssignment,
4990
42
                                &CXXMethodDecl::isCopyAssignmentOperator);
4991
6
    return false;
4992
67
  case UTT_HasNothrowMoveAssign:
4993
    //  This trait is implemented by MSVC 2012 and needed to parse the
4994
    //  standard library headers. Specifically this is used as the logic
4995
    //  behind std::is_nothrow_move_assignable (20.9.4.3).
4996
67
    if (T.isPODType(C))
4997
28
      return true;
4998
4999
39
    if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>())
5000
39
      return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
5001
39
                                &CXXRecordDecl::hasTrivialMoveAssignment,
5002
39
                                &CXXRecordDecl::hasNonTrivialMoveAssignment,
5003
39
                                &CXXMethodDecl::isMoveAssignmentOperator);
5004
0
    return false;
5005
107
  case UTT_HasNothrowCopy:
5006
    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5007
    //   If __has_trivial_copy (type) is true then the trait is true, else
5008
    //   if type is a cv class or union type with copy constructors that are
5009
    //   known not to throw an exception then the trait is true, else it is
5010
    //   false.
5011
107
    if (T.isPODType(C) || 
T->isReferenceType()60
||
T->isObjCLifetimeType()57
)
5012
54
      return true;
5013
53
    if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
5014
44
      if (RD->hasTrivialCopyConstructor() &&
5015
19
          !RD->hasNonTrivialCopyConstructor())
5016
19
        return true;
5017
5018
25
      bool FoundConstructor = false;
5019
25
      unsigned FoundTQs;
5020
50
      for (const auto *ND : Self.LookupConstructors(RD)) {
5021
        // A template constructor is never a copy constructor.
5022
        // FIXME: However, it may actually be selected at the actual overload
5023
        // resolution point.
5024
50
        if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
5025
3
          continue;
5026
        // UsingDecl itself is not a constructor
5027
47
        if (isa<UsingDecl>(ND))
5028
1
          continue;
5029
46
        auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
5030
46
        if (Constructor->isCopyConstructor(FoundTQs)) {
5031
31
          FoundConstructor = true;
5032
31
          auto *CPT = Constructor->getType()->castAs<FunctionProtoType>();
5033
31
          CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
5034
31
          if (!CPT)
5035
0
            return false;
5036
          // TODO: check whether evaluating default arguments can throw.
5037
          // For now, we'll be conservative and assume that they can throw.
5038
31
          if (!CPT->isNothrow() || 
CPT->getNumParams() > 124
)
5039
7
            return false;
5040
31
        }
5041
46
      }
5042
5043
18
      return FoundConstructor;
5044
9
    }
5045
9
    return false;
5046
104
  case UTT_HasNothrowConstructor:
5047
    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
5048
    //   If __has_trivial_constructor (type) is true then the trait is
5049
    //   true, else if type is a cv class or union type (or array
5050
    //   thereof) with a default constructor that is known not to
5051
    //   throw an exception then the trait is true, else it is false.
5052
104
    if (T.isPODType(C) || 
T->isObjCLifetimeType()57
)
5053
51
      return true;
5054
53
    if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
5055
44
      if (RD->hasTrivialDefaultConstructor() &&
5056
6
          !RD->hasNonTrivialDefaultConstructor())
5057
6
        return true;
5058
5059
38
      bool FoundConstructor = false;
5060
84
      for (const auto *ND : Self.LookupConstructors(RD)) {
5061
        // FIXME: In C++0x, a constructor template can be a default constructor.
5062
84
        if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
5063
4
          continue;
5064
        // UsingDecl itself is not a constructor
5065
80
        if (isa<UsingDecl>(ND))
5066
2
          continue;
5067
78
        auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
5068
78
        if (Constructor->isDefaultConstructor()) {
5069
29
          FoundConstructor = true;
5070
29
          auto *CPT = Constructor->getType()->castAs<FunctionProtoType>();
5071
29
          CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
5072
29
          if (!CPT)
5073
0
            return false;
5074
          // FIXME: check whether evaluating default arguments can throw.
5075
          // For now, we'll be conservative and assume that they can throw.
5076
29
          if (!CPT->isNothrow() || 
CPT->getNumParams() > 020
)
5077
12
            return false;
5078
29
        }
5079
78
      }
5080
26
      return FoundConstructor;
5081
9
    }
5082
9
    return false;
5083
85
  case UTT_HasVirtualDestructor:
5084
    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5085
    //   If type is a class type with a virtual destructor ([class.dtor])
5086
    //   then the trait is true, else it is false.
5087
85
    if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
5088
42
      if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
5089
42
        return Destructor->isVirtual();
5090
43
    return false;
5091
5092
    // These type trait expressions are modeled on the specifications for the
5093
    // Embarcadero C++0x type trait functions:
5094
    //   http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
5095
50
  case UTT_IsCompleteType:
5096
    // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
5097
    //   Returns True if and only if T is a complete type at the point of the
5098
    //   function call.
5099
50
    return !T->isIncompleteType();
5100
360
  case UTT_HasUniqueObjectRepresentations:
5101
360
    return C.hasUniqueObjectRepresentations(T);
5102
75.7k
  }
5103
75.7k
}
5104
5105
static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
5106
                                    QualType RhsT, SourceLocation KeyLoc);
5107
5108
static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc,
5109
                              ArrayRef<TypeSourceInfo *> Args,
5110
179k
                              SourceLocation RParenLoc) {
5111
179k
  if (Kind <= UTT_Last)
5112
75.7k
    return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]->getType());
5113
5114
  // Evaluate BTT_ReferenceBindsToTemporary alongside the IsConstructible
5115
  // traits to avoid duplication.
5116
103k
  if (Kind <= BTT_Last && 
Kind != BTT_ReferenceBindsToTemporary92.8k
)
5117
92.2k
    return EvaluateBinaryTypeTrait(S, Kind, Args[0]->getType(),
5118
92.2k
                                   Args[1]->getType(), RParenLoc);
5119
5120
11.5k
  switch (Kind) {
5121
641
  case clang::BTT_ReferenceBindsToTemporary:
5122
6.83k
  case clang::TT_IsConstructible:
5123
10.9k
  case clang::TT_IsNothrowConstructible:
5124
11.5k
  case clang::TT_IsTriviallyConstructible: {
5125
    // C++11 [meta.unary.prop]:
5126
    //   is_trivially_constructible is defined as:
5127
    //
5128
    //     is_constructible<T, Args...>::value is true and the variable
5129
    //     definition for is_constructible, as defined below, is known to call
5130
    //     no operation that is not trivial.
5131
    //