CGException.cpp 65 KB

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