Coverage Report

Created: 2020-09-15 12:33

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/CodeGen/CGCleanup.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- CGCleanup.cpp - Bookkeeping and code emission for cleanups -------===//
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 file contains code dealing with the IR generation for cleanups
10
// and related information.
11
//
12
// A "cleanup" is a piece of code which needs to be executed whenever
13
// control transfers out of a particular scope.  This can be
14
// conditionalized to occur only on exceptional control flow, only on
15
// normal control flow, or both.
16
//
17
//===----------------------------------------------------------------------===//
18
19
#include "CGCleanup.h"
20
#include "CodeGenFunction.h"
21
#include "llvm/Support/SaveAndRestore.h"
22
23
using namespace clang;
24
using namespace CodeGen;
25
26
0
bool DominatingValue<RValue>::saved_type::needsSaving(RValue rv) {
27
0
  if (rv.isScalar())
28
0
    return DominatingLLVMValue::needsSaving(rv.getScalarVal());
29
0
  if (rv.isAggregate())
30
0
    return DominatingLLVMValue::needsSaving(rv.getAggregatePointer());
31
0
  return true;
32
0
}
33
34
DominatingValue<RValue>::saved_type
35
16
DominatingValue<RValue>::saved_type::save(CodeGenFunction &CGF, RValue rv) {
36
16
  if (rv.isScalar()) {
37
16
    llvm::Value *V = rv.getScalarVal();
38
16
39
    // These automatically dominate and don't need to be saved.
40
16
    if (!DominatingLLVMValue::needsSaving(V))
41
10
      return saved_type(V, ScalarLiteral);
42
6
43
    // Everything else needs an alloca.
44
6
    Address addr =
45
6
      CGF.CreateDefaultAlignTempAlloca(V->getType(), "saved-rvalue");
46
6
    CGF.Builder.CreateStore(V, addr);
47
6
    return saved_type(addr.getPointer(), ScalarAddress);
48
6
  }
49
0
50
0
  if (rv.isComplex()) {
51
0
    CodeGenFunction::ComplexPairTy V = rv.getComplexVal();
52
0
    llvm::Type *ComplexTy =
53
0
        llvm::StructType::get(V.first->getType(), V.second->getType());
54
0
    Address addr = CGF.CreateDefaultAlignTempAlloca(ComplexTy, "saved-complex");
55
0
    CGF.Builder.CreateStore(V.first, CGF.Builder.CreateStructGEP(addr, 0));
56
0
    CGF.Builder.CreateStore(V.second, CGF.Builder.CreateStructGEP(addr, 1));
57
0
    return saved_type(addr.getPointer(), ComplexAddress);
58
0
  }
59
0
60
0
  assert(rv.isAggregate());
61
0
  Address V = rv.getAggregateAddress(); // TODO: volatile?
62
0
  if (!DominatingLLVMValue::needsSaving(V.getPointer()))
63
0
    return saved_type(V.getPointer(), AggregateLiteral,
64
0
                      V.getAlignment().getQuantity());
65
0
66
0
  Address addr =
67
0
    CGF.CreateTempAlloca(V.getType(), CGF.getPointerAlign(), "saved-rvalue");
68
0
  CGF.Builder.CreateStore(V.getPointer(), addr);
69
0
  return saved_type(addr.getPointer(), AggregateAddress,
70
0
                    V.getAlignment().getQuantity());
71
0
}
72
73
/// Given a saved r-value produced by SaveRValue, perform the code
74
/// necessary to restore it to usability at the current insertion
75
/// point.
76
10
RValue DominatingValue<RValue>::saved_type::restore(CodeGenFunction &CGF) {
77
6
  auto getSavingAddress = [&](llvm::Value *value) {
78
6
    auto alignment = cast<llvm::AllocaInst>(value)->getAlignment();
79
6
    return Address(value, CharUnits::fromQuantity(alignment));
80
6
  };
81
10
  switch (K) {
82
4
  case ScalarLiteral:
83
4
    return RValue::get(Value);
84
6
  case ScalarAddress:
85
6
    return RValue::get(CGF.Builder.CreateLoad(getSavingAddress(Value)));
86
0
  case AggregateLiteral:
87
0
    return RValue::getAggregate(Address(Value, CharUnits::fromQuantity(Align)));
88
0
  case AggregateAddress: {
89
0
    auto addr = CGF.Builder.CreateLoad(getSavingAddress(Value));
90
0
    return RValue::getAggregate(Address(addr, CharUnits::fromQuantity(Align)));
91
0
  }
92
0
  case ComplexAddress: {
93
0
    Address address = getSavingAddress(Value);
94
0
    llvm::Value *real =
95
0
        CGF.Builder.CreateLoad(CGF.Builder.CreateStructGEP(address, 0));
96
0
    llvm::Value *imag =
97
0
        CGF.Builder.CreateLoad(CGF.Builder.CreateStructGEP(address, 1));
98
0
    return RValue::getComplex(real, imag);
99
0
  }
100
0
  }
101
0
102
0
  llvm_unreachable("bad saved r-value kind");
103
0
}
104
105
/// Push an entry of the given size onto this protected-scope stack.
106
161k
char *EHScopeStack::allocate(size_t Size) {
107
161k
  Size = llvm::alignTo(Size, ScopeStackAlignment);
108
161k
  if (!StartOfBuffer) {
109
90.7k
    unsigned Capacity = 1024;
110
90.7k
    while (Capacity < Size) 
Capacity *= 20
;
111
90.7k
    StartOfBuffer = new char[Capacity];
112
90.7k
    StartOfData = EndOfBuffer = StartOfBuffer + Capacity;
113
70.4k
  } else if (static_cast<size_t>(StartOfData - StartOfBuffer) < Size) {
114
115
    unsigned CurrentCapacity = EndOfBuffer - StartOfBuffer;
115
115
    unsigned UsedCapacity = CurrentCapacity - (StartOfData - StartOfBuffer);
116
115
117
115
    unsigned NewCapacity = CurrentCapacity;
118
115
    do {
119
115
      NewCapacity *= 2;
120
115
    } while (NewCapacity < UsedCapacity + Size);
121
115
122
115
    char *NewStartOfBuffer = new char[NewCapacity];
123
115
    char *NewEndOfBuffer = NewStartOfBuffer + NewCapacity;
124
115
    char *NewStartOfData = NewEndOfBuffer - UsedCapacity;
125
115
    memcpy(NewStartOfData, StartOfData, UsedCapacity);
126
115
    delete [] StartOfBuffer;
127
115
    StartOfBuffer = NewStartOfBuffer;
128
115
    EndOfBuffer = NewEndOfBuffer;
129
115
    StartOfData = NewStartOfData;
130
115
  }
131
161k
132
161k
  assert(StartOfBuffer + Size <= StartOfData);
133
161k
  StartOfData -= Size;
134
161k
  return StartOfData;
135
161k
}
136
137
161k
void EHScopeStack::deallocate(size_t Size) {
138
161k
  StartOfData += llvm::alignTo(Size, ScopeStackAlignment);
139
161k
}
140
141
bool EHScopeStack::containsOnlyLifetimeMarkers(
142
8.00k
    EHScopeStack::stable_iterator Old) const {
143
11.3k
  for (EHScopeStack::iterator it = begin(); stabilize(it) != Old; 
it++3.36k
) {
144
8.69k
    EHCleanupScope *cleanup = dyn_cast<EHCleanupScope>(&*it);
145
8.69k
    if (!cleanup || !cleanup->isLifetimeMarker())
146
5.32k
      return false;
147
8.69k
  }
148
8.00k
149
2.67k
  return true;
150
8.00k
}
151
152
253k
bool EHScopeStack::requiresLandingPad() const {
153
261k
  for (stable_iterator si = getInnermostEHScope(); si != stable_end(); ) {
154
    // Skip lifetime markers.
155
103k
    if (auto *cleanup = dyn_cast<EHCleanupScope>(&*find(si)))
156
73.0k
      if (cleanup->isLifetimeMarker()) {
157
8.45k
        si = cleanup->getEnclosingEHScope();
158
8.45k
        continue;
159
8.45k
      }
160
94.9k
    return true;
161
94.9k
  }
162
253k
163
158k
  return false;
164
253k
}
165
166
EHScopeStack::stable_iterator
167
153k
EHScopeStack::getInnermostActiveNormalCleanup() const {
168
153k
  for (stable_iterator si = getInnermostNormalCleanup(), se = stable_end();
169
153k
         si != se; ) {
170
9.51k
    EHCleanupScope &cleanup = cast<EHCleanupScope>(*find(si));
171
9.51k
    if (cleanup.isActive()) return si;
172
0
    si = cleanup.getEnclosingNormalCleanup();
173
0
  }
174
143k
  return stable_end();
175
153k
}
176
177
178
46.7k
void *EHScopeStack::pushCleanup(CleanupKind Kind, size_t Size) {
179
46.7k
  char *Buffer = allocate(EHCleanupScope::getSizeForCleanupSize(Size));
180
46.7k
  bool IsNormalCleanup = Kind & NormalCleanup;
181
46.7k
  bool IsEHCleanup = Kind & EHCleanup;
182
46.7k
  bool IsLifetimeMarker = Kind & LifetimeMarker;
183
46.7k
  EHCleanupScope *Scope =
184
46.7k
    new (Buffer) EHCleanupScope(IsNormalCleanup,
185
46.7k
                                IsEHCleanup,
186
46.7k
                                Size,
187
46.7k
                                BranchFixups.size(),
188
46.7k
                                InnermostNormalCleanup,
189
46.7k
                                InnermostEHScope);
190
46.7k
  if (IsNormalCleanup)
191
40.6k
    InnermostNormalCleanup = stable_begin();
192
46.7k
  if (IsEHCleanup)
193
42.7k
    InnermostEHScope = stable_begin();
194
46.7k
  if (IsLifetimeMarker)
195
5.67k
    Scope->setLifetimeMarker();
196
46.7k
197
46.7k
  return Scope->getCleanupBuffer();
198
46.7k
}
199
200
46.7k
void EHScopeStack::popCleanup() {
201
46.7k
  assert(!empty() && "popping exception stack when not empty");
202
46.7k
203
46.7k
  assert(isa<EHCleanupScope>(*begin()));
204
46.7k
  EHCleanupScope &Cleanup = cast<EHCleanupScope>(*begin());
205
46.7k
  InnermostNormalCleanup = Cleanup.getEnclosingNormalCleanup();
206
46.7k
  InnermostEHScope = Cleanup.getEnclosingEHScope();
207
46.7k
  deallocate(Cleanup.getAllocatedSize());
208
46.7k
209
  // Destroy the cleanup.
210
46.7k
  Cleanup.Destroy();
211
46.7k
212
  // Check whether we can shrink the branch-fixups stack.
213
46.7k
  if (!BranchFixups.empty()) {
214
    // If we no longer have any normal cleanups, all the fixups are
215
    // complete.
216
11
    if (!hasNormalCleanups())
217
0
      BranchFixups.clear();
218
11
219
    // Otherwise we can still trim out unnecessary nulls.
220
11
    else
221
11
      popNullFixups();
222
11
  }
223
46.7k
}
224
225
89
EHFilterScope *EHScopeStack::pushFilter(unsigned numFilters) {
226
89
  assert(getInnermostEHScope() == stable_end());
227
89
  char *buffer = allocate(EHFilterScope::getSizeForNumFilters(numFilters));
228
89
  EHFilterScope *filter = new (buffer) EHFilterScope(numFilters);
229
89
  InnermostEHScope = stable_begin();
230
89
  return filter;
231
89
}
232
233
89
void EHScopeStack::popFilter() {
234
89
  assert(!empty() && "popping exception stack when not empty");
235
89
236
89
  EHFilterScope &filter = cast<EHFilterScope>(*begin());
237
89
  deallocate(EHFilterScope::getSizeForNumFilters(filter.getNumFilters()));
238
89
239
89
  InnermostEHScope = filter.getEnclosingEHScope();
240
89
}
241
242
599
EHCatchScope *EHScopeStack::pushCatch(unsigned numHandlers) {
243
599
  char *buffer = allocate(EHCatchScope::getSizeForNumHandlers(numHandlers));
244
599
  EHCatchScope *scope =
245
599
    new (buffer) EHCatchScope(numHandlers, InnermostEHScope);
246
599
  InnermostEHScope = stable_begin();
247
599
  return scope;
248
599
}
249
250
113k
void EHScopeStack::pushTerminate() {
251
113k
  char *Buffer = allocate(EHTerminateScope::getSize());
252
113k
  new (Buffer) EHTerminateScope(InnermostEHScope);
253
113k
  InnermostEHScope = stable_begin();
254
113k
}
255
256
/// Remove any 'null' fixups on the stack.  However, we can't pop more
257
/// fixups than the fixup depth on the innermost normal cleanup, or
258
/// else fixups that we try to add to that cleanup will end up in the
259
/// wrong place.  We *could* try to shrink fixup depths, but that's
260
/// actually a lot of work for little benefit.
261
16
void EHScopeStack::popNullFixups() {
262
  // We expect this to only be called when there's still an innermost
263
  // normal cleanup;  otherwise there really shouldn't be any fixups.
264
16
  assert(hasNormalCleanups());
265
16
266
16
  EHScopeStack::iterator it = find(InnermostNormalCleanup);
267
16
  unsigned MinSize = cast<EHCleanupScope>(*it).getFixupDepth();
268
16
  assert(BranchFixups.size() >= MinSize && "fixup stack out of order");
269
16
270
3.02k
  while (BranchFixups.size() > MinSize &&
271
3.01k
         BranchFixups.back().Destination == nullptr)
272
3.00k
    BranchFixups.pop_back();
273
16
}
274
275
262
Address CodeGenFunction::createCleanupActiveFlag() {
276
  // Create a variable to decide whether the cleanup needs to be run.
277
262
  Address active = CreateTempAllocaWithoutCast(
278
262
      Builder.getInt1Ty(), CharUnits::One(), "cleanup.cond");
279
262
280
  // Initialize it to false at a site that's guaranteed to be run
281
  // before each evaluation.
282
262
  setBeforeOutermostConditional(Builder.getFalse(), active);
283
262
284
  // Initialize it to true at the current location.
285
262
  Builder.CreateStore(Builder.getTrue(), active);
286
262
287
262
  return active;
288
262
}
289
290
273
void CodeGenFunction::initFullExprCleanupWithFlag(Address ActiveFlag) {
291
  // Set that as the active flag in the cleanup.
292
273
  EHCleanupScope &cleanup = cast<EHCleanupScope>(*EHStack.begin());
293
273
  assert(!cleanup.hasActiveFlag() && "cleanup already has active flag?");
294
273
  cleanup.setActiveFlag(ActiveFlag);
295
273
296
273
  if (cleanup.isNormalCleanup()) 
cleanup.setTestFlagInNormalCleanup()235
;
297
273
  if (cleanup.isEHCleanup()) 
cleanup.setTestFlagInEHCleanup()247
;
298
273
}
299
300
0
void EHScopeStack::Cleanup::anchor() {}
301
302
static void createStoreInstBefore(llvm::Value *value, Address addr,
303
5.50k
                                  llvm::Instruction *beforeInst) {
304
5.50k
  auto store = new llvm::StoreInst(value, addr.getPointer(), beforeInst);
305
5.50k
  store->setAlignment(addr.getAlignment().getAsAlign());
306
5.50k
}
307
308
static llvm::LoadInst *createLoadInstBefore(Address addr, const Twine &name,
309
216
                                            llvm::Instruction *beforeInst) {
310
216
  return new llvm::LoadInst(addr.getElementType(), addr.getPointer(), name,
311
216
                            false, addr.getAlignment().getAsAlign(),
312
216
                            beforeInst);
313
216
}
314
315
/// All the branch fixups on the EH stack have propagated out past the
316
/// outermost normal cleanup; resolve them all by adding cases to the
317
/// given switch instruction.
318
static void ResolveAllBranchFixups(CodeGenFunction &CGF,
319
                                   llvm::SwitchInst *Switch,
320
4
                                   llvm::BasicBlock *CleanupEntry) {
321
4
  llvm::SmallPtrSet<llvm::BasicBlock*, 4> CasesAdded;
322
4
323
8
  for (unsigned I = 0, E = CGF.EHStack.getNumBranchFixups(); I != E; 
++I4
) {
324
    // Skip this fixup if its destination isn't set.
325
4
    BranchFixup &Fixup = CGF.EHStack.getBranchFixup(I);
326
4
    if (Fixup.Destination == nullptr) 
continue0
;
327
4
328
    // If there isn't an OptimisticBranchBlock, then InitialBranch is
329
    // still pointing directly to its destination; forward it to the
330
    // appropriate cleanup entry.  This is required in the specific
331
    // case of
332
    //   { std::string s; goto lbl; }
333
    //   lbl:
334
    // i.e. where there's an unresolved fixup inside a single cleanup
335
    // entry which we're currently popping.
336
4
    if (Fixup.OptimisticBranchBlock == nullptr) {
337
2
      createStoreInstBefore(CGF.Builder.getInt32(Fixup.DestinationIndex),
338
2
                            CGF.getNormalCleanupDestSlot(),
339
2
                            Fixup.InitialBranch);
340
2
      Fixup.InitialBranch->setSuccessor(0, CleanupEntry);
341
2
    }
342
4
343
    // Don't add this case to the switch statement twice.
344
4
    if (!CasesAdded.insert(Fixup.Destination).second)
345
0
      continue;
346
4
347
4
    Switch->addCase(CGF.Builder.getInt32(Fixup.DestinationIndex),
348
4
                    Fixup.Destination);
349
4
  }
350
4
351
4
  CGF.EHStack.clearFixups();
352
4
}
353
354
/// Transitions the terminator of the given exit-block of a cleanup to
355
/// be a cleanup switch.
356
static llvm::SwitchInst *TransitionToCleanupSwitch(CodeGenFunction &CGF,
357
4
                                                   llvm::BasicBlock *Block) {
358
  // If it's a branch, turn it into a switch whose default
359
  // destination is its original target.
360
4
  llvm::Instruction *Term = Block->getTerminator();
361
4
  assert(Term && "can't transition block without terminator");
362
4
363
4
  if (llvm::BranchInst *Br = dyn_cast<llvm::BranchInst>(Term)) {
364
4
    assert(Br->isUnconditional());
365
4
    auto Load = createLoadInstBefore(CGF.getNormalCleanupDestSlot(),
366
4
                                     "cleanup.dest", Term);
367
4
    llvm::SwitchInst *Switch =
368
4
      llvm::SwitchInst::Create(Load, Br->getSuccessor(0), 4, Block);
369
4
    Br->eraseFromParent();
370
4
    return Switch;
371
0
  } else {
372
0
    return cast<llvm::SwitchInst>(Term);
373
0
  }
374
4
}
375
376
139
void CodeGenFunction::ResolveBranchFixups(llvm::BasicBlock *Block) {
377
139
  assert(Block && "resolving a null target block");
378
139
  if (!EHStack.getNumBranchFixups()) 
return134
;
379
5
380
5
  assert(EHStack.hasNormalCleanups() &&
381
5
         "branch fixups exist with no normal cleanups on stack");
382
5
383
5
  llvm::SmallPtrSet<llvm::BasicBlock*, 4> ModifiedOptimisticBlocks;
384
5
  bool ResolvedAny = false;
385
5
386
3.00k
  for (unsigned I = 0, E = EHStack.getNumBranchFixups(); I != E; 
++I3.00k
) {
387
    // Skip this fixup if its destination doesn't match.
388
3.00k
    BranchFixup &Fixup = EHStack.getBranchFixup(I);
389
3.00k
    if (Fixup.Destination != Block) 
continue0
;
390
3.00k
391
3.00k
    Fixup.Destination = nullptr;
392
3.00k
    ResolvedAny = true;
393
3.00k
394
    // If it doesn't have an optimistic branch block, LatestBranch is
395
    // already pointing to the right place.
396
3.00k
    llvm::BasicBlock *BranchBB = Fixup.OptimisticBranchBlock;
397
3.00k
    if (!BranchBB)
398
3.00k
      continue;
399
4
400
    // Don't process the same optimistic branch block twice.
401
4
    if (!ModifiedOptimisticBlocks.insert(BranchBB).second)
402
0
      continue;
403
4
404
4
    llvm::SwitchInst *Switch = TransitionToCleanupSwitch(*this, BranchBB);
405
4
406
    // Add a case to the switch.
407
4
    Switch->addCase(Builder.getInt32(Fixup.DestinationIndex), Block);
408
4
  }
409
5
410
5
  if (ResolvedAny)
411
5
    EHStack.popNullFixups();
412
5
}
413
414
/// Pops cleanup blocks until the given savepoint is reached.
415
void CodeGenFunction::PopCleanupBlocks(
416
    EHScopeStack::stable_iterator Old,
417
782k
    std::initializer_list<llvm::Value **> ValuesToReload) {
418
782k
  assert(Old.isValid());
419
782k
420
782k
  bool HadBranches = false;
421
824k
  while (EHStack.stable_begin() != Old) {
422
42.2k
    EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.begin());
423
42.2k
    HadBranches |= Scope.hasBranches();
424
42.2k
425
    // As long as Old strictly encloses the scope's enclosing normal
426
    // cleanup, we're going to emit another normal cleanup which
427
    // fallthrough can propagate through.
428
42.2k
    bool FallThroughIsBranchThrough =
429
42.2k
      Old.strictlyEncloses(Scope.getEnclosingNormalCleanup());
430
42.2k
431
42.2k
    PopCleanupBlock(FallThroughIsBranchThrough);
432
42.2k
  }
433
782k
434
  // If we didn't have any branches, the insertion point before cleanups must
435
  // dominate the current insertion point and we don't need to reload any
436
  // values.
437
782k
  if (!HadBranches)
438
777k
    return;
439
5.18k
440
  // Spill and reload all values that the caller wants to be live at the current
441
  // insertion point.
442
5.18k
  for (llvm::Value **ReloadedValue : ValuesToReload) {
443
12
    auto *Inst = dyn_cast_or_null<llvm::Instruction>(*ReloadedValue);
444
12
    if (!Inst)
445
4
      continue;
446
8
447
    // Don't spill static allocas, they dominate all cleanups. These are created
448
    // by binding a reference to a local variable or temporary.
449
8
    auto *AI = dyn_cast<llvm::AllocaInst>(Inst);
450
8
    if (AI && 
AI->isStaticAlloca()2
)
451
2
      continue;
452
6
453
6
    Address Tmp =
454
6
        CreateDefaultAlignTempAlloca(Inst->getType(), "tmp.exprcleanup");
455
6
456
    // Find an insertion point after Inst and spill it to the temporary.
457
6
    llvm::BasicBlock::iterator InsertBefore;
458
6
    if (auto *Invoke = dyn_cast<llvm::InvokeInst>(Inst))
459
0
      InsertBefore = Invoke->getNormalDest()->getFirstInsertionPt();
460
6
    else
461
6
      InsertBefore = std::next(Inst->getIterator());
462
6
    CGBuilderTy(CGM, &*InsertBefore).CreateStore(Inst, Tmp);
463
6
464
    // Reload the value at the current insertion point.
465
6
    *ReloadedValue = Builder.CreateLoad(Tmp);
466
6
  }
467
5.18k
}
468
469
/// Pops cleanup blocks until the given savepoint is reached, then add the
470
/// cleanups from the given savepoint in the lifetime-extended cleanups stack.
471
void CodeGenFunction::PopCleanupBlocks(
472
    EHScopeStack::stable_iterator Old, size_t OldLifetimeExtendedSize,
473
774k
    std::initializer_list<llvm::Value **> ValuesToReload) {
474
774k
  PopCleanupBlocks(Old, ValuesToReload);
475
774k
476
  // Move our deferred cleanups onto the EH stack.
477
774k
  for (size_t I = OldLifetimeExtendedSize,
478
774k
              E = LifetimeExtendedCleanupStack.size(); I != E; /**/) {
479
    // Alignment should be guaranteed by the vptrs in the individual cleanups.
480
539
    assert((I % alignof(LifetimeExtendedCleanupHeader) == 0) &&
481
539
           "misaligned cleanup stack entry");
482
539
483
539
    LifetimeExtendedCleanupHeader &Header =
484
539
        reinterpret_cast<LifetimeExtendedCleanupHeader&>(
485
539
            LifetimeExtendedCleanupStack[I]);
486
539
    I += sizeof(Header);
487
539
488
539
    EHStack.pushCopyOfCleanup(Header.getKind(),
489
539
                              &LifetimeExtendedCleanupStack[I],
490
539
                              Header.getSize());
491
539
    I += Header.getSize();
492
539
493
539
    if (Header.isConditional()) {
494
24
      Address ActiveFlag =
495
24
          reinterpret_cast<Address &>(LifetimeExtendedCleanupStack[I]);
496
24
      initFullExprCleanupWithFlag(ActiveFlag);
497
24
      I += sizeof(ActiveFlag);
498
24
    }
499
539
  }
500
774k
  LifetimeExtendedCleanupStack.resize(OldLifetimeExtendedSize);
501
774k
}
502
503
static llvm::BasicBlock *CreateNormalEntry(CodeGenFunction &CGF,
504
15.2k
                                           EHCleanupScope &Scope) {
505
15.2k
  assert(Scope.isNormalCleanup());
506
15.2k
  llvm::BasicBlock *Entry = Scope.getNormalBlock();
507
15.2k
  if (!Entry) {
508
7.52k
    Entry = CGF.createBasicBlock("cleanup");
509
7.52k
    Scope.setNormalBlock(Entry);
510
7.52k
  }
511
15.2k
  return Entry;
512
15.2k
}
513
514
/// Attempts to reduce a cleanup's entry block to a fallthrough.  This
515
/// is basically llvm::MergeBlockIntoPredecessor, except
516
/// simplified/optimized for the tighter constraints on cleanup blocks.
517
///
518
/// Returns the new block, whatever it is.
519
static llvm::BasicBlock *SimplifyCleanupEntry(CodeGenFunction &CGF,
520
14.1k
                                              llvm::BasicBlock *Entry) {
521
14.1k
  llvm::BasicBlock *Pred = Entry->getSinglePredecessor();
522
14.1k
  if (!Pred) 
return Entry1.44k
;
523
12.7k
524
12.7k
  llvm::BranchInst *Br = dyn_cast<llvm::BranchInst>(Pred->getTerminator());
525
12.7k
  if (!Br || 
Br->isConditional()12.5k
)
return Entry198
;
526
12.5k
  assert(Br->getSuccessor(0) == Entry);
527
12.5k
528
  // If we were previously inserting at the end of the cleanup entry
529
  // block, we'll need to continue inserting at the end of the
530
  // predecessor.
531
12.5k
  bool WasInsertBlock = CGF.Builder.GetInsertBlock() == Entry;
532
12.5k
  assert(!WasInsertBlock || CGF.Builder.GetInsertPoint() == Entry->end());
533
12.5k
534
  // Kill the branch.
535
12.5k
  Br->eraseFromParent();
536
12.5k
537
  // Replace all uses of the entry with the predecessor, in case there
538
  // are phis in the cleanup.
539
12.5k
  Entry->replaceAllUsesWith(Pred);
540
12.5k
541
  // Merge the blocks.
542
12.5k
  Pred->getInstList().splice(Pred->end(), Entry->getInstList());
543
12.5k
544
  // Kill the entry block.
545
12.5k
  Entry->eraseFromParent();
546
12.5k
547
12.5k
  if (WasInsertBlock)
548
8
    CGF.Builder.SetInsertPoint(Pred);
549
12.5k
550
12.5k
  return Pred;
551
12.5k
}
552
553
static void EmitCleanup(CodeGenFunction &CGF,
554
                        EHScopeStack::Cleanup *Fn,
555
                        EHScopeStack::Cleanup::Flags flags,
556
47.1k
                        Address ActiveFlag) {
557
  // If there's an active flag, load it and skip the cleanup if it's
558
  // false.
559
47.1k
  llvm::BasicBlock *ContBB = nullptr;
560
47.1k
  if (ActiveFlag.isValid()) {
561
310
    ContBB = CGF.createBasicBlock("cleanup.done");
562
310
    llvm::BasicBlock *CleanupBB = CGF.createBasicBlock("cleanup.action");
563
310
    llvm::Value *IsActive
564
310
      = CGF.Builder.CreateLoad(ActiveFlag, "cleanup.is_active");
565
310
    CGF.Builder.CreateCondBr(IsActive, CleanupBB, ContBB);
566
310
    CGF.EmitBlock(CleanupBB);
567
310
  }
568
47.1k
569
  // Ask the cleanup to emit itself.
570
47.1k
  Fn->Emit(CGF, flags);
571
47.1k
  assert(CGF.HaveInsertPoint() && "cleanup ended with no insertion point?");
572
47.1k
573
  // Emit the continuation block if there was an active flag.
574
47.1k
  if (ActiveFlag.isValid())
575
310
    CGF.EmitBlock(ContBB);
576
47.1k
}
577
578
static void ForwardPrebranchedFallthrough(llvm::BasicBlock *Exit,
579
                                          llvm::BasicBlock *From,
580
0
                                          llvm::BasicBlock *To) {
581
  // Exit is the exit block of a cleanup, so it always terminates in
582
  // an unconditional branch or a switch.
583
0
  llvm::Instruction *Term = Exit->getTerminator();
584
0
585
0
  if (llvm::BranchInst *Br = dyn_cast<llvm::BranchInst>(Term)) {
586
0
    assert(Br->isUnconditional() && Br->getSuccessor(0) == From);
587
0
    Br->setSuccessor(0, To);
588
0
  } else {
589
0
    llvm::SwitchInst *Switch = cast<llvm::SwitchInst>(Term);
590
0
    for (unsigned I = 0, E = Switch->getNumSuccessors(); I != E; ++I)
591
0
      if (Switch->getSuccessor(I) == From)
592
0
        Switch->setSuccessor(I, To);
593
0
  }
594
0
}
595
596
/// We don't need a normal entry block for the given cleanup.
597
/// Optimistic fixup branches can cause these blocks to come into
598
/// existence anyway;  if so, destroy it.
599
///
600
/// The validity of this transformation is very much specific to the
601
/// exact ways in which we form branches to cleanup entries.
602
static void destroyOptimisticNormalEntry(CodeGenFunction &CGF,
603
39.1k
                                         EHCleanupScope &scope) {
604
39.1k
  llvm::BasicBlock *entry = scope.getNormalBlock();
605
39.1k
  if (!entry) 
return39.1k
;
606
4
607
  // Replace all the uses with unreachable.
608
4
  llvm::BasicBlock *unreachableBB = CGF.getUnreachableBlock();
609
4
  for (llvm::BasicBlock::use_iterator
610
8
         i = entry->use_begin(), e = entry->use_end(); i != e; ) {
611
4
    llvm::Use &use = *i;
612
4
    ++i;
613
4
614
4
    use.set(unreachableBB);
615
4
616
    // The only uses should be fixup switches.
617
4
    llvm::SwitchInst *si = cast<llvm::SwitchInst>(use.getUser());
618
4
    if (si->getNumCases() == 1 && si->getDefaultDest() == unreachableBB) {
619
      // Replace the switch with a branch.
620
4
      llvm::BranchInst::Create(si->case_begin()->getCaseSuccessor(), si);
621
4
622
      // The switch operand is a load from the cleanup-dest alloca.
623
4
      llvm::LoadInst *condition = cast<llvm::LoadInst>(si->getCondition());
624
4
625
      // Destroy the switch.
626
4
      si->eraseFromParent();
627
4
628
      // Destroy the load.
629
4
      assert(condition->getOperand(0) == CGF.NormalCleanupDest.getPointer());
630
4
      assert(condition->use_empty());
631
4
      condition->eraseFromParent();
632
4
    }
633
4
  }
634
4
635
4
  assert(entry->use_empty());
636
4
  delete entry;
637
4
}
638
639
/// Pops a cleanup block.  If the block includes a normal cleanup, the
640
/// current insertion point is threaded through the cleanup, as are
641
/// any branch fixups on the cleanup.
642
46.7k
void CodeGenFunction::PopCleanupBlock(bool FallthroughIsBranchThrough) {
643
46.7k
  assert(!EHStack.empty() && "cleanup stack is empty!");
644
46.7k
  assert(isa<EHCleanupScope>(*EHStack.begin()) && "top not a cleanup!");
645
46.7k
  EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.begin());
646
46.7k
  assert(Scope.getFixupDepth() <= EHStack.getNumBranchFixups());
647
46.7k
648
  // Remember activation information.
649
46.7k
  bool IsActive = Scope.isActive();
650
46.7k
  Address NormalActiveFlag =
651
238
    Scope.shouldTestFlagInNormalCleanup() ? Scope.getActiveFlag()
652
46.4k
                                          : Address::invalid();
653
46.7k
  Address EHActiveFlag =
654
295
    Scope.shouldTestFlagInEHCleanup() ? Scope.getActiveFlag()
655
46.4k
                                      : Address::invalid();
656
46.7k
657
  // Check whether we need an EH cleanup.  This is only true if we've
658
  // generated a lazy EH cleanup block.
659
46.7k
  llvm::BasicBlock *EHEntry = Scope.getCachedEHDispatchBlock();
660
46.7k
  assert(Scope.hasEHBranches() == (EHEntry != nullptr));
661
46.7k
  bool RequiresEHCleanup = (EHEntry != nullptr);
662
46.7k
  EHScopeStack::stable_iterator EHParent = Scope.getEnclosingEHScope();
663
46.7k
664
  // Check the three conditions which might require a normal cleanup:
665
46.7k
666
  // - whether there are branch fix-ups through this cleanup
667
46.7k
  unsigned FixupDepth = Scope.getFixupDepth();
668
46.7k
  bool HasFixups = EHStack.getNumBranchFixups() != FixupDepth;
669
46.7k
670
  // - whether there are branch-throughs or branch-afters
671
46.7k
  bool HasExistingBranches = Scope.hasBranches();
672
46.7k
673
  // - whether there's a fallthrough
674
46.7k
  llvm::BasicBlock *FallthroughSource = Builder.GetInsertBlock();
675
46.7k
  bool HasFallthrough = (FallthroughSource != nullptr && 
IsActive37.8k
);
676
46.7k
677
  // Branch-through fall-throughs leave the insertion point set to the
678
  // end of the last cleanup, which points to the current scope.  The
679
  // rest of IR gen doesn't need to worry about this; it only happens
680
  // during the execution of PopCleanupBlocks().
681
46.7k
  bool HasPrebranchedFallthrough =
682
46.7k
    (FallthroughSource && 
FallthroughSource->getTerminator()37.8k
);
683
46.7k
684
  // If this is a normal cleanup, then having a prebranched
685
  // fallthrough implies that the fallthrough source unconditionally
686
  // jumps here.
687
46.7k
  assert(!Scope.isNormalCleanup() || !HasPrebranchedFallthrough ||
688
46.7k
         (Scope.getNormalBlock() &&
689
46.7k
          FallthroughSource->getTerminator()->getSuccessor(0)
690
46.7k
            == Scope.getNormalBlock()));
691
46.7k
692
46.7k
  bool RequiresNormalCleanup = false;
693
46.7k
  if (Scope.isNormalCleanup() &&
694
40.6k
      (HasFixups || 
HasExistingBranches40.6k
||
HasFallthrough33.1k
)) {
695
40.5k
    RequiresNormalCleanup = true;
696
40.5k
  }
697
46.7k
698
  // If we have a prebranched fallthrough into an inactive normal
699
  // cleanup, rewrite it so that it leads to the appropriate place.
700
46.7k
  if (Scope.isNormalCleanup() && 
HasPrebranchedFallthrough40.6k
&&
!IsActive28
) {
701
0
    llvm::BasicBlock *prebranchDest;
702
0
703
    // If the prebranch is semantically branching through the next
704
    // cleanup, just forward it to the next block, leaving the
705
    // insertion point in the prebranched block.
706
0
    if (FallthroughIsBranchThrough) {
707
0
      EHScope &enclosing = *EHStack.find(Scope.getEnclosingNormalCleanup());
708
0
      prebranchDest = CreateNormalEntry(*this, cast<EHCleanupScope>(enclosing));
709
0
710
    // Otherwise, we need to make a new block.  If the normal cleanup
711
    // isn't being used at all, we could actually reuse the normal
712
    // entry block, but this is simpler, and it avoids conflicts with
713
    // dead optimistic fixup branches.
714
0
    } else {
715
0
      prebranchDest = createBasicBlock("forwarded-prebranch");
716
0
      EmitBlock(prebranchDest);
717
0
    }
718
0
719
0
    llvm::BasicBlock *normalEntry = Scope.getNormalBlock();
720
0
    assert(normalEntry && !normalEntry->use_empty());
721
0
722
0
    ForwardPrebranchedFallthrough(FallthroughSource,
723
0
                                  normalEntry, prebranchDest);
724
0
  }
725
46.7k
726
  // If we don't need the cleanup at all, we're done.
727
46.7k
  if (!RequiresNormalCleanup && 
!RequiresEHCleanup6.16k
) {
728
4.53k
    destroyOptimisticNormalEntry(*this, Scope);
729
4.53k
    EHStack.popCleanup(); // safe because there are no fixups
730
4.53k
    assert(EHStack.getNumBranchFixups() == 0 ||
731
4.53k
           EHStack.hasNormalCleanups());
732
4.53k
    return;
733
4.53k
  }
734
42.1k
735
  // Copy the cleanup emission data out.  This uses either a stack
736
  // array or malloc'd memory, depending on the size, which is
737
  // behavior that SmallVector would provide, if we could use it
738
  // here. Unfortunately, if you ask for a SmallVector<char>, the
739
  // alignment isn't sufficient.
740
42.1k
  auto *CleanupSource = reinterpret_cast<char *>(Scope.getCleanupBuffer());
741
42.1k
  alignas(EHScopeStack::ScopeStackAlignment) char
742
42.1k
      CleanupBufferStack[8 * sizeof(void *)];
743
42.1k
  std::unique_ptr<char[]> CleanupBufferHeap;
744
42.1k
  size_t CleanupSize = Scope.getCleanupSize();
745
42.1k
  EHScopeStack::Cleanup *Fn;
746
42.1k
747
42.1k
  if (CleanupSize <= sizeof(CleanupBufferStack)) {
748
42.0k
    memcpy(CleanupBufferStack, CleanupSource, CleanupSize);
749
42.0k
    Fn = reinterpret_cast<EHScopeStack::Cleanup *>(CleanupBufferStack);
750
77
  } else {
751
77
    CleanupBufferHeap.reset(new char[CleanupSize]);
752
77
    memcpy(CleanupBufferHeap.get(), CleanupSource, CleanupSize);
753
77
    Fn = reinterpret_cast<EHScopeStack::Cleanup *>(CleanupBufferHeap.get());
754
77
  }
755
42.1k
756
42.1k
  EHScopeStack::Cleanup::Flags cleanupFlags;
757
42.1k
  if (Scope.isNormalCleanup())
758
40.6k
    cleanupFlags.setIsNormalCleanupKind();
759
42.1k
  if (Scope.isEHCleanup())
760
38.1k
    cleanupFlags.setIsEHCleanupKind();
761
42.1k
762
42.1k
  if (!RequiresNormalCleanup) {
763
1.62k
    destroyOptimisticNormalEntry(*this, Scope);
764
1.62k
    EHStack.popCleanup();
765
40.5k
  } else {
766
    // If we have a fallthrough and no other need for the cleanup,
767
    // emit it directly.
768
40.5k
    if (HasFallthrough && 
!HasPrebranchedFallthrough33.2k
&&
769
33.2k
        !HasFixups && 
!HasExistingBranches33.2k
) {
770
33.0k
771
33.0k
      destroyOptimisticNormalEntry(*this, Scope);
772
33.0k
      EHStack.popCleanup();
773
33.0k
774
33.0k
      EmitCleanup(*this, Fn, cleanupFlags, NormalActiveFlag);
775
33.0k
776
    // Otherwise, the best approach is to thread everything through
777
    // the cleanup block and then try to clean up after ourselves.
778
7.52k
    } else {
779
      // Force the entry block to exist.
780
7.52k
      llvm::BasicBlock *NormalEntry = CreateNormalEntry(*this, Scope);
781
7.52k
782
      // I.  Set up the fallthrough edge in.
783
7.52k
784
7.52k
      CGBuilderTy::InsertPoint savedInactiveFallthroughIP;
785
7.52k
786
      // If there's a fallthrough, we need to store the cleanup
787
      // destination index.  For fall-throughs this is always zero.
788
7.52k
      if (HasFallthrough) {
789
233
        if (!HasPrebranchedFallthrough)
790
205
          Builder.CreateStore(Builder.getInt32(0), getNormalCleanupDestSlot());
791
233
792
      // Otherwise, save and clear the IP if we don't have fallthrough
793
      // because the cleanup is inactive.
794
7.28k
      } else if (FallthroughSource) {
795
0
        assert(!IsActive && "source without fallthrough for active cleanup");
796
0
        savedInactiveFallthroughIP = Builder.saveAndClearIP();
797
0
      }
798
7.52k
799
      // II.  Emit the entry block.  This implicitly branches to it if
800
      // we have fallthrough.  All the fixups and existing branches
801
      // should already be branched to it.
802
7.52k
      EmitBlock(NormalEntry);
803
7.52k
804
      // III.  Figure out where we're going and build the cleanup
805
      // epilogue.
806
7.52k
807
7.52k
      bool HasEnclosingCleanups =
808
7.52k
        (Scope.getEnclosingNormalCleanup() != EHStack.stable_end());
809
7.52k
810
      // Compute the branch-through dest if we need it:
811
      //   - if there are branch-throughs threaded through the scope
812
      //   - if fall-through is a branch-through
813
      //   - if there are fixups that will be optimistically forwarded
814
      //     to the enclosing cleanup
815
7.52k
      llvm::BasicBlock *BranchThroughDest = nullptr;
816
7.52k
      if (Scope.hasBranchThroughs() ||
817
5.20k
          (FallthroughSource && 
FallthroughIsBranchThrough195
) ||
818
5.20k
          (HasFixups && 
HasEnclosingCleanups14
)) {
819
2.32k
        assert(HasEnclosingCleanups);
820
2.32k
        EHScope &S = *EHStack.find(Scope.getEnclosingNormalCleanup());
821
2.32k
        BranchThroughDest = CreateNormalEntry(*this, cast<EHCleanupScope>(S));
822
2.32k
      }
823
7.52k
824
7.52k
      llvm::BasicBlock *FallthroughDest = nullptr;
825
7.52k
      SmallVector<llvm::Instruction*, 2> InstsToAppend;
826
7.52k
827
      // If there's exactly one branch-after and no other threads,
828
      // we can route it without a switch.
829
7.52k
      if (!Scope.hasBranchThroughs() && 
!HasFixups5.20k
&&
!HasFallthrough5.19k
&&
830
5.00k
          Scope.getNumBranchAfters() == 1) {
831
4.99k
        assert(!BranchThroughDest || !IsActive);
832
4.99k
833
        // Clean up the possibly dead store to the cleanup dest slot.
834
4.99k
        llvm::Instruction *NormalCleanupDestSlot =
835
4.99k
            cast<llvm::Instruction>(getNormalCleanupDestSlot().getPointer());
836
4.99k
        if (NormalCleanupDestSlot->hasOneUse()) {
837
4.90k
          NormalCleanupDestSlot->user_back()->eraseFromParent();
838
4.90k
          NormalCleanupDestSlot->eraseFromParent();
839
4.90k
          NormalCleanupDest = Address::invalid();
840
4.90k
        }
841
4.99k
842
4.99k
        llvm::BasicBlock *BranchAfter = Scope.getBranchAfterBlock(0);
843
4.99k
        InstsToAppend.push_back(llvm::BranchInst::Create(BranchAfter));
844
4.99k
845
      // Build a switch-out if we need it:
846
      //   - if there are branch-afters threaded through the scope
847
      //   - if fall-through is a branch-after
848
      //   - if there are fixups that have nowhere left to go and
849
      //     so must be immediately resolved
850
2.52k
      } else if (Scope.getNumBranchAfters() ||
851
2.32k
                 (HasFallthrough && 
!FallthroughIsBranchThrough40
) ||
852
2.31k
                 (HasFixups && 
!HasEnclosingCleanups12
)) {
853
212
854
212
        llvm::BasicBlock *Default =
855
200
          (BranchThroughDest ? 
BranchThroughDest12
: getUnreachableBlock());
856
212
857
        // TODO: base this on the number of branch-afters and fixups
858
212
        const unsigned SwitchCapacity = 10;
859
212
860
        // pass the abnormal exit flag to Fn (SEH cleanup)
861
212
        cleanupFlags.setHasExitSwitch();
862
212
863
212
        llvm::LoadInst *Load =
864
212
          createLoadInstBefore(getNormalCleanupDestSlot(), "cleanup.dest",
865
212
                               nullptr);
866
212
        llvm::SwitchInst *Switch =
867
212
          llvm::SwitchInst::Create(Load, Default, SwitchCapacity);
868
212
869
212
        InstsToAppend.push_back(Load);
870
212
        InstsToAppend.push_back(Switch);
871
212
872
        // Branch-after fallthrough.
873
212
        if (FallthroughSource && 
!FallthroughIsBranchThrough206
) {
874
205
          FallthroughDest = createBasicBlock("cleanup.cont");
875
205
          if (HasFallthrough)
876
205
            Switch->addCase(Builder.getInt32(0), FallthroughDest);
877
205
        }
878
212
879
420
        for (unsigned I = 0, E = Scope.getNumBranchAfters(); I != E; 
++I208
) {
880
208
          Switch->addCase(Scope.getBranchAfterIndex(I),
881
208
                          Scope.getBranchAfterBlock(I));
882
208
        }
883
212
884
        // If there aren't any enclosing cleanups, we can resolve all
885
        // the fixups now.
886
212
        if (HasFixups && 
!HasEnclosingCleanups4
)
887
4
          ResolveAllBranchFixups(*this, Switch, NormalEntry);
888
2.31k
      } else {
889
        // We should always have a branch-through destination in this case.
890
2.31k
        assert(BranchThroughDest);
891
2.31k
        InstsToAppend.push_back(llvm::BranchInst::Create(BranchThroughDest));
892
2.31k
      }
893
7.52k
894
      // IV.  Pop the cleanup and emit it.
895
7.52k
      EHStack.popCleanup();
896
7.52k
      assert(EHStack.hasNormalCleanups() == HasEnclosingCleanups);
897
7.52k
898
7.52k
      EmitCleanup(*this, Fn, cleanupFlags, NormalActiveFlag);
899
7.52k
900
      // Append the prepared cleanup prologue from above.
901
7.52k
      llvm::BasicBlock *NormalExit = Builder.GetInsertBlock();
902
15.2k
      for (unsigned I = 0, E = InstsToAppend.size(); I != E; 
++I7.73k
)
903
7.73k
        NormalExit->getInstList().push_back(InstsToAppend[I]);
904
7.52k
905
      // Optimistically hope that any fixups will continue falling through.
906
7.52k
      for (unsigned I = FixupDepth, E = EHStack.getNumBranchFixups();
907
7.53k
           I < E; 
++I10
) {
908
10
        BranchFixup &Fixup = EHStack.getBranchFixup(I);
909
10
        if (!Fixup.Destination) 
continue0
;
910
10
        if (!Fixup.OptimisticBranchBlock) {
911
6
          createStoreInstBefore(Builder.getInt32(Fixup.DestinationIndex),
912
6
                                getNormalCleanupDestSlot(),
913
6
                                Fixup.InitialBranch);
914
6
          Fixup.InitialBranch->setSuccessor(0, NormalEntry);
915
6
        }
916
10
        Fixup.OptimisticBranchBlock = NormalExit;
917
10
      }
918
7.52k
919
      // V.  Set up the fallthrough edge out.
920
7.52k
921
      // Case 1: a fallthrough source exists but doesn't branch to the
922
      // cleanup because the cleanup is inactive.
923
7.52k
      if (!HasFallthrough && 
FallthroughSource7.28k
) {
924
        // Prebranched fallthrough was forwarded earlier.
925
        // Non-prebranched fallthrough doesn't need to be forwarded.
926
        // Either way, all we need to do is restore the IP we cleared before.
927
0
        assert(!IsActive);
928
0
        Builder.restoreIP(savedInactiveFallthroughIP);
929
0
930
      // Case 2: a fallthrough source exists and should branch to the
931
      // cleanup, but we're not supposed to branch through to the next
932
      // cleanup.
933
7.52k
      } else if (HasFallthrough && 
FallthroughDest233
) {
934
205
        assert(!FallthroughIsBranchThrough);
935
205
        EmitBlock(FallthroughDest);
936
205
937
      // Case 3: a fallthrough source exists and should branch to the
938
      // cleanup and then through to the next.
939
7.31k
      } else if (HasFallthrough) {
940
        // Everything is already set up for this.
941
28
942
      // Case 4: no fallthrough source exists.
943
7.28k
      } else {
944
7.28k
        Builder.ClearInsertionPoint();
945
7.28k
      }
946
7.52k
947
      // VI.  Assorted cleaning.
948
7.52k
949
      // Check whether we can merge NormalEntry into a single predecessor.
950
      // This might invalidate (non-IR) pointers to NormalEntry.
951
7.52k
      llvm::BasicBlock *NewNormalEntry =
952
7.52k
        SimplifyCleanupEntry(*this, NormalEntry);
953
7.52k
954
      // If it did invalidate those pointers, and NormalEntry was the same
955
      // as NormalExit, go back and patch up the fixups.
956
7.52k
      if (NewNormalEntry != NormalEntry && 
NormalEntry == NormalExit7.21k
)
957
6.12k
        for (unsigned I = FixupDepth, E = EHStack.getNumBranchFixups();
958
6.13k
               I < E; 
++I5
)
959
5
          EHStack.getBranchFixup(I).OptimisticBranchBlock = NewNormalEntry;
960
7.52k
    }
961
40.5k
  }
962
42.1k
963
42.1k
  assert(EHStack.hasNormalCleanups() || EHStack.getNumBranchFixups() == 0);
964
42.1k
965
  // Emit the EH cleanup if required.
966
42.1k
  if (RequiresEHCleanup) {
967
6.64k
    CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
968
6.64k
969
6.64k
    EmitBlock(EHEntry);
970
6.64k
971
6.64k
    llvm::BasicBlock *NextAction = getEHDispatchBlock(EHParent);
972
6.64k
973
    // Push a terminate scope or cleanupendpad scope around the potentially
974
    // throwing cleanups. For funclet EH personalities, the cleanupendpad models
975
    // program termination when cleanups throw.
976
6.64k
    bool PushedTerminate = false;
977
6.64k
    SaveAndRestore<llvm::Instruction *> RestoreCurrentFuncletPad(
978
6.64k
        CurrentFuncletPad);
979
6.64k
    llvm::CleanupPadInst *CPI = nullptr;
980
6.64k
981
6.64k
    const EHPersonality &Personality = EHPersonality::get(*this);
982
6.64k
    if (Personality.usesFuncletPads()) {
983
243
      llvm::Value *ParentPad = CurrentFuncletPad;
984
243
      if (!ParentPad)
985
177
        ParentPad = llvm::ConstantTokenNone::get(CGM.getLLVMContext());
986
243
      CurrentFuncletPad = CPI = Builder.CreateCleanupPad(ParentPad);
987
243
    }
988
6.64k
989
    // Non-MSVC personalities need to terminate when an EH cleanup throws.
990
6.64k
    if (!Personality.isMSVCPersonality()) {
991
6.49k
      EHStack.pushTerminate();
992
6.49k
      PushedTerminate = true;
993
6.49k
    }
994
6.64k
995
    // We only actually emit the cleanup code if the cleanup is either
996
    // active or was used before it was deactivated.
997
6.64k
    if (EHActiveFlag.isValid() || 
IsActive6.57k
) {
998
6.64k
      cleanupFlags.setIsForEHCleanup();
999
6.64k
      EmitCleanup(*this, Fn, cleanupFlags, EHActiveFlag);
1000
6.64k
    }
1001
6.64k
1002
6.64k
    if (CPI)
1003
243
      Builder.CreateCleanupRet(CPI, NextAction);
1004
6.40k
    else
1005
6.40k
      Builder.CreateBr(NextAction);
1006
6.64k
1007
    // Leave the terminate scope.
1008
6.64k
    if (PushedTerminate)
1009
6.49k
      EHStack.popTerminate();
1010
6.64k
1011
6.64k
    Builder.restoreIP(SavedIP);
1012
6.64k
1013
6.64k
    SimplifyCleanupEntry(*this, EHEntry);
1014
6.64k
  }
1015
42.1k
}
1016
1017
/// isObviouslyBranchWithoutCleanups - Return true if a branch to the
1018
/// specified destination obviously has no cleanups to run.  'false' is always
1019
/// a conservatively correct answer for this method.
1020
0
bool CodeGenFunction::isObviouslyBranchWithoutCleanups(JumpDest Dest) const {
1021
0
  assert(Dest.getScopeDepth().encloses(EHStack.stable_begin())
1022
0
         && "stale jump destination");
1023
0
1024
  // Calculate the innermost active normal cleanup.
1025
0
  EHScopeStack::stable_iterator TopCleanup =
1026
0
    EHStack.getInnermostActiveNormalCleanup();
1027
0
1028
  // If we're not in an active normal cleanup scope, or if the
1029
  // destination scope is within the innermost active normal cleanup
1030
  // scope, we don't need to worry about fixups.
1031
0
  if (TopCleanup == EHStack.stable_end() ||
1032
0
      TopCleanup.encloses(Dest.getScopeDepth())) // works for invalid
1033
0
    return true;
1034
0
1035
  // Otherwise, we might need some cleanups.
1036
0
  return false;
1037
0
}
1038
1039
1040
/// Terminate the current block by emitting a branch which might leave
1041
/// the current cleanup-protected scope.  The target scope may not yet
1042
/// be known, in which case this will require a fixup.
1043
///
1044
/// As a side-effect, this method clears the insertion point.
1045
153k
void CodeGenFunction::EmitBranchThroughCleanup(JumpDest Dest) {
1046
153k
  assert(Dest.getScopeDepth().encloses(EHStack.stable_begin())
1047
153k
         && "stale jump destination");
1048
153k
1049
153k
  if (!HaveInsertPoint())
1050
62
    return;
1051
153k
1052
  // Create the branch.
1053
153k
  llvm::BranchInst *BI = Builder.CreateBr(Dest.getBlock());
1054
153k
1055
  // Calculate the innermost active normal cleanup.
1056
153k
  EHScopeStack::stable_iterator
1057
153k
    TopCleanup = EHStack.getInnermostActiveNormalCleanup();
1058
153k
1059
  // If we're not in an active normal cleanup scope, or if the
1060
  // destination scope is within the innermost active normal cleanup
1061
  // scope, we don't need to worry about fixups.
1062
153k
  if (TopCleanup == EHStack.stable_end() ||
1063
145k
      
TopCleanup.encloses(Dest.getScopeDepth())9.51k
) { // works for invalid
1064
145k
    Builder.ClearInsertionPoint();
1065
145k
    return;
1066
145k
  }
1067
8.45k
1068
  // If we can't resolve the destination cleanup scope, just add this
1069
  // to the current cleanup scope as a branch fixup.
1070
8.45k
  if (!Dest.getScopeDepth().isValid()) {
1071
3.00k
    BranchFixup &Fixup = EHStack.addBranchFixup();
1072
3.00k
    Fixup.Destination = Dest.getBlock();
1073
3.00k
    Fixup.DestinationIndex = Dest.getDestIndex();
1074
3.00k
    Fixup.InitialBranch = BI;
1075
3.00k
    Fixup.OptimisticBranchBlock = nullptr;
1076
3.00k
1077
3.00k
    Builder.ClearInsertionPoint();
1078
3.00k
    return;
1079
3.00k
  }
1080
5.44k
1081
  // Otherwise, thread through all the normal cleanups in scope.
1082
5.44k
1083
  // Store the index at the start.
1084
5.44k
  llvm::ConstantInt *Index = Builder.getInt32(Dest.getDestIndex());
1085
5.44k
  createStoreInstBefore(Index, getNormalCleanupDestSlot(), BI);
1086
5.44k
1087
  // Adjust BI to point to the first cleanup block.
1088
5.44k
  {
1089
5.44k
    EHCleanupScope &Scope =
1090
5.44k
      cast<EHCleanupScope>(*EHStack.find(TopCleanup));
1091
5.44k
    BI->setSuccessor(0, CreateNormalEntry(*this, Scope));
1092
5.44k
  }
1093
5.44k
1094
  // Add this destination to all the scopes involved.
1095
5.44k
  EHScopeStack::stable_iterator I = TopCleanup;
1096
5.44k
  EHScopeStack::stable_iterator E = Dest.getScopeDepth();
1097
5.44k
  if (E.strictlyEncloses(I)) {
1098
7.76k
    while (true) {
1099
7.76k
      EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(I));
1100
7.76k
      assert(Scope.isNormalCleanup());
1101
7.76k
      I = Scope.getEnclosingNormalCleanup();
1102
7.76k
1103
      // If this is the last cleanup we're propagating through, tell it
1104
      // that there's a resolved jump moving through it.
1105
7.76k
      if (!E.strictlyEncloses(I)) {
1106
5.38k
        Scope.addBranchAfter(Index, Dest.getBlock());
1107
5.38k
        break;
1108
5.38k
      }
1109
2.37k
1110
      // Otherwise, tell the scope that there's a jump propagating
1111
      // through it.  If this isn't new information, all the rest of
1112
      // the work has been done before.
1113
2.37k
      if (!Scope.addBranchThrough(Dest.getBlock()))
1114
64
        break;
1115
2.37k
    }
1116
5.44k
  }
1117
5.44k
1118
5.44k
  Builder.ClearInsertionPoint();
1119
5.44k
}
1120
1121
static bool IsUsedAsNormalCleanup(EHScopeStack &EHStack,
1122
2
                                  EHScopeStack::stable_iterator C) {
1123
  // If we needed a normal block for any reason, that counts.
1124
2
  if (cast<EHCleanupScope>(*EHStack.find(C)).getNormalBlock())
1125
0
    return true;
1126
2
1127
  // Check whether any enclosed cleanups were needed.
1128
2
  for (EHScopeStack::stable_iterator
1129
2
         I = EHStack.getInnermostNormalCleanup();
1130
3
         I != C; ) {
1131
1
    assert(C.strictlyEncloses(I));
1132
1
    EHCleanupScope &S = cast<EHCleanupScope>(*EHStack.find(I));
1133
1
    if (S.getNormalBlock()) 
return true0
;
1134
1
    I = S.getEnclosingNormalCleanup();
1135
1
  }
1136
2
1137
2
  return false;
1138
2
}
1139
1140
static bool IsUsedAsEHCleanup(EHScopeStack &EHStack,
1141
89
                              EHScopeStack::stable_iterator cleanup) {
1142
  // If we needed an EH block for any reason, that counts.
1143
89
  if (EHStack.find(cleanup)->hasEHBranches())
1144
49
    return true;
1145
40
1146
  // Check whether any enclosed cleanups were needed.
1147
40
  for (EHScopeStack::stable_iterator
1148
57
         i = EHStack.getInnermostEHScope(); i != cleanup; ) {
1149
21
    assert(cleanup.strictlyEncloses(i));
1150
21
1151
21
    EHScope &scope = *EHStack.find(i);
1152
21
    if (scope.hasEHBranches())
1153
4
      return true;
1154
17
1155
17
    i = scope.getEnclosingEHScope();
1156
17
  }
1157
40
1158
36
  return false;
1159
40
}
1160
1161
enum ForActivation_t {
1162
  ForActivation,
1163
  ForDeactivation
1164
};
1165
1166
/// The given cleanup block is changing activation state.  Configure a
1167
/// cleanup variable if necessary.
1168
///
1169
/// It would be good if we had some way of determining if there were
1170
/// extra uses *after* the change-over point.
1171
static void SetupCleanupBlockActivation(CodeGenFunction &CGF,
1172
                                        EHScopeStack::stable_iterator C,
1173
                                        ForActivation_t kind,
1174
90
                                        llvm::Instruction *dominatingIP) {
1175
90
  EHCleanupScope &Scope = cast<EHCleanupScope>(*CGF.EHStack.find(C));
1176
90
1177
  // We always need the flag if we're activating the cleanup in a
1178
  // conditional context, because we have to assume that the current
1179
  // location doesn't necessarily dominate the cleanup's code.
1180
90
  bool isActivatedInConditional =
1181
90
    (kind == ForActivation && 
CGF.isInConditionalBranch()0
);
1182
90
1183
90
  bool needFlag = false;
1184
90
1185
  // Calculate whether the cleanup was used:
1186
90
1187
  //   - as a normal cleanup
1188
90
  if (Scope.isNormalCleanup() &&
1189
2
      (isActivatedInConditional || IsUsedAsNormalCleanup(CGF.EHStack, C))) {
1190
0
    Scope.setTestFlagInNormalCleanup();
1191
0
    needFlag = true;
1192
0
  }
1193
90
1194
  //  - as an EH cleanup
1195
90
  if (Scope.isEHCleanup() &&
1196
89
      (isActivatedInConditional || IsUsedAsEHCleanup(CGF.EHStack, C))) {
1197
53
    Scope.setTestFlagInEHCleanup();
1198
53
    needFlag = true;
1199
53
  }
1200
90
1201
  // If it hasn't yet been used as either, we're done.
1202
90
  if (!needFlag) 
return37
;
1203
53
1204
53
  Address var = Scope.getActiveFlag();
1205
53
  if (!var.isValid()) {
1206
45
    var = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), CharUnits::One(),
1207
45
                               "cleanup.isactive");
1208
45
    Scope.setActiveFlag(var);
1209
45
1210
45
    assert(dominatingIP && "no existing variable and no dominating IP!");
1211
45
1212
    // Initialize to true or false depending on whether it was
1213
    // active up to this point.
1214
45
    llvm::Constant *value = CGF.Builder.getInt1(kind == ForDeactivation);
1215
45
1216
    // If we're in a conditional block, ignore the dominating IP and
1217
    // use the outermost conditional branch.
1218
45
    if (CGF.isInConditionalBranch()) {
1219
0
      CGF.setBeforeOutermostConditional(value, var);
1220
45
    } else {
1221
45
      createStoreInstBefore(value, var, dominatingIP);
1222
45
    }
1223
45
  }
1224
53
1225
53
  CGF.Builder.CreateStore(CGF.Builder.getInt1(kind == ForActivation), var);
1226
53
}
1227
1228
/// Activate a cleanup that was created in an inactivated state.
1229
void CodeGenFunction::ActivateCleanupBlock(EHScopeStack::stable_iterator C,
1230
0
                                           llvm::Instruction *dominatingIP) {
1231
0
  assert(C != EHStack.stable_end() && "activating bottom of stack?");
1232
0
  EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(C));
1233
0
  assert(!Scope.isActive() && "double activation");
1234
0
1235
0
  SetupCleanupBlockActivation(*this, C, ForActivation, dominatingIP);
1236
0
1237
0
  Scope.setActive(true);
1238
0
}
1239
1240
/// Deactive a cleanup that was created in an active state.
1241
void CodeGenFunction::DeactivateCleanupBlock(EHScopeStack::stable_iterator C,
1242
1.52k
                                             llvm::Instruction *dominatingIP) {
1243
1.52k
  assert(C != EHStack.stable_end() && "deactivating bottom of stack?");
1244
1.52k
  EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(C));
1245
1.52k
  assert(Scope.isActive() && "double deactivation");
1246
1.52k
1247
  // If it's the top of the stack, just pop it, but do so only if it belongs
1248
  // to the current RunCleanupsScope.
1249
1.52k
  if (C == EHStack.stable_begin() &&
1250
1.45k
      CurrentCleanupScopeDepth.strictlyEncloses(C)) {
1251
    // If it's a normal cleanup, we need to pretend that the
1252
    // fallthrough is unreachable.
1253
1.43k
    CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1254
1.43k
    PopCleanupBlock();
1255
1.43k
    Builder.restoreIP(SavedIP);
1256
1.43k
    return;
1257
1.43k
  }
1258
90
1259
  // Otherwise, follow the general case.
1260
90
  SetupCleanupBlockActivation(*this, C, ForDeactivation, dominatingIP);
1261
90
1262
90
  Scope.setActive(false);
1263
90
}
1264
1265
10.9k
Address CodeGenFunction::getNormalCleanupDestSlot() {
1266
10.9k
  if (!NormalCleanupDest.isValid())
1267
5.18k
    NormalCleanupDest =
1268
5.18k
      CreateDefaultAlignTempAlloca(Builder.getInt32Ty(), "cleanup.dest.slot");
1269
10.9k
  return NormalCleanupDest;
1270
10.9k
}
1271
1272
/// Emits all the code to cause the given temporary to be cleaned up.
1273
void CodeGenFunction::EmitCXXTemporary(const CXXTemporary *Temporary,
1274
                                       QualType TempType,
1275
763
                                       Address Ptr) {
1276
763
  pushDestroy(NormalAndEHCleanup, Ptr, TempType, destroyCXXObject,
1277
763
              /*useEHCleanup*/ true);
1278
763
}