Coverage Report

Created: 2020-03-31 06:27

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