CGException.cpp 77 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112
  1. //===--- CGException.cpp - Emit LLVM Code for C++ exceptions ----*- C++ -*-===//
  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 contains code dealing with C++ exception related code generation.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "CodeGenFunction.h"
  13. #include "CGCXXABI.h"
  14. #include "CGCleanup.h"
  15. #include "CGObjCRuntime.h"
  16. #include "ConstantEmitter.h"
  17. #include "TargetInfo.h"
  18. #include "clang/AST/Mangle.h"
  19. #include "clang/AST/StmtCXX.h"
  20. #include "clang/AST/StmtObjC.h"
  21. #include "clang/AST/StmtVisitor.h"
  22. #include "clang/Basic/TargetBuiltins.h"
  23. #include "llvm/IR/Intrinsics.h"
  24. #include "llvm/IR/IntrinsicInst.h"
  25. #include "llvm/Support/SaveAndRestore.h"
  26. using namespace clang;
  27. using namespace CodeGen;
  28. static llvm::FunctionCallee getFreeExceptionFn(CodeGenModule &CGM) {
  29. // void __cxa_free_exception(void *thrown_exception);
  30. llvm::FunctionType *FTy =
  31. llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*isVarArg=*/false);
  32. return CGM.CreateRuntimeFunction(FTy, "__cxa_free_exception");
  33. }
  34. static llvm::FunctionCallee getUnexpectedFn(CodeGenModule &CGM) {
  35. // void __cxa_call_unexpected(void *thrown_exception);
  36. llvm::FunctionType *FTy =
  37. llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*isVarArg=*/false);
  38. return CGM.CreateRuntimeFunction(FTy, "__cxa_call_unexpected");
  39. }
  40. llvm::FunctionCallee CodeGenModule::getTerminateFn() {
  41. // void __terminate();
  42. llvm::FunctionType *FTy =
  43. llvm::FunctionType::get(VoidTy, /*isVarArg=*/false);
  44. StringRef name;
  45. // In C++, use std::terminate().
  46. if (getLangOpts().CPlusPlus &&
  47. getTarget().getCXXABI().isItaniumFamily()) {
  48. name = "_ZSt9terminatev";
  49. } else if (getLangOpts().CPlusPlus &&
  50. getTarget().getCXXABI().isMicrosoft()) {
  51. if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
  52. name = "__std_terminate";
  53. else
  54. name = "?terminate@@YAXXZ";
  55. } else if (getLangOpts().ObjC &&
  56. getLangOpts().ObjCRuntime.hasTerminate())
  57. name = "objc_terminate";
  58. else
  59. name = "abort";
  60. return CreateRuntimeFunction(FTy, name);
  61. }
  62. static llvm::FunctionCallee getCatchallRethrowFn(CodeGenModule &CGM,
  63. StringRef Name) {
  64. llvm::FunctionType *FTy =
  65. llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*isVarArg=*/false);
  66. return CGM.CreateRuntimeFunction(FTy, Name);
  67. }
  68. const EHPersonality EHPersonality::GNU_C = { "__gcc_personality_v0", nullptr };
  69. const EHPersonality
  70. EHPersonality::GNU_C_SJLJ = { "__gcc_personality_sj0", nullptr };
  71. const EHPersonality
  72. EHPersonality::GNU_C_SEH = { "__gcc_personality_seh0", nullptr };
  73. const EHPersonality
  74. EHPersonality::NeXT_ObjC = { "__objc_personality_v0", nullptr };
  75. const EHPersonality
  76. EHPersonality::GNU_CPlusPlus = { "__gxx_personality_v0", nullptr };
  77. const EHPersonality
  78. EHPersonality::GNU_CPlusPlus_SJLJ = { "__gxx_personality_sj0", nullptr };
  79. const EHPersonality
  80. EHPersonality::GNU_CPlusPlus_SEH = { "__gxx_personality_seh0", nullptr };
  81. const EHPersonality
  82. EHPersonality::GNU_ObjC = {"__gnu_objc_personality_v0", "objc_exception_throw"};
  83. const EHPersonality
  84. EHPersonality::GNU_ObjC_SJLJ = {"__gnu_objc_personality_sj0", "objc_exception_throw"};
  85. const EHPersonality
  86. EHPersonality::GNU_ObjC_SEH = {"__gnu_objc_personality_seh0", "objc_exception_throw"};
  87. const EHPersonality
  88. EHPersonality::GNU_ObjCXX = { "__gnustep_objcxx_personality_v0", nullptr };
  89. const EHPersonality
  90. EHPersonality::GNUstep_ObjC = { "__gnustep_objc_personality_v0", nullptr };
  91. const EHPersonality
  92. EHPersonality::MSVC_except_handler = { "_except_handler3", nullptr };
  93. const EHPersonality
  94. EHPersonality::MSVC_C_specific_handler = { "__C_specific_handler", nullptr };
  95. const EHPersonality
  96. EHPersonality::MSVC_CxxFrameHandler3 = { "__CxxFrameHandler3", nullptr };
  97. const EHPersonality
  98. EHPersonality::GNU_Wasm_CPlusPlus = { "__gxx_wasm_personality_v0", nullptr };
  99. static const EHPersonality &getCPersonality(const TargetInfo &Target,
  100. const LangOptions &L) {
  101. const llvm::Triple &T = Target.getTriple();
  102. if (T.isWindowsMSVCEnvironment())
  103. return EHPersonality::MSVC_CxxFrameHandler3;
  104. if (L.SjLjExceptions)
  105. return EHPersonality::GNU_C_SJLJ;
  106. if (L.DWARFExceptions)
  107. return EHPersonality::GNU_C;
  108. if (L.SEHExceptions)
  109. return EHPersonality::GNU_C_SEH;
  110. return EHPersonality::GNU_C;
  111. }
  112. static const EHPersonality &getObjCPersonality(const TargetInfo &Target,
  113. const LangOptions &L) {
  114. const llvm::Triple &T = Target.getTriple();
  115. if (T.isWindowsMSVCEnvironment())
  116. return EHPersonality::MSVC_CxxFrameHandler3;
  117. switch (L.ObjCRuntime.getKind()) {
  118. case ObjCRuntime::FragileMacOSX:
  119. return getCPersonality(Target, L);
  120. case ObjCRuntime::MacOSX:
  121. case ObjCRuntime::iOS:
  122. case ObjCRuntime::WatchOS:
  123. return EHPersonality::NeXT_ObjC;
  124. case ObjCRuntime::GNUstep:
  125. if (L.ObjCRuntime.getVersion() >= VersionTuple(1, 7))
  126. return EHPersonality::GNUstep_ObjC;
  127. LLVM_FALLTHROUGH;
  128. case ObjCRuntime::GCC:
  129. case ObjCRuntime::ObjFW:
  130. if (L.SjLjExceptions)
  131. return EHPersonality::GNU_ObjC_SJLJ;
  132. if (L.SEHExceptions)
  133. return EHPersonality::GNU_ObjC_SEH;
  134. return EHPersonality::GNU_ObjC;
  135. }
  136. llvm_unreachable("bad runtime kind");
  137. }
  138. static const EHPersonality &getCXXPersonality(const TargetInfo &Target,
  139. const LangOptions &L) {
  140. const llvm::Triple &T = Target.getTriple();
  141. if (T.isWindowsMSVCEnvironment())
  142. return EHPersonality::MSVC_CxxFrameHandler3;
  143. if (L.SjLjExceptions)
  144. return EHPersonality::GNU_CPlusPlus_SJLJ;
  145. if (L.DWARFExceptions)
  146. return EHPersonality::GNU_CPlusPlus;
  147. if (L.SEHExceptions)
  148. return EHPersonality::GNU_CPlusPlus_SEH;
  149. if (L.WasmExceptions)
  150. return EHPersonality::GNU_Wasm_CPlusPlus;
  151. return EHPersonality::GNU_CPlusPlus;
  152. }
  153. /// Determines the personality function to use when both C++
  154. /// and Objective-C exceptions are being caught.
  155. static const EHPersonality &getObjCXXPersonality(const TargetInfo &Target,
  156. const LangOptions &L) {
  157. if (Target.getTriple().isWindowsMSVCEnvironment())
  158. return EHPersonality::MSVC_CxxFrameHandler3;
  159. switch (L.ObjCRuntime.getKind()) {
  160. // In the fragile ABI, just use C++ exception handling and hope
  161. // they're not doing crazy exception mixing.
  162. case ObjCRuntime::FragileMacOSX:
  163. return getCXXPersonality(Target, L);
  164. // The ObjC personality defers to the C++ personality for non-ObjC
  165. // handlers. Unlike the C++ case, we use the same personality
  166. // function on targets using (backend-driven) SJLJ EH.
  167. case ObjCRuntime::MacOSX:
  168. case ObjCRuntime::iOS:
  169. case ObjCRuntime::WatchOS:
  170. return getObjCPersonality(Target, L);
  171. case ObjCRuntime::GNUstep:
  172. return EHPersonality::GNU_ObjCXX;
  173. // The GCC runtime's personality function inherently doesn't support
  174. // mixed EH. Use the ObjC personality just to avoid returning null.
  175. case ObjCRuntime::GCC:
  176. case ObjCRuntime::ObjFW:
  177. return getObjCPersonality(Target, L);
  178. }
  179. llvm_unreachable("bad runtime kind");
  180. }
  181. static const EHPersonality &getSEHPersonalityMSVC(const llvm::Triple &T) {
  182. if (T.getArch() == llvm::Triple::x86)
  183. return EHPersonality::MSVC_except_handler;
  184. return EHPersonality::MSVC_C_specific_handler;
  185. }
  186. const EHPersonality &EHPersonality::get(CodeGenModule &CGM,
  187. const FunctionDecl *FD) {
  188. const llvm::Triple &T = CGM.getTarget().getTriple();
  189. const LangOptions &L = CGM.getLangOpts();
  190. const TargetInfo &Target = CGM.getTarget();
  191. // Functions using SEH get an SEH personality.
  192. if (FD && FD->usesSEHTry())
  193. return getSEHPersonalityMSVC(T);
  194. if (L.ObjC)
  195. return L.CPlusPlus ? getObjCXXPersonality(Target, L)
  196. : getObjCPersonality(Target, L);
  197. return L.CPlusPlus ? getCXXPersonality(Target, L)
  198. : getCPersonality(Target, L);
  199. }
  200. const EHPersonality &EHPersonality::get(CodeGenFunction &CGF) {
  201. const auto *FD = CGF.CurCodeDecl;
  202. // For outlined finallys and filters, use the SEH personality in case they
  203. // contain more SEH. This mostly only affects finallys. Filters could
  204. // hypothetically use gnu statement expressions to sneak in nested SEH.
  205. FD = FD ? FD : CGF.CurSEHParent;
  206. return get(CGF.CGM, dyn_cast_or_null<FunctionDecl>(FD));
  207. }
  208. static llvm::FunctionCallee getPersonalityFn(CodeGenModule &CGM,
  209. const EHPersonality &Personality) {
  210. return CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.Int32Ty, true),
  211. Personality.PersonalityFn,
  212. llvm::AttributeList(), /*Local=*/true);
  213. }
  214. static llvm::Constant *getOpaquePersonalityFn(CodeGenModule &CGM,
  215. const EHPersonality &Personality) {
  216. llvm::FunctionCallee Fn = getPersonalityFn(CGM, Personality);
  217. llvm::PointerType* Int8PtrTy = llvm::PointerType::get(
  218. llvm::Type::getInt8Ty(CGM.getLLVMContext()),
  219. CGM.getDataLayout().getProgramAddressSpace());
  220. return llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(Fn.getCallee()),
  221. Int8PtrTy);
  222. }
  223. /// Check whether a landingpad instruction only uses C++ features.
  224. static bool LandingPadHasOnlyCXXUses(llvm::LandingPadInst *LPI) {
  225. for (unsigned I = 0, E = LPI->getNumClauses(); I != E; ++I) {
  226. // Look for something that would've been returned by the ObjC
  227. // runtime's GetEHType() method.
  228. llvm::Value *Val = LPI->getClause(I)->stripPointerCasts();
  229. if (LPI->isCatch(I)) {
  230. // Check if the catch value has the ObjC prefix.
  231. if (llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Val))
  232. // ObjC EH selector entries are always global variables with
  233. // names starting like this.
  234. if (GV->getName().startswith("OBJC_EHTYPE"))
  235. return false;
  236. } else {
  237. // Check if any of the filter values have the ObjC prefix.
  238. llvm::Constant *CVal = cast<llvm::Constant>(Val);
  239. for (llvm::User::op_iterator
  240. II = CVal->op_begin(), IE = CVal->op_end(); II != IE; ++II) {
  241. if (llvm::GlobalVariable *GV =
  242. cast<llvm::GlobalVariable>((*II)->stripPointerCasts()))
  243. // ObjC EH selector entries are always global variables with
  244. // names starting like this.
  245. if (GV->getName().startswith("OBJC_EHTYPE"))
  246. return false;
  247. }
  248. }
  249. }
  250. return true;
  251. }
  252. /// Check whether a personality function could reasonably be swapped
  253. /// for a C++ personality function.
  254. static bool PersonalityHasOnlyCXXUses(llvm::Constant *Fn) {
  255. for (llvm::User *U : Fn->users()) {
  256. // Conditionally white-list bitcasts.
  257. if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(U)) {
  258. if (CE->getOpcode() != llvm::Instruction::BitCast) return false;
  259. if (!PersonalityHasOnlyCXXUses(CE))
  260. return false;
  261. continue;
  262. }
  263. // Otherwise it must be a function.
  264. llvm::Function *F = dyn_cast<llvm::Function>(U);
  265. if (!F) return false;
  266. for (auto BB = F->begin(), E = F->end(); BB != E; ++BB) {
  267. if (BB->isLandingPad())
  268. if (!LandingPadHasOnlyCXXUses(BB->getLandingPadInst()))
  269. return false;
  270. }
  271. }
  272. return true;
  273. }
  274. /// Try to use the C++ personality function in ObjC++. Not doing this
  275. /// can cause some incompatibilities with gcc, which is more
  276. /// aggressive about only using the ObjC++ personality in a function
  277. /// when it really needs it.
  278. void CodeGenModule::SimplifyPersonality() {
  279. // If we're not in ObjC++ -fexceptions, there's nothing to do.
  280. if (!LangOpts.CPlusPlus || !LangOpts.ObjC || !LangOpts.Exceptions)
  281. return;
  282. // Both the problem this endeavors to fix and the way the logic
  283. // above works is specific to the NeXT runtime.
  284. if (!LangOpts.ObjCRuntime.isNeXTFamily())
  285. return;
  286. const EHPersonality &ObjCXX = EHPersonality::get(*this, /*FD=*/nullptr);
  287. const EHPersonality &CXX = getCXXPersonality(getTarget(), LangOpts);
  288. if (&ObjCXX == &CXX)
  289. return;
  290. assert(std::strcmp(ObjCXX.PersonalityFn, CXX.PersonalityFn) != 0 &&
  291. "Different EHPersonalities using the same personality function.");
  292. llvm::Function *Fn = getModule().getFunction(ObjCXX.PersonalityFn);
  293. // Nothing to do if it's unused.
  294. if (!Fn || Fn->use_empty()) return;
  295. // Can't do the optimization if it has non-C++ uses.
  296. if (!PersonalityHasOnlyCXXUses(Fn)) return;
  297. // Create the C++ personality function and kill off the old
  298. // function.
  299. llvm::FunctionCallee CXXFn = getPersonalityFn(*this, CXX);
  300. // This can happen if the user is screwing with us.
  301. if (Fn->getType() != CXXFn.getCallee()->getType())
  302. return;
  303. Fn->replaceAllUsesWith(CXXFn.getCallee());
  304. Fn->eraseFromParent();
  305. }
  306. /// Returns the value to inject into a selector to indicate the
  307. /// presence of a catch-all.
  308. static llvm::Constant *getCatchAllValue(CodeGenFunction &CGF) {
  309. // Possibly we should use @llvm.eh.catch.all.value here.
  310. return llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
  311. }
  312. namespace {
  313. /// A cleanup to free the exception object if its initialization
  314. /// throws.
  315. struct FreeException final : EHScopeStack::Cleanup {
  316. llvm::Value *exn;
  317. FreeException(llvm::Value *exn) : exn(exn) {}
  318. void Emit(CodeGenFunction &CGF, Flags flags) override {
  319. CGF.EmitNounwindRuntimeCall(getFreeExceptionFn(CGF.CGM), exn);
  320. }
  321. };
  322. } // end anonymous namespace
  323. // Emits an exception expression into the given location. This
  324. // differs from EmitAnyExprToMem only in that, if a final copy-ctor
  325. // call is required, an exception within that copy ctor causes
  326. // std::terminate to be invoked.
  327. void CodeGenFunction::EmitAnyExprToExn(const Expr *e, Address addr) {
  328. // Make sure the exception object is cleaned up if there's an
  329. // exception during initialization.
  330. pushFullExprCleanup<FreeException>(EHCleanup, addr.getPointer());
  331. EHScopeStack::stable_iterator cleanup = EHStack.stable_begin();
  332. // __cxa_allocate_exception returns a void*; we need to cast this
  333. // to the appropriate type for the object.
  334. llvm::Type *ty = ConvertTypeForMem(e->getType())->getPointerTo();
  335. Address typedAddr = Builder.CreateBitCast(addr, ty);
  336. // FIXME: this isn't quite right! If there's a final unelided call
  337. // to a copy constructor, then according to [except.terminate]p1 we
  338. // must call std::terminate() if that constructor throws, because
  339. // technically that copy occurs after the exception expression is
  340. // evaluated but before the exception is caught. But the best way
  341. // to handle that is to teach EmitAggExpr to do the final copy
  342. // differently if it can't be elided.
  343. EmitAnyExprToMem(e, typedAddr, e->getType().getQualifiers(),
  344. /*IsInit*/ true);
  345. // Deactivate the cleanup block.
  346. DeactivateCleanupBlock(cleanup,
  347. cast<llvm::Instruction>(typedAddr.getPointer()));
  348. }
  349. Address CodeGenFunction::getExceptionSlot() {
  350. if (!ExceptionSlot)
  351. ExceptionSlot = CreateTempAlloca(Int8PtrTy, "exn.slot");
  352. return Address(ExceptionSlot, getPointerAlign());
  353. }
  354. Address CodeGenFunction::getEHSelectorSlot() {
  355. if (!EHSelectorSlot)
  356. EHSelectorSlot = CreateTempAlloca(Int32Ty, "ehselector.slot");
  357. return Address(EHSelectorSlot, CharUnits::fromQuantity(4));
  358. }
  359. llvm::Value *CodeGenFunction::getExceptionFromSlot() {
  360. return Builder.CreateLoad(getExceptionSlot(), "exn");
  361. }
  362. llvm::Value *CodeGenFunction::getSelectorFromSlot() {
  363. return Builder.CreateLoad(getEHSelectorSlot(), "sel");
  364. }
  365. void CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr *E,
  366. bool KeepInsertionPoint) {
  367. if (const Expr *SubExpr = E->getSubExpr()) {
  368. QualType ThrowType = SubExpr->getType();
  369. if (ThrowType->isObjCObjectPointerType()) {
  370. const Stmt *ThrowStmt = E->getSubExpr();
  371. const ObjCAtThrowStmt S(E->getExprLoc(), const_cast<Stmt *>(ThrowStmt));
  372. CGM.getObjCRuntime().EmitThrowStmt(*this, S, false);
  373. } else {
  374. CGM.getCXXABI().emitThrow(*this, E);
  375. }
  376. } else {
  377. CGM.getCXXABI().emitRethrow(*this, /*isNoReturn=*/true);
  378. }
  379. // throw is an expression, and the expression emitters expect us
  380. // to leave ourselves at a valid insertion point.
  381. if (KeepInsertionPoint)
  382. EmitBlock(createBasicBlock("throw.cont"));
  383. }
  384. void CodeGenFunction::EmitStartEHSpec(const Decl *D) {
  385. if (!CGM.getLangOpts().CXXExceptions)
  386. return;
  387. const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
  388. if (!FD) {
  389. // Check if CapturedDecl is nothrow and create terminate scope for it.
  390. if (const CapturedDecl* CD = dyn_cast_or_null<CapturedDecl>(D)) {
  391. if (CD->isNothrow())
  392. EHStack.pushTerminate();
  393. }
  394. return;
  395. }
  396. const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
  397. if (!Proto)
  398. return;
  399. ExceptionSpecificationType EST = Proto->getExceptionSpecType();
  400. if (isNoexceptExceptionSpec(EST) && Proto->canThrow() == CT_Cannot) {
  401. // noexcept functions are simple terminate scopes.
  402. EHStack.pushTerminate();
  403. } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
  404. // TODO: Revisit exception specifications for the MS ABI. There is a way to
  405. // encode these in an object file but MSVC doesn't do anything with it.
  406. if (getTarget().getCXXABI().isMicrosoft())
  407. return;
  408. unsigned NumExceptions = Proto->getNumExceptions();
  409. EHFilterScope *Filter = EHStack.pushFilter(NumExceptions);
  410. for (unsigned I = 0; I != NumExceptions; ++I) {
  411. QualType Ty = Proto->getExceptionType(I);
  412. QualType ExceptType = Ty.getNonReferenceType().getUnqualifiedType();
  413. llvm::Value *EHType = CGM.GetAddrOfRTTIDescriptor(ExceptType,
  414. /*ForEH=*/true);
  415. Filter->setFilter(I, EHType);
  416. }
  417. }
  418. }
  419. /// Emit the dispatch block for a filter scope if necessary.
  420. static void emitFilterDispatchBlock(CodeGenFunction &CGF,
  421. EHFilterScope &filterScope) {
  422. llvm::BasicBlock *dispatchBlock = filterScope.getCachedEHDispatchBlock();
  423. if (!dispatchBlock) return;
  424. if (dispatchBlock->use_empty()) {
  425. delete dispatchBlock;
  426. return;
  427. }
  428. CGF.EmitBlockAfterUses(dispatchBlock);
  429. // If this isn't a catch-all filter, we need to check whether we got
  430. // here because the filter triggered.
  431. if (filterScope.getNumFilters()) {
  432. // Load the selector value.
  433. llvm::Value *selector = CGF.getSelectorFromSlot();
  434. llvm::BasicBlock *unexpectedBB = CGF.createBasicBlock("ehspec.unexpected");
  435. llvm::Value *zero = CGF.Builder.getInt32(0);
  436. llvm::Value *failsFilter =
  437. CGF.Builder.CreateICmpSLT(selector, zero, "ehspec.fails");
  438. CGF.Builder.CreateCondBr(failsFilter, unexpectedBB,
  439. CGF.getEHResumeBlock(false));
  440. CGF.EmitBlock(unexpectedBB);
  441. }
  442. // Call __cxa_call_unexpected. This doesn't need to be an invoke
  443. // because __cxa_call_unexpected magically filters exceptions
  444. // according to the last landing pad the exception was thrown
  445. // into. Seriously.
  446. llvm::Value *exn = CGF.getExceptionFromSlot();
  447. CGF.EmitRuntimeCall(getUnexpectedFn(CGF.CGM), exn)
  448. ->setDoesNotReturn();
  449. CGF.Builder.CreateUnreachable();
  450. }
  451. void CodeGenFunction::EmitEndEHSpec(const Decl *D) {
  452. if (!CGM.getLangOpts().CXXExceptions)
  453. return;
  454. const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
  455. if (!FD) {
  456. // Check if CapturedDecl is nothrow and pop terminate scope for it.
  457. if (const CapturedDecl* CD = dyn_cast_or_null<CapturedDecl>(D)) {
  458. if (CD->isNothrow())
  459. EHStack.popTerminate();
  460. }
  461. return;
  462. }
  463. const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
  464. if (!Proto)
  465. return;
  466. ExceptionSpecificationType EST = Proto->getExceptionSpecType();
  467. if (isNoexceptExceptionSpec(EST) && Proto->canThrow() == CT_Cannot) {
  468. EHStack.popTerminate();
  469. } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
  470. // TODO: Revisit exception specifications for the MS ABI. There is a way to
  471. // encode these in an object file but MSVC doesn't do anything with it.
  472. if (getTarget().getCXXABI().isMicrosoft())
  473. return;
  474. EHFilterScope &filterScope = cast<EHFilterScope>(*EHStack.begin());
  475. emitFilterDispatchBlock(*this, filterScope);
  476. EHStack.popFilter();
  477. }
  478. }
  479. void CodeGenFunction::EmitCXXTryStmt(const CXXTryStmt &S) {
  480. EnterCXXTryStmt(S);
  481. EmitStmt(S.getTryBlock());
  482. ExitCXXTryStmt(S);
  483. }
  484. void CodeGenFunction::EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
  485. unsigned NumHandlers = S.getNumHandlers();
  486. EHCatchScope *CatchScope = EHStack.pushCatch(NumHandlers);
  487. for (unsigned I = 0; I != NumHandlers; ++I) {
  488. const CXXCatchStmt *C = S.getHandler(I);
  489. llvm::BasicBlock *Handler = createBasicBlock("catch");
  490. if (C->getExceptionDecl()) {
  491. // FIXME: Dropping the reference type on the type into makes it
  492. // impossible to correctly implement catch-by-reference
  493. // semantics for pointers. Unfortunately, this is what all
  494. // existing compilers do, and it's not clear that the standard
  495. // personality routine is capable of doing this right. See C++ DR 388:
  496. // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#388
  497. Qualifiers CaughtTypeQuals;
  498. QualType CaughtType = CGM.getContext().getUnqualifiedArrayType(
  499. C->getCaughtType().getNonReferenceType(), CaughtTypeQuals);
  500. CatchTypeInfo TypeInfo{nullptr, 0};
  501. if (CaughtType->isObjCObjectPointerType())
  502. TypeInfo.RTTI = CGM.getObjCRuntime().GetEHType(CaughtType);
  503. else
  504. TypeInfo = CGM.getCXXABI().getAddrOfCXXCatchHandlerType(
  505. CaughtType, C->getCaughtType());
  506. CatchScope->setHandler(I, TypeInfo, Handler);
  507. } else {
  508. // No exception decl indicates '...', a catch-all.
  509. CatchScope->setHandler(I, CGM.getCXXABI().getCatchAllTypeInfo(), Handler);
  510. }
  511. }
  512. }
  513. llvm::BasicBlock *
  514. CodeGenFunction::getEHDispatchBlock(EHScopeStack::stable_iterator si) {
  515. if (EHPersonality::get(*this).usesFuncletPads())
  516. return getFuncletEHDispatchBlock(si);
  517. // The dispatch block for the end of the scope chain is a block that
  518. // just resumes unwinding.
  519. if (si == EHStack.stable_end())
  520. return getEHResumeBlock(true);
  521. // Otherwise, we should look at the actual scope.
  522. EHScope &scope = *EHStack.find(si);
  523. llvm::BasicBlock *dispatchBlock = scope.getCachedEHDispatchBlock();
  524. if (!dispatchBlock) {
  525. switch (scope.getKind()) {
  526. case EHScope::Catch: {
  527. // Apply a special case to a single catch-all.
  528. EHCatchScope &catchScope = cast<EHCatchScope>(scope);
  529. if (catchScope.getNumHandlers() == 1 &&
  530. catchScope.getHandler(0).isCatchAll()) {
  531. dispatchBlock = catchScope.getHandler(0).Block;
  532. // Otherwise, make a dispatch block.
  533. } else {
  534. dispatchBlock = createBasicBlock("catch.dispatch");
  535. }
  536. break;
  537. }
  538. case EHScope::Cleanup:
  539. dispatchBlock = createBasicBlock("ehcleanup");
  540. break;
  541. case EHScope::Filter:
  542. dispatchBlock = createBasicBlock("filter.dispatch");
  543. break;
  544. case EHScope::Terminate:
  545. dispatchBlock = getTerminateHandler();
  546. break;
  547. case EHScope::PadEnd:
  548. llvm_unreachable("PadEnd unnecessary for Itanium!");
  549. }
  550. scope.setCachedEHDispatchBlock(dispatchBlock);
  551. }
  552. return dispatchBlock;
  553. }
  554. llvm::BasicBlock *
  555. CodeGenFunction::getFuncletEHDispatchBlock(EHScopeStack::stable_iterator SI) {
  556. // Returning nullptr indicates that the previous dispatch block should unwind
  557. // to caller.
  558. if (SI == EHStack.stable_end())
  559. return nullptr;
  560. // Otherwise, we should look at the actual scope.
  561. EHScope &EHS = *EHStack.find(SI);
  562. llvm::BasicBlock *DispatchBlock = EHS.getCachedEHDispatchBlock();
  563. if (DispatchBlock)
  564. return DispatchBlock;
  565. if (EHS.getKind() == EHScope::Terminate)
  566. DispatchBlock = getTerminateFunclet();
  567. else
  568. DispatchBlock = createBasicBlock();
  569. CGBuilderTy Builder(*this, DispatchBlock);
  570. switch (EHS.getKind()) {
  571. case EHScope::Catch:
  572. DispatchBlock->setName("catch.dispatch");
  573. break;
  574. case EHScope::Cleanup:
  575. DispatchBlock->setName("ehcleanup");
  576. break;
  577. case EHScope::Filter:
  578. llvm_unreachable("exception specifications not handled yet!");
  579. case EHScope::Terminate:
  580. DispatchBlock->setName("terminate");
  581. break;
  582. case EHScope::PadEnd:
  583. llvm_unreachable("PadEnd dispatch block missing!");
  584. }
  585. EHS.setCachedEHDispatchBlock(DispatchBlock);
  586. return DispatchBlock;
  587. }
  588. /// Check whether this is a non-EH scope, i.e. a scope which doesn't
  589. /// affect exception handling. Currently, the only non-EH scopes are
  590. /// normal-only cleanup scopes.
  591. static bool isNonEHScope(const EHScope &S) {
  592. switch (S.getKind()) {
  593. case EHScope::Cleanup:
  594. return !cast<EHCleanupScope>(S).isEHCleanup();
  595. case EHScope::Filter:
  596. case EHScope::Catch:
  597. case EHScope::Terminate:
  598. case EHScope::PadEnd:
  599. return false;
  600. }
  601. llvm_unreachable("Invalid EHScope Kind!");
  602. }
  603. llvm::BasicBlock *CodeGenFunction::getInvokeDestImpl() {
  604. assert(EHStack.requiresLandingPad());
  605. assert(!EHStack.empty());
  606. // If exceptions are disabled and SEH is not in use, then there is no invoke
  607. // destination. SEH "works" even if exceptions are off. In practice, this
  608. // means that C++ destructors and other EH cleanups don't run, which is
  609. // consistent with MSVC's behavior.
  610. const LangOptions &LO = CGM.getLangOpts();
  611. if (!LO.Exceptions) {
  612. if (!LO.Borland && !LO.MicrosoftExt)
  613. return nullptr;
  614. if (!currentFunctionUsesSEHTry())
  615. return nullptr;
  616. }
  617. // CUDA device code doesn't have exceptions.
  618. if (LO.CUDA && LO.CUDAIsDevice)
  619. return nullptr;
  620. // Check the innermost scope for a cached landing pad. If this is
  621. // a non-EH cleanup, we'll check enclosing scopes in EmitLandingPad.
  622. llvm::BasicBlock *LP = EHStack.begin()->getCachedLandingPad();
  623. if (LP) return LP;
  624. const EHPersonality &Personality = EHPersonality::get(*this);
  625. if (!CurFn->hasPersonalityFn())
  626. CurFn->setPersonalityFn(getOpaquePersonalityFn(CGM, Personality));
  627. if (Personality.usesFuncletPads()) {
  628. // We don't need separate landing pads in the funclet model.
  629. LP = getEHDispatchBlock(EHStack.getInnermostEHScope());
  630. } else {
  631. // Build the landing pad for this scope.
  632. LP = EmitLandingPad();
  633. }
  634. assert(LP);
  635. // Cache the landing pad on the innermost scope. If this is a
  636. // non-EH scope, cache the landing pad on the enclosing scope, too.
  637. for (EHScopeStack::iterator ir = EHStack.begin(); true; ++ir) {
  638. ir->setCachedLandingPad(LP);
  639. if (!isNonEHScope(*ir)) break;
  640. }
  641. return LP;
  642. }
  643. llvm::BasicBlock *CodeGenFunction::EmitLandingPad() {
  644. assert(EHStack.requiresLandingPad());
  645. EHScope &innermostEHScope = *EHStack.find(EHStack.getInnermostEHScope());
  646. switch (innermostEHScope.getKind()) {
  647. case EHScope::Terminate:
  648. return getTerminateLandingPad();
  649. case EHScope::PadEnd:
  650. llvm_unreachable("PadEnd unnecessary for Itanium!");
  651. case EHScope::Catch:
  652. case EHScope::Cleanup:
  653. case EHScope::Filter:
  654. if (llvm::BasicBlock *lpad = innermostEHScope.getCachedLandingPad())
  655. return lpad;
  656. }
  657. // Save the current IR generation state.
  658. CGBuilderTy::InsertPoint savedIP = Builder.saveAndClearIP();
  659. auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, CurEHLocation);
  660. // Create and configure the landing pad.
  661. llvm::BasicBlock *lpad = createBasicBlock("lpad");
  662. EmitBlock(lpad);
  663. llvm::LandingPadInst *LPadInst =
  664. Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty), 0);
  665. llvm::Value *LPadExn = Builder.CreateExtractValue(LPadInst, 0);
  666. Builder.CreateStore(LPadExn, getExceptionSlot());
  667. llvm::Value *LPadSel = Builder.CreateExtractValue(LPadInst, 1);
  668. Builder.CreateStore(LPadSel, getEHSelectorSlot());
  669. // Save the exception pointer. It's safe to use a single exception
  670. // pointer per function because EH cleanups can never have nested
  671. // try/catches.
  672. // Build the landingpad instruction.
  673. // Accumulate all the handlers in scope.
  674. bool hasCatchAll = false;
  675. bool hasCleanup = false;
  676. bool hasFilter = false;
  677. SmallVector<llvm::Value*, 4> filterTypes;
  678. llvm::SmallPtrSet<llvm::Value*, 4> catchTypes;
  679. for (EHScopeStack::iterator I = EHStack.begin(), E = EHStack.end(); I != E;
  680. ++I) {
  681. switch (I->getKind()) {
  682. case EHScope::Cleanup:
  683. // If we have a cleanup, remember that.
  684. hasCleanup = (hasCleanup || cast<EHCleanupScope>(*I).isEHCleanup());
  685. continue;
  686. case EHScope::Filter: {
  687. assert(I.next() == EHStack.end() && "EH filter is not end of EH stack");
  688. assert(!hasCatchAll && "EH filter reached after catch-all");
  689. // Filter scopes get added to the landingpad in weird ways.
  690. EHFilterScope &filter = cast<EHFilterScope>(*I);
  691. hasFilter = true;
  692. // Add all the filter values.
  693. for (unsigned i = 0, e = filter.getNumFilters(); i != e; ++i)
  694. filterTypes.push_back(filter.getFilter(i));
  695. goto done;
  696. }
  697. case EHScope::Terminate:
  698. // Terminate scopes are basically catch-alls.
  699. assert(!hasCatchAll);
  700. hasCatchAll = true;
  701. goto done;
  702. case EHScope::Catch:
  703. break;
  704. case EHScope::PadEnd:
  705. llvm_unreachable("PadEnd unnecessary for Itanium!");
  706. }
  707. EHCatchScope &catchScope = cast<EHCatchScope>(*I);
  708. for (unsigned hi = 0, he = catchScope.getNumHandlers(); hi != he; ++hi) {
  709. EHCatchScope::Handler handler = catchScope.getHandler(hi);
  710. assert(handler.Type.Flags == 0 &&
  711. "landingpads do not support catch handler flags");
  712. // If this is a catch-all, register that and abort.
  713. if (!handler.Type.RTTI) {
  714. assert(!hasCatchAll);
  715. hasCatchAll = true;
  716. goto done;
  717. }
  718. // Check whether we already have a handler for this type.
  719. if (catchTypes.insert(handler.Type.RTTI).second)
  720. // If not, add it directly to the landingpad.
  721. LPadInst->addClause(handler.Type.RTTI);
  722. }
  723. }
  724. done:
  725. // If we have a catch-all, add null to the landingpad.
  726. assert(!(hasCatchAll && hasFilter));
  727. if (hasCatchAll) {
  728. LPadInst->addClause(getCatchAllValue(*this));
  729. // If we have an EH filter, we need to add those handlers in the
  730. // right place in the landingpad, which is to say, at the end.
  731. } else if (hasFilter) {
  732. // Create a filter expression: a constant array indicating which filter
  733. // types there are. The personality routine only lands here if the filter
  734. // doesn't match.
  735. SmallVector<llvm::Constant*, 8> Filters;
  736. llvm::ArrayType *AType =
  737. llvm::ArrayType::get(!filterTypes.empty() ?
  738. filterTypes[0]->getType() : Int8PtrTy,
  739. filterTypes.size());
  740. for (unsigned i = 0, e = filterTypes.size(); i != e; ++i)
  741. Filters.push_back(cast<llvm::Constant>(filterTypes[i]));
  742. llvm::Constant *FilterArray = llvm::ConstantArray::get(AType, Filters);
  743. LPadInst->addClause(FilterArray);
  744. // Also check whether we need a cleanup.
  745. if (hasCleanup)
  746. LPadInst->setCleanup(true);
  747. // Otherwise, signal that we at least have cleanups.
  748. } else if (hasCleanup) {
  749. LPadInst->setCleanup(true);
  750. }
  751. assert((LPadInst->getNumClauses() > 0 || LPadInst->isCleanup()) &&
  752. "landingpad instruction has no clauses!");
  753. // Tell the backend how to generate the landing pad.
  754. Builder.CreateBr(getEHDispatchBlock(EHStack.getInnermostEHScope()));
  755. // Restore the old IR generation state.
  756. Builder.restoreIP(savedIP);
  757. return lpad;
  758. }
  759. static void emitCatchPadBlock(CodeGenFunction &CGF, EHCatchScope &CatchScope) {
  760. llvm::BasicBlock *DispatchBlock = CatchScope.getCachedEHDispatchBlock();
  761. assert(DispatchBlock);
  762. CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveIP();
  763. CGF.EmitBlockAfterUses(DispatchBlock);
  764. llvm::Value *ParentPad = CGF.CurrentFuncletPad;
  765. if (!ParentPad)
  766. ParentPad = llvm::ConstantTokenNone::get(CGF.getLLVMContext());
  767. llvm::BasicBlock *UnwindBB =
  768. CGF.getEHDispatchBlock(CatchScope.getEnclosingEHScope());
  769. unsigned NumHandlers = CatchScope.getNumHandlers();
  770. llvm::CatchSwitchInst *CatchSwitch =
  771. CGF.Builder.CreateCatchSwitch(ParentPad, UnwindBB, NumHandlers);
  772. // Test against each of the exception types we claim to catch.
  773. for (unsigned I = 0; I < NumHandlers; ++I) {
  774. const EHCatchScope::Handler &Handler = CatchScope.getHandler(I);
  775. CatchTypeInfo TypeInfo = Handler.Type;
  776. if (!TypeInfo.RTTI)
  777. TypeInfo.RTTI = llvm::Constant::getNullValue(CGF.VoidPtrTy);
  778. CGF.Builder.SetInsertPoint(Handler.Block);
  779. if (EHPersonality::get(CGF).isMSVCXXPersonality()) {
  780. CGF.Builder.CreateCatchPad(
  781. CatchSwitch, {TypeInfo.RTTI, CGF.Builder.getInt32(TypeInfo.Flags),
  782. llvm::Constant::getNullValue(CGF.VoidPtrTy)});
  783. } else {
  784. CGF.Builder.CreateCatchPad(CatchSwitch, {TypeInfo.RTTI});
  785. }
  786. CatchSwitch->addHandler(Handler.Block);
  787. }
  788. CGF.Builder.restoreIP(SavedIP);
  789. }
  790. // Wasm uses Windows-style EH instructions, but it merges all catch clauses into
  791. // one big catchpad, within which we use Itanium's landingpad-style selector
  792. // comparison instructions.
  793. static void emitWasmCatchPadBlock(CodeGenFunction &CGF,
  794. EHCatchScope &CatchScope) {
  795. llvm::BasicBlock *DispatchBlock = CatchScope.getCachedEHDispatchBlock();
  796. assert(DispatchBlock);
  797. CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveIP();
  798. CGF.EmitBlockAfterUses(DispatchBlock);
  799. llvm::Value *ParentPad = CGF.CurrentFuncletPad;
  800. if (!ParentPad)
  801. ParentPad = llvm::ConstantTokenNone::get(CGF.getLLVMContext());
  802. llvm::BasicBlock *UnwindBB =
  803. CGF.getEHDispatchBlock(CatchScope.getEnclosingEHScope());
  804. unsigned NumHandlers = CatchScope.getNumHandlers();
  805. llvm::CatchSwitchInst *CatchSwitch =
  806. CGF.Builder.CreateCatchSwitch(ParentPad, UnwindBB, NumHandlers);
  807. // We don't use a landingpad instruction, so generate intrinsic calls to
  808. // provide exception and selector values.
  809. llvm::BasicBlock *WasmCatchStartBlock = CGF.createBasicBlock("catch.start");
  810. CatchSwitch->addHandler(WasmCatchStartBlock);
  811. CGF.EmitBlockAfterUses(WasmCatchStartBlock);
  812. // Create a catchpad instruction.
  813. SmallVector<llvm::Value *, 4> CatchTypes;
  814. for (unsigned I = 0, E = NumHandlers; I < E; ++I) {
  815. const EHCatchScope::Handler &Handler = CatchScope.getHandler(I);
  816. CatchTypeInfo TypeInfo = Handler.Type;
  817. if (!TypeInfo.RTTI)
  818. TypeInfo.RTTI = llvm::Constant::getNullValue(CGF.VoidPtrTy);
  819. CatchTypes.push_back(TypeInfo.RTTI);
  820. }
  821. auto *CPI = CGF.Builder.CreateCatchPad(CatchSwitch, CatchTypes);
  822. // Create calls to wasm.get.exception and wasm.get.ehselector intrinsics.
  823. // Before they are lowered appropriately later, they provide values for the
  824. // exception and selector.
  825. llvm::Function *GetExnFn =
  826. CGF.CGM.getIntrinsic(llvm::Intrinsic::wasm_get_exception);
  827. llvm::Function *GetSelectorFn =
  828. CGF.CGM.getIntrinsic(llvm::Intrinsic::wasm_get_ehselector);
  829. llvm::CallInst *Exn = CGF.Builder.CreateCall(GetExnFn, CPI);
  830. CGF.Builder.CreateStore(Exn, CGF.getExceptionSlot());
  831. llvm::CallInst *Selector = CGF.Builder.CreateCall(GetSelectorFn, CPI);
  832. llvm::Function *TypeIDFn = CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
  833. // If there's only a single catch-all, branch directly to its handler.
  834. if (CatchScope.getNumHandlers() == 1 &&
  835. CatchScope.getHandler(0).isCatchAll()) {
  836. CGF.Builder.CreateBr(CatchScope.getHandler(0).Block);
  837. CGF.Builder.restoreIP(SavedIP);
  838. return;
  839. }
  840. // Test against each of the exception types we claim to catch.
  841. for (unsigned I = 0, E = NumHandlers;; ++I) {
  842. assert(I < E && "ran off end of handlers!");
  843. const EHCatchScope::Handler &Handler = CatchScope.getHandler(I);
  844. CatchTypeInfo TypeInfo = Handler.Type;
  845. if (!TypeInfo.RTTI)
  846. TypeInfo.RTTI = llvm::Constant::getNullValue(CGF.VoidPtrTy);
  847. // Figure out the next block.
  848. llvm::BasicBlock *NextBlock;
  849. bool EmitNextBlock = false, NextIsEnd = false;
  850. // If this is the last handler, we're at the end, and the next block is a
  851. // block that contains a call to the rethrow function, so we can unwind to
  852. // the enclosing EH scope. The call itself will be generated later.
  853. if (I + 1 == E) {
  854. NextBlock = CGF.createBasicBlock("rethrow");
  855. EmitNextBlock = true;
  856. NextIsEnd = true;
  857. // If the next handler is a catch-all, we're at the end, and the
  858. // next block is that handler.
  859. } else if (CatchScope.getHandler(I + 1).isCatchAll()) {
  860. NextBlock = CatchScope.getHandler(I + 1).Block;
  861. NextIsEnd = true;
  862. // Otherwise, we're not at the end and we need a new block.
  863. } else {
  864. NextBlock = CGF.createBasicBlock("catch.fallthrough");
  865. EmitNextBlock = true;
  866. }
  867. // Figure out the catch type's index in the LSDA's type table.
  868. llvm::CallInst *TypeIndex = CGF.Builder.CreateCall(TypeIDFn, TypeInfo.RTTI);
  869. TypeIndex->setDoesNotThrow();
  870. llvm::Value *MatchesTypeIndex =
  871. CGF.Builder.CreateICmpEQ(Selector, TypeIndex, "matches");
  872. CGF.Builder.CreateCondBr(MatchesTypeIndex, Handler.Block, NextBlock);
  873. if (EmitNextBlock)
  874. CGF.EmitBlock(NextBlock);
  875. if (NextIsEnd)
  876. break;
  877. }
  878. CGF.Builder.restoreIP(SavedIP);
  879. }
  880. /// Emit the structure of the dispatch block for the given catch scope.
  881. /// It is an invariant that the dispatch block already exists.
  882. static void emitCatchDispatchBlock(CodeGenFunction &CGF,
  883. EHCatchScope &catchScope) {
  884. if (EHPersonality::get(CGF).isWasmPersonality())
  885. return emitWasmCatchPadBlock(CGF, catchScope);
  886. if (EHPersonality::get(CGF).usesFuncletPads())
  887. return emitCatchPadBlock(CGF, catchScope);
  888. llvm::BasicBlock *dispatchBlock = catchScope.getCachedEHDispatchBlock();
  889. assert(dispatchBlock);
  890. // If there's only a single catch-all, getEHDispatchBlock returned
  891. // that catch-all as the dispatch block.
  892. if (catchScope.getNumHandlers() == 1 &&
  893. catchScope.getHandler(0).isCatchAll()) {
  894. assert(dispatchBlock == catchScope.getHandler(0).Block);
  895. return;
  896. }
  897. CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveIP();
  898. CGF.EmitBlockAfterUses(dispatchBlock);
  899. // Select the right handler.
  900. llvm::Function *llvm_eh_typeid_for =
  901. CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
  902. // Load the selector value.
  903. llvm::Value *selector = CGF.getSelectorFromSlot();
  904. // Test against each of the exception types we claim to catch.
  905. for (unsigned i = 0, e = catchScope.getNumHandlers(); ; ++i) {
  906. assert(i < e && "ran off end of handlers!");
  907. const EHCatchScope::Handler &handler = catchScope.getHandler(i);
  908. llvm::Value *typeValue = handler.Type.RTTI;
  909. assert(handler.Type.Flags == 0 &&
  910. "landingpads do not support catch handler flags");
  911. assert(typeValue && "fell into catch-all case!");
  912. typeValue = CGF.Builder.CreateBitCast(typeValue, CGF.Int8PtrTy);
  913. // Figure out the next block.
  914. bool nextIsEnd;
  915. llvm::BasicBlock *nextBlock;
  916. // If this is the last handler, we're at the end, and the next
  917. // block is the block for the enclosing EH scope.
  918. if (i + 1 == e) {
  919. nextBlock = CGF.getEHDispatchBlock(catchScope.getEnclosingEHScope());
  920. nextIsEnd = true;
  921. // If the next handler is a catch-all, we're at the end, and the
  922. // next block is that handler.
  923. } else if (catchScope.getHandler(i+1).isCatchAll()) {
  924. nextBlock = catchScope.getHandler(i+1).Block;
  925. nextIsEnd = true;
  926. // Otherwise, we're not at the end and we need a new block.
  927. } else {
  928. nextBlock = CGF.createBasicBlock("catch.fallthrough");
  929. nextIsEnd = false;
  930. }
  931. // Figure out the catch type's index in the LSDA's type table.
  932. llvm::CallInst *typeIndex =
  933. CGF.Builder.CreateCall(llvm_eh_typeid_for, typeValue);
  934. typeIndex->setDoesNotThrow();
  935. llvm::Value *matchesTypeIndex =
  936. CGF.Builder.CreateICmpEQ(selector, typeIndex, "matches");
  937. CGF.Builder.CreateCondBr(matchesTypeIndex, handler.Block, nextBlock);
  938. // If the next handler is a catch-all, we're completely done.
  939. if (nextIsEnd) {
  940. CGF.Builder.restoreIP(savedIP);
  941. return;
  942. }
  943. // Otherwise we need to emit and continue at that block.
  944. CGF.EmitBlock(nextBlock);
  945. }
  946. }
  947. void CodeGenFunction::popCatchScope() {
  948. EHCatchScope &catchScope = cast<EHCatchScope>(*EHStack.begin());
  949. if (catchScope.hasEHBranches())
  950. emitCatchDispatchBlock(*this, catchScope);
  951. EHStack.popCatch();
  952. }
  953. void CodeGenFunction::ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
  954. unsigned NumHandlers = S.getNumHandlers();
  955. EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
  956. assert(CatchScope.getNumHandlers() == NumHandlers);
  957. llvm::BasicBlock *DispatchBlock = CatchScope.getCachedEHDispatchBlock();
  958. // If the catch was not required, bail out now.
  959. if (!CatchScope.hasEHBranches()) {
  960. CatchScope.clearHandlerBlocks();
  961. EHStack.popCatch();
  962. return;
  963. }
  964. // Emit the structure of the EH dispatch for this catch.
  965. emitCatchDispatchBlock(*this, CatchScope);
  966. // Copy the handler blocks off before we pop the EH stack. Emitting
  967. // the handlers might scribble on this memory.
  968. SmallVector<EHCatchScope::Handler, 8> Handlers(
  969. CatchScope.begin(), CatchScope.begin() + NumHandlers);
  970. EHStack.popCatch();
  971. // The fall-through block.
  972. llvm::BasicBlock *ContBB = createBasicBlock("try.cont");
  973. // We just emitted the body of the try; jump to the continue block.
  974. if (HaveInsertPoint())
  975. Builder.CreateBr(ContBB);
  976. // Determine if we need an implicit rethrow for all these catch handlers;
  977. // see the comment below.
  978. bool doImplicitRethrow = false;
  979. if (IsFnTryBlock)
  980. doImplicitRethrow = isa<CXXDestructorDecl>(CurCodeDecl) ||
  981. isa<CXXConstructorDecl>(CurCodeDecl);
  982. // Wasm uses Windows-style EH instructions, but merges all catch clauses into
  983. // one big catchpad. So we save the old funclet pad here before we traverse
  984. // each catch handler.
  985. SaveAndRestore<llvm::Instruction *> RestoreCurrentFuncletPad(
  986. CurrentFuncletPad);
  987. llvm::BasicBlock *WasmCatchStartBlock = nullptr;
  988. if (EHPersonality::get(*this).isWasmPersonality()) {
  989. auto *CatchSwitch =
  990. cast<llvm::CatchSwitchInst>(DispatchBlock->getFirstNonPHI());
  991. WasmCatchStartBlock = CatchSwitch->hasUnwindDest()
  992. ? CatchSwitch->getSuccessor(1)
  993. : CatchSwitch->getSuccessor(0);
  994. auto *CPI = cast<llvm::CatchPadInst>(WasmCatchStartBlock->getFirstNonPHI());
  995. CurrentFuncletPad = CPI;
  996. }
  997. // Perversely, we emit the handlers backwards precisely because we
  998. // want them to appear in source order. In all of these cases, the
  999. // catch block will have exactly one predecessor, which will be a
  1000. // particular block in the catch dispatch. However, in the case of
  1001. // a catch-all, one of the dispatch blocks will branch to two
  1002. // different handlers, and EmitBlockAfterUses will cause the second
  1003. // handler to be moved before the first.
  1004. bool HasCatchAll = false;
  1005. for (unsigned I = NumHandlers; I != 0; --I) {
  1006. HasCatchAll |= Handlers[I - 1].isCatchAll();
  1007. llvm::BasicBlock *CatchBlock = Handlers[I-1].Block;
  1008. EmitBlockAfterUses(CatchBlock);
  1009. // Catch the exception if this isn't a catch-all.
  1010. const CXXCatchStmt *C = S.getHandler(I-1);
  1011. // Enter a cleanup scope, including the catch variable and the
  1012. // end-catch.
  1013. RunCleanupsScope CatchScope(*this);
  1014. // Initialize the catch variable and set up the cleanups.
  1015. SaveAndRestore<llvm::Instruction *> RestoreCurrentFuncletPad(
  1016. CurrentFuncletPad);
  1017. CGM.getCXXABI().emitBeginCatch(*this, C);
  1018. // Emit the PGO counter increment.
  1019. incrementProfileCounter(C);
  1020. // Perform the body of the catch.
  1021. EmitStmt(C->getHandlerBlock());
  1022. // [except.handle]p11:
  1023. // The currently handled exception is rethrown if control
  1024. // reaches the end of a handler of the function-try-block of a
  1025. // constructor or destructor.
  1026. // It is important that we only do this on fallthrough and not on
  1027. // return. Note that it's illegal to put a return in a
  1028. // constructor function-try-block's catch handler (p14), so this
  1029. // really only applies to destructors.
  1030. if (doImplicitRethrow && HaveInsertPoint()) {
  1031. CGM.getCXXABI().emitRethrow(*this, /*isNoReturn*/false);
  1032. Builder.CreateUnreachable();
  1033. Builder.ClearInsertionPoint();
  1034. }
  1035. // Fall out through the catch cleanups.
  1036. CatchScope.ForceCleanup();
  1037. // Branch out of the try.
  1038. if (HaveInsertPoint())
  1039. Builder.CreateBr(ContBB);
  1040. }
  1041. // Because in wasm we merge all catch clauses into one big catchpad, in case
  1042. // none of the types in catch handlers matches after we test against each of
  1043. // them, we should unwind to the next EH enclosing scope. We generate a call
  1044. // to rethrow function here to do that.
  1045. if (EHPersonality::get(*this).isWasmPersonality() && !HasCatchAll) {
  1046. assert(WasmCatchStartBlock);
  1047. // Navigate for the "rethrow" block we created in emitWasmCatchPadBlock().
  1048. // Wasm uses landingpad-style conditional branches to compare selectors, so
  1049. // we follow the false destination for each of the cond branches to reach
  1050. // the rethrow block.
  1051. llvm::BasicBlock *RethrowBlock = WasmCatchStartBlock;
  1052. while (llvm::Instruction *TI = RethrowBlock->getTerminator()) {
  1053. auto *BI = cast<llvm::BranchInst>(TI);
  1054. assert(BI->isConditional());
  1055. RethrowBlock = BI->getSuccessor(1);
  1056. }
  1057. assert(RethrowBlock != WasmCatchStartBlock && RethrowBlock->empty());
  1058. Builder.SetInsertPoint(RethrowBlock);
  1059. llvm::Function *RethrowInCatchFn =
  1060. CGM.getIntrinsic(llvm::Intrinsic::wasm_rethrow_in_catch);
  1061. EmitNoreturnRuntimeCallOrInvoke(RethrowInCatchFn, {});
  1062. }
  1063. EmitBlock(ContBB);
  1064. incrementProfileCounter(&S);
  1065. }
  1066. namespace {
  1067. struct CallEndCatchForFinally final : EHScopeStack::Cleanup {
  1068. llvm::Value *ForEHVar;
  1069. llvm::FunctionCallee EndCatchFn;
  1070. CallEndCatchForFinally(llvm::Value *ForEHVar,
  1071. llvm::FunctionCallee EndCatchFn)
  1072. : ForEHVar(ForEHVar), EndCatchFn(EndCatchFn) {}
  1073. void Emit(CodeGenFunction &CGF, Flags flags) override {
  1074. llvm::BasicBlock *EndCatchBB = CGF.createBasicBlock("finally.endcatch");
  1075. llvm::BasicBlock *CleanupContBB =
  1076. CGF.createBasicBlock("finally.cleanup.cont");
  1077. llvm::Value *ShouldEndCatch =
  1078. CGF.Builder.CreateFlagLoad(ForEHVar, "finally.endcatch");
  1079. CGF.Builder.CreateCondBr(ShouldEndCatch, EndCatchBB, CleanupContBB);
  1080. CGF.EmitBlock(EndCatchBB);
  1081. CGF.EmitRuntimeCallOrInvoke(EndCatchFn); // catch-all, so might throw
  1082. CGF.EmitBlock(CleanupContBB);
  1083. }
  1084. };
  1085. struct PerformFinally final : EHScopeStack::Cleanup {
  1086. const Stmt *Body;
  1087. llvm::Value *ForEHVar;
  1088. llvm::FunctionCallee EndCatchFn;
  1089. llvm::FunctionCallee RethrowFn;
  1090. llvm::Value *SavedExnVar;
  1091. PerformFinally(const Stmt *Body, llvm::Value *ForEHVar,
  1092. llvm::FunctionCallee EndCatchFn,
  1093. llvm::FunctionCallee RethrowFn, llvm::Value *SavedExnVar)
  1094. : Body(Body), ForEHVar(ForEHVar), EndCatchFn(EndCatchFn),
  1095. RethrowFn(RethrowFn), SavedExnVar(SavedExnVar) {}
  1096. void Emit(CodeGenFunction &CGF, Flags flags) override {
  1097. // Enter a cleanup to call the end-catch function if one was provided.
  1098. if (EndCatchFn)
  1099. CGF.EHStack.pushCleanup<CallEndCatchForFinally>(NormalAndEHCleanup,
  1100. ForEHVar, EndCatchFn);
  1101. // Save the current cleanup destination in case there are
  1102. // cleanups in the finally block.
  1103. llvm::Value *SavedCleanupDest =
  1104. CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot(),
  1105. "cleanup.dest.saved");
  1106. // Emit the finally block.
  1107. CGF.EmitStmt(Body);
  1108. // If the end of the finally is reachable, check whether this was
  1109. // for EH. If so, rethrow.
  1110. if (CGF.HaveInsertPoint()) {
  1111. llvm::BasicBlock *RethrowBB = CGF.createBasicBlock("finally.rethrow");
  1112. llvm::BasicBlock *ContBB = CGF.createBasicBlock("finally.cont");
  1113. llvm::Value *ShouldRethrow =
  1114. CGF.Builder.CreateFlagLoad(ForEHVar, "finally.shouldthrow");
  1115. CGF.Builder.CreateCondBr(ShouldRethrow, RethrowBB, ContBB);
  1116. CGF.EmitBlock(RethrowBB);
  1117. if (SavedExnVar) {
  1118. CGF.EmitRuntimeCallOrInvoke(RethrowFn,
  1119. CGF.Builder.CreateAlignedLoad(SavedExnVar, CGF.getPointerAlign()));
  1120. } else {
  1121. CGF.EmitRuntimeCallOrInvoke(RethrowFn);
  1122. }
  1123. CGF.Builder.CreateUnreachable();
  1124. CGF.EmitBlock(ContBB);
  1125. // Restore the cleanup destination.
  1126. CGF.Builder.CreateStore(SavedCleanupDest,
  1127. CGF.getNormalCleanupDestSlot());
  1128. }
  1129. // Leave the end-catch cleanup. As an optimization, pretend that
  1130. // the fallthrough path was inaccessible; we've dynamically proven
  1131. // that we're not in the EH case along that path.
  1132. if (EndCatchFn) {
  1133. CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
  1134. CGF.PopCleanupBlock();
  1135. CGF.Builder.restoreIP(SavedIP);
  1136. }
  1137. // Now make sure we actually have an insertion point or the
  1138. // cleanup gods will hate us.
  1139. CGF.EnsureInsertPoint();
  1140. }
  1141. };
  1142. } // end anonymous namespace
  1143. /// Enters a finally block for an implementation using zero-cost
  1144. /// exceptions. This is mostly general, but hard-codes some
  1145. /// language/ABI-specific behavior in the catch-all sections.
  1146. void CodeGenFunction::FinallyInfo::enter(CodeGenFunction &CGF, const Stmt *body,
  1147. llvm::FunctionCallee beginCatchFn,
  1148. llvm::FunctionCallee endCatchFn,
  1149. llvm::FunctionCallee rethrowFn) {
  1150. assert((!!beginCatchFn) == (!!endCatchFn) &&
  1151. "begin/end catch functions not paired");
  1152. assert(rethrowFn && "rethrow function is required");
  1153. BeginCatchFn = beginCatchFn;
  1154. // The rethrow function has one of the following two types:
  1155. // void (*)()
  1156. // void (*)(void*)
  1157. // In the latter case we need to pass it the exception object.
  1158. // But we can't use the exception slot because the @finally might
  1159. // have a landing pad (which would overwrite the exception slot).
  1160. llvm::FunctionType *rethrowFnTy = rethrowFn.getFunctionType();
  1161. SavedExnVar = nullptr;
  1162. if (rethrowFnTy->getNumParams())
  1163. SavedExnVar = CGF.CreateTempAlloca(CGF.Int8PtrTy, "finally.exn");
  1164. // A finally block is a statement which must be executed on any edge
  1165. // out of a given scope. Unlike a cleanup, the finally block may
  1166. // contain arbitrary control flow leading out of itself. In
  1167. // addition, finally blocks should always be executed, even if there
  1168. // are no catch handlers higher on the stack. Therefore, we
  1169. // surround the protected scope with a combination of a normal
  1170. // cleanup (to catch attempts to break out of the block via normal
  1171. // control flow) and an EH catch-all (semantically "outside" any try
  1172. // statement to which the finally block might have been attached).
  1173. // The finally block itself is generated in the context of a cleanup
  1174. // which conditionally leaves the catch-all.
  1175. // Jump destination for performing the finally block on an exception
  1176. // edge. We'll never actually reach this block, so unreachable is
  1177. // fine.
  1178. RethrowDest = CGF.getJumpDestInCurrentScope(CGF.getUnreachableBlock());
  1179. // Whether the finally block is being executed for EH purposes.
  1180. ForEHVar = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), "finally.for-eh");
  1181. CGF.Builder.CreateFlagStore(false, ForEHVar);
  1182. // Enter a normal cleanup which will perform the @finally block.
  1183. CGF.EHStack.pushCleanup<PerformFinally>(NormalCleanup, body,
  1184. ForEHVar, endCatchFn,
  1185. rethrowFn, SavedExnVar);
  1186. // Enter a catch-all scope.
  1187. llvm::BasicBlock *catchBB = CGF.createBasicBlock("finally.catchall");
  1188. EHCatchScope *catchScope = CGF.EHStack.pushCatch(1);
  1189. catchScope->setCatchAllHandler(0, catchBB);
  1190. }
  1191. void CodeGenFunction::FinallyInfo::exit(CodeGenFunction &CGF) {
  1192. // Leave the finally catch-all.
  1193. EHCatchScope &catchScope = cast<EHCatchScope>(*CGF.EHStack.begin());
  1194. llvm::BasicBlock *catchBB = catchScope.getHandler(0).Block;
  1195. CGF.popCatchScope();
  1196. // If there are any references to the catch-all block, emit it.
  1197. if (catchBB->use_empty()) {
  1198. delete catchBB;
  1199. } else {
  1200. CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveAndClearIP();
  1201. CGF.EmitBlock(catchBB);
  1202. llvm::Value *exn = nullptr;
  1203. // If there's a begin-catch function, call it.
  1204. if (BeginCatchFn) {
  1205. exn = CGF.getExceptionFromSlot();
  1206. CGF.EmitNounwindRuntimeCall(BeginCatchFn, exn);
  1207. }
  1208. // If we need to remember the exception pointer to rethrow later, do so.
  1209. if (SavedExnVar) {
  1210. if (!exn) exn = CGF.getExceptionFromSlot();
  1211. CGF.Builder.CreateAlignedStore(exn, SavedExnVar, CGF.getPointerAlign());
  1212. }
  1213. // Tell the cleanups in the finally block that we're do this for EH.
  1214. CGF.Builder.CreateFlagStore(true, ForEHVar);
  1215. // Thread a jump through the finally cleanup.
  1216. CGF.EmitBranchThroughCleanup(RethrowDest);
  1217. CGF.Builder.restoreIP(savedIP);
  1218. }
  1219. // Finally, leave the @finally cleanup.
  1220. CGF.PopCleanupBlock();
  1221. }
  1222. llvm::BasicBlock *CodeGenFunction::getTerminateLandingPad() {
  1223. if (TerminateLandingPad)
  1224. return TerminateLandingPad;
  1225. CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
  1226. // This will get inserted at the end of the function.
  1227. TerminateLandingPad = createBasicBlock("terminate.lpad");
  1228. Builder.SetInsertPoint(TerminateLandingPad);
  1229. // Tell the backend that this is a landing pad.
  1230. const EHPersonality &Personality = EHPersonality::get(*this);
  1231. if (!CurFn->hasPersonalityFn())
  1232. CurFn->setPersonalityFn(getOpaquePersonalityFn(CGM, Personality));
  1233. llvm::LandingPadInst *LPadInst =
  1234. Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty), 0);
  1235. LPadInst->addClause(getCatchAllValue(*this));
  1236. llvm::Value *Exn = nullptr;
  1237. if (getLangOpts().CPlusPlus)
  1238. Exn = Builder.CreateExtractValue(LPadInst, 0);
  1239. llvm::CallInst *terminateCall =
  1240. CGM.getCXXABI().emitTerminateForUnexpectedException(*this, Exn);
  1241. terminateCall->setDoesNotReturn();
  1242. Builder.CreateUnreachable();
  1243. // Restore the saved insertion state.
  1244. Builder.restoreIP(SavedIP);
  1245. return TerminateLandingPad;
  1246. }
  1247. llvm::BasicBlock *CodeGenFunction::getTerminateHandler() {
  1248. if (TerminateHandler)
  1249. return TerminateHandler;
  1250. // Set up the terminate handler. This block is inserted at the very
  1251. // end of the function by FinishFunction.
  1252. TerminateHandler = createBasicBlock("terminate.handler");
  1253. CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
  1254. Builder.SetInsertPoint(TerminateHandler);
  1255. llvm::Value *Exn = nullptr;
  1256. if (getLangOpts().CPlusPlus)
  1257. Exn = getExceptionFromSlot();
  1258. llvm::CallInst *terminateCall =
  1259. CGM.getCXXABI().emitTerminateForUnexpectedException(*this, Exn);
  1260. terminateCall->setDoesNotReturn();
  1261. Builder.CreateUnreachable();
  1262. // Restore the saved insertion state.
  1263. Builder.restoreIP(SavedIP);
  1264. return TerminateHandler;
  1265. }
  1266. llvm::BasicBlock *CodeGenFunction::getTerminateFunclet() {
  1267. assert(EHPersonality::get(*this).usesFuncletPads() &&
  1268. "use getTerminateLandingPad for non-funclet EH");
  1269. llvm::BasicBlock *&TerminateFunclet = TerminateFunclets[CurrentFuncletPad];
  1270. if (TerminateFunclet)
  1271. return TerminateFunclet;
  1272. CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
  1273. // Set up the terminate handler. This block is inserted at the very
  1274. // end of the function by FinishFunction.
  1275. TerminateFunclet = createBasicBlock("terminate.handler");
  1276. Builder.SetInsertPoint(TerminateFunclet);
  1277. // Create the cleanuppad using the current parent pad as its token. Use 'none'
  1278. // if this is a top-level terminate scope, which is the common case.
  1279. SaveAndRestore<llvm::Instruction *> RestoreCurrentFuncletPad(
  1280. CurrentFuncletPad);
  1281. llvm::Value *ParentPad = CurrentFuncletPad;
  1282. if (!ParentPad)
  1283. ParentPad = llvm::ConstantTokenNone::get(CGM.getLLVMContext());
  1284. CurrentFuncletPad = Builder.CreateCleanupPad(ParentPad);
  1285. // Emit the __std_terminate call.
  1286. llvm::Value *Exn = nullptr;
  1287. // In case of wasm personality, we need to pass the exception value to
  1288. // __clang_call_terminate function.
  1289. if (getLangOpts().CPlusPlus &&
  1290. EHPersonality::get(*this).isWasmPersonality()) {
  1291. llvm::Function *GetExnFn =
  1292. CGM.getIntrinsic(llvm::Intrinsic::wasm_get_exception);
  1293. Exn = Builder.CreateCall(GetExnFn, CurrentFuncletPad);
  1294. }
  1295. llvm::CallInst *terminateCall =
  1296. CGM.getCXXABI().emitTerminateForUnexpectedException(*this, Exn);
  1297. terminateCall->setDoesNotReturn();
  1298. Builder.CreateUnreachable();
  1299. // Restore the saved insertion state.
  1300. Builder.restoreIP(SavedIP);
  1301. return TerminateFunclet;
  1302. }
  1303. llvm::BasicBlock *CodeGenFunction::getEHResumeBlock(bool isCleanup) {
  1304. if (EHResumeBlock) return EHResumeBlock;
  1305. CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
  1306. // We emit a jump to a notional label at the outermost unwind state.
  1307. EHResumeBlock = createBasicBlock("eh.resume");
  1308. Builder.SetInsertPoint(EHResumeBlock);
  1309. const EHPersonality &Personality = EHPersonality::get(*this);
  1310. // This can always be a call because we necessarily didn't find
  1311. // anything on the EH stack which needs our help.
  1312. const char *RethrowName = Personality.CatchallRethrowFn;
  1313. if (RethrowName != nullptr && !isCleanup) {
  1314. EmitRuntimeCall(getCatchallRethrowFn(CGM, RethrowName),
  1315. getExceptionFromSlot())->setDoesNotReturn();
  1316. Builder.CreateUnreachable();
  1317. Builder.restoreIP(SavedIP);
  1318. return EHResumeBlock;
  1319. }
  1320. // Recreate the landingpad's return value for the 'resume' instruction.
  1321. llvm::Value *Exn = getExceptionFromSlot();
  1322. llvm::Value *Sel = getSelectorFromSlot();
  1323. llvm::Type *LPadType = llvm::StructType::get(Exn->getType(), Sel->getType());
  1324. llvm::Value *LPadVal = llvm::UndefValue::get(LPadType);
  1325. LPadVal = Builder.CreateInsertValue(LPadVal, Exn, 0, "lpad.val");
  1326. LPadVal = Builder.CreateInsertValue(LPadVal, Sel, 1, "lpad.val");
  1327. Builder.CreateResume(LPadVal);
  1328. Builder.restoreIP(SavedIP);
  1329. return EHResumeBlock;
  1330. }
  1331. void CodeGenFunction::EmitSEHTryStmt(const SEHTryStmt &S) {
  1332. EnterSEHTryStmt(S);
  1333. {
  1334. JumpDest TryExit = getJumpDestInCurrentScope("__try.__leave");
  1335. SEHTryEpilogueStack.push_back(&TryExit);
  1336. EmitStmt(S.getTryBlock());
  1337. SEHTryEpilogueStack.pop_back();
  1338. if (!TryExit.getBlock()->use_empty())
  1339. EmitBlock(TryExit.getBlock(), /*IsFinished=*/true);
  1340. else
  1341. delete TryExit.getBlock();
  1342. }
  1343. ExitSEHTryStmt(S);
  1344. }
  1345. namespace {
  1346. struct PerformSEHFinally final : EHScopeStack::Cleanup {
  1347. llvm::Function *OutlinedFinally;
  1348. PerformSEHFinally(llvm::Function *OutlinedFinally)
  1349. : OutlinedFinally(OutlinedFinally) {}
  1350. void Emit(CodeGenFunction &CGF, Flags F) override {
  1351. ASTContext &Context = CGF.getContext();
  1352. CodeGenModule &CGM = CGF.CGM;
  1353. CallArgList Args;
  1354. // Compute the two argument values.
  1355. QualType ArgTys[2] = {Context.UnsignedCharTy, Context.VoidPtrTy};
  1356. llvm::Value *FP = nullptr;
  1357. // If CFG.IsOutlinedSEHHelper is true, then we are within a finally block.
  1358. if (CGF.IsOutlinedSEHHelper) {
  1359. FP = &CGF.CurFn->arg_begin()[1];
  1360. } else {
  1361. llvm::Function *LocalAddrFn =
  1362. CGM.getIntrinsic(llvm::Intrinsic::localaddress);
  1363. FP = CGF.Builder.CreateCall(LocalAddrFn);
  1364. }
  1365. llvm::Value *IsForEH =
  1366. llvm::ConstantInt::get(CGF.ConvertType(ArgTys[0]), F.isForEHCleanup());
  1367. Args.add(RValue::get(IsForEH), ArgTys[0]);
  1368. Args.add(RValue::get(FP), ArgTys[1]);
  1369. // Arrange a two-arg function info and type.
  1370. const CGFunctionInfo &FnInfo =
  1371. CGM.getTypes().arrangeBuiltinFunctionCall(Context.VoidTy, Args);
  1372. auto Callee = CGCallee::forDirect(OutlinedFinally);
  1373. CGF.EmitCall(FnInfo, Callee, ReturnValueSlot(), Args);
  1374. }
  1375. };
  1376. } // end anonymous namespace
  1377. namespace {
  1378. /// Find all local variable captures in the statement.
  1379. struct CaptureFinder : ConstStmtVisitor<CaptureFinder> {
  1380. CodeGenFunction &ParentCGF;
  1381. const VarDecl *ParentThis;
  1382. llvm::SmallSetVector<const VarDecl *, 4> Captures;
  1383. Address SEHCodeSlot = Address::invalid();
  1384. CaptureFinder(CodeGenFunction &ParentCGF, const VarDecl *ParentThis)
  1385. : ParentCGF(ParentCGF), ParentThis(ParentThis) {}
  1386. // Return true if we need to do any capturing work.
  1387. bool foundCaptures() {
  1388. return !Captures.empty() || SEHCodeSlot.isValid();
  1389. }
  1390. void Visit(const Stmt *S) {
  1391. // See if this is a capture, then recurse.
  1392. ConstStmtVisitor<CaptureFinder>::Visit(S);
  1393. for (const Stmt *Child : S->children())
  1394. if (Child)
  1395. Visit(Child);
  1396. }
  1397. void VisitDeclRefExpr(const DeclRefExpr *E) {
  1398. // If this is already a capture, just make sure we capture 'this'.
  1399. if (E->refersToEnclosingVariableOrCapture()) {
  1400. Captures.insert(ParentThis);
  1401. return;
  1402. }
  1403. const auto *D = dyn_cast<VarDecl>(E->getDecl());
  1404. if (D && D->isLocalVarDeclOrParm() && D->hasLocalStorage())
  1405. Captures.insert(D);
  1406. }
  1407. void VisitCXXThisExpr(const CXXThisExpr *E) {
  1408. Captures.insert(ParentThis);
  1409. }
  1410. void VisitCallExpr(const CallExpr *E) {
  1411. // We only need to add parent frame allocations for these builtins in x86.
  1412. if (ParentCGF.getTarget().getTriple().getArch() != llvm::Triple::x86)
  1413. return;
  1414. unsigned ID = E->getBuiltinCallee();
  1415. switch (ID) {
  1416. case Builtin::BI__exception_code:
  1417. case Builtin::BI_exception_code:
  1418. // This is the simple case where we are the outermost finally. All we
  1419. // have to do here is make sure we escape this and recover it in the
  1420. // outlined handler.
  1421. if (!SEHCodeSlot.isValid())
  1422. SEHCodeSlot = ParentCGF.SEHCodeSlotStack.back();
  1423. break;
  1424. }
  1425. }
  1426. };
  1427. } // end anonymous namespace
  1428. Address CodeGenFunction::recoverAddrOfEscapedLocal(CodeGenFunction &ParentCGF,
  1429. Address ParentVar,
  1430. llvm::Value *ParentFP) {
  1431. llvm::CallInst *RecoverCall = nullptr;
  1432. CGBuilderTy Builder(*this, AllocaInsertPt);
  1433. if (auto *ParentAlloca = dyn_cast<llvm::AllocaInst>(ParentVar.getPointer())) {
  1434. // Mark the variable escaped if nobody else referenced it and compute the
  1435. // localescape index.
  1436. auto InsertPair = ParentCGF.EscapedLocals.insert(
  1437. std::make_pair(ParentAlloca, ParentCGF.EscapedLocals.size()));
  1438. int FrameEscapeIdx = InsertPair.first->second;
  1439. // call i8* @llvm.localrecover(i8* bitcast(@parentFn), i8* %fp, i32 N)
  1440. llvm::Function *FrameRecoverFn = llvm::Intrinsic::getDeclaration(
  1441. &CGM.getModule(), llvm::Intrinsic::localrecover);
  1442. llvm::Constant *ParentI8Fn =
  1443. llvm::ConstantExpr::getBitCast(ParentCGF.CurFn, Int8PtrTy);
  1444. RecoverCall = Builder.CreateCall(
  1445. FrameRecoverFn, {ParentI8Fn, ParentFP,
  1446. llvm::ConstantInt::get(Int32Ty, FrameEscapeIdx)});
  1447. } else {
  1448. // If the parent didn't have an alloca, we're doing some nested outlining.
  1449. // Just clone the existing localrecover call, but tweak the FP argument to
  1450. // use our FP value. All other arguments are constants.
  1451. auto *ParentRecover =
  1452. cast<llvm::IntrinsicInst>(ParentVar.getPointer()->stripPointerCasts());
  1453. assert(ParentRecover->getIntrinsicID() == llvm::Intrinsic::localrecover &&
  1454. "expected alloca or localrecover in parent LocalDeclMap");
  1455. RecoverCall = cast<llvm::CallInst>(ParentRecover->clone());
  1456. RecoverCall->setArgOperand(1, ParentFP);
  1457. RecoverCall->insertBefore(AllocaInsertPt);
  1458. }
  1459. // Bitcast the variable, rename it, and insert it in the local decl map.
  1460. llvm::Value *ChildVar =
  1461. Builder.CreateBitCast(RecoverCall, ParentVar.getType());
  1462. ChildVar->setName(ParentVar.getName());
  1463. return Address(ChildVar, ParentVar.getAlignment());
  1464. }
  1465. void CodeGenFunction::EmitCapturedLocals(CodeGenFunction &ParentCGF,
  1466. const Stmt *OutlinedStmt,
  1467. bool IsFilter) {
  1468. // Find all captures in the Stmt.
  1469. CaptureFinder Finder(ParentCGF, ParentCGF.CXXABIThisDecl);
  1470. Finder.Visit(OutlinedStmt);
  1471. // We can exit early on x86_64 when there are no captures. We just have to
  1472. // save the exception code in filters so that __exception_code() works.
  1473. if (!Finder.foundCaptures() &&
  1474. CGM.getTarget().getTriple().getArch() != llvm::Triple::x86) {
  1475. if (IsFilter)
  1476. EmitSEHExceptionCodeSave(ParentCGF, nullptr, nullptr);
  1477. return;
  1478. }
  1479. llvm::Value *EntryFP = nullptr;
  1480. CGBuilderTy Builder(CGM, AllocaInsertPt);
  1481. if (IsFilter && CGM.getTarget().getTriple().getArch() == llvm::Triple::x86) {
  1482. // 32-bit SEH filters need to be careful about FP recovery. The end of the
  1483. // EH registration is passed in as the EBP physical register. We can
  1484. // recover that with llvm.frameaddress(1).
  1485. EntryFP = Builder.CreateCall(
  1486. CGM.getIntrinsic(llvm::Intrinsic::frameaddress, AllocaInt8PtrTy),
  1487. {Builder.getInt32(1)});
  1488. } else {
  1489. // Otherwise, for x64 and 32-bit finally functions, the parent FP is the
  1490. // second parameter.
  1491. auto AI = CurFn->arg_begin();
  1492. ++AI;
  1493. EntryFP = &*AI;
  1494. }
  1495. llvm::Value *ParentFP = EntryFP;
  1496. if (IsFilter) {
  1497. // Given whatever FP the runtime provided us in EntryFP, recover the true
  1498. // frame pointer of the parent function. We only need to do this in filters,
  1499. // since finally funclets recover the parent FP for us.
  1500. llvm::Function *RecoverFPIntrin =
  1501. CGM.getIntrinsic(llvm::Intrinsic::eh_recoverfp);
  1502. llvm::Constant *ParentI8Fn =
  1503. llvm::ConstantExpr::getBitCast(ParentCGF.CurFn, Int8PtrTy);
  1504. ParentFP = Builder.CreateCall(RecoverFPIntrin, {ParentI8Fn, EntryFP});
  1505. }
  1506. // Create llvm.localrecover calls for all captures.
  1507. for (const VarDecl *VD : Finder.Captures) {
  1508. if (isa<ImplicitParamDecl>(VD)) {
  1509. CGM.ErrorUnsupported(VD, "'this' captured by SEH");
  1510. CXXThisValue = llvm::UndefValue::get(ConvertTypeForMem(VD->getType()));
  1511. continue;
  1512. }
  1513. if (VD->getType()->isVariablyModifiedType()) {
  1514. CGM.ErrorUnsupported(VD, "VLA captured by SEH");
  1515. continue;
  1516. }
  1517. assert((isa<ImplicitParamDecl>(VD) || VD->isLocalVarDeclOrParm()) &&
  1518. "captured non-local variable");
  1519. // If this decl hasn't been declared yet, it will be declared in the
  1520. // OutlinedStmt.
  1521. auto I = ParentCGF.LocalDeclMap.find(VD);
  1522. if (I == ParentCGF.LocalDeclMap.end())
  1523. continue;
  1524. Address ParentVar = I->second;
  1525. setAddrOfLocalVar(
  1526. VD, recoverAddrOfEscapedLocal(ParentCGF, ParentVar, ParentFP));
  1527. }
  1528. if (Finder.SEHCodeSlot.isValid()) {
  1529. SEHCodeSlotStack.push_back(
  1530. recoverAddrOfEscapedLocal(ParentCGF, Finder.SEHCodeSlot, ParentFP));
  1531. }
  1532. if (IsFilter)
  1533. EmitSEHExceptionCodeSave(ParentCGF, ParentFP, EntryFP);
  1534. }
  1535. /// Arrange a function prototype that can be called by Windows exception
  1536. /// handling personalities. On Win64, the prototype looks like:
  1537. /// RetTy func(void *EHPtrs, void *ParentFP);
  1538. void CodeGenFunction::startOutlinedSEHHelper(CodeGenFunction &ParentCGF,
  1539. bool IsFilter,
  1540. const Stmt *OutlinedStmt) {
  1541. SourceLocation StartLoc = OutlinedStmt->getBeginLoc();
  1542. // Get the mangled function name.
  1543. SmallString<128> Name;
  1544. {
  1545. llvm::raw_svector_ostream OS(Name);
  1546. const NamedDecl *ParentSEHFn = ParentCGF.CurSEHParent;
  1547. assert(ParentSEHFn && "No CurSEHParent!");
  1548. MangleContext &Mangler = CGM.getCXXABI().getMangleContext();
  1549. if (IsFilter)
  1550. Mangler.mangleSEHFilterExpression(ParentSEHFn, OS);
  1551. else
  1552. Mangler.mangleSEHFinallyBlock(ParentSEHFn, OS);
  1553. }
  1554. FunctionArgList Args;
  1555. if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86 || !IsFilter) {
  1556. // All SEH finally functions take two parameters. Win64 filters take two
  1557. // parameters. Win32 filters take no parameters.
  1558. if (IsFilter) {
  1559. Args.push_back(ImplicitParamDecl::Create(
  1560. getContext(), /*DC=*/nullptr, StartLoc,
  1561. &getContext().Idents.get("exception_pointers"),
  1562. getContext().VoidPtrTy, ImplicitParamDecl::Other));
  1563. } else {
  1564. Args.push_back(ImplicitParamDecl::Create(
  1565. getContext(), /*DC=*/nullptr, StartLoc,
  1566. &getContext().Idents.get("abnormal_termination"),
  1567. getContext().UnsignedCharTy, ImplicitParamDecl::Other));
  1568. }
  1569. Args.push_back(ImplicitParamDecl::Create(
  1570. getContext(), /*DC=*/nullptr, StartLoc,
  1571. &getContext().Idents.get("frame_pointer"), getContext().VoidPtrTy,
  1572. ImplicitParamDecl::Other));
  1573. }
  1574. QualType RetTy = IsFilter ? getContext().LongTy : getContext().VoidTy;
  1575. const CGFunctionInfo &FnInfo =
  1576. CGM.getTypes().arrangeBuiltinFunctionDeclaration(RetTy, Args);
  1577. llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
  1578. llvm::Function *Fn = llvm::Function::Create(
  1579. FnTy, llvm::GlobalValue::InternalLinkage, Name.str(), &CGM.getModule());
  1580. IsOutlinedSEHHelper = true;
  1581. StartFunction(GlobalDecl(), RetTy, Fn, FnInfo, Args,
  1582. OutlinedStmt->getBeginLoc(), OutlinedStmt->getBeginLoc());
  1583. CurSEHParent = ParentCGF.CurSEHParent;
  1584. CGM.SetLLVMFunctionAttributes(GlobalDecl(), FnInfo, CurFn);
  1585. EmitCapturedLocals(ParentCGF, OutlinedStmt, IsFilter);
  1586. }
  1587. /// Create a stub filter function that will ultimately hold the code of the
  1588. /// filter expression. The EH preparation passes in LLVM will outline the code
  1589. /// from the main function body into this stub.
  1590. llvm::Function *
  1591. CodeGenFunction::GenerateSEHFilterFunction(CodeGenFunction &ParentCGF,
  1592. const SEHExceptStmt &Except) {
  1593. const Expr *FilterExpr = Except.getFilterExpr();
  1594. startOutlinedSEHHelper(ParentCGF, true, FilterExpr);
  1595. // Emit the original filter expression, convert to i32, and return.
  1596. llvm::Value *R = EmitScalarExpr(FilterExpr);
  1597. R = Builder.CreateIntCast(R, ConvertType(getContext().LongTy),
  1598. FilterExpr->getType()->isSignedIntegerType());
  1599. Builder.CreateStore(R, ReturnValue);
  1600. FinishFunction(FilterExpr->getEndLoc());
  1601. return CurFn;
  1602. }
  1603. llvm::Function *
  1604. CodeGenFunction::GenerateSEHFinallyFunction(CodeGenFunction &ParentCGF,
  1605. const SEHFinallyStmt &Finally) {
  1606. const Stmt *FinallyBlock = Finally.getBlock();
  1607. startOutlinedSEHHelper(ParentCGF, false, FinallyBlock);
  1608. // Emit the original filter expression, convert to i32, and return.
  1609. EmitStmt(FinallyBlock);
  1610. FinishFunction(FinallyBlock->getEndLoc());
  1611. return CurFn;
  1612. }
  1613. void CodeGenFunction::EmitSEHExceptionCodeSave(CodeGenFunction &ParentCGF,
  1614. llvm::Value *ParentFP,
  1615. llvm::Value *EntryFP) {
  1616. // Get the pointer to the EXCEPTION_POINTERS struct. This is returned by the
  1617. // __exception_info intrinsic.
  1618. if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86) {
  1619. // On Win64, the info is passed as the first parameter to the filter.
  1620. SEHInfo = &*CurFn->arg_begin();
  1621. SEHCodeSlotStack.push_back(
  1622. CreateMemTemp(getContext().IntTy, "__exception_code"));
  1623. } else {
  1624. // On Win32, the EBP on entry to the filter points to the end of an
  1625. // exception registration object. It contains 6 32-bit fields, and the info
  1626. // pointer is stored in the second field. So, GEP 20 bytes backwards and
  1627. // load the pointer.
  1628. SEHInfo = Builder.CreateConstInBoundsGEP1_32(Int8Ty, EntryFP, -20);
  1629. SEHInfo = Builder.CreateBitCast(SEHInfo, Int8PtrTy->getPointerTo());
  1630. SEHInfo = Builder.CreateAlignedLoad(Int8PtrTy, SEHInfo, getPointerAlign());
  1631. SEHCodeSlotStack.push_back(recoverAddrOfEscapedLocal(
  1632. ParentCGF, ParentCGF.SEHCodeSlotStack.back(), ParentFP));
  1633. }
  1634. // Save the exception code in the exception slot to unify exception access in
  1635. // the filter function and the landing pad.
  1636. // struct EXCEPTION_POINTERS {
  1637. // EXCEPTION_RECORD *ExceptionRecord;
  1638. // CONTEXT *ContextRecord;
  1639. // };
  1640. // int exceptioncode = exception_pointers->ExceptionRecord->ExceptionCode;
  1641. llvm::Type *RecordTy = CGM.Int32Ty->getPointerTo();
  1642. llvm::Type *PtrsTy = llvm::StructType::get(RecordTy, CGM.VoidPtrTy);
  1643. llvm::Value *Ptrs = Builder.CreateBitCast(SEHInfo, PtrsTy->getPointerTo());
  1644. llvm::Value *Rec = Builder.CreateStructGEP(PtrsTy, Ptrs, 0);
  1645. Rec = Builder.CreateAlignedLoad(Rec, getPointerAlign());
  1646. llvm::Value *Code = Builder.CreateAlignedLoad(Rec, getIntAlign());
  1647. assert(!SEHCodeSlotStack.empty() && "emitting EH code outside of __except");
  1648. Builder.CreateStore(Code, SEHCodeSlotStack.back());
  1649. }
  1650. llvm::Value *CodeGenFunction::EmitSEHExceptionInfo() {
  1651. // Sema should diagnose calling this builtin outside of a filter context, but
  1652. // don't crash if we screw up.
  1653. if (!SEHInfo)
  1654. return llvm::UndefValue::get(Int8PtrTy);
  1655. assert(SEHInfo->getType() == Int8PtrTy);
  1656. return SEHInfo;
  1657. }
  1658. llvm::Value *CodeGenFunction::EmitSEHExceptionCode() {
  1659. assert(!SEHCodeSlotStack.empty() && "emitting EH code outside of __except");
  1660. return Builder.CreateLoad(SEHCodeSlotStack.back());
  1661. }
  1662. llvm::Value *CodeGenFunction::EmitSEHAbnormalTermination() {
  1663. // Abnormal termination is just the first parameter to the outlined finally
  1664. // helper.
  1665. auto AI = CurFn->arg_begin();
  1666. return Builder.CreateZExt(&*AI, Int32Ty);
  1667. }
  1668. void CodeGenFunction::pushSEHCleanup(CleanupKind Kind,
  1669. llvm::Function *FinallyFunc) {
  1670. EHStack.pushCleanup<PerformSEHFinally>(Kind, FinallyFunc);
  1671. }
  1672. void CodeGenFunction::EnterSEHTryStmt(const SEHTryStmt &S) {
  1673. CodeGenFunction HelperCGF(CGM, /*suppressNewContext=*/true);
  1674. if (const SEHFinallyStmt *Finally = S.getFinallyHandler()) {
  1675. // Outline the finally block.
  1676. llvm::Function *FinallyFunc =
  1677. HelperCGF.GenerateSEHFinallyFunction(*this, *Finally);
  1678. // Push a cleanup for __finally blocks.
  1679. EHStack.pushCleanup<PerformSEHFinally>(NormalAndEHCleanup, FinallyFunc);
  1680. return;
  1681. }
  1682. // Otherwise, we must have an __except block.
  1683. const SEHExceptStmt *Except = S.getExceptHandler();
  1684. assert(Except);
  1685. EHCatchScope *CatchScope = EHStack.pushCatch(1);
  1686. SEHCodeSlotStack.push_back(
  1687. CreateMemTemp(getContext().IntTy, "__exception_code"));
  1688. // If the filter is known to evaluate to 1, then we can use the clause
  1689. // "catch i8* null". We can't do this on x86 because the filter has to save
  1690. // the exception code.
  1691. llvm::Constant *C =
  1692. ConstantEmitter(*this).tryEmitAbstract(Except->getFilterExpr(),
  1693. getContext().IntTy);
  1694. if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86 && C &&
  1695. C->isOneValue()) {
  1696. CatchScope->setCatchAllHandler(0, createBasicBlock("__except"));
  1697. return;
  1698. }
  1699. // In general, we have to emit an outlined filter function. Use the function
  1700. // in place of the RTTI typeinfo global that C++ EH uses.
  1701. llvm::Function *FilterFunc =
  1702. HelperCGF.GenerateSEHFilterFunction(*this, *Except);
  1703. llvm::Constant *OpaqueFunc =
  1704. llvm::ConstantExpr::getBitCast(FilterFunc, Int8PtrTy);
  1705. CatchScope->setHandler(0, OpaqueFunc, createBasicBlock("__except.ret"));
  1706. }
  1707. void CodeGenFunction::ExitSEHTryStmt(const SEHTryStmt &S) {
  1708. // Just pop the cleanup if it's a __finally block.
  1709. if (S.getFinallyHandler()) {
  1710. PopCleanupBlock();
  1711. return;
  1712. }
  1713. // Otherwise, we must have an __except block.
  1714. const SEHExceptStmt *Except = S.getExceptHandler();
  1715. assert(Except && "__try must have __finally xor __except");
  1716. EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
  1717. // Don't emit the __except block if the __try block lacked invokes.
  1718. // TODO: Model unwind edges from instructions, either with iload / istore or
  1719. // a try body function.
  1720. if (!CatchScope.hasEHBranches()) {
  1721. CatchScope.clearHandlerBlocks();
  1722. EHStack.popCatch();
  1723. SEHCodeSlotStack.pop_back();
  1724. return;
  1725. }
  1726. // The fall-through block.
  1727. llvm::BasicBlock *ContBB = createBasicBlock("__try.cont");
  1728. // We just emitted the body of the __try; jump to the continue block.
  1729. if (HaveInsertPoint())
  1730. Builder.CreateBr(ContBB);
  1731. // Check if our filter function returned true.
  1732. emitCatchDispatchBlock(*this, CatchScope);
  1733. // Grab the block before we pop the handler.
  1734. llvm::BasicBlock *CatchPadBB = CatchScope.getHandler(0).Block;
  1735. EHStack.popCatch();
  1736. EmitBlockAfterUses(CatchPadBB);
  1737. // __except blocks don't get outlined into funclets, so immediately do a
  1738. // catchret.
  1739. llvm::CatchPadInst *CPI =
  1740. cast<llvm::CatchPadInst>(CatchPadBB->getFirstNonPHI());
  1741. llvm::BasicBlock *ExceptBB = createBasicBlock("__except");
  1742. Builder.CreateCatchRet(CPI, ExceptBB);
  1743. EmitBlock(ExceptBB);
  1744. // On Win64, the exception code is returned in EAX. Copy it into the slot.
  1745. if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86) {
  1746. llvm::Function *SEHCodeIntrin =
  1747. CGM.getIntrinsic(llvm::Intrinsic::eh_exceptioncode);
  1748. llvm::Value *Code = Builder.CreateCall(SEHCodeIntrin, {CPI});
  1749. Builder.CreateStore(Code, SEHCodeSlotStack.back());
  1750. }
  1751. // Emit the __except body.
  1752. EmitStmt(Except->getBlock());
  1753. // End the lifetime of the exception code.
  1754. SEHCodeSlotStack.pop_back();
  1755. if (HaveInsertPoint())
  1756. Builder.CreateBr(ContBB);
  1757. EmitBlock(ContBB);
  1758. }
  1759. void CodeGenFunction::EmitSEHLeaveStmt(const SEHLeaveStmt &S) {
  1760. // If this code is reachable then emit a stop point (if generating
  1761. // debug info). We have to do this ourselves because we are on the
  1762. // "simple" statement path.
  1763. if (HaveInsertPoint())
  1764. EmitStopPoint(&S);
  1765. // This must be a __leave from a __finally block, which we warn on and is UB.
  1766. // Just emit unreachable.
  1767. if (!isSEHTryScope()) {
  1768. Builder.CreateUnreachable();
  1769. Builder.ClearInsertionPoint();
  1770. return;
  1771. }
  1772. EmitBranchThroughCleanup(*SEHTryEpilogueStack.back());
  1773. }