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