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