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