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