CGCleanup.cpp 51 KB

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