Coverage Report

Created: 2020-02-25 14:32

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