Coverage Report

Created: 2021-08-24 07:12

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/CodeGen/CGExprCXX.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- CGExprCXX.cpp - Emit LLVM Code for C++ 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
// This contains code dealing with code generation of C++ expressions
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "CGCUDARuntime.h"
14
#include "CGCXXABI.h"
15
#include "CGDebugInfo.h"
16
#include "CGObjCRuntime.h"
17
#include "CodeGenFunction.h"
18
#include "ConstantEmitter.h"
19
#include "TargetInfo.h"
20
#include "clang/Basic/CodeGenOptions.h"
21
#include "clang/CodeGen/CGFunctionInfo.h"
22
#include "llvm/IR/Intrinsics.h"
23
24
using namespace clang;
25
using namespace CodeGen;
26
27
namespace {
28
struct MemberCallInfo {
29
  RequiredArgs ReqArgs;
30
  // Number of prefix arguments for the call. Ignores the `this` pointer.
31
  unsigned PrefixSize;
32
};
33
}
34
35
static MemberCallInfo
36
commonEmitCXXMemberOrOperatorCall(CodeGenFunction &CGF, const CXXMethodDecl *MD,
37
                                  llvm::Value *This, llvm::Value *ImplicitParam,
38
                                  QualType ImplicitParamTy, const CallExpr *CE,
39
103k
                                  CallArgList &Args, CallArgList *RtlArgs) {
40
103k
  assert(CE == nullptr || isa<CXXMemberCallExpr>(CE) ||
41
103k
         isa<CXXOperatorCallExpr>(CE));
42
0
  assert(MD->isInstance() &&
43
103k
         "Trying to emit a member or operator call expr on a static method!");
44
45
  // Push the this ptr.
46
0
  const CXXRecordDecl *RD =
47
103k
      CGF.CGM.getCXXABI().getThisArgumentTypeForMethod(MD);
48
103k
  Args.add(RValue::get(This), CGF.getTypes().DeriveThisType(RD, MD));
49
50
  // If there is an implicit parameter (e.g. VTT), emit it.
51
103k
  if (ImplicitParam) {
52
194
    Args.add(RValue::get(ImplicitParam), ImplicitParamTy);
53
194
  }
54
55
103k
  const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
56
103k
  RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, Args.size());
57
103k
  unsigned PrefixSize = Args.size() - 1;
58
59
  // And the rest of the call args.
60
103k
  if (RtlArgs) {
61
    // Special case: if the caller emitted the arguments right-to-left already
62
    // (prior to emitting the *this argument), we're done. This happens for
63
    // assignment operators.
64
908
    Args.addFrom(*RtlArgs);
65
103k
  } else if (CE) {
66
    // Special case: skip first argument of CXXOperatorCall (it is "this").
67
72.9k
    unsigned ArgsToSkip = isa<CXXOperatorCallExpr>(CE) ? 
17.73k
:
065.2k
;
68
72.9k
    CGF.EmitCallArgs(Args, FPT, drop_begin(CE->arguments(), ArgsToSkip),
69
72.9k
                     CE->getDirectCallee());
70
72.9k
  } else {
71
30.0k
    assert(
72
30.0k
        FPT->getNumParams() == 0 &&
73
30.0k
        "No CallExpr specified for function with non-zero number of arguments");
74
30.0k
  }
75
0
  return {required, PrefixSize};
76
103k
}
77
78
RValue CodeGenFunction::EmitCXXMemberOrOperatorCall(
79
    const CXXMethodDecl *MD, const CGCallee &Callee,
80
    ReturnValueSlot ReturnValue,
81
    llvm::Value *This, llvm::Value *ImplicitParam, QualType ImplicitParamTy,
82
73.6k
    const CallExpr *CE, CallArgList *RtlArgs) {
83
73.6k
  const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
84
73.6k
  CallArgList Args;
85
73.6k
  MemberCallInfo CallInfo = commonEmitCXXMemberOrOperatorCall(
86
73.6k
      *this, MD, This, ImplicitParam, ImplicitParamTy, CE, Args, RtlArgs);
87
73.6k
  auto &FnInfo = CGM.getTypes().arrangeCXXMethodCall(
88
73.6k
      Args, FPT, CallInfo.ReqArgs, CallInfo.PrefixSize);
89
73.6k
  return EmitCall(FnInfo, Callee, ReturnValue, Args, nullptr,
90
73.6k
                  CE && CE == MustTailCall,
91
73.6k
                  CE ? CE->getExprLoc() : 
SourceLocation()0
);
92
73.6k
}
93
94
RValue CodeGenFunction::EmitCXXDestructorCall(
95
    GlobalDecl Dtor, const CGCallee &Callee, llvm::Value *This, QualType ThisTy,
96
30.3k
    llvm::Value *ImplicitParam, QualType ImplicitParamTy, const CallExpr *CE) {
97
30.3k
  const CXXMethodDecl *DtorDecl = cast<CXXMethodDecl>(Dtor.getDecl());
98
99
30.3k
  assert(!ThisTy.isNull());
100
0
  assert(ThisTy->getAsCXXRecordDecl() == DtorDecl->getParent() &&
101
30.3k
         "Pointer/Object mixup");
102
103
0
  LangAS SrcAS = ThisTy.getAddressSpace();
104
30.3k
  LangAS DstAS = DtorDecl->getMethodQualifiers().getAddressSpace();
105
30.3k
  if (SrcAS != DstAS) {
106
2
    QualType DstTy = DtorDecl->getThisType();
107
2
    llvm::Type *NewType = CGM.getTypes().ConvertType(DstTy);
108
2
    This = getTargetHooks().performAddrSpaceCast(*this, This, SrcAS, DstAS,
109
2
                                                 NewType);
110
2
  }
111
112
30.3k
  CallArgList Args;
113
30.3k
  commonEmitCXXMemberOrOperatorCall(*this, DtorDecl, This, ImplicitParam,
114
30.3k
                                    ImplicitParamTy, CE, Args, nullptr);
115
30.3k
  return EmitCall(CGM.getTypes().arrangeCXXStructorDeclaration(Dtor), Callee,
116
30.3k
                  ReturnValueSlot(), Args, nullptr, CE && 
CE == MustTailCall229
,
117
30.3k
                  CE ? 
CE->getExprLoc()229
:
SourceLocation{}30.0k
);
118
30.3k
}
119
120
RValue CodeGenFunction::EmitCXXPseudoDestructorExpr(
121
193
                                            const CXXPseudoDestructorExpr *E) {
122
193
  QualType DestroyedType = E->getDestroyedType();
123
193
  if (DestroyedType.hasStrongOrWeakObjCLifetime()) {
124
    // Automatic Reference Counting:
125
    //   If the pseudo-expression names a retainable object with weak or
126
    //   strong lifetime, the object shall be released.
127
4
    Expr *BaseExpr = E->getBase();
128
4
    Address BaseValue = Address::invalid();
129
4
    Qualifiers BaseQuals;
130
131
    // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar.
132
4
    if (E->isArrow()) {
133
2
      BaseValue = EmitPointerWithAlignment(BaseExpr);
134
2
      const auto *PTy = BaseExpr->getType()->castAs<PointerType>();
135
2
      BaseQuals = PTy->getPointeeType().getQualifiers();
136
2
    } else {
137
2
      LValue BaseLV = EmitLValue(BaseExpr);
138
2
      BaseValue = BaseLV.getAddress(*this);
139
2
      QualType BaseTy = BaseExpr->getType();
140
2
      BaseQuals = BaseTy.getQualifiers();
141
2
    }
142
143
4
    switch (DestroyedType.getObjCLifetime()) {
144
0
    case Qualifiers::OCL_None:
145
0
    case Qualifiers::OCL_ExplicitNone:
146
0
    case Qualifiers::OCL_Autoreleasing:
147
0
      break;
148
149
2
    case Qualifiers::OCL_Strong:
150
2
      EmitARCRelease(Builder.CreateLoad(BaseValue,
151
2
                        DestroyedType.isVolatileQualified()),
152
2
                     ARCPreciseLifetime);
153
2
      break;
154
155
2
    case Qualifiers::OCL_Weak:
156
2
      EmitARCDestroyWeak(BaseValue);
157
2
      break;
158
4
    }
159
189
  } else {
160
    // C++ [expr.pseudo]p1:
161
    //   The result shall only be used as the operand for the function call
162
    //   operator (), and the result of such a call has type void. The only
163
    //   effect is the evaluation of the postfix-expression before the dot or
164
    //   arrow.
165
189
    EmitIgnoredExpr(E->getBase());
166
189
  }
167
168
193
  return RValue::get(nullptr);
169
193
}
170
171
493
static CXXRecordDecl *getCXXRecord(const Expr *E) {
172
493
  QualType T = E->getType();
173
493
  if (const PointerType *PTy = T->getAs<PointerType>())
174
31
    T = PTy->getPointeeType();
175
493
  const RecordType *Ty = T->castAs<RecordType>();
176
493
  return cast<CXXRecordDecl>(Ty->getDecl());
177
493
}
178
179
// Note: This function also emit constructor calls to support a MSVC
180
// extensions allowing explicit constructor function call.
181
RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE,
182
65.7k
                                              ReturnValueSlot ReturnValue) {
183
65.7k
  const Expr *callee = CE->getCallee()->IgnoreParens();
184
185
65.7k
  if (isa<BinaryOperator>(callee))
186
149
    return EmitCXXMemberPointerCallExpr(CE, ReturnValue);
187
188
65.6k
  const MemberExpr *ME = cast<MemberExpr>(callee);
189
65.6k
  const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
190
191
65.6k
  if (MD->isStatic()) {
192
    // The method is static, emit it as we would a regular call.
193
0
    CGCallee callee =
194
0
        CGCallee::forDirect(CGM.GetAddrOfFunction(MD), GlobalDecl(MD));
195
0
    return EmitCall(getContext().getPointerType(MD->getType()), callee, CE,
196
0
                    ReturnValue);
197
0
  }
198
199
65.6k
  bool HasQualifier = ME->hasQualifier();
200
65.6k
  NestedNameSpecifier *Qualifier = HasQualifier ? 
ME->getQualifier()1.95k
:
nullptr63.6k
;
201
65.6k
  bool IsArrow = ME->isArrow();
202
65.6k
  const Expr *Base = ME->getBase();
203
204
65.6k
  return EmitCXXMemberOrOperatorMemberCallExpr(
205
65.6k
      CE, MD, ReturnValue, HasQualifier, Qualifier, IsArrow, Base);
206
65.6k
}
207
208
RValue CodeGenFunction::EmitCXXMemberOrOperatorMemberCallExpr(
209
    const CallExpr *CE, const CXXMethodDecl *MD, ReturnValueSlot ReturnValue,
210
    bool HasQualifier, NestedNameSpecifier *Qualifier, bool IsArrow,
211
76.7k
    const Expr *Base) {
212
76.7k
  assert(isa<CXXMemberCallExpr>(CE) || isa<CXXOperatorCallExpr>(CE));
213
214
  // Compute the object pointer.
215
76.7k
  bool CanUseVirtualCall = MD->isVirtual() && 
!HasQualifier1.38k
;
216
217
76.7k
  const CXXMethodDecl *DevirtualizedMethod = nullptr;
218
76.7k
  if (CanUseVirtualCall &&
219
76.7k
      
MD->getDevirtualizedMethod(Base, getLangOpts().AppleKext)1.34k
) {
220
422
    const CXXRecordDecl *BestDynamicDecl = Base->getBestDynamicClassType();
221
422
    DevirtualizedMethod = MD->getCorrespondingMethodInClass(BestDynamicDecl);
222
422
    assert(DevirtualizedMethod);
223
0
    const CXXRecordDecl *DevirtualizedClass = DevirtualizedMethod->getParent();
224
422
    const Expr *Inner = Base->IgnoreParenBaseCasts();
225
422
    if (DevirtualizedMethod->getReturnType().getCanonicalType() !=
226
422
        MD->getReturnType().getCanonicalType())
227
      // If the return types are not the same, this might be a case where more
228
      // code needs to run to compensate for it. For example, the derived
229
      // method might return a type that inherits form from the return
230
      // type of MD and has a prefix.
231
      // For now we just avoid devirtualizing these covariant cases.
232
2
      DevirtualizedMethod = nullptr;
233
420
    else if (getCXXRecord(Inner) == DevirtualizedClass)
234
      // If the class of the Inner expression is where the dynamic method
235
      // is defined, build the this pointer from it.
236
349
      Base = Inner;
237
71
    else if (getCXXRecord(Base) != DevirtualizedClass) {
238
      // If the method is defined in a class that is not the best dynamic
239
      // one or the one of the full expression, we would have to build
240
      // a derived-to-base cast to compute the correct this pointer, but
241
      // we don't have support for that yet, so do a virtual call.
242
6
      DevirtualizedMethod = nullptr;
243
6
    }
244
422
  }
245
246
0
  bool TrivialForCodegen =
247
76.7k
      MD->isTrivial() || 
(73.8k
MD->isDefaulted()73.8k
&&
MD->getParent()->isUnion()228
);
248
76.7k
  bool TrivialAssignment =
249
76.7k
      TrivialForCodegen &&
250
76.7k
      
(2.85k
MD->isCopyAssignmentOperator()2.85k
||
MD->isMoveAssignmentOperator()800
) &&
251
76.7k
      
!MD->getParent()->mayInsertExtraPadding()2.65k
;
252
253
  // C++17 demands that we evaluate the RHS of a (possibly-compound) assignment
254
  // operator before the LHS.
255
76.7k
  CallArgList RtlArgStorage;
256
76.7k
  CallArgList *RtlArgs = nullptr;
257
76.7k
  LValue TrivialAssignmentRHS;
258
76.7k
  if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(CE)) {
259
11.1k
    if (OCE->isAssignmentOp()) {
260
3.38k
      if (TrivialAssignment) {
261
2.47k
        TrivialAssignmentRHS = EmitLValue(CE->getArg(1));
262
2.47k
      } else {
263
908
        RtlArgs = &RtlArgStorage;
264
908
        EmitCallArgs(*RtlArgs, MD->getType()->castAs<FunctionProtoType>(),
265
908
                     drop_begin(CE->arguments(), 1), CE->getDirectCallee(),
266
908
                     /*ParamsToSkip*/0, EvaluationOrder::ForceRightToLeft);
267
908
      }
268
3.38k
    }
269
11.1k
  }
270
271
76.7k
  LValue This;
272
76.7k
  if (IsArrow) {
273
27.5k
    LValueBaseInfo BaseInfo;
274
27.5k
    TBAAAccessInfo TBAAInfo;
275
27.5k
    Address ThisValue = EmitPointerWithAlignment(Base, &BaseInfo, &TBAAInfo);
276
27.5k
    This = MakeAddrLValue(ThisValue, Base->getType(), BaseInfo, TBAAInfo);
277
49.2k
  } else {
278
49.2k
    This = EmitLValue(Base);
279
49.2k
  }
280
281
76.7k
  if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
282
    // This is the MSVC p->Ctor::Ctor(...) extension. We assume that's
283
    // constructing a new complete object of type Ctor.
284
12
    assert(!RtlArgs);
285
0
    assert(ReturnValue.isNull() && "Constructor shouldn't have return value");
286
0
    CallArgList Args;
287
12
    commonEmitCXXMemberOrOperatorCall(
288
12
        *this, Ctor, This.getPointer(*this), /*ImplicitParam=*/nullptr,
289
12
        /*ImplicitParamTy=*/QualType(), CE, Args, nullptr);
290
291
12
    EmitCXXConstructorCall(Ctor, Ctor_Complete, /*ForVirtualBase=*/false,
292
12
                           /*Delegating=*/false, This.getAddress(*this), Args,
293
12
                           AggValueSlot::DoesNotOverlap, CE->getExprLoc(),
294
12
                           /*NewPointerIsChecked=*/false);
295
12
    return RValue::get(nullptr);
296
12
  }
297
298
76.7k
  if (TrivialForCodegen) {
299
2.84k
    if (isa<CXXDestructorDecl>(MD))
300
190
      return RValue::get(nullptr);
301
302
2.65k
    if (TrivialAssignment) {
303
      // We don't like to generate the trivial copy/move assignment operator
304
      // when it isn't necessary; just produce the proper effect here.
305
      // It's important that we use the result of EmitLValue here rather than
306
      // emitting call arguments, in order to preserve TBAA information from
307
      // the RHS.
308
2.65k
      LValue RHS = isa<CXXOperatorCallExpr>(CE)
309
2.65k
                       ? 
TrivialAssignmentRHS2.47k
310
2.65k
                       : 
EmitLValue(*CE->arg_begin())181
;
311
2.65k
      EmitAggregateAssign(This, RHS, CE->getType());
312
2.65k
      return RValue::get(This.getPointer(*this));
313
2.65k
    }
314
315
2
    assert(MD->getParent()->mayInsertExtraPadding() &&
316
2
           "unknown trivial member function");
317
2
  }
318
319
  // Compute the function type we're calling.
320
73.8k
  const CXXMethodDecl *CalleeDecl =
321
73.8k
      DevirtualizedMethod ? 
DevirtualizedMethod414
:
MD73.4k
;
322
73.8k
  const CGFunctionInfo *FInfo = nullptr;
323
73.8k
  if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(CalleeDecl))
324
237
    FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
325
237
        GlobalDecl(Dtor, Dtor_Complete));
326
73.6k
  else
327
73.6k
    FInfo = &CGM.getTypes().arrangeCXXMethodDeclaration(CalleeDecl);
328
329
73.8k
  llvm::FunctionType *Ty = CGM.getTypes().GetFunctionType(*FInfo);
330
331
  // C++11 [class.mfct.non-static]p2:
332
  //   If a non-static member function of a class X is called for an object that
333
  //   is not of type X, or of a type derived from X, the behavior is undefined.
334
73.8k
  SourceLocation CallLoc;
335
73.8k
  ASTContext &C = getContext();
336
73.8k
  if (CE)
337
73.8k
    CallLoc = CE->getExprLoc();
338
339
73.8k
  SanitizerSet SkippedChecks;
340
73.8k
  if (const auto *CMCE = dyn_cast<CXXMemberCallExpr>(CE)) {
341
65.2k
    auto *IOA = CMCE->getImplicitObjectArgument();
342
65.2k
    bool IsImplicitObjectCXXThis = IsWrappedCXXThis(IOA);
343
65.2k
    if (IsImplicitObjectCXXThis)
344
24.0k
      SkippedChecks.set(SanitizerKind::Alignment, true);
345
65.2k
    if (IsImplicitObjectCXXThis || 
isa<DeclRefExpr>(IOA)41.1k
)
346
38.6k
      SkippedChecks.set(SanitizerKind::Null, true);
347
65.2k
  }
348
73.8k
  EmitTypeCheck(CodeGenFunction::TCK_MemberCall, CallLoc,
349
73.8k
                This.getPointer(*this),
350
73.8k
                C.getRecordType(CalleeDecl->getParent()),
351
73.8k
                /*Alignment=*/CharUnits::Zero(), SkippedChecks);
352
353
  // C++ [class.virtual]p12:
354
  //   Explicit qualification with the scope operator (5.1) suppresses the
355
  //   virtual call mechanism.
356
  //
357
  // We also don't emit a virtual call if the base expression has a record type
358
  // because then we know what the type is.
359
73.8k
  bool UseVirtualCall = CanUseVirtualCall && 
!DevirtualizedMethod1.34k
;
360
361
73.8k
  if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(CalleeDecl)) {
362
237
    assert(CE->arg_begin() == CE->arg_end() &&
363
237
           "Destructor shouldn't have explicit parameters");
364
0
    assert(ReturnValue.isNull() && "Destructor shouldn't have return value");
365
237
    if (UseVirtualCall) {
366
12
      CGM.getCXXABI().EmitVirtualDestructorCall(*this, Dtor, Dtor_Complete,
367
12
                                                This.getAddress(*this),
368
12
                                                cast<CXXMemberCallExpr>(CE));
369
225
    } else {
370
225
      GlobalDecl GD(Dtor, Dtor_Complete);
371
225
      CGCallee Callee;
372
225
      if (getLangOpts().AppleKext && 
Dtor->isVirtual()2
&&
HasQualifier2
)
373
2
        Callee = BuildAppleKextVirtualCall(Dtor, Qualifier, Ty);
374
223
      else if (!DevirtualizedMethod)
375
221
        Callee =
376
221
            CGCallee::forDirect(CGM.getAddrOfCXXStructor(GD, FInfo, Ty), GD);
377
2
      else {
378
2
        Callee = CGCallee::forDirect(CGM.GetAddrOfFunction(GD, Ty), GD);
379
2
      }
380
381
225
      QualType ThisTy =
382
225
          IsArrow ? 
Base->getType()->getPointeeType()185
:
Base->getType()40
;
383
225
      EmitCXXDestructorCall(GD, Callee, This.getPointer(*this), ThisTy,
384
225
                            /*ImplicitParam=*/nullptr,
385
225
                            /*ImplicitParamTy=*/QualType(), CE);
386
225
    }
387
237
    return RValue::get(nullptr);
388
237
  }
389
390
  // FIXME: Uses of 'MD' past this point need to be audited. We may need to use
391
  // 'CalleeDecl' instead.
392
393
73.6k
  CGCallee Callee;
394
73.6k
  if (UseVirtualCall) {
395
920
    Callee = CGCallee::forVirtual(CE, MD, This.getAddress(*this), Ty);
396
72.7k
  } else {
397
72.7k
    if (SanOpts.has(SanitizerKind::CFINVCall) &&
398
72.7k
        
MD->getParent()->isDynamicClass()8
) {
399
8
      llvm::Value *VTable;
400
8
      const CXXRecordDecl *RD;
401
8
      std::tie(VTable, RD) = CGM.getCXXABI().LoadVTablePtr(
402
8
          *this, This.getAddress(*this), CalleeDecl->getParent());
403
8
      EmitVTablePtrCheckForCall(RD, VTable, CFITCK_NVCall, CE->getBeginLoc());
404
8
    }
405
406
72.7k
    if (getLangOpts().AppleKext && 
MD->isVirtual()6
&&
HasQualifier6
)
407
6
      Callee = BuildAppleKextVirtualCall(MD, Qualifier, Ty);
408
72.7k
    else if (!DevirtualizedMethod)
409
72.3k
      Callee =
410
72.3k
          CGCallee::forDirect(CGM.GetAddrOfFunction(MD, Ty), GlobalDecl(MD));
411
412
    else {
412
412
      Callee =
413
412
          CGCallee::forDirect(CGM.GetAddrOfFunction(DevirtualizedMethod, Ty),
414
412
                              GlobalDecl(DevirtualizedMethod));
415
412
    }
416
72.7k
  }
417
418
73.6k
  if (MD->isVirtual()) {
419
1.36k
    Address NewThisAddr =
420
1.36k
        CGM.getCXXABI().adjustThisArgumentForVirtualFunctionCall(
421
1.36k
            *this, CalleeDecl, This.getAddress(*this), UseVirtualCall);
422
1.36k
    This.setAddress(NewThisAddr);
423
1.36k
  }
424
425
73.6k
  return EmitCXXMemberOrOperatorCall(
426
73.6k
      CalleeDecl, Callee, ReturnValue, This.getPointer(*this),
427
73.6k
      /*ImplicitParam=*/nullptr, QualType(), CE, RtlArgs);
428
73.8k
}
429
430
RValue
431
CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
432
149
                                              ReturnValueSlot ReturnValue) {
433
149
  const BinaryOperator *BO =
434
149
      cast<BinaryOperator>(E->getCallee()->IgnoreParens());
435
149
  const Expr *BaseExpr = BO->getLHS();
436
149
  const Expr *MemFnExpr = BO->getRHS();
437
438
149
  const auto *MPT = MemFnExpr->getType()->castAs<MemberPointerType>();
439
149
  const auto *FPT = MPT->getPointeeType()->castAs<FunctionProtoType>();
440
149
  const auto *RD =
441
149
      cast<CXXRecordDecl>(MPT->getClass()->castAs<RecordType>()->getDecl());
442
443
  // Emit the 'this' pointer.
444
149
  Address This = Address::invalid();
445
149
  if (BO->getOpcode() == BO_PtrMemI)
446
88
    This = EmitPointerWithAlignment(BaseExpr);
447
61
  else
448
61
    This = EmitLValue(BaseExpr).getAddress(*this);
449
450
149
  EmitTypeCheck(TCK_MemberCall, E->getExprLoc(), This.getPointer(),
451
149
                QualType(MPT->getClass(), 0));
452
453
  // Get the member function pointer.
454
149
  llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
455
456
  // Ask the ABI to load the callee.  Note that This is modified.
457
149
  llvm::Value *ThisPtrForCall = nullptr;
458
149
  CGCallee Callee =
459
149
    CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, BO, This,
460
149
                                             ThisPtrForCall, MemFnPtr, MPT);
461
462
149
  CallArgList Args;
463
464
149
  QualType ThisType =
465
149
    getContext().getPointerType(getContext().getTagDeclType(RD));
466
467
  // Push the this ptr.
468
149
  Args.add(RValue::get(ThisPtrForCall), ThisType);
469
470
149
  RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, 1);
471
472
  // And the rest of the call args
473
149
  EmitCallArgs(Args, FPT, E->arguments());
474
149
  return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required,
475
149
                                                      /*PrefixSize=*/0),
476
149
                  Callee, ReturnValue, Args, nullptr, E == MustTailCall,
477
149
                  E->getExprLoc());
478
149
}
479
480
RValue
481
CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
482
                                               const CXXMethodDecl *MD,
483
11.1k
                                               ReturnValueSlot ReturnValue) {
484
11.1k
  assert(MD->isInstance() &&
485
11.1k
         "Trying to emit a member call expr on a static method!");
486
0
  return EmitCXXMemberOrOperatorMemberCallExpr(
487
11.1k
      E, MD, ReturnValue, /*HasQualifier=*/false, /*Qualifier=*/nullptr,
488
11.1k
      /*IsArrow=*/false, E->getArg(0));
489
11.1k
}
490
491
RValue CodeGenFunction::EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
492
37
                                               ReturnValueSlot ReturnValue) {
493
37
  return CGM.getCUDARuntime().EmitCUDAKernelCallExpr(*this, E, ReturnValue);
494
37
}
495
496
static void EmitNullBaseClassInitialization(CodeGenFunction &CGF,
497
                                            Address DestPtr,
498
100
                                            const CXXRecordDecl *Base) {
499
100
  if (Base->isEmpty())
500
81
    return;
501
502
19
  DestPtr = CGF.Builder.CreateElementBitCast(DestPtr, CGF.Int8Ty);
503
504
19
  const ASTRecordLayout &Layout = CGF.getContext().getASTRecordLayout(Base);
505
19
  CharUnits NVSize = Layout.getNonVirtualSize();
506
507
  // We cannot simply zero-initialize the entire base sub-object if vbptrs are
508
  // present, they are initialized by the most derived class before calling the
509
  // constructor.
510
19
  SmallVector<std::pair<CharUnits, CharUnits>, 1> Stores;
511
19
  Stores.emplace_back(CharUnits::Zero(), NVSize);
512
513
  // Each store is split by the existence of a vbptr.
514
19
  CharUnits VBPtrWidth = CGF.getPointerSize();
515
19
  std::vector<CharUnits> VBPtrOffsets =
516
19
      CGF.CGM.getCXXABI().getVBPtrOffsets(Base);
517
19
  for (CharUnits VBPtrOffset : VBPtrOffsets) {
518
    // Stop before we hit any virtual base pointers located in virtual bases.
519
6
    if (VBPtrOffset >= NVSize)
520
2
      break;
521
4
    std::pair<CharUnits, CharUnits> LastStore = Stores.pop_back_val();
522
4
    CharUnits LastStoreOffset = LastStore.first;
523
4
    CharUnits LastStoreSize = LastStore.second;
524
525
4
    CharUnits SplitBeforeOffset = LastStoreOffset;
526
4
    CharUnits SplitBeforeSize = VBPtrOffset - SplitBeforeOffset;
527
4
    assert(!SplitBeforeSize.isNegative() && "negative store size!");
528
4
    if (!SplitBeforeSize.isZero())
529
2
      Stores.emplace_back(SplitBeforeOffset, SplitBeforeSize);
530
531
4
    CharUnits SplitAfterOffset = VBPtrOffset + VBPtrWidth;
532
4
    CharUnits SplitAfterSize = LastStoreSize - SplitAfterOffset;
533
4
    assert(!SplitAfterSize.isNegative() && "negative store size!");
534
4
    if (!SplitAfterSize.isZero())
535
4
      Stores.emplace_back(SplitAfterOffset, SplitAfterSize);
536
4
  }
537
538
  // If the type contains a pointer to data member we can't memset it to zero.
539
  // Instead, create a null constant and copy it to the destination.
540
  // TODO: there are other patterns besides zero that we can usefully memset,
541
  // like -1, which happens to be the pattern used by member-pointers.
542
  // TODO: isZeroInitializable can be over-conservative in the case where a
543
  // virtual base contains a member pointer.
544
19
  llvm::Constant *NullConstantForBase = CGF.CGM.EmitNullConstantForBase(Base);
545
19
  if (!NullConstantForBase->isNullValue()) {
546
4
    llvm::GlobalVariable *NullVariable = new llvm::GlobalVariable(
547
4
        CGF.CGM.getModule(), NullConstantForBase->getType(),
548
4
        /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage,
549
4
        NullConstantForBase, Twine());
550
551
4
    CharUnits Align = std::max(Layout.getNonVirtualAlignment(),
552
4
                               DestPtr.getAlignment());
553
4
    NullVariable->setAlignment(Align.getAsAlign());
554
555
4
    Address SrcPtr = Address(CGF.EmitCastToVoidPtr(NullVariable), Align);
556
557
    // Get and call the appropriate llvm.memcpy overload.
558
4
    for (std::pair<CharUnits, CharUnits> Store : Stores) {
559
4
      CharUnits StoreOffset = Store.first;
560
4
      CharUnits StoreSize = Store.second;
561
4
      llvm::Value *StoreSizeVal = CGF.CGM.getSize(StoreSize);
562
4
      CGF.Builder.CreateMemCpy(
563
4
          CGF.Builder.CreateConstInBoundsByteGEP(DestPtr, StoreOffset),
564
4
          CGF.Builder.CreateConstInBoundsByteGEP(SrcPtr, StoreOffset),
565
4
          StoreSizeVal);
566
4
    }
567
568
  // Otherwise, just memset the whole thing to zero.  This is legal
569
  // because in LLVM, all default initializers (other than the ones we just
570
  // handled above) are guaranteed to have a bit pattern of all zeros.
571
15
  } else {
572
17
    for (std::pair<CharUnits, CharUnits> Store : Stores) {
573
17
      CharUnits StoreOffset = Store.first;
574
17
      CharUnits StoreSize = Store.second;
575
17
      llvm::Value *StoreSizeVal = CGF.CGM.getSize(StoreSize);
576
17
      CGF.Builder.CreateMemSet(
577
17
          CGF.Builder.CreateConstInBoundsByteGEP(DestPtr, StoreOffset),
578
17
          CGF.Builder.getInt8(0), StoreSizeVal);
579
17
    }
580
15
  }
581
19
}
582
583
void
584
CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
585
64.6k
                                      AggValueSlot Dest) {
586
64.6k
  assert(!Dest.isIgnored() && "Must have a destination!");
587
0
  const CXXConstructorDecl *CD = E->getConstructor();
588
589
  // If we require zero initialization before (or instead of) calling the
590
  // constructor, as can be the case with a non-user-provided default
591
  // constructor, emit the zero initialization now, unless destination is
592
  // already zeroed.
593
64.6k
  if (E->requiresZeroInitialization() && 
!Dest.isZeroed()6.67k
) {
594
6.67k
    switch (E->getConstructionKind()) {
595
2
    case CXXConstructExpr::CK_Delegating:
596
6.57k
    case CXXConstructExpr::CK_Complete:
597
6.57k
      EmitNullInitialization(Dest.getAddress(), E->getType());
598
6.57k
      break;
599
0
    case CXXConstructExpr::CK_VirtualBase:
600
100
    case CXXConstructExpr::CK_NonVirtualBase:
601
100
      EmitNullBaseClassInitialization(*this, Dest.getAddress(),
602
100
                                      CD->getParent());
603
100
      break;
604
6.67k
    }
605
6.67k
  }
606
607
  // If this is a call to a trivial default constructor, do nothing.
608
64.6k
  if (CD->isTrivial() && 
CD->isDefaultConstructor()23.4k
)
609
7.65k
    return;
610
611
  // Elide the constructor if we're constructing from a temporary.
612
  // The temporary check is required because Sema sets this on NRVO
613
  // returns.
614
57.0k
  if (getLangOpts().ElideConstructors && 
E->isElidable()56.9k
) {
615
13.1k
    assert(getContext().hasSameUnqualifiedType(E->getType(),
616
13.1k
                                               E->getArg(0)->getType()));
617
13.1k
    if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) {
618
13.1k
      EmitAggExpr(E->getArg(0), Dest);
619
13.1k
      return;
620
13.1k
    }
621
13.1k
  }
622
623
43.9k
  if (const ArrayType *arrayType
624
43.9k
        = getContext().getAsArrayType(E->getType())) {
625
892
    EmitCXXAggrConstructorCall(CD, arrayType, Dest.getAddress(), E,
626
892
                               Dest.isSanitizerChecked());
627
43.0k
  } else {
628
43.0k
    CXXCtorType Type = Ctor_Complete;
629
43.0k
    bool ForVirtualBase = false;
630
43.0k
    bool Delegating = false;
631
632
43.0k
    switch (E->getConstructionKind()) {
633
92
     case CXXConstructExpr::CK_Delegating:
634
      // We should be emitting a constructor; GlobalDecl will assert this
635
92
      Type = CurGD.getCtorType();
636
92
      Delegating = true;
637
92
      break;
638
639
33.6k
     case CXXConstructExpr::CK_Complete:
640
33.6k
      Type = Ctor_Complete;
641
33.6k
      break;
642
643
555
     case CXXConstructExpr::CK_VirtualBase:
644
555
      ForVirtualBase = true;
645
555
      LLVM_FALLTHROUGH;
646
647
9.25k
     case CXXConstructExpr::CK_NonVirtualBase:
648
9.25k
      Type = Ctor_Base;
649
43.0k
     }
650
651
     // Call the constructor.
652
43.0k
     EmitCXXConstructorCall(CD, Type, ForVirtualBase, Delegating, Dest, E);
653
43.0k
  }
654
43.9k
}
655
656
void CodeGenFunction::EmitSynthesizedCXXCopyCtor(Address Dest, Address Src,
657
57
                                                 const Expr *Exp) {
658
57
  if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))
659
2
    Exp = E->getSubExpr();
660
57
  assert(isa<CXXConstructExpr>(Exp) &&
661
57
         "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr");
662
0
  const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp);
663
57
  const CXXConstructorDecl *CD = E->getConstructor();
664
57
  RunCleanupsScope Scope(*this);
665
666
  // If we require zero initialization before (or instead of) calling the
667
  // constructor, as can be the case with a non-user-provided default
668
  // constructor, emit the zero initialization now.
669
  // FIXME. Do I still need this for a copy ctor synthesis?
670
57
  if (E->requiresZeroInitialization())
671
0
    EmitNullInitialization(Dest, E->getType());
672
673
57
  assert(!getContext().getAsConstantArrayType(E->getType())
674
57
         && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
675
0
  EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src, E);
676
57
}
677
678
static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
679
2.36k
                                        const CXXNewExpr *E) {
680
2.36k
  if (!E->isArray())
681
1.67k
    return CharUnits::Zero();
682
683
  // No cookie is required if the operator new[] being used is the
684
  // reserved placement operator new[].
685
684
  if (E->getOperatorNew()->isReservedGlobalPlacementOperator())
686
16
    return CharUnits::Zero();
687
688
668
  return CGF.CGM.getCXXABI().GetArrayCookieSize(E);
689
684
}
690
691
static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF,
692
                                        const CXXNewExpr *e,
693
                                        unsigned minElements,
694
                                        llvm::Value *&numElements,
695
2.02k
                                        llvm::Value *&sizeWithoutCookie) {
696
2.02k
  QualType type = e->getAllocatedType();
697
698
2.02k
  if (!e->isArray()) {
699
1.67k
    CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
700
1.67k
    sizeWithoutCookie
701
1.67k
      = llvm::ConstantInt::get(CGF.SizeTy, typeSize.getQuantity());
702
1.67k
    return sizeWithoutCookie;
703
1.67k
  }
704
705
  // The width of size_t.
706
342
  unsigned sizeWidth = CGF.SizeTy->getBitWidth();
707
708
  // Figure out the cookie size.
709
342
  llvm::APInt cookieSize(sizeWidth,
710
342
                         CalculateCookiePadding(CGF, e).getQuantity());
711
712
  // Emit the array size expression.
713
  // We multiply the size of all dimensions for NumElements.
714
  // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
715
342
  numElements =
716
342
    ConstantEmitter(CGF).tryEmitAbstract(*e->getArraySize(), e->getType());
717
342
  if (!numElements)
718
112
    numElements = CGF.EmitScalarExpr(*e->getArraySize());
719
342
  assert(isa<llvm::IntegerType>(numElements->getType()));
720
721
  // The number of elements can be have an arbitrary integer type;
722
  // essentially, we need to multiply it by a constant factor, add a
723
  // cookie size, and verify that the result is representable as a
724
  // size_t.  That's just a gloss, though, and it's wrong in one
725
  // important way: if the count is negative, it's an error even if
726
  // the cookie size would bring the total size >= 0.
727
0
  bool isSigned
728
342
    = (*e->getArraySize())->getType()->isSignedIntegerOrEnumerationType();
729
342
  llvm::IntegerType *numElementsType
730
342
    = cast<llvm::IntegerType>(numElements->getType());
731
342
  unsigned numElementsWidth = numElementsType->getBitWidth();
732
733
  // Compute the constant factor.
734
342
  llvm::APInt arraySizeMultiplier(sizeWidth, 1);
735
367
  while (const ConstantArrayType *CAT
736
342
             = CGF.getContext().getAsConstantArrayType(type)) {
737
25
    type = CAT->getElementType();
738
25
    arraySizeMultiplier *= CAT->getSize();
739
25
  }
740
741
342
  CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
742
342
  llvm::APInt typeSizeMultiplier(sizeWidth, typeSize.getQuantity());
743
342
  typeSizeMultiplier *= arraySizeMultiplier;
744
745
  // This will be a size_t.
746
342
  llvm::Value *size;
747
748
  // If someone is doing 'new int[42]' there is no need to do a dynamic check.
749
  // Don't bloat the -O0 code.
750
342
  if (llvm::ConstantInt *numElementsC =
751
342
        dyn_cast<llvm::ConstantInt>(numElements)) {
752
230
    const llvm::APInt &count = numElementsC->getValue();
753
754
230
    bool hasAnyOverflow = false;
755
756
    // If 'count' was a negative number, it's an overflow.
757
230
    if (isSigned && 
count.isNegative()158
)
758
0
      hasAnyOverflow = true;
759
760
    // We want to do all this arithmetic in size_t.  If numElements is
761
    // wider than that, check whether it's already too big, and if so,
762
    // overflow.
763
230
    else if (numElementsWidth > sizeWidth &&
764
230
             
numElementsWidth - sizeWidth > count.countLeadingZeros()0
)
765
0
      hasAnyOverflow = true;
766
767
    // Okay, compute a count at the right width.
768
230
    llvm::APInt adjustedCount = count.zextOrTrunc(sizeWidth);
769
770
    // If there is a brace-initializer, we cannot allocate fewer elements than
771
    // there are initializers. If we do, that's treated like an overflow.
772
230
    if (adjustedCount.ult(minElements))
773
0
      hasAnyOverflow = true;
774
775
    // Scale numElements by that.  This might overflow, but we don't
776
    // care because it only overflows if allocationSize does, too, and
777
    // if that overflows then we shouldn't use this.
778
230
    numElements = llvm::ConstantInt::get(CGF.SizeTy,
779
230
                                         adjustedCount * arraySizeMultiplier);
780
781
    // Compute the size before cookie, and track whether it overflowed.
782
230
    bool overflow;
783
230
    llvm::APInt allocationSize
784
230
      = adjustedCount.umul_ov(typeSizeMultiplier, overflow);
785
230
    hasAnyOverflow |= overflow;
786
787
    // Add in the cookie, and check whether it's overflowed.
788
230
    if (cookieSize != 0) {
789
      // Save the current size without a cookie.  This shouldn't be
790
      // used if there was overflow.
791
45
      sizeWithoutCookie = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
792
793
45
      allocationSize = allocationSize.uadd_ov(cookieSize, overflow);
794
45
      hasAnyOverflow |= overflow;
795
45
    }
796
797
    // On overflow, produce a -1 so operator new will fail.
798
230
    if (hasAnyOverflow) {
799
0
      size = llvm::Constant::getAllOnesValue(CGF.SizeTy);
800
230
    } else {
801
230
      size = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
802
230
    }
803
804
  // Otherwise, we might need to use the overflow intrinsics.
805
230
  } else {
806
    // There are up to five conditions we need to test for:
807
    // 1) if isSigned, we need to check whether numElements is negative;
808
    // 2) if numElementsWidth > sizeWidth, we need to check whether
809
    //   numElements is larger than something representable in size_t;
810
    // 3) if minElements > 0, we need to check whether numElements is smaller
811
    //    than that.
812
    // 4) we need to compute
813
    //      sizeWithoutCookie := numElements * typeSizeMultiplier
814
    //    and check whether it overflows; and
815
    // 5) if we need a cookie, we need to compute
816
    //      size := sizeWithoutCookie + cookieSize
817
    //    and check whether it overflows.
818
819
112
    llvm::Value *hasOverflow = nullptr;
820
821
    // If numElementsWidth > sizeWidth, then one way or another, we're
822
    // going to have to do a comparison for (2), and this happens to
823
    // take care of (1), too.
824
112
    if (numElementsWidth > sizeWidth) {
825
0
      llvm::APInt threshold(numElementsWidth, 1);
826
0
      threshold <<= sizeWidth;
827
828
0
      llvm::Value *thresholdV
829
0
        = llvm::ConstantInt::get(numElementsType, threshold);
830
831
0
      hasOverflow = CGF.Builder.CreateICmpUGE(numElements, thresholdV);
832
0
      numElements = CGF.Builder.CreateTrunc(numElements, CGF.SizeTy);
833
834
    // Otherwise, if we're signed, we want to sext up to size_t.
835
112
    } else if (isSigned) {
836
28
      if (numElementsWidth < sizeWidth)
837
8
        numElements = CGF.Builder.CreateSExt(numElements, CGF.SizeTy);
838
839
      // If there's a non-1 type size multiplier, then we can do the
840
      // signedness check at the same time as we do the multiply
841
      // because a negative number times anything will cause an
842
      // unsigned overflow.  Otherwise, we have to do it here. But at least
843
      // in this case, we can subsume the >= minElements check.
844
28
      if (typeSizeMultiplier == 1)
845
8
        hasOverflow = CGF.Builder.CreateICmpSLT(numElements,
846
8
                              llvm::ConstantInt::get(CGF.SizeTy, minElements));
847
848
    // Otherwise, zext up to size_t if necessary.
849
84
    } else if (numElementsWidth < sizeWidth) {
850
0
      numElements = CGF.Builder.CreateZExt(numElements, CGF.SizeTy);
851
0
    }
852
853
112
    assert(numElements->getType() == CGF.SizeTy);
854
855
112
    if (minElements) {
856
      // Don't allow allocation of fewer elements than we have initializers.
857
9
      if (!hasOverflow) {
858
6
        hasOverflow = CGF.Builder.CreateICmpULT(numElements,
859
6
                              llvm::ConstantInt::get(CGF.SizeTy, minElements));
860
6
      } else 
if (3
numElementsWidth > sizeWidth3
) {
861
        // The other existing overflow subsumes this check.
862
        // We do an unsigned comparison, since any signed value < -1 is
863
        // taken care of either above or below.
864
0
        hasOverflow = CGF.Builder.CreateOr(hasOverflow,
865
0
                          CGF.Builder.CreateICmpULT(numElements,
866
0
                              llvm::ConstantInt::get(CGF.SizeTy, minElements)));
867
0
      }
868
9
    }
869
870
112
    size = numElements;
871
872
    // Multiply by the type size if necessary.  This multiplier
873
    // includes all the factors for nested arrays.
874
    //
875
    // This step also causes numElements to be scaled up by the
876
    // nested-array factor if necessary.  Overflow on this computation
877
    // can be ignored because the result shouldn't be used if
878
    // allocation fails.
879
112
    if (typeSizeMultiplier != 1) {
880
53
      llvm::Function *umul_with_overflow
881
53
        = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, CGF.SizeTy);
882
883
53
      llvm::Value *tsmV =
884
53
        llvm::ConstantInt::get(CGF.SizeTy, typeSizeMultiplier);
885
53
      llvm::Value *result =
886
53
          CGF.Builder.CreateCall(umul_with_overflow, {size, tsmV});
887
888
53
      llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
889
53
      if (hasOverflow)
890
6
        hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
891
47
      else
892
47
        hasOverflow = overflowed;
893
894
53
      size = CGF.Builder.CreateExtractValue(result, 0);
895
896
      // Also scale up numElements by the array size multiplier.
897
53
      if (arraySizeMultiplier != 1) {
898
        // If the base element type size is 1, then we can re-use the
899
        // multiply we just did.
900
10
        if (typeSize.isOne()) {
901
0
          assert(arraySizeMultiplier == typeSizeMultiplier);
902
0
          numElements = size;
903
904
        // Otherwise we need a separate multiply.
905
10
        } else {
906
10
          llvm::Value *asmV =
907
10
            llvm::ConstantInt::get(CGF.SizeTy, arraySizeMultiplier);
908
10
          numElements = CGF.Builder.CreateMul(numElements, asmV);
909
10
        }
910
10
      }
911
59
    } else {
912
      // numElements doesn't need to be scaled.
913
59
      assert(arraySizeMultiplier == 1);
914
59
    }
915
916
    // Add in the cookie size if necessary.
917
112
    if (cookieSize != 0) {
918
19
      sizeWithoutCookie = size;
919
920
19
      llvm::Function *uadd_with_overflow
921
19
        = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, CGF.SizeTy);
922
923
19
      llvm::Value *cookieSizeV = llvm::ConstantInt::get(CGF.SizeTy, cookieSize);
924
19
      llvm::Value *result =
925
19
          CGF.Builder.CreateCall(uadd_with_overflow, {size, cookieSizeV});
926
927
19
      llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
928
19
      if (hasOverflow)
929
18
        hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
930
1
      else
931
1
        hasOverflow = overflowed;
932
933
19
      size = CGF.Builder.CreateExtractValue(result, 0);
934
19
    }
935
936
    // If we had any possibility of dynamic overflow, make a select to
937
    // overwrite 'size' with an all-ones value, which should cause
938
    // operator new to throw.
939
112
    if (hasOverflow)
940
62
      size = CGF.Builder.CreateSelect(hasOverflow,
941
62
                                 llvm::Constant::getAllOnesValue(CGF.SizeTy),
942
62
                                      size);
943
112
  }
944
945
342
  if (cookieSize == 0)
946
278
    sizeWithoutCookie = size;
947
64
  else
948
64
    assert(sizeWithoutCookie && "didn't set sizeWithoutCookie?");
949
950
0
  return size;
951
2.02k
}
952
953
static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const Expr *Init,
954
                                    QualType AllocType, Address NewPtr,
955
1.68k
                                    AggValueSlot::Overlap_t MayOverlap) {
956
  // FIXME: Refactor with EmitExprAsInit.
957
1.68k
  switch (CGF.getEvaluationKind(AllocType)) {
958
269
  case TEK_Scalar:
959
269
    CGF.EmitScalarInit(Init, nullptr,
960
269
                       CGF.MakeAddrLValue(NewPtr, AllocType), false);
961
269
    return;
962
1
  case TEK_Complex:
963
1
    CGF.EmitComplexExprIntoLValue(Init, CGF.MakeAddrLValue(NewPtr, AllocType),
964
1
                                  /*isInit*/ true);
965
1
    return;
966
1.41k
  case TEK_Aggregate: {
967
1.41k
    AggValueSlot Slot
968
1.41k
      = AggValueSlot::forAddr(NewPtr, AllocType.getQualifiers(),
969
1.41k
                              AggValueSlot::IsDestructed,
970
1.41k
                              AggValueSlot::DoesNotNeedGCBarriers,
971
1.41k
                              AggValueSlot::IsNotAliased,
972
1.41k
                              MayOverlap, AggValueSlot::IsNotZeroed,
973
1.41k
                              AggValueSlot::IsSanitizerChecked);
974
1.41k
    CGF.EmitAggExpr(Init, Slot);
975
1.41k
    return;
976
0
  }
977
1.68k
  }
978
0
  llvm_unreachable("bad evaluation kind");
979
0
}
980
981
void CodeGenFunction::EmitNewArrayInitializer(
982
    const CXXNewExpr *E, QualType ElementType, llvm::Type *ElementTy,
983
    Address BeginPtr, llvm::Value *NumElements,
984
342
    llvm::Value *AllocSizeWithoutCookie) {
985
  // If we have a type with trivial initialization and no initializer,
986
  // there's nothing to do.
987
342
  if (!E->hasInitializer())
988
187
    return;
989
990
155
  Address CurPtr = BeginPtr;
991
992
155
  unsigned InitListElements = 0;
993
994
155
  const Expr *Init = E->getInitializer();
995
155
  Address EndOfInit = Address::invalid();
996
155
  QualType::DestructionKind DtorKind = ElementType.isDestructedType();
997
155
  EHScopeStack::stable_iterator Cleanup;
998
155
  llvm::Instruction *CleanupDominator = nullptr;
999
1000
155
  CharUnits ElementSize = getContext().getTypeSizeInChars(ElementType);
1001
155
  CharUnits ElementAlign =
1002
155
    BeginPtr.getAlignment().alignmentOfArrayElement(ElementSize);
1003
1004
  // Attempt to perform zero-initialization using memset.
1005
155
  auto TryMemsetInitialization = [&]() -> bool {
1006
    // FIXME: If the type is a pointer-to-data-member under the Itanium ABI,
1007
    // we can initialize with a memset to -1.
1008
21
    if (!CGM.getTypes().isZeroInitializable(ElementType))
1009
4
      return false;
1010
1011
    // Optimization: since zero initialization will just set the memory
1012
    // to all zeroes, generate a single memset to do it in one shot.
1013
1014
    // Subtract out the size of any elements we've already initialized.
1015
17
    auto *RemainingSize = AllocSizeWithoutCookie;
1016
17
    if (InitListElements) {
1017
      // We know this can't overflow; we check this when doing the allocation.
1018
9
      auto *InitializedSize = llvm::ConstantInt::get(
1019
9
          RemainingSize->getType(),
1020
9
          getContext().getTypeSizeInChars(ElementType).getQuantity() *
1021
9
              InitListElements);
1022
9
      RemainingSize = Builder.CreateSub(RemainingSize, InitializedSize);
1023
9
    }
1024
1025
    // Create the memset.
1026
17
    Builder.CreateMemSet(CurPtr, Builder.getInt8(0), RemainingSize, false);
1027
17
    return true;
1028
21
  };
1029
1030
  // If the initializer is an initializer list, first do the explicit elements.
1031
155
  if (const InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
1032
    // Initializing from a (braced) string literal is a special case; the init
1033
    // list element does not initialize a (single) array element.
1034
28
    if (ILE->isStringLiteralInit()) {
1035
      // Initialize the initial portion of length equal to that of the string
1036
      // literal. The allocation must be for at least this much; we emitted a
1037
      // check for that earlier.
1038
8
      AggValueSlot Slot =
1039
8
          AggValueSlot::forAddr(CurPtr, ElementType.getQualifiers(),
1040
8
                                AggValueSlot::IsDestructed,
1041
8
                                AggValueSlot::DoesNotNeedGCBarriers,
1042
8
                                AggValueSlot::IsNotAliased,
1043
8
                                AggValueSlot::DoesNotOverlap,
1044
8
                                AggValueSlot::IsNotZeroed,
1045
8
                                AggValueSlot::IsSanitizerChecked);
1046
8
      EmitAggExpr(ILE->getInit(0), Slot);
1047
1048
      // Move past these elements.
1049
8
      InitListElements =
1050
8
          cast<ConstantArrayType>(ILE->getType()->getAsArrayTypeUnsafe())
1051
8
              ->getSize().getZExtValue();
1052
8
      CurPtr =
1053
8
          Address(Builder.CreateInBoundsGEP(CurPtr.getElementType(),
1054
8
                                            CurPtr.getPointer(),
1055
8
                                            Builder.getSize(InitListElements),
1056
8
                                            "string.init.end"),
1057
8
                  CurPtr.getAlignment().alignmentAtOffset(InitListElements *
1058
8
                                                          ElementSize));
1059
1060
      // Zero out the rest, if any remain.
1061
8
      llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements);
1062
8
      if (!ConstNum || 
!ConstNum->equalsInt(InitListElements)6
) {
1063
2
        bool OK = TryMemsetInitialization();
1064
2
        (void)OK;
1065
2
        assert(OK && "couldn't memset character type?");
1066
2
      }
1067
0
      return;
1068
8
    }
1069
1070
20
    InitListElements = ILE->getNumInits();
1071
1072
    // If this is a multi-dimensional array new, we will initialize multiple
1073
    // elements with each init list element.
1074
20
    QualType AllocType = E->getAllocatedType();
1075
20
    if (const ConstantArrayType *CAT = dyn_cast_or_null<ConstantArrayType>(
1076
20
            AllocType->getAsArrayTypeUnsafe())) {
1077
3
      ElementTy = ConvertTypeForMem(AllocType);
1078
3
      CurPtr = Builder.CreateElementBitCast(CurPtr, ElementTy);
1079
3
      InitListElements *= getContext().getConstantArrayElementCount(CAT);
1080
3
    }
1081
1082
    // Enter a partial-destruction Cleanup if necessary.
1083
20
    if (needsEHCleanup(DtorKind)) {
1084
      // In principle we could tell the Cleanup where we are more
1085
      // directly, but the control flow can get so varied here that it
1086
      // would actually be quite complex.  Therefore we go through an
1087
      // alloca.
1088
2
      EndOfInit = CreateTempAlloca(BeginPtr.getType(), getPointerAlign(),
1089
2
                                   "array.init.end");
1090
2
      CleanupDominator = Builder.CreateStore(BeginPtr.getPointer(), EndOfInit);
1091
2
      pushIrregularPartialArrayCleanup(BeginPtr.getPointer(), EndOfInit,
1092
2
                                       ElementType, ElementAlign,
1093
2
                                       getDestroyer(DtorKind));
1094
2
      Cleanup = EHStack.stable_begin();
1095
2
    }
1096
1097
20
    CharUnits StartAlign = CurPtr.getAlignment();
1098
64
    for (unsigned i = 0, e = ILE->getNumInits(); i != e; 
++i44
) {
1099
      // Tell the cleanup that it needs to destroy up to this
1100
      // element.  TODO: some of these stores can be trivially
1101
      // observed to be unnecessary.
1102
44
      if (EndOfInit.isValid()) {
1103
6
        auto FinishedPtr =
1104
6
          Builder.CreateBitCast(CurPtr.getPointer(), BeginPtr.getType());
1105
6
        Builder.CreateStore(FinishedPtr, EndOfInit);
1106
6
      }
1107
      // FIXME: If the last initializer is an incomplete initializer list for
1108
      // an array, and we have an array filler, we can fold together the two
1109
      // initialization loops.
1110
44
      StoreAnyExprIntoOneUnit(*this, ILE->getInit(i),
1111
44
                              ILE->getInit(i)->getType(), CurPtr,
1112
44
                              AggValueSlot::DoesNotOverlap);
1113
44
      CurPtr = Address(Builder.CreateInBoundsGEP(CurPtr.getElementType(),
1114
44
                                                 CurPtr.getPointer(),
1115
44
                                                 Builder.getSize(1),
1116
44
                                                 "array.exp.next"),
1117
44
                       StartAlign.alignmentAtOffset((i + 1) * ElementSize));
1118
44
    }
1119
1120
    // The remaining elements are filled with the array filler expression.
1121
20
    Init = ILE->getArrayFiller();
1122
1123
    // Extract the initializer for the individual array elements by pulling
1124
    // out the array filler from all the nested initializer lists. This avoids
1125
    // generating a nested loop for the initialization.
1126
22
    while (Init && 
Init->getType()->isConstantArrayType()14
) {
1127
2
      auto *SubILE = dyn_cast<InitListExpr>(Init);
1128
2
      if (!SubILE)
1129
0
        break;
1130
2
      assert(SubILE->getNumInits() == 0 && "explicit inits in array filler?");
1131
0
      Init = SubILE->getArrayFiller();
1132
2
    }
1133
1134
    // Switch back to initializing one base element at a time.
1135
20
    CurPtr = Builder.CreateBitCast(CurPtr, BeginPtr.getType());
1136
20
  }
1137
1138
  // If all elements have already been initialized, skip any further
1139
  // initialization.
1140
147
  llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements);
1141
147
  if (ConstNum && 
ConstNum->getZExtValue() <= InitListElements98
) {
1142
    // If there was a Cleanup, deactivate it.
1143
12
    if (CleanupDominator)
1144
1
      DeactivateCleanupBlock(Cleanup, CleanupDominator);
1145
12
    return;
1146
12
  }
1147
1148
135
  assert(Init && "have trailing elements to initialize but no initializer");
1149
1150
  // If this is a constructor call, try to optimize it out, and failing that
1151
  // emit a single loop to initialize all remaining elements.
1152
135
  if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
1153
118
    CXXConstructorDecl *Ctor = CCE->getConstructor();
1154
118
    if (Ctor->isTrivial()) {
1155
      // If new expression did not specify value-initialization, then there
1156
      // is no initialization.
1157
54
      if (!CCE->requiresZeroInitialization() || 
Ctor->getParent()->isEmpty()3
)
1158
52
        return;
1159
1160
2
      if (TryMemsetInitialization())
1161
1
        return;
1162
2
    }
1163
1164
    // Store the new Cleanup position for irregular Cleanups.
1165
    //
1166
    // FIXME: Share this cleanup with the constructor call emission rather than
1167
    // having it create a cleanup of its own.
1168
65
    if (EndOfInit.isValid())
1169
1
      Builder.CreateStore(CurPtr.getPointer(), EndOfInit);
1170
1171
    // Emit a constructor call loop to initialize the remaining elements.
1172
65
    if (InitListElements)
1173
2
      NumElements = Builder.CreateSub(
1174
2
          NumElements,
1175
2
          llvm::ConstantInt::get(NumElements->getType(), InitListElements));
1176
65
    EmitCXXAggrConstructorCall(Ctor, NumElements, CurPtr, CCE,
1177
65
                               /*NewPointerIsChecked*/true,
1178
65
                               CCE->requiresZeroInitialization());
1179
65
    return;
1180
118
  }
1181
1182
  // If this is value-initialization, we can usually use memset.
1183
17
  ImplicitValueInitExpr IVIE(ElementType);
1184
17
  if (isa<ImplicitValueInitExpr>(Init)) {
1185
14
    if (TryMemsetInitialization())
1186
11
      return;
1187
1188
    // Switch to an ImplicitValueInitExpr for the element type. This handles
1189
    // only one case: multidimensional array new of pointers to members. In
1190
    // all other cases, we already have an initializer for the array element.
1191
3
    Init = &IVIE;
1192
3
  }
1193
1194
  // At this point we should have found an initializer for the individual
1195
  // elements of the array.
1196
6
  assert(getContext().hasSameUnqualifiedType(ElementType, Init->getType()) &&
1197
6
         "got wrong type of element to initialize");
1198
1199
  // If we have an empty initializer list, we can usually use memset.
1200
6
  if (auto *ILE = dyn_cast<InitListExpr>(Init))
1201
3
    if (ILE->getNumInits() == 0 && 
TryMemsetInitialization()0
)
1202
0
      return;
1203
1204
  // If we have a struct whose every field is value-initialized, we can
1205
  // usually use memset.
1206
6
  if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
1207
3
    if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
1208
3
      if (RType->getDecl()->isStruct()) {
1209
3
        unsigned NumElements = 0;
1210
3
        if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RType->getDecl()))
1211
3
          NumElements = CXXRD->getNumBases();
1212
3
        for (auto *Field : RType->getDecl()->fields())
1213
5
          if (!Field->isUnnamedBitfield())
1214
5
            ++NumElements;
1215
        // FIXME: Recurse into nested InitListExprs.
1216
3
        if (ILE->getNumInits() == NumElements)
1217
8
          
for (unsigned i = 0, e = ILE->getNumInits(); 3
i != e;
++i5
)
1218
5
            if (!isa<ImplicitValueInitExpr>(ILE->getInit(i)))
1219
0
              --NumElements;
1220
3
        if (ILE->getNumInits() == NumElements && TryMemsetInitialization())
1221
3
          return;
1222
3
      }
1223
3
    }
1224
3
  }
1225
1226
  // Create the loop blocks.
1227
3
  llvm::BasicBlock *EntryBB = Builder.GetInsertBlock();
1228
3
  llvm::BasicBlock *LoopBB = createBasicBlock("new.loop");
1229
3
  llvm::BasicBlock *ContBB = createBasicBlock("new.loop.end");
1230
1231
  // Find the end of the array, hoisted out of the loop.
1232
3
  llvm::Value *EndPtr =
1233
3
    Builder.CreateInBoundsGEP(BeginPtr.getElementType(), BeginPtr.getPointer(),
1234
3
                              NumElements, "array.end");
1235
1236
  // If the number of elements isn't constant, we have to now check if there is
1237
  // anything left to initialize.
1238
3
  if (!ConstNum) {
1239
0
    llvm::Value *IsEmpty =
1240
0
      Builder.CreateICmpEQ(CurPtr.getPointer(), EndPtr, "array.isempty");
1241
0
    Builder.CreateCondBr(IsEmpty, ContBB, LoopBB);
1242
0
  }
1243
1244
  // Enter the loop.
1245
3
  EmitBlock(LoopBB);
1246
1247
  // Set up the current-element phi.
1248
3
  llvm::PHINode *CurPtrPhi =
1249
3
    Builder.CreatePHI(CurPtr.getType(), 2, "array.cur");
1250
3
  CurPtrPhi->addIncoming(CurPtr.getPointer(), EntryBB);
1251
1252
3
  CurPtr = Address(CurPtrPhi, ElementAlign);
1253
1254
  // Store the new Cleanup position for irregular Cleanups.
1255
3
  if (EndOfInit.isValid())
1256
0
    Builder.CreateStore(CurPtr.getPointer(), EndOfInit);
1257
1258
  // Enter a partial-destruction Cleanup if necessary.
1259
3
  if (!CleanupDominator && needsEHCleanup(DtorKind)) {
1260
0
    pushRegularPartialArrayCleanup(BeginPtr.getPointer(), CurPtr.getPointer(),
1261
0
                                   ElementType, ElementAlign,
1262
0
                                   getDestroyer(DtorKind));
1263
0
    Cleanup = EHStack.stable_begin();
1264
0
    CleanupDominator = Builder.CreateUnreachable();
1265
0
  }
1266
1267
  // Emit the initializer into this element.
1268
3
  StoreAnyExprIntoOneUnit(*this, Init, Init->getType(), CurPtr,
1269
3
                          AggValueSlot::DoesNotOverlap);
1270
1271
  // Leave the Cleanup if we entered one.
1272
3
  if (CleanupDominator) {
1273
0
    DeactivateCleanupBlock(Cleanup, CleanupDominator);
1274
0
    CleanupDominator->eraseFromParent();
1275
0
  }
1276
1277
  // Advance to the next element by adjusting the pointer type as necessary.
1278
3
  llvm::Value *NextPtr =
1279
3
    Builder.CreateConstInBoundsGEP1_32(ElementTy, CurPtr.getPointer(), 1,
1280
3
                                       "array.next");
1281
1282
  // Check whether we've gotten to the end of the array and, if so,
1283
  // exit the loop.
1284
3
  llvm::Value *IsEnd = Builder.CreateICmpEQ(NextPtr, EndPtr, "array.atend");
1285
3
  Builder.CreateCondBr(IsEnd, ContBB, LoopBB);
1286
3
  CurPtrPhi->addIncoming(NextPtr, Builder.GetInsertBlock());
1287
1288
3
  EmitBlock(ContBB);
1289
3
}
1290
1291
static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
1292
                               QualType ElementType, llvm::Type *ElementTy,
1293
                               Address NewPtr, llvm::Value *NumElements,
1294
2.02k
                               llvm::Value *AllocSizeWithoutCookie) {
1295
2.02k
  ApplyDebugLocation DL(CGF, E);
1296
2.02k
  if (E->isArray())
1297
342
    CGF.EmitNewArrayInitializer(E, ElementType, ElementTy, NewPtr, NumElements,
1298
342
                                AllocSizeWithoutCookie);
1299
1.67k
  else if (const Expr *Init = E->getInitializer())
1300
1.64k
    StoreAnyExprIntoOneUnit(CGF, Init, E->getAllocatedType(), NewPtr,
1301
1.64k
                            AggValueSlot::DoesNotOverlap);
1302
2.02k
}
1303
1304
/// Emit a call to an operator new or operator delete function, as implicitly
1305
/// created by new-expressions and delete-expressions.
1306
static RValue EmitNewDeleteCall(CodeGenFunction &CGF,
1307
                                const FunctionDecl *CalleeDecl,
1308
                                const FunctionProtoType *CalleeType,
1309
4.21k
                                const CallArgList &Args) {
1310
4.21k
  llvm::CallBase *CallOrInvoke;
1311
4.21k
  llvm::Constant *CalleePtr = CGF.CGM.GetAddrOfFunction(CalleeDecl);
1312
4.21k
  CGCallee Callee = CGCallee::forDirect(CalleePtr, GlobalDecl(CalleeDecl));
1313
4.21k
  RValue RV =
1314
4.21k
      CGF.EmitCall(CGF.CGM.getTypes().arrangeFreeFunctionCall(
1315
4.21k
                       Args, CalleeType, /*ChainCall=*/false),
1316
4.21k
                   Callee, ReturnValueSlot(), Args, &CallOrInvoke);
1317
1318
  /// C++1y [expr.new]p10:
1319
  ///   [In a new-expression,] an implementation is allowed to omit a call
1320
  ///   to a replaceable global allocation function.
1321
  ///
1322
  /// We model such elidable calls with the 'builtin' attribute.
1323
4.21k
  llvm::Function *Fn = dyn_cast<llvm::Function>(CalleePtr);
1324
4.21k
  if (CalleeDecl->isReplaceableGlobalAllocationFunction() &&
1325
4.21k
      
Fn3.88k
&&
Fn->hasFnAttribute(llvm::Attribute::NoBuiltin)3.88k
) {
1326
3.88k
    CallOrInvoke->addFnAttr(llvm::Attribute::Builtin);
1327
3.88k
  }
1328
1329
4.21k
  return RV;
1330
4.21k
}
1331
1332
RValue CodeGenFunction::EmitBuiltinNewDeleteCall(const FunctionProtoType *Type,
1333
                                                 const CallExpr *TheCall,
1334
630
                                                 bool IsDelete) {
1335
630
  CallArgList Args;
1336
630
  EmitCallArgs(Args, Type, TheCall->arguments());
1337
  // Find the allocation or deallocation function that we're calling.
1338
630
  ASTContext &Ctx = getContext();
1339
630
  DeclarationName Name = Ctx.DeclarationNames
1340
630
      .getCXXOperatorName(IsDelete ? 
OO_Delete333
:
OO_New297
);
1341
1342
630
  for (auto *Decl : Ctx.getTranslationUnitDecl()->lookup(Name))
1343
640
    if (auto *FD = dyn_cast<FunctionDecl>(Decl))
1344
640
      if (Ctx.hasSameType(FD->getType(), QualType(Type, 0)))
1345
630
        return EmitNewDeleteCall(*this, FD, Type, Args);
1346
0
  llvm_unreachable("predeclared global operator new/delete is missing");
1347
0
}
1348
1349
namespace {
1350
/// The parameters to pass to a usual operator delete.
1351
struct UsualDeleteParams {
1352
  bool DestroyingDelete = false;
1353
  bool Size = false;
1354
  bool Alignment = false;
1355
};
1356
}
1357
1358
2.24k
static UsualDeleteParams getUsualDeleteParams(const FunctionDecl *FD) {
1359
2.24k
  UsualDeleteParams Params;
1360
1361
2.24k
  const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
1362
2.24k
  auto AI = FPT->param_type_begin(), AE = FPT->param_type_end();
1363
1364
  // The first argument is always a void*.
1365
2.24k
  ++AI;
1366
1367
  // The next parameter may be a std::destroying_delete_t.
1368
2.24k
  if (FD->isDestroyingOperatorDelete()) {
1369
30
    Params.DestroyingDelete = true;
1370
30
    assert(AI != AE);
1371
0
    ++AI;
1372
30
  }
1373
1374
  // Figure out what other parameters we should be implicitly passing.
1375
2.24k
  if (AI != AE && 
(*AI)->isIntegerType()122
) {
1376
90
    Params.Size = true;
1377
90
    ++AI;
1378
90
  }
1379
1380
2.24k
  if (AI != AE && 
(*AI)->isAlignValT()58
) {
1381
58
    Params.Alignment = true;
1382
58
    ++AI;
1383
58
  }
1384
1385
2.24k
  assert(AI == AE && "unexpected usual deallocation function parameter");
1386
0
  return Params;
1387
2.24k
}
1388
1389
namespace {
1390
  /// A cleanup to call the given 'operator delete' function upon abnormal
1391
  /// exit from a new expression. Templated on a traits type that deals with
1392
  /// ensuring that the arguments dominate the cleanup if necessary.
1393
  template<typename Traits>
1394
  class CallDeleteDuringNew final : public EHScopeStack::Cleanup {
1395
    /// Type used to hold llvm::Value*s.
1396
    typedef typename Traits::ValueTy ValueTy;
1397
    /// Type used to hold RValues.
1398
    typedef typename Traits::RValueTy RValueTy;
1399
    struct PlacementArg {
1400
      RValueTy ArgValue;
1401
      QualType ArgType;
1402
    };
1403
1404
    unsigned NumPlacementArgs : 31;
1405
    unsigned PassAlignmentToPlacementDelete : 1;
1406
    const FunctionDecl *OperatorDelete;
1407
    ValueTy Ptr;
1408
    ValueTy AllocSize;
1409
    CharUnits AllocAlign;
1410
1411
80
    PlacementArg *getPlacementArgs() {
1412
80
      return reinterpret_cast<PlacementArg *>(this + 1);
1413
80
    }
CGExprCXX.cpp:(anonymous namespace)::CallDeleteDuringNew<EnterNewDeleteCleanup(clang::CodeGen::CodeGenFunction&, clang::CXXNewExpr const*, clang::CodeGen::Address, llvm::Value*, clang::CharUnits, clang::CodeGen::CallArgList const&)::DirectCleanupTraits>::getPlacementArgs()
Line
Count
Source
1411
72
    PlacementArg *getPlacementArgs() {
1412
72
      return reinterpret_cast<PlacementArg *>(this + 1);
1413
72
    }
CGExprCXX.cpp:(anonymous namespace)::CallDeleteDuringNew<EnterNewDeleteCleanup(clang::CodeGen::CodeGenFunction&, clang::CXXNewExpr const*, clang::CodeGen::Address, llvm::Value*, clang::CharUnits, clang::CodeGen::CallArgList const&)::ConditionalCleanupTraits>::getPlacementArgs()
Line
Count
Source
1411
8
    PlacementArg *getPlacementArgs() {
1412
8
      return reinterpret_cast<PlacementArg *>(this + 1);
1413
8
    }
1414
1415
  public:
1416
835
    static size_t getExtraSize(size_t NumPlacementArgs) {
1417
835
      return NumPlacementArgs * sizeof(PlacementArg);
1418
835
    }
CGExprCXX.cpp:(anonymous namespace)::CallDeleteDuringNew<EnterNewDeleteCleanup(clang::CodeGen::CodeGenFunction&, clang::CXXNewExpr const*, clang::CodeGen::Address, llvm::Value*, clang::CharUnits, clang::CodeGen::CallArgList const&)::DirectCleanupTraits>::getExtraSize(unsigned long)
Line
Count
Source
1416
829
    static size_t getExtraSize(size_t NumPlacementArgs) {
1417
829
      return NumPlacementArgs * sizeof(PlacementArg);
1418
829
    }
CGExprCXX.cpp:(anonymous namespace)::CallDeleteDuringNew<EnterNewDeleteCleanup(clang::CodeGen::CodeGenFunction&, clang::CXXNewExpr const*, clang::CodeGen::Address, llvm::Value*, clang::CharUnits, clang::CodeGen::CallArgList const&)::ConditionalCleanupTraits>::getExtraSize(unsigned long)
Line
Count
Source
1416
6
    static size_t getExtraSize(size_t NumPlacementArgs) {
1417
6
      return NumPlacementArgs * sizeof(PlacementArg);
1418
6
    }
1419
1420
    CallDeleteDuringNew(size_t NumPlacementArgs,
1421
                        const FunctionDecl *OperatorDelete, ValueTy Ptr,
1422
                        ValueTy AllocSize, bool PassAlignmentToPlacementDelete,
1423
                        CharUnits AllocAlign)
1424
      : NumPlacementArgs(NumPlacementArgs),
1425
        PassAlignmentToPlacementDelete(PassAlignmentToPlacementDelete),
1426
        OperatorDelete(OperatorDelete), Ptr(Ptr), AllocSize(AllocSize),
1427
835
        AllocAlign(AllocAlign) {}
CGExprCXX.cpp:(anonymous namespace)::CallDeleteDuringNew<EnterNewDeleteCleanup(clang::CodeGen::CodeGenFunction&, clang::CXXNewExpr const*, clang::CodeGen::Address, llvm::Value*, clang::CharUnits, clang::CodeGen::CallArgList const&)::DirectCleanupTraits>::CallDeleteDuringNew(unsigned long, clang::FunctionDecl const*, llvm::Value*, llvm::Value*, bool, clang::CharUnits)
Line
Count
Source
1427
829
        AllocAlign(AllocAlign) {}
CGExprCXX.cpp:(anonymous namespace)::CallDeleteDuringNew<EnterNewDeleteCleanup(clang::CodeGen::CodeGenFunction&, clang::CXXNewExpr const*, clang::CodeGen::Address, llvm::Value*, clang::CharUnits, clang::CodeGen::CallArgList const&)::ConditionalCleanupTraits>::CallDeleteDuringNew(unsigned long, clang::FunctionDecl const*, clang::CodeGen::DominatingValue<clang::CodeGen::RValue>::saved_type, clang::CodeGen::DominatingValue<clang::CodeGen::RValue>::saved_type, bool, clang::CharUnits)
Line
Count
Source
1427
6
        AllocAlign(AllocAlign) {}
1428
1429
40
    void setPlacementArg(unsigned I, RValueTy Arg, QualType Type) {
1430
40
      assert(I < NumPlacementArgs && "index out of range");
1431
0
      getPlacementArgs()[I] = {Arg, Type};
1432
40
    }
CGExprCXX.cpp:(anonymous namespace)::CallDeleteDuringNew<EnterNewDeleteCleanup(clang::CodeGen::CodeGenFunction&, clang::CXXNewExpr const*, clang::CodeGen::Address, llvm::Value*, clang::CharUnits, clang::CodeGen::CallArgList const&)::DirectCleanupTraits>::setPlacementArg(unsigned int, clang::CodeGen::RValue, clang::QualType)
Line
Count
Source
1429
36
    void setPlacementArg(unsigned I, RValueTy Arg, QualType Type) {
1430
36
      assert(I < NumPlacementArgs && "index out of range");
1431
0
      getPlacementArgs()[I] = {Arg, Type};
1432
36
    }
CGExprCXX.cpp:(anonymous namespace)::CallDeleteDuringNew<EnterNewDeleteCleanup(clang::CodeGen::CodeGenFunction&, clang::CXXNewExpr const*, clang::CodeGen::Address, llvm::Value*, clang::CharUnits, clang::CodeGen::CallArgList const&)::ConditionalCleanupTraits>::setPlacementArg(unsigned int, clang::CodeGen::DominatingValue<clang::CodeGen::RValue>::saved_type, clang::QualType)
Line
Count
Source
1429
4
    void setPlacementArg(unsigned I, RValueTy Arg, QualType Type) {
1430
4
      assert(I < NumPlacementArgs && "index out of range");
1431
0
      getPlacementArgs()[I] = {Arg, Type};
1432
4
    }
1433
1434
589
    void Emit(CodeGenFunction &CGF, Flags flags) override {
1435
589
      const auto *FPT = OperatorDelete->getType()->castAs<FunctionProtoType>();
1436
589
      CallArgList DeleteArgs;
1437
1438
      // The first argument is always a void* (or C* for a destroying operator
1439
      // delete for class type C).
1440
589
      DeleteArgs.add(Traits::get(CGF, Ptr), FPT->getParamType(0));
1441
1442
      // Figure out what other parameters we should be implicitly passing.
1443
589
      UsualDeleteParams Params;
1444
589
      if (NumPlacementArgs) {
1445
        // A placement deallocation function is implicitly passed an alignment
1446
        // if the placement allocation function was, but is never passed a size.
1447
36
        Params.Alignment = PassAlignmentToPlacementDelete;
1448
553
      } else {
1449
        // For a non-placement new-expression, 'operator delete' can take a
1450
        // size and/or an alignment if it has the right parameters.
1451
553
        Params = getUsualDeleteParams(OperatorDelete);
1452
553
      }
1453
1454
589
      assert(!Params.DestroyingDelete &&
1455
589
             "should not call destroying delete in a new-expression");
1456
1457
      // The second argument can be a std::size_t (for non-placement delete).
1458
589
      if (Params.Size)
1459
6
        DeleteArgs.add(Traits::get(CGF, AllocSize),
1460
6
                       CGF.getContext().getSizeType());
1461
1462
      // The next (second or third) argument can be a std::align_val_t, which
1463
      // is an enum whose underlying type is std::size_t.
1464
      // FIXME: Use the right type as the parameter type. Note that in a call
1465
      // to operator delete(size_t, ...), we may not have it available.
1466
589
      if (Params.Alignment)
1467
36
        DeleteArgs.add(RValue::get(llvm::ConstantInt::get(
1468
36
                           CGF.SizeTy, AllocAlign.getQuantity())),
1469
36
                       CGF.getContext().getSizeType());
1470
1471
      // Pass the rest of the arguments, which must match exactly.
1472
629
      for (unsigned I = 0; I != NumPlacementArgs; 
++I40
) {
1473
40
        auto Arg = getPlacementArgs()[I];
1474
40
        DeleteArgs.add(Traits::get(CGF, Arg.ArgValue), Arg.ArgType);
1475
40
      }
1476
1477
      // Call 'operator delete'.
1478
589
      EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs);
1479
589
    }
CGExprCXX.cpp:(anonymous namespace)::CallDeleteDuringNew<EnterNewDeleteCleanup(clang::CodeGen::CodeGenFunction&, clang::CXXNewExpr const*, clang::CodeGen::Address, llvm::Value*, clang::CharUnits, clang::CodeGen::CallArgList const&)::DirectCleanupTraits>::Emit(clang::CodeGen::CodeGenFunction&, clang::CodeGen::EHScopeStack::Cleanup::Flags)
Line
Count
Source
1434
583
    void Emit(CodeGenFunction &CGF, Flags flags) override {
1435
583
      const auto *FPT = OperatorDelete->getType()->castAs<FunctionProtoType>();
1436
583
      CallArgList DeleteArgs;
1437
1438
      // The first argument is always a void* (or C* for a destroying operator
1439
      // delete for class type C).
1440
583
      DeleteArgs.add(Traits::get(CGF, Ptr), FPT->getParamType(0));
1441
1442
      // Figure out what other parameters we should be implicitly passing.
1443
583
      UsualDeleteParams Params;
1444
583
      if (NumPlacementArgs) {
1445
        // A placement deallocation function is implicitly passed an alignment
1446
        // if the placement allocation function was, but is never passed a size.
1447
34
        Params.Alignment = PassAlignmentToPlacementDelete;
1448
549
      } else {
1449
        // For a non-placement new-expression, 'operator delete' can take a
1450
        // size and/or an alignment if it has the right parameters.
1451
549
        Params = getUsualDeleteParams(OperatorDelete);
1452
549
      }
1453
1454
583
      assert(!Params.DestroyingDelete &&
1455
583
             "should not call destroying delete in a new-expression");
1456
1457
      // The second argument can be a std::size_t (for non-placement delete).
1458
583
      if (Params.Size)
1459
6
        DeleteArgs.add(Traits::get(CGF, AllocSize),
1460
6
                       CGF.getContext().getSizeType());
1461
1462
      // The next (second or third) argument can be a std::align_val_t, which
1463
      // is an enum whose underlying type is std::size_t.
1464
      // FIXME: Use the right type as the parameter type. Note that in a call
1465
      // to operator delete(size_t, ...), we may not have it available.
1466
583
      if (Params.Alignment)
1467
36
        DeleteArgs.add(RValue::get(llvm::ConstantInt::get(
1468
36
                           CGF.SizeTy, AllocAlign.getQuantity())),
1469
36
                       CGF.getContext().getSizeType());
1470
1471
      // Pass the rest of the arguments, which must match exactly.
1472
619
      for (unsigned I = 0; I != NumPlacementArgs; 
++I36
) {
1473
36
        auto Arg = getPlacementArgs()[I];
1474
36
        DeleteArgs.add(Traits::get(CGF, Arg.ArgValue), Arg.ArgType);
1475
36
      }
1476
1477
      // Call 'operator delete'.
1478
583
      EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs);
1479
583
    }
CGExprCXX.cpp:(anonymous namespace)::CallDeleteDuringNew<EnterNewDeleteCleanup(clang::CodeGen::CodeGenFunction&, clang::CXXNewExpr const*, clang::CodeGen::Address, llvm::Value*, clang::CharUnits, clang::CodeGen::CallArgList const&)::ConditionalCleanupTraits>::Emit(clang::CodeGen::CodeGenFunction&, clang::CodeGen::EHScopeStack::Cleanup::Flags)
Line
Count
Source
1434
6
    void Emit(CodeGenFunction &CGF, Flags flags) override {
1435
6
      const auto *FPT = OperatorDelete->getType()->castAs<FunctionProtoType>();
1436
6
      CallArgList DeleteArgs;
1437
1438
      // The first argument is always a void* (or C* for a destroying operator
1439
      // delete for class type C).
1440
6
      DeleteArgs.add(Traits::get(CGF, Ptr), FPT->getParamType(0));
1441
1442
      // Figure out what other parameters we should be implicitly passing.
1443
6
      UsualDeleteParams Params;
1444
6
      if (NumPlacementArgs) {
1445
        // A placement deallocation function is implicitly passed an alignment
1446
        // if the placement allocation function was, but is never passed a size.
1447
2
        Params.Alignment = PassAlignmentToPlacementDelete;
1448
4
      } else {
1449
        // For a non-placement new-expression, 'operator delete' can take a
1450
        // size and/or an alignment if it has the right parameters.
1451
4
        Params = getUsualDeleteParams(OperatorDelete);
1452
4
      }
1453
1454
6
      assert(!Params.DestroyingDelete &&
1455
6
             "should not call destroying delete in a new-expression");
1456
1457
      // The second argument can be a std::size_t (for non-placement delete).
1458
6
      if (Params.Size)
1459
0
        DeleteArgs.add(Traits::get(CGF, AllocSize),
1460
0
                       CGF.getContext().getSizeType());
1461
1462
      // The next (second or third) argument can be a std::align_val_t, which
1463
      // is an enum whose underlying type is std::size_t.
1464
      // FIXME: Use the right type as the parameter type. Note that in a call
1465
      // to operator delete(size_t, ...), we may not have it available.
1466
6
      if (Params.Alignment)
1467
0
        DeleteArgs.add(RValue::get(llvm::ConstantInt::get(
1468
0
                           CGF.SizeTy, AllocAlign.getQuantity())),
1469
0
                       CGF.getContext().getSizeType());
1470
1471
      // Pass the rest of the arguments, which must match exactly.
1472
10
      for (unsigned I = 0; I != NumPlacementArgs; 
++I4
) {
1473
4
        auto Arg = getPlacementArgs()[I];
1474
4
        DeleteArgs.add(Traits::get(CGF, Arg.ArgValue), Arg.ArgType);
1475
4
      }
1476
1477
      // Call 'operator delete'.
1478
6
      EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs);
1479
6
    }
1480
  };
1481
}
1482
1483
/// Enter a cleanup to call 'operator delete' if the initializer in a
1484
/// new-expression throws.
1485
static void EnterNewDeleteCleanup(CodeGenFunction &CGF,
1486
                                  const CXXNewExpr *E,
1487
                                  Address NewPtr,
1488
                                  llvm::Value *AllocSize,
1489
                                  CharUnits AllocAlign,
1490
835
                                  const CallArgList &NewArgs) {
1491
835
  unsigned NumNonPlacementArgs = E->passAlignment() ? 
240
:
1795
;
1492
1493
  // If we're not inside a conditional branch, then the cleanup will
1494
  // dominate and we can do the easier (and more efficient) thing.
1495
835
  if (!CGF.isInConditionalBranch()) {
1496
829
    struct DirectCleanupTraits {
1497
829
      typedef llvm::Value *ValueTy;
1498
829
      typedef RValue RValueTy;
1499
829
      static RValue get(CodeGenFunction &, ValueTy V) 
{ return RValue::get(V); }589
1500
829
      static RValue get(CodeGenFunction &, RValueTy V) 
{ return V; }36
1501
829
    };
1502
1503
829
    typedef CallDeleteDuringNew<DirectCleanupTraits> DirectCleanup;
1504
1505
829
    DirectCleanup *Cleanup = CGF.EHStack
1506
829
      .pushCleanupWithExtra<DirectCleanup>(EHCleanup,
1507
829
                                           E->getNumPlacementArgs(),
1508
829
                                           E->getOperatorDelete(),
1509
829
                                           NewPtr.getPointer(),
1510
829
                                           AllocSize,
1511
829
                                           E->passAlignment(),
1512
829
                                           AllocAlign);
1513
865
    for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; 
++I36
) {
1514
36
      auto &Arg = NewArgs[I + NumNonPlacementArgs];
1515
36
      Cleanup->setPlacementArg(I, Arg.getRValue(CGF), Arg.Ty);
1516
36
    }
1517
1518
829
    return;
1519
829
  }
1520
1521
  // Otherwise, we need to save all this stuff.
1522
6
  DominatingValue<RValue>::saved_type SavedNewPtr =
1523
6
    DominatingValue<RValue>::save(CGF, RValue::get(NewPtr.getPointer()));
1524
6
  DominatingValue<RValue>::saved_type SavedAllocSize =
1525
6
    DominatingValue<RValue>::save(CGF, RValue::get(AllocSize));
1526
1527
6
  struct ConditionalCleanupTraits {
1528
6
    typedef DominatingValue<RValue>::saved_type ValueTy;
1529
6
    typedef DominatingValue<RValue>::saved_type RValueTy;
1530
10
    static RValue get(CodeGenFunction &CGF, ValueTy V) {
1531
10
      return V.restore(CGF);
1532
10
    }
1533
6
  };
1534
6
  typedef CallDeleteDuringNew<ConditionalCleanupTraits> ConditionalCleanup;
1535
1536
6
  ConditionalCleanup *Cleanup = CGF.EHStack
1537
6
    .pushCleanupWithExtra<ConditionalCleanup>(EHCleanup,
1538
6
                                              E->getNumPlacementArgs(),
1539
6
                                              E->getOperatorDelete(),
1540
6
                                              SavedNewPtr,
1541
6
                                              SavedAllocSize,
1542
6
                                              E->passAlignment(),
1543
6
                                              AllocAlign);
1544
10
  for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; 
++I4
) {
1545
4
    auto &Arg = NewArgs[I + NumNonPlacementArgs];
1546
4
    Cleanup->setPlacementArg(
1547
4
        I, DominatingValue<RValue>::save(CGF, Arg.getRValue(CGF)), Arg.Ty);
1548
4
  }
1549
1550
6
  CGF.initFullExprCleanup();
1551
6
}
1552
1553
2.02k
llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
1554
  // The element type being allocated.
1555
2.02k
  QualType allocType = getContext().getBaseElementType(E->getAllocatedType());
1556
1557
  // 1. Build a call to the allocation function.
1558
2.02k
  FunctionDecl *allocator = E->getOperatorNew();
1559
1560
  // If there is a brace-initializer, cannot allocate fewer elements than inits.
1561
2.02k
  unsigned minElements = 0;
1562
2.02k
  if (E->isArray() && 
E->hasInitializer()342
) {
1563
155
    const InitListExpr *ILE = dyn_cast<InitListExpr>(E->getInitializer());
1564
155
    if (ILE && 
ILE->isStringLiteralInit()28
)
1565
8
      minElements =
1566
8
          cast<ConstantArrayType>(ILE->getType()->getAsArrayTypeUnsafe())
1567
8
              ->getSize().getZExtValue();
1568
147
    else if (ILE)
1569
20
      minElements = ILE->getNumInits();
1570
155
  }
1571
1572
2.02k
  llvm::Value *numElements = nullptr;
1573
2.02k
  llvm::Value *allocSizeWithoutCookie = nullptr;
1574
2.02k
  llvm::Value *allocSize =
1575
2.02k
    EmitCXXNewAllocSize(*this, E, minElements, numElements,
1576
2.02k
                        allocSizeWithoutCookie);
1577
2.02k
  CharUnits allocAlign = getContext().getPreferredTypeAlignInChars(allocType);
1578
1579
  // Emit the allocation call.  If the allocator is a global placement
1580
  // operator, just "inline" it directly.
1581
2.02k
  Address allocation = Address::invalid();
1582
2.02k
  CallArgList allocatorArgs;
1583
2.02k
  if (allocator->isReservedGlobalPlacementOperator()) {
1584
720
    assert(E->getNumPlacementArgs() == 1);
1585
0
    const Expr *arg = *E->placement_arguments().begin();
1586
1587
720
    LValueBaseInfo BaseInfo;
1588
720
    allocation = EmitPointerWithAlignment(arg, &BaseInfo);
1589
1590
    // The pointer expression will, in many cases, be an opaque void*.
1591
    // In these cases, discard the computed alignment and use the
1592
    // formal alignment of the allocated type.
1593
720
    if (BaseInfo.getAlignmentSource() != AlignmentSource::Decl)
1594
717
      allocation = Address(allocation.getPointer(), allocAlign);
1595
1596
    // Set up allocatorArgs for the call to operator delete if it's not
1597
    // the reserved global operator.
1598
720
    if (E->getOperatorDelete() &&
1599
720
        
!E->getOperatorDelete()->isReservedGlobalPlacementOperator()605
) {
1600
2
      allocatorArgs.add(RValue::get(allocSize), getContext().getSizeType());
1601
2
      allocatorArgs.add(RValue::get(allocation.getPointer()), arg->getType());
1602
2
    }
1603
1604
1.30k
  } else {
1605
1.30k
    const FunctionProtoType *allocatorType =
1606
1.30k
      allocator->getType()->castAs<FunctionProtoType>();
1607
1.30k
    unsigned ParamsToSkip = 0;
1608
1609
    // The allocation size is the first argument.
1610
1.30k
    QualType sizeType = getContext().getSizeType();
1611
1.30k
    allocatorArgs.add(RValue::get(allocSize), sizeType);
1612
1.30k
    ++ParamsToSkip;
1613
1614
1.30k
    if (allocSize != allocSizeWithoutCookie) {
1615
64
      CharUnits cookieAlign = getSizeAlign(); // FIXME: Ask the ABI.
1616
64
      allocAlign = std::max(allocAlign, cookieAlign);
1617
64
    }
1618
1619
    // The allocation alignment may be passed as the second argument.
1620
1.30k
    if (E->passAlignment()) {
1621
44
      QualType AlignValT = sizeType;
1622
44
      if (allocatorType->getNumParams() > 1) {
1623
36
        AlignValT = allocatorType->getParamType(1);
1624
36
        assert(getContext().hasSameUnqualifiedType(
1625
36
                   AlignValT->castAs<EnumType>()->getDecl()->getIntegerType(),
1626
36
                   sizeType) &&
1627
36
               "wrong type for alignment parameter");
1628
0
        ++ParamsToSkip;
1629
36
      } else {
1630
        // Corner case, passing alignment to 'operator new(size_t, ...)'.
1631
8
        assert(allocator->isVariadic() && "can't pass alignment to allocator");
1632
8
      }
1633
0
      allocatorArgs.add(
1634
44
          RValue::get(llvm::ConstantInt::get(SizeTy, allocAlign.getQuantity())),
1635
44
          AlignValT);
1636
44
    }
1637
1638
    // FIXME: Why do we not pass a CalleeDecl here?
1639
0
    EmitCallArgs(allocatorArgs, allocatorType, E->placement_arguments(),
1640
1.30k
                 /*AC*/AbstractCallee(), /*ParamsToSkip*/ParamsToSkip);
1641
1642
1.30k
    RValue RV =
1643
1.30k
      EmitNewDeleteCall(*this, allocator, allocatorType, allocatorArgs);
1644
1645
    // Set !heapallocsite metadata on the call to operator new.
1646
1.30k
    if (getDebugInfo())
1647
688
      if (auto *newCall = dyn_cast<llvm::CallBase>(RV.getScalarVal()))
1648
688
        getDebugInfo()->addHeapAllocSiteMetadata(newCall, allocType,
1649
688
                                                 E->getExprLoc());
1650
1651
    // If this was a call to a global replaceable allocation function that does
1652
    // not take an alignment argument, the allocator is known to produce
1653
    // storage that's suitably aligned for any object that fits, up to a known
1654
    // threshold. Otherwise assume it's suitably aligned for the allocated type.
1655
1.30k
    CharUnits allocationAlign = allocAlign;
1656
1.30k
    if (!E->passAlignment() &&
1657
1.30k
        
allocator->isReplaceableGlobalAllocationFunction()1.25k
) {
1658
1.16k
      unsigned AllocatorAlign = llvm::PowerOf2Floor(std::min<uint64_t>(
1659
1.16k
          Target.getNewAlign(), getContext().getTypeSize(allocType)));
1660
1.16k
      allocationAlign = std::max(
1661
1.16k
          allocationAlign, getContext().toCharUnitsFromBits(AllocatorAlign));
1662
1.16k
    }
1663
1664
1.30k
    allocation = Address(RV.getScalarVal(), allocationAlign);
1665
1.30k
  }
1666
1667
  // Emit a null check on the allocation result if the allocation
1668
  // function is allowed to return null (because it has a non-throwing
1669
  // exception spec or is the reserved placement new) and we have an
1670
  // interesting initializer will be running sanitizers on the initialization.
1671
2.02k
  bool nullCheck = E->shouldNullCheckAllocation() &&
1672
2.02k
                   
(26
!allocType.isPODType(getContext())26
||
E->hasInitializer()10
||
1673
26
                    
sanitizePerformTypeCheck()10
);
1674
1675
2.02k
  llvm::BasicBlock *nullCheckBB = nullptr;
1676
2.02k
  llvm::BasicBlock *contBB = nullptr;
1677
1678
  // The null-check means that the initializer is conditionally
1679
  // evaluated.
1680
2.02k
  ConditionalEvaluation conditional(*this);
1681
1682
2.02k
  if (nullCheck) {
1683
22
    conditional.begin(*this);
1684
1685
22
    nullCheckBB = Builder.GetInsertBlock();
1686
22
    llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull");
1687
22
    contBB = createBasicBlock("new.cont");
1688
1689
22
    llvm::Value *isNull =
1690
22
      Builder.CreateIsNull(allocation.getPointer(), "new.isnull");
1691
22
    Builder.CreateCondBr(isNull, contBB, notNullBB);
1692
22
    EmitBlock(notNullBB);
1693
22
  }
1694
1695
  // If there's an operator delete, enter a cleanup to call it if an
1696
  // exception is thrown.
1697
2.02k
  EHScopeStack::stable_iterator operatorDeleteCleanup;
1698
2.02k
  llvm::Instruction *cleanupDominator = nullptr;
1699
2.02k
  if (E->getOperatorDelete() &&
1700
2.02k
      
!E->getOperatorDelete()->isReservedGlobalPlacementOperator()1.43k
) {
1701
835
    EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocAlign,
1702
835
                          allocatorArgs);
1703
835
    operatorDeleteCleanup = EHStack.stable_begin();
1704
835
    cleanupDominator = Builder.CreateUnreachable();
1705
835
  }
1706
1707
2.02k
  assert((allocSize == allocSizeWithoutCookie) ==
1708
2.02k
         CalculateCookiePadding(*this, E).isZero());
1709
2.02k
  if (allocSize != allocSizeWithoutCookie) {
1710
64
    assert(E->isArray());
1711
0
    allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation,
1712
64
                                                       numElements,
1713
64
                                                       E, allocType);
1714
64
  }
1715
1716
0
  llvm::Type *elementTy = ConvertTypeForMem(allocType);
1717
2.02k
  Address result = Builder.CreateElementBitCast(allocation, elementTy);
1718
1719
  // Passing pointer through launder.invariant.group to avoid propagation of
1720
  // vptrs information which may be included in previous type.
1721
  // To not break LTO with different optimizations levels, we do it regardless
1722
  // of optimization level.
1723
2.02k
  if (CGM.getCodeGenOpts().StrictVTablePointers &&
1724
2.02k
      
allocator->isReservedGlobalPlacementOperator()32
)
1725
5
    result = Address(Builder.CreateLaunderInvariantGroup(result.getPointer()),
1726
5
                     result.getAlignment());
1727
1728
  // Emit sanitizer checks for pointer value now, so that in the case of an
1729
  // array it was checked only once and not at each constructor call. We may
1730
  // have already checked that the pointer is non-null.
1731
  // FIXME: If we have an array cookie and a potentially-throwing allocator,
1732
  // we'll null check the wrong pointer here.
1733
2.02k
  SanitizerSet SkippedChecks;
1734
2.02k
  SkippedChecks.set(SanitizerKind::Null, nullCheck);
1735
2.02k
  EmitTypeCheck(CodeGenFunction::TCK_ConstructorCall,
1736
2.02k
                E->getAllocatedTypeSourceInfo()->getTypeLoc().getBeginLoc(),
1737
2.02k
                result.getPointer(), allocType, result.getAlignment(),
1738
2.02k
                SkippedChecks, numElements);
1739
1740
2.02k
  EmitNewInitializer(*this, E, allocType, elementTy, result, numElements,
1741
2.02k
                     allocSizeWithoutCookie);
1742
2.02k
  if (E->isArray()) {
1743
    // NewPtr is a pointer to the base element type.  If we're
1744
    // allocating an array of arrays, we'll need to cast back to the
1745
    // array pointer type.
1746
342
    llvm::Type *resultType = ConvertTypeForMem(E->getType());
1747
342
    if (result.getType() != resultType)
1748
21
      result = Builder.CreateBitCast(result, resultType);
1749
342
  }
1750
1751
  // Deactivate the 'operator delete' cleanup if we finished
1752
  // initialization.
1753
2.02k
  if (operatorDeleteCleanup.isValid()) {
1754
835
    DeactivateCleanupBlock(operatorDeleteCleanup, cleanupDominator);
1755
835
    cleanupDominator->eraseFromParent();
1756
835
  }
1757
1758
2.02k
  llvm::Value *resultPtr = result.getPointer();
1759
2.02k
  if (nullCheck) {
1760
22
    conditional.end(*this);
1761
1762
22
    llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
1763
22
    EmitBlock(contBB);
1764
1765
22
    llvm::PHINode *PHI = Builder.CreatePHI(resultPtr->getType(), 2);
1766
22
    PHI->addIncoming(resultPtr, notNullBB);
1767
22
    PHI->addIncoming(llvm::Constant::getNullValue(resultPtr->getType()),
1768
22
                     nullCheckBB);
1769
1770
22
    resultPtr = PHI;
1771
22
  }
1772
1773
2.02k
  return resultPtr;
1774
2.02k
}
1775
1776
void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
1777
                                     llvm::Value *Ptr, QualType DeleteTy,
1778
                                     llvm::Value *NumElements,
1779
1.69k
                                     CharUnits CookieSize) {
1780
1.69k
  assert((!NumElements && CookieSize.isZero()) ||
1781
1.69k
         DeleteFD->getOverloadedOperator() == OO_Array_Delete);
1782
1783
0
  const auto *DeleteFTy = DeleteFD->getType()->castAs<FunctionProtoType>();
1784
1.69k
  CallArgList DeleteArgs;
1785
1786
1.69k
  auto Params = getUsualDeleteParams(DeleteFD);
1787
1.69k
  auto ParamTypeIt = DeleteFTy->param_type_begin();
1788
1789
  // Pass the pointer itself.
1790
1.69k
  QualType ArgTy = *ParamTypeIt++;
1791
1.69k
  llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
1792
1.69k
  DeleteArgs.add(RValue::get(DeletePtr), ArgTy);
1793
1794
  // Pass the std::destroying_delete tag if present.
1795
1.69k
  llvm::AllocaInst *DestroyingDeleteTag = nullptr;
1796
1.69k
  if (Params.DestroyingDelete) {
1797
30
    QualType DDTag = *ParamTypeIt++;
1798
30
    llvm::Type *Ty = getTypes().ConvertType(DDTag);
1799
30
    CharUnits Align = CGM.getNaturalTypeAlignment(DDTag);
1800
30
    DestroyingDeleteTag = CreateTempAlloca(Ty, "destroying.delete.tag");
1801
30
    DestroyingDeleteTag->setAlignment(Align.getAsAlign());
1802
30
    DeleteArgs.add(RValue::getAggregate(Address(DestroyingDeleteTag, Align)), DDTag);
1803
30
  }
1804
1805
  // Pass the size if the delete function has a size_t parameter.
1806
1.69k
  if (Params.Size) {
1807
84
    QualType SizeType = *ParamTypeIt++;
1808
84
    CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
1809
84
    llvm::Value *Size = llvm::ConstantInt::get(ConvertType(SizeType),
1810
84
                                               DeleteTypeSize.getQuantity());
1811
1812
    // For array new, multiply by the number of elements.
1813
84
    if (NumElements)
1814
23
      Size = Builder.CreateMul(Size, NumElements);
1815
1816
    // If there is a cookie, add the cookie size.
1817
84
    if (!CookieSize.isZero())
1818
23
      Size = Builder.CreateAdd(
1819
23
          Size, llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity()));
1820
1821
84
    DeleteArgs.add(RValue::get(Size), SizeType);
1822
84
  }
1823
1824
  // Pass the alignment if the delete function has an align_val_t parameter.
1825
1.69k
  if (Params.Alignment) {
1826
38
    QualType AlignValType = *ParamTypeIt++;
1827
38
    CharUnits DeleteTypeAlign =
1828
38
        getContext().toCharUnitsFromBits(getContext().getTypeAlignIfKnown(
1829
38
            DeleteTy, true /* NeedsPreferredAlignment */));
1830
38
    llvm::Value *Align = llvm::ConstantInt::get(ConvertType(AlignValType),
1831
38
                                                DeleteTypeAlign.getQuantity());
1832
38
    DeleteArgs.add(RValue::get(Align), AlignValType);
1833
38
  }
1834
1835
1.69k
  assert(ParamTypeIt == DeleteFTy->param_type_end() &&
1836
1.69k
         "unknown parameter to usual delete function");
1837
1838
  // Emit the call to delete.
1839
0
  EmitNewDeleteCall(*this, DeleteFD, DeleteFTy, DeleteArgs);
1840
1841
  // If call argument lowering didn't use the destroying_delete_t alloca,
1842
  // remove it again.
1843
1.69k
  if (DestroyingDeleteTag && 
DestroyingDeleteTag->use_empty()30
)
1844
10
    DestroyingDeleteTag->eraseFromParent();
1845
1.69k
}
1846
1847
namespace {
1848
  /// Calls the given 'operator delete' on a single object.
1849
  struct CallObjectDelete final : EHScopeStack::Cleanup {
1850
    llvm::Value *Ptr;
1851
    const FunctionDecl *OperatorDelete;
1852
    QualType ElementType;
1853
1854
    CallObjectDelete(llvm::Value *Ptr,
1855
                     const FunctionDecl *OperatorDelete,
1856
                     QualType ElementType)
1857
538
      : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
1858
1859
538
    void Emit(CodeGenFunction &CGF, Flags flags) override {
1860
538
      CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
1861
538
    }
1862
  };
1863
}
1864
1865
void
1866
CodeGenFunction::pushCallObjectDeleteCleanup(const FunctionDecl *OperatorDelete,
1867
                                             llvm::Value *CompletePtr,
1868
6
                                             QualType ElementType) {
1869
6
  EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup, CompletePtr,
1870
6
                                        OperatorDelete, ElementType);
1871
6
}
1872
1873
/// Emit the code for deleting a single object with a destroying operator
1874
/// delete. If the element type has a non-virtual destructor, Ptr has already
1875
/// been converted to the type of the parameter of 'operator delete'. Otherwise
1876
/// Ptr points to an object of the static type.
1877
static void EmitDestroyingObjectDelete(CodeGenFunction &CGF,
1878
                                       const CXXDeleteExpr *DE, Address Ptr,
1879
30
                                       QualType ElementType) {
1880
30
  auto *Dtor = ElementType->getAsCXXRecordDecl()->getDestructor();
1881
30
  if (Dtor && Dtor->isVirtual())
1882
12
    CGF.CGM.getCXXABI().emitVirtualObjectDelete(CGF, DE, Ptr, ElementType,
1883
12
                                                Dtor);
1884
18
  else
1885
18
    CGF.EmitDeleteCall(DE->getOperatorDelete(), Ptr.getPointer(), ElementType);
1886
30
}
1887
1888
/// Emit the code for deleting a single object.
1889
/// \return \c true if we started emitting UnconditionalDeleteBlock, \c false
1890
/// if not.
1891
static bool EmitObjectDelete(CodeGenFunction &CGF,
1892
                             const CXXDeleteExpr *DE,
1893
                             Address Ptr,
1894
                             QualType ElementType,
1895
597
                             llvm::BasicBlock *UnconditionalDeleteBlock) {
1896
  // C++11 [expr.delete]p3:
1897
  //   If the static type of the object to be deleted is different from its
1898
  //   dynamic type, the static type shall be a base class of the dynamic type
1899
  //   of the object to be deleted and the static type shall have a virtual
1900
  //   destructor or the behavior is undefined.
1901
597
  CGF.EmitTypeCheck(CodeGenFunction::TCK_MemberCall,
1902
597
                    DE->getExprLoc(), Ptr.getPointer(),
1903
597
                    ElementType);
1904
1905
597
  const FunctionDecl *OperatorDelete = DE->getOperatorDelete();
1906
597
  assert(!OperatorDelete->isDestroyingOperatorDelete());
1907
1908
  // Find the destructor for the type, if applicable.  If the
1909
  // destructor is virtual, we'll just emit the vcall and return.
1910
0
  const CXXDestructorDecl *Dtor = nullptr;
1911
597
  if (const RecordType *RT = ElementType->getAs<RecordType>()) {
1912
536
    CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1913
536
    if (RD->hasDefinition() && 
!RD->hasTrivialDestructor()534
) {
1914
426
      Dtor = RD->getDestructor();
1915
1916
426
      if (Dtor->isVirtual()) {
1917
67
        bool UseVirtualCall = true;
1918
67
        const Expr *Base = DE->getArgument();
1919
67
        if (auto *DevirtualizedDtor =
1920
67
                dyn_cast_or_null<const CXXDestructorDecl>(
1921
67
                    Dtor->getDevirtualizedMethod(
1922
67
                        Base, CGF.CGM.getLangOpts().AppleKext))) {
1923
2
          UseVirtualCall = false;
1924
2
          const CXXRecordDecl *DevirtualizedClass =
1925
2
              DevirtualizedDtor->getParent();
1926
2
          if (declaresSameEntity(getCXXRecord(Base), DevirtualizedClass)) {
1927
            // Devirtualized to the class of the base type (the type of the
1928
            // whole expression).
1929
2
            Dtor = DevirtualizedDtor;
1930
2
          } else {
1931
            // Devirtualized to some other type. Would need to cast the this
1932
            // pointer to that type but we don't have support for that yet, so
1933
            // do a virtual call. FIXME: handle the case where it is
1934
            // devirtualized to the derived type (the type of the inner
1935
            // expression) as in EmitCXXMemberOrOperatorMemberCallExpr.
1936
0
            UseVirtualCall = true;
1937
0
          }
1938
2
        }
1939
67
        if (UseVirtualCall) {
1940
65
          CGF.CGM.getCXXABI().emitVirtualObjectDelete(CGF, DE, Ptr, ElementType,
1941
65
                                                      Dtor);
1942
65
          return false;
1943
65
        }
1944
67
      }
1945
426
    }
1946
536
  }
1947
1948
  // Make sure that we call delete even if the dtor throws.
1949
  // This doesn't have to a conditional cleanup because we're going
1950
  // to pop it off in a second.
1951
532
  CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
1952
532
                                            Ptr.getPointer(),
1953
532
                                            OperatorDelete, ElementType);
1954
1955
532
  if (Dtor)
1956
361
    CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
1957
361
                              /*ForVirtualBase=*/false,
1958
361
                              /*Delegating=*/false,
1959
361
                              Ptr, ElementType);
1960
171
  else if (auto Lifetime = ElementType.getObjCLifetime()) {
1961
4
    switch (Lifetime) {
1962
0
    case Qualifiers::OCL_None:
1963
0
    case Qualifiers::OCL_ExplicitNone:
1964
0
    case Qualifiers::OCL_Autoreleasing:
1965
0
      break;
1966
1967
2
    case Qualifiers::OCL_Strong:
1968
2
      CGF.EmitARCDestroyStrong(Ptr, ARCPreciseLifetime);
1969
2
      break;
1970
1971
2
    case Qualifiers::OCL_Weak:
1972
2
      CGF.EmitARCDestroyWeak(Ptr);
1973
2
      break;
1974
4
    }
1975
4
  }
1976
1977
  // When optimizing for size, call 'operator delete' unconditionally.
1978
532
  if (CGF.CGM.getCodeGenOpts().OptimizeSize > 1) {
1979
7
    CGF.EmitBlock(UnconditionalDeleteBlock);
1980
7
    CGF.PopCleanupBlock();
1981
7
    return true;
1982
7
  }
1983
1984
525
  CGF.PopCleanupBlock();
1985
525
  return false;
1986
532
}
1987
1988
namespace {
1989
  /// Calls the given 'operator delete' on an array of objects.
1990
  struct CallArrayDelete final : EHScopeStack::Cleanup {
1991
    llvm::Value *Ptr;
1992
    const FunctionDecl *OperatorDelete;
1993
    llvm::Value *NumElements;
1994
    QualType ElementType;
1995
    CharUnits CookieSize;
1996
1997
    CallArrayDelete(llvm::Value *Ptr,
1998
                    const FunctionDecl *OperatorDelete,
1999
                    llvm::Value *NumElements,
2000
                    QualType ElementType,
2001
                    CharUnits CookieSize)
2002
      : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
2003
250
        ElementType(ElementType), CookieSize(CookieSize) {}
2004
2005
253
    void Emit(CodeGenFunction &CGF, Flags flags) override {
2006
253
      CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType, NumElements,
2007
253
                         CookieSize);
2008
253
    }
2009
  };
2010
}
2011
2012
/// Emit the code for deleting an array of objects.
2013
static void EmitArrayDelete(CodeGenFunction &CGF,
2014
                            const CXXDeleteExpr *E,
2015
                            Address deletedPtr,
2016
250
                            QualType elementType) {
2017
250
  llvm::Value *numElements = nullptr;
2018
250
  llvm::Value *allocatedPtr = nullptr;
2019
250
  CharUnits cookieSize;
2020
250
  CGF.CGM.getCXXABI().ReadArrayCookie(CGF, deletedPtr, E, elementType,
2021
250
                                      numElements, allocatedPtr, cookieSize);
2022
2023
250
  assert(allocatedPtr && "ReadArrayCookie didn't set allocated pointer");
2024
2025
  // Make sure that we call delete even if one of the dtors throws.
2026
0
  const FunctionDecl *operatorDelete = E->getOperatorDelete();
2027
250
  CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
2028
250
                                           allocatedPtr, operatorDelete,
2029
250
                                           numElements, elementType,
2030
250
                                           cookieSize);
2031
2032
  // Destroy the elements.
2033
250
  if (QualType::DestructionKind dtorKind = elementType.isDestructedType()) {
2034
43
    assert(numElements && "no element count for a type with a destructor!");
2035
2036
0
    CharUnits elementSize = CGF.getContext().getTypeSizeInChars(elementType);
2037
43
    CharUnits elementAlign =
2038
43
      deletedPtr.getAlignment().alignmentOfArrayElement(elementSize);
2039
2040
43
    llvm::Value *arrayBegin = deletedPtr.getPointer();
2041
43
    llvm::Value *arrayEnd = CGF.Builder.CreateInBoundsGEP(
2042
43
      deletedPtr.getElementType(), arrayBegin, numElements, "delete.end");
2043
2044
    // Note that it is legal to allocate a zero-length array, and we
2045
    // can never fold the check away because the length should always
2046
    // come from a cookie.
2047
43
    CGF.emitArrayDestroy(arrayBegin, arrayEnd, elementType, elementAlign,
2048
43
                         CGF.getDestroyer(dtorKind),
2049
43
                         /*checkZeroLength*/ true,
2050
43
                         CGF.needsEHCleanup(dtorKind));
2051
43
  }
2052
2053
  // Pop the cleanup block.
2054
0
  CGF.PopCleanupBlock();
2055
250
}
2056
2057
877
void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
2058
877
  const Expr *Arg = E->getArgument();
2059
877
  Address Ptr = EmitPointerWithAlignment(Arg);
2060
2061
  // Null check the pointer.
2062
  //
2063
  // We could avoid this null check if we can determine that the object
2064
  // destruction is trivial and doesn't require an array cookie; we can
2065
  // unconditionally perform the operator delete call in that case. For now, we
2066
  // assume that deleted pointers are null rarely enough that it's better to
2067
  // keep the branch. This might be worth revisiting for a -O0 code size win.
2068
877
  llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
2069
877
  llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
2070
2071
877
  llvm::Value *IsNull = Builder.CreateIsNull(Ptr.getPointer(), "isnull");
2072
2073
877
  Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
2074
877
  EmitBlock(DeleteNotNull);
2075
2076
877
  QualType DeleteTy = E->getDestroyedType();
2077
2078
  // A destroying operator delete overrides the entire operation of the
2079
  // delete expression.
2080
877
  if (E->getOperatorDelete()->isDestroyingOperatorDelete()) {
2081
30
    EmitDestroyingObjectDelete(*this, E, Ptr, DeleteTy);
2082
30
    EmitBlock(DeleteEnd);
2083
30
    return;
2084
30
  }
2085
2086
  // We might be deleting a pointer to array.  If so, GEP down to the
2087
  // first non-array element.
2088
  // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
2089
847
  if (DeleteTy->isConstantArrayType()) {
2090
10
    llvm::Value *Zero = Builder.getInt32(0);
2091
10
    SmallVector<llvm::Value*,8> GEP;
2092
2093
10
    GEP.push_back(Zero); // point at the outermost array
2094
2095
    // For each layer of array type we're pointing at:
2096
22
    while (const ConstantArrayType *Arr
2097
12
             = getContext().getAsConstantArrayType(DeleteTy)) {
2098
      // 1. Unpeel the array type.
2099
12
      DeleteTy = Arr->getElementType();
2100
2101
      // 2. GEP to the first element of the array.
2102
12
      GEP.push_back(Zero);
2103
12
    }
2104
2105
10
    Ptr = Address(Builder.CreateInBoundsGEP(Ptr.getElementType(),
2106
10
                                            Ptr.getPointer(), GEP, "del.first"),
2107
10
                  Ptr.getAlignment());
2108
10
  }
2109
2110
847
  assert(ConvertTypeForMem(DeleteTy) == Ptr.getElementType());
2111
2112
847
  if (E->isArrayForm()) {
2113
250
    EmitArrayDelete(*this, E, Ptr, DeleteTy);
2114
250
    EmitBlock(DeleteEnd);
2115
597
  } else {
2116
597
    if (!EmitObjectDelete(*this, E, Ptr, DeleteTy, DeleteEnd))
2117
590
      EmitBlock(DeleteEnd);
2118
597
  }
2119
847
}
2120
2121
52
static bool isGLValueFromPointerDeref(const Expr *E) {
2122
52
  E = E->IgnoreParens();
2123
2124
52
  if (const auto *CE = dyn_cast<CastExpr>(E)) {
2125
6
    if (!CE->getSubExpr()->isGLValue())
2126
0
      return false;
2127
6
    return isGLValueFromPointerDeref(CE->getSubExpr());
2128
6
  }
2129
2130
46
  if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
2131
4
    return isGLValueFromPointerDeref(OVE->getSourceExpr());
2132
2133
42
  if (const auto *BO = dyn_cast<BinaryOperator>(E))
2134
1
    if (BO->getOpcode() == BO_Comma)
2135
1
      return isGLValueFromPointerDeref(BO->getRHS());
2136
2137
41
  if (const auto *ACO = dyn_cast<AbstractConditionalOperator>(E))
2138
7
    return isGLValueFromPointerDeref(ACO->getTrueExpr()) ||
2139
7
           
isGLValueFromPointerDeref(ACO->getFalseExpr())3
;
2140
2141
  // C++11 [expr.sub]p1:
2142
  //   The expression E1[E2] is identical (by definition) to *((E1)+(E2))
2143
34
  if (isa<ArraySubscriptExpr>(E))
2144
2
    return true;
2145
2146
32
  if (const auto *UO = dyn_cast<UnaryOperator>(E))
2147
19
    if (UO->getOpcode() == UO_Deref)
2148
19
      return true;
2149
2150
13
  return false;
2151
32
}
2152
2153
static llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF, const Expr *E,
2154
31
                                         llvm::Type *StdTypeInfoPtrTy) {
2155
  // Get the vtable pointer.
2156
31
  Address ThisPtr = CGF.EmitLValue(E).getAddress(CGF);
2157
2158
31
  QualType SrcRecordTy = E->getType();
2159
2160
  // C++ [class.cdtor]p4:
2161
  //   If the operand of typeid refers to the object under construction or
2162
  //   destruction and the static type of the operand is neither the constructor
2163
  //   or destructor’s class nor one of its bases, the behavior is undefined.
2164
31
  CGF.EmitTypeCheck(CodeGenFunction::TCK_DynamicOperation, E->getExprLoc(),
2165
31
                    ThisPtr.getPointer(), SrcRecordTy);
2166
2167
  // C++ [expr.typeid]p2:
2168
  //   If the glvalue expression is obtained by applying the unary * operator to
2169
  //   a pointer and the pointer is a null pointer value, the typeid expression
2170
  //   throws the std::bad_typeid exception.
2171
  //
2172
  // However, this paragraph's intent is not clear.  We choose a very generous
2173
  // interpretation which implores us to consider comma operators, conditional
2174
  // operators, parentheses and other such constructs.
2175
31
  if (CGF.CGM.getCXXABI().shouldTypeidBeNullChecked(
2176
31
          isGLValueFromPointerDeref(E), SrcRecordTy)) {
2177
20
    llvm::BasicBlock *BadTypeidBlock =
2178
20
        CGF.createBasicBlock("typeid.bad_typeid");
2179
20
    llvm::BasicBlock *EndBlock = CGF.createBasicBlock("typeid.end");
2180
2181
20
    llvm::Value *IsNull = CGF.Builder.CreateIsNull(ThisPtr.getPointer());
2182
20
    CGF.Builder.CreateCondBr(IsNull, BadTypeidBlock, EndBlock);
2183
2184
20
    CGF.EmitBlock(BadTypeidBlock);
2185
20
    CGF.CGM.getCXXABI().EmitBadTypeidCall(CGF);
2186
20
    CGF.EmitBlock(EndBlock);
2187
20
  }
2188
2189
31
  return CGF.CGM.getCXXABI().EmitTypeid(CGF, SrcRecordTy, ThisPtr,
2190
31
                                        StdTypeInfoPtrTy);
2191
31
}
2192
2193
356
llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
2194
356
  llvm::Type *StdTypeInfoPtrTy =
2195
356
    ConvertType(E->getType())->getPointerTo();
2196
2197
356
  if (E->isTypeOperand()) {
2198
284
    llvm::Constant *TypeInfo =
2199
284
        CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand(getContext()));
2200
284
    return Builder.CreateBitCast(TypeInfo, StdTypeInfoPtrTy);
2201
284
  }
2202
2203
  // C++ [expr.typeid]p2:
2204
  //   When typeid is applied to a glvalue expression whose type is a
2205
  //   polymorphic class type, the result refers to a std::type_info object
2206
  //   representing the type of the most derived object (that is, the dynamic
2207
  //   type) to which the glvalue refers.
2208
  // If the operand is already most derived object, no need to look up vtable.
2209
72
  if (E->isPotentiallyEvaluated() && 
!E->isMostDerived(getContext())33
)
2210
31
    return EmitTypeidFromVTable(*this, E->getExprOperand(),
2211
31
                                StdTypeInfoPtrTy);
2212
2213
41
  QualType OperandTy = E->getExprOperand()->getType();
2214
41
  return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(OperandTy),
2215
41
                               StdTypeInfoPtrTy);
2216
72
}
2217
2218
static llvm::Value *EmitDynamicCastToNull(CodeGenFunction &CGF,
2219
2
                                          QualType DestTy) {
2220
2
  llvm::Type *DestLTy = CGF.ConvertType(DestTy);
2221
2
  if (DestTy->isPointerType())
2222
1
    return llvm::Constant::getNullValue(DestLTy);
2223
2224
  /// C++ [expr.dynamic.cast]p9:
2225
  ///   A failed cast to reference type throws std::bad_cast
2226
1
  if (!CGF.CGM.getCXXABI().EmitBadCastCall(CGF))
2227
0
    return nullptr;
2228
2229
1
  CGF.EmitBlock(CGF.createBasicBlock("dynamic_cast.end"));
2230
1
  return llvm::UndefValue::get(DestLTy);
2231
1
}
2232
2233
llvm::Value *CodeGenFunction::EmitDynamicCast(Address ThisAddr,
2234
77
                                              const CXXDynamicCastExpr *DCE) {
2235
77
  CGM.EmitExplicitCastExprType(DCE, this);
2236
77
  QualType DestTy = DCE->getTypeAsWritten();
2237
2238
77
  QualType SrcTy = DCE->getSubExpr()->getType();
2239
2240
  // C++ [expr.dynamic.cast]p7:
2241
  //   If T is "pointer to cv void," then the result is a pointer to the most
2242
  //   derived object pointed to by v.
2243
77
  const PointerType *DestPTy = DestTy->getAs<PointerType>();
2244
2245
77
  bool isDynamicCastToVoid;
2246
77
  QualType SrcRecordTy;
2247
77
  QualType DestRecordTy;
2248
77
  if (DestPTy) {
2249
64
    isDynamicCastToVoid = DestPTy->getPointeeType()->isVoidType();
2250
64
    SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType();
2251
64
    DestRecordTy = DestPTy->getPointeeType();
2252
64
  } else {
2253
13
    isDynamicCastToVoid = false;
2254
13
    SrcRecordTy = SrcTy;
2255
13
    DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType();
2256
13
  }
2257
2258
  // C++ [class.cdtor]p5:
2259
  //   If the operand of the dynamic_cast refers to the object under
2260
  //   construction or destruction and the static type of the operand is not a
2261
  //   pointer to or object of the constructor or destructor’s own class or one
2262
  //   of its bases, the dynamic_cast results in undefined behavior.
2263
77
  EmitTypeCheck(TCK_DynamicOperation, DCE->getExprLoc(), ThisAddr.getPointer(),
2264
77
                SrcRecordTy);
2265
2266
77
  if (DCE->isAlwaysNull())
2267
2
    if (llvm::Value *T = EmitDynamicCastToNull(*this, DestTy))
2268
2
      return T;
2269
2270
75
  assert(SrcRecordTy->isRecordType() && "source type must be a record type!");
2271
2272
  // C++ [expr.dynamic.cast]p4:
2273
  //   If the value of v is a null pointer value in the pointer case, the result
2274
  //   is the null pointer value of type T.
2275
0
  bool ShouldNullCheckSrcValue =
2276
75
      CGM.getCXXABI().shouldDynamicCastCallBeNullChecked(SrcTy->isPointerType(),
2277
75
                                                         SrcRecordTy);
2278
2279
75
  llvm::BasicBlock *CastNull = nullptr;
2280
75
  llvm::BasicBlock *CastNotNull = nullptr;
2281
75
  llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end");
2282
2283
75
  if (ShouldNullCheckSrcValue) {
2284
59
    CastNull = createBasicBlock("dynamic_cast.null");
2285
59
    CastNotNull = createBasicBlock("dynamic_cast.notnull");
2286
2287
59
    llvm::Value *IsNull = Builder.CreateIsNull(ThisAddr.getPointer());
2288
59
    Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
2289
59
    EmitBlock(CastNotNull);
2290
59
  }
2291
2292
75
  llvm::Value *Value;
2293
75
  if (isDynamicCastToVoid) {
2294
6
    Value = CGM.getCXXABI().EmitDynamicCastToVoid(*this, ThisAddr, SrcRecordTy,
2295
6
                                                  DestTy);
2296
69
  } else {
2297
69
    assert(DestRecordTy->isRecordType() &&
2298
69
           "destination type must be a record type!");
2299
0
    Value = CGM.getCXXABI().EmitDynamicCastCall(*this, ThisAddr, SrcRecordTy,
2300
69
                                                DestTy, DestRecordTy, CastEnd);
2301
69
    CastNotNull = Builder.GetInsertBlock();
2302
69
  }
2303
2304
75
  if (ShouldNullCheckSrcValue) {
2305
59
    EmitBranch(CastEnd);
2306
2307
59
    EmitBlock(CastNull);
2308
59
    EmitBranch(CastEnd);
2309
59
  }
2310
2311
75
  EmitBlock(CastEnd);
2312
2313
75
  if (ShouldNullCheckSrcValue) {
2314
59
    llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
2315
59
    PHI->addIncoming(Value, CastNotNull);
2316
59
    PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
2317
2318
59
    Value = PHI;
2319
59
  }
2320
2321
75
  return Value;
2322
77
}