Coverage Report

Created: 2021-08-24 07:12

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