CGCleanup.cpp 43 KB

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