Coverage Report

Created: 2022-01-18 06:27

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