CGException.cpp 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607
  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 "CGCleanup.h"
  15. #include "CGObjCRuntime.h"
  16. #include "TargetInfo.h"
  17. #include "clang/AST/StmtCXX.h"
  18. #include "llvm/Intrinsics.h"
  19. #include "llvm/Support/CallSite.h"
  20. using namespace clang;
  21. using namespace CodeGen;
  22. static llvm::Constant *getAllocateExceptionFn(CodeGenFunction &CGF) {
  23. // void *__cxa_allocate_exception(size_t thrown_size);
  24. llvm::FunctionType *FTy =
  25. llvm::FunctionType::get(CGF.Int8PtrTy, CGF.SizeTy, /*IsVarArgs=*/false);
  26. return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
  27. }
  28. static llvm::Constant *getFreeExceptionFn(CodeGenFunction &CGF) {
  29. // void __cxa_free_exception(void *thrown_exception);
  30. llvm::FunctionType *FTy =
  31. llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, /*IsVarArgs=*/false);
  32. return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_free_exception");
  33. }
  34. static llvm::Constant *getThrowFn(CodeGenFunction &CGF) {
  35. // void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
  36. // void (*dest) (void *));
  37. llvm::Type *Args[3] = { CGF.Int8PtrTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
  38. llvm::FunctionType *FTy =
  39. llvm::FunctionType::get(CGF.VoidTy, Args, /*IsVarArgs=*/false);
  40. return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
  41. }
  42. static llvm::Constant *getReThrowFn(CodeGenFunction &CGF) {
  43. // void __cxa_rethrow();
  44. llvm::FunctionType *FTy =
  45. llvm::FunctionType::get(CGF.VoidTy, /*IsVarArgs=*/false);
  46. return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow");
  47. }
  48. static llvm::Constant *getGetExceptionPtrFn(CodeGenFunction &CGF) {
  49. // void *__cxa_get_exception_ptr(void*);
  50. llvm::FunctionType *FTy =
  51. llvm::FunctionType::get(CGF.Int8PtrTy, CGF.Int8PtrTy, /*IsVarArgs=*/false);
  52. return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
  53. }
  54. static llvm::Constant *getBeginCatchFn(CodeGenFunction &CGF) {
  55. // void *__cxa_begin_catch(void*);
  56. llvm::FunctionType *FTy =
  57. llvm::FunctionType::get(CGF.Int8PtrTy, CGF.Int8PtrTy, /*IsVarArgs=*/false);
  58. return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
  59. }
  60. static llvm::Constant *getEndCatchFn(CodeGenFunction &CGF) {
  61. // void __cxa_end_catch();
  62. llvm::FunctionType *FTy =
  63. llvm::FunctionType::get(CGF.VoidTy, /*IsVarArgs=*/false);
  64. return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
  65. }
  66. static llvm::Constant *getUnexpectedFn(CodeGenFunction &CGF) {
  67. // void __cxa_call_unexepcted(void *thrown_exception);
  68. llvm::FunctionType *FTy =
  69. llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, /*IsVarArgs=*/false);
  70. return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_call_unexpected");
  71. }
  72. llvm::Constant *CodeGenFunction::getUnwindResumeFn() {
  73. llvm::FunctionType *FTy =
  74. llvm::FunctionType::get(VoidTy, Int8PtrTy, /*IsVarArgs=*/false);
  75. if (CGM.getLangOpts().SjLjExceptions)
  76. return CGM.CreateRuntimeFunction(FTy, "_Unwind_SjLj_Resume");
  77. return CGM.CreateRuntimeFunction(FTy, "_Unwind_Resume");
  78. }
  79. llvm::Constant *CodeGenFunction::getUnwindResumeOrRethrowFn() {
  80. llvm::FunctionType *FTy =
  81. llvm::FunctionType::get(VoidTy, Int8PtrTy, /*IsVarArgs=*/false);
  82. if (CGM.getLangOpts().SjLjExceptions)
  83. return CGM.CreateRuntimeFunction(FTy, "_Unwind_SjLj_Resume_or_Rethrow");
  84. return CGM.CreateRuntimeFunction(FTy, "_Unwind_Resume_or_Rethrow");
  85. }
  86. static llvm::Constant *getTerminateFn(CodeGenFunction &CGF) {
  87. // void __terminate();
  88. llvm::FunctionType *FTy =
  89. llvm::FunctionType::get(CGF.VoidTy, /*IsVarArgs=*/false);
  90. StringRef name;
  91. // In C++, use std::terminate().
  92. if (CGF.getLangOpts().CPlusPlus)
  93. name = "_ZSt9terminatev"; // FIXME: mangling!
  94. else if (CGF.getLangOpts().ObjC1 &&
  95. CGF.getLangOpts().ObjCRuntime.hasTerminate())
  96. name = "objc_terminate";
  97. else
  98. name = "abort";
  99. return CGF.CGM.CreateRuntimeFunction(FTy, name);
  100. }
  101. static llvm::Constant *getCatchallRethrowFn(CodeGenFunction &CGF,
  102. StringRef Name) {
  103. llvm::FunctionType *FTy =
  104. llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, /*IsVarArgs=*/false);
  105. return CGF.CGM.CreateRuntimeFunction(FTy, Name);
  106. }
  107. namespace {
  108. /// The exceptions personality for a function.
  109. struct EHPersonality {
  110. const char *PersonalityFn;
  111. // If this is non-null, this personality requires a non-standard
  112. // function for rethrowing an exception after a catchall cleanup.
  113. // This function must have prototype void(void*).
  114. const char *CatchallRethrowFn;
  115. static const EHPersonality &get(const LangOptions &Lang);
  116. static const EHPersonality GNU_C;
  117. static const EHPersonality GNU_C_SJLJ;
  118. static const EHPersonality GNU_ObjC;
  119. static const EHPersonality GNU_ObjCXX;
  120. static const EHPersonality NeXT_ObjC;
  121. static const EHPersonality GNU_CPlusPlus;
  122. static const EHPersonality GNU_CPlusPlus_SJLJ;
  123. };
  124. }
  125. const EHPersonality EHPersonality::GNU_C = { "__gcc_personality_v0", 0 };
  126. const EHPersonality EHPersonality::GNU_C_SJLJ = { "__gcc_personality_sj0", 0 };
  127. const EHPersonality EHPersonality::NeXT_ObjC = { "__objc_personality_v0", 0 };
  128. const EHPersonality EHPersonality::GNU_CPlusPlus = { "__gxx_personality_v0", 0};
  129. const EHPersonality
  130. EHPersonality::GNU_CPlusPlus_SJLJ = { "__gxx_personality_sj0", 0 };
  131. const EHPersonality
  132. EHPersonality::GNU_ObjC = {"__gnu_objc_personality_v0", "objc_exception_throw"};
  133. const EHPersonality
  134. EHPersonality::GNU_ObjCXX = { "__gnustep_objcxx_personality_v0", 0 };
  135. static const EHPersonality &getCPersonality(const LangOptions &L) {
  136. if (L.SjLjExceptions)
  137. return EHPersonality::GNU_C_SJLJ;
  138. return EHPersonality::GNU_C;
  139. }
  140. static const EHPersonality &getObjCPersonality(const LangOptions &L) {
  141. switch (L.ObjCRuntime.getKind()) {
  142. case ObjCRuntime::FragileMacOSX:
  143. return getCPersonality(L);
  144. case ObjCRuntime::MacOSX:
  145. case ObjCRuntime::iOS:
  146. return EHPersonality::NeXT_ObjC;
  147. case ObjCRuntime::GNUstep:
  148. case ObjCRuntime::GCC:
  149. return EHPersonality::GNU_ObjC;
  150. }
  151. llvm_unreachable("bad runtime kind");
  152. }
  153. static const EHPersonality &getCXXPersonality(const LangOptions &L) {
  154. if (L.SjLjExceptions)
  155. return EHPersonality::GNU_CPlusPlus_SJLJ;
  156. else
  157. return EHPersonality::GNU_CPlusPlus;
  158. }
  159. /// Determines the personality function to use when both C++
  160. /// and Objective-C exceptions are being caught.
  161. static const EHPersonality &getObjCXXPersonality(const LangOptions &L) {
  162. switch (L.ObjCRuntime.getKind()) {
  163. // The ObjC personality defers to the C++ personality for non-ObjC
  164. // handlers. Unlike the C++ case, we use the same personality
  165. // function on targets using (backend-driven) SJLJ EH.
  166. case ObjCRuntime::MacOSX:
  167. case ObjCRuntime::iOS:
  168. return EHPersonality::NeXT_ObjC;
  169. // In the fragile ABI, just use C++ exception handling and hope
  170. // they're not doing crazy exception mixing.
  171. case ObjCRuntime::FragileMacOSX:
  172. return getCXXPersonality(L);
  173. // The GCC runtime's personality function inherently doesn't support
  174. // mixed EH. Use the C++ personality just to avoid returning null.
  175. case ObjCRuntime::GCC:
  176. return EHPersonality::GNU_ObjC;
  177. case ObjCRuntime::GNUstep:
  178. return EHPersonality::GNU_ObjCXX;
  179. }
  180. llvm_unreachable("bad runtime kind");
  181. }
  182. const EHPersonality &EHPersonality::get(const LangOptions &L) {
  183. if (L.CPlusPlus && L.ObjC1)
  184. return getObjCXXPersonality(L);
  185. else if (L.CPlusPlus)
  186. return getCXXPersonality(L);
  187. else if (L.ObjC1)
  188. return getObjCPersonality(L);
  189. else
  190. return getCPersonality(L);
  191. }
  192. static llvm::Constant *getPersonalityFn(CodeGenModule &CGM,
  193. const EHPersonality &Personality) {
  194. llvm::Constant *Fn =
  195. CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.Int32Ty, true),
  196. Personality.PersonalityFn);
  197. return Fn;
  198. }
  199. static llvm::Constant *getOpaquePersonalityFn(CodeGenModule &CGM,
  200. const EHPersonality &Personality) {
  201. llvm::Constant *Fn = getPersonalityFn(CGM, Personality);
  202. return llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
  203. }
  204. /// Check whether a personality function could reasonably be swapped
  205. /// for a C++ personality function.
  206. static bool PersonalityHasOnlyCXXUses(llvm::Constant *Fn) {
  207. for (llvm::Constant::use_iterator
  208. I = Fn->use_begin(), E = Fn->use_end(); I != E; ++I) {
  209. llvm::User *User = *I;
  210. // Conditionally white-list bitcasts.
  211. if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(User)) {
  212. if (CE->getOpcode() != llvm::Instruction::BitCast) return false;
  213. if (!PersonalityHasOnlyCXXUses(CE))
  214. return false;
  215. continue;
  216. }
  217. // Otherwise, it has to be a landingpad instruction.
  218. llvm::LandingPadInst *LPI = dyn_cast<llvm::LandingPadInst>(User);
  219. if (!LPI) return false;
  220. for (unsigned I = 0, E = LPI->getNumClauses(); I != E; ++I) {
  221. // Look for something that would've been returned by the ObjC
  222. // runtime's GetEHType() method.
  223. llvm::Value *Val = LPI->getClause(I)->stripPointerCasts();
  224. if (LPI->isCatch(I)) {
  225. // Check if the catch value has the ObjC prefix.
  226. if (llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Val))
  227. // ObjC EH selector entries are always global variables with
  228. // names starting like this.
  229. if (GV->getName().startswith("OBJC_EHTYPE"))
  230. return false;
  231. } else {
  232. // Check if any of the filter values have the ObjC prefix.
  233. llvm::Constant *CVal = cast<llvm::Constant>(Val);
  234. for (llvm::User::op_iterator
  235. II = CVal->op_begin(), IE = CVal->op_end(); II != IE; ++II) {
  236. if (llvm::GlobalVariable *GV =
  237. cast<llvm::GlobalVariable>((*II)->stripPointerCasts()))
  238. // ObjC EH selector entries are always global variables with
  239. // names starting like this.
  240. if (GV->getName().startswith("OBJC_EHTYPE"))
  241. return false;
  242. }
  243. }
  244. }
  245. }
  246. return true;
  247. }
  248. /// Try to use the C++ personality function in ObjC++. Not doing this
  249. /// can cause some incompatibilities with gcc, which is more
  250. /// aggressive about only using the ObjC++ personality in a function
  251. /// when it really needs it.
  252. void CodeGenModule::SimplifyPersonality() {
  253. // For now, this is really a Darwin-specific operation.
  254. if (!Context.getTargetInfo().getTriple().isOSDarwin())
  255. return;
  256. // If we're not in ObjC++ -fexceptions, there's nothing to do.
  257. if (!LangOpts.CPlusPlus || !LangOpts.ObjC1 || !LangOpts.Exceptions)
  258. return;
  259. const EHPersonality &ObjCXX = EHPersonality::get(LangOpts);
  260. const EHPersonality &CXX = getCXXPersonality(LangOpts);
  261. if (&ObjCXX == &CXX)
  262. return;
  263. assert(std::strcmp(ObjCXX.PersonalityFn, CXX.PersonalityFn) != 0 &&
  264. "Different EHPersonalities using the same personality function.");
  265. llvm::Function *Fn = getModule().getFunction(ObjCXX.PersonalityFn);
  266. // Nothing to do if it's unused.
  267. if (!Fn || Fn->use_empty()) return;
  268. // Can't do the optimization if it has non-C++ uses.
  269. if (!PersonalityHasOnlyCXXUses(Fn)) return;
  270. // Create the C++ personality function and kill off the old
  271. // function.
  272. llvm::Constant *CXXFn = getPersonalityFn(*this, CXX);
  273. // This can happen if the user is screwing with us.
  274. if (Fn->getType() != CXXFn->getType()) return;
  275. Fn->replaceAllUsesWith(CXXFn);
  276. Fn->eraseFromParent();
  277. }
  278. /// Returns the value to inject into a selector to indicate the
  279. /// presence of a catch-all.
  280. static llvm::Constant *getCatchAllValue(CodeGenFunction &CGF) {
  281. // Possibly we should use @llvm.eh.catch.all.value here.
  282. return llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
  283. }
  284. namespace {
  285. /// A cleanup to free the exception object if its initialization
  286. /// throws.
  287. struct FreeException : EHScopeStack::Cleanup {
  288. llvm::Value *exn;
  289. FreeException(llvm::Value *exn) : exn(exn) {}
  290. void Emit(CodeGenFunction &CGF, Flags flags) {
  291. CGF.Builder.CreateCall(getFreeExceptionFn(CGF), exn)
  292. ->setDoesNotThrow();
  293. }
  294. };
  295. }
  296. // Emits an exception expression into the given location. This
  297. // differs from EmitAnyExprToMem only in that, if a final copy-ctor
  298. // call is required, an exception within that copy ctor causes
  299. // std::terminate to be invoked.
  300. static void EmitAnyExprToExn(CodeGenFunction &CGF, const Expr *e,
  301. llvm::Value *addr) {
  302. // Make sure the exception object is cleaned up if there's an
  303. // exception during initialization.
  304. CGF.pushFullExprCleanup<FreeException>(EHCleanup, addr);
  305. EHScopeStack::stable_iterator cleanup = CGF.EHStack.stable_begin();
  306. // __cxa_allocate_exception returns a void*; we need to cast this
  307. // to the appropriate type for the object.
  308. llvm::Type *ty = CGF.ConvertTypeForMem(e->getType())->getPointerTo();
  309. llvm::Value *typedAddr = CGF.Builder.CreateBitCast(addr, ty);
  310. // FIXME: this isn't quite right! If there's a final unelided call
  311. // to a copy constructor, then according to [except.terminate]p1 we
  312. // must call std::terminate() if that constructor throws, because
  313. // technically that copy occurs after the exception expression is
  314. // evaluated but before the exception is caught. But the best way
  315. // to handle that is to teach EmitAggExpr to do the final copy
  316. // differently if it can't be elided.
  317. CGF.EmitAnyExprToMem(e, typedAddr, e->getType().getQualifiers(),
  318. /*IsInit*/ true);
  319. // Deactivate the cleanup block.
  320. CGF.DeactivateCleanupBlock(cleanup, cast<llvm::Instruction>(typedAddr));
  321. }
  322. llvm::Value *CodeGenFunction::getExceptionSlot() {
  323. if (!ExceptionSlot)
  324. ExceptionSlot = CreateTempAlloca(Int8PtrTy, "exn.slot");
  325. return ExceptionSlot;
  326. }
  327. llvm::Value *CodeGenFunction::getEHSelectorSlot() {
  328. if (!EHSelectorSlot)
  329. EHSelectorSlot = CreateTempAlloca(Int32Ty, "ehselector.slot");
  330. return EHSelectorSlot;
  331. }
  332. llvm::Value *CodeGenFunction::getExceptionFromSlot() {
  333. return Builder.CreateLoad(getExceptionSlot(), "exn");
  334. }
  335. llvm::Value *CodeGenFunction::getSelectorFromSlot() {
  336. return Builder.CreateLoad(getEHSelectorSlot(), "sel");
  337. }
  338. void CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr *E) {
  339. if (!E->getSubExpr()) {
  340. if (getInvokeDest()) {
  341. Builder.CreateInvoke(getReThrowFn(*this),
  342. getUnreachableBlock(),
  343. getInvokeDest())
  344. ->setDoesNotReturn();
  345. } else {
  346. Builder.CreateCall(getReThrowFn(*this))->setDoesNotReturn();
  347. Builder.CreateUnreachable();
  348. }
  349. // throw is an expression, and the expression emitters expect us
  350. // to leave ourselves at a valid insertion point.
  351. EmitBlock(createBasicBlock("throw.cont"));
  352. return;
  353. }
  354. QualType ThrowType = E->getSubExpr()->getType();
  355. // Now allocate the exception object.
  356. llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
  357. uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
  358. llvm::Constant *AllocExceptionFn = getAllocateExceptionFn(*this);
  359. llvm::CallInst *ExceptionPtr =
  360. Builder.CreateCall(AllocExceptionFn,
  361. llvm::ConstantInt::get(SizeTy, TypeSize),
  362. "exception");
  363. ExceptionPtr->setDoesNotThrow();
  364. EmitAnyExprToExn(*this, E->getSubExpr(), ExceptionPtr);
  365. // Now throw the exception.
  366. llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType,
  367. /*ForEH=*/true);
  368. // The address of the destructor. If the exception type has a
  369. // trivial destructor (or isn't a record), we just pass null.
  370. llvm::Constant *Dtor = 0;
  371. if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
  372. CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
  373. if (!Record->hasTrivialDestructor()) {
  374. CXXDestructorDecl *DtorD = Record->getDestructor();
  375. Dtor = CGM.GetAddrOfCXXDestructor(DtorD, Dtor_Complete);
  376. Dtor = llvm::ConstantExpr::getBitCast(Dtor, Int8PtrTy);
  377. }
  378. }
  379. if (!Dtor) Dtor = llvm::Constant::getNullValue(Int8PtrTy);
  380. if (getInvokeDest()) {
  381. llvm::InvokeInst *ThrowCall =
  382. Builder.CreateInvoke3(getThrowFn(*this),
  383. getUnreachableBlock(), getInvokeDest(),
  384. ExceptionPtr, TypeInfo, Dtor);
  385. ThrowCall->setDoesNotReturn();
  386. } else {
  387. llvm::CallInst *ThrowCall =
  388. Builder.CreateCall3(getThrowFn(*this), ExceptionPtr, TypeInfo, Dtor);
  389. ThrowCall->setDoesNotReturn();
  390. Builder.CreateUnreachable();
  391. }
  392. // throw is an expression, and the expression emitters expect us
  393. // to leave ourselves at a valid insertion point.
  394. EmitBlock(createBasicBlock("throw.cont"));
  395. }
  396. void CodeGenFunction::EmitStartEHSpec(const Decl *D) {
  397. if (!CGM.getLangOpts().CXXExceptions)
  398. return;
  399. const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
  400. if (FD == 0)
  401. return;
  402. const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
  403. if (Proto == 0)
  404. return;
  405. ExceptionSpecificationType EST = Proto->getExceptionSpecType();
  406. if (isNoexceptExceptionSpec(EST)) {
  407. if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
  408. // noexcept functions are simple terminate scopes.
  409. EHStack.pushTerminate();
  410. }
  411. } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
  412. unsigned NumExceptions = Proto->getNumExceptions();
  413. EHFilterScope *Filter = EHStack.pushFilter(NumExceptions);
  414. for (unsigned I = 0; I != NumExceptions; ++I) {
  415. QualType Ty = Proto->getExceptionType(I);
  416. QualType ExceptType = Ty.getNonReferenceType().getUnqualifiedType();
  417. llvm::Value *EHType = CGM.GetAddrOfRTTIDescriptor(ExceptType,
  418. /*ForEH=*/true);
  419. Filter->setFilter(I, EHType);
  420. }
  421. }
  422. }
  423. /// Emit the dispatch block for a filter scope if necessary.
  424. static void emitFilterDispatchBlock(CodeGenFunction &CGF,
  425. EHFilterScope &filterScope) {
  426. llvm::BasicBlock *dispatchBlock = filterScope.getCachedEHDispatchBlock();
  427. if (!dispatchBlock) return;
  428. if (dispatchBlock->use_empty()) {
  429. delete dispatchBlock;
  430. return;
  431. }
  432. CGF.EmitBlockAfterUses(dispatchBlock);
  433. // If this isn't a catch-all filter, we need to check whether we got
  434. // here because the filter triggered.
  435. if (filterScope.getNumFilters()) {
  436. // Load the selector value.
  437. llvm::Value *selector = CGF.getSelectorFromSlot();
  438. llvm::BasicBlock *unexpectedBB = CGF.createBasicBlock("ehspec.unexpected");
  439. llvm::Value *zero = CGF.Builder.getInt32(0);
  440. llvm::Value *failsFilter =
  441. CGF.Builder.CreateICmpSLT(selector, zero, "ehspec.fails");
  442. CGF.Builder.CreateCondBr(failsFilter, unexpectedBB, CGF.getEHResumeBlock());
  443. CGF.EmitBlock(unexpectedBB);
  444. }
  445. // Call __cxa_call_unexpected. This doesn't need to be an invoke
  446. // because __cxa_call_unexpected magically filters exceptions
  447. // according to the last landing pad the exception was thrown
  448. // into. Seriously.
  449. llvm::Value *exn = CGF.getExceptionFromSlot();
  450. CGF.Builder.CreateCall(getUnexpectedFn(CGF), exn)
  451. ->setDoesNotReturn();
  452. CGF.Builder.CreateUnreachable();
  453. }
  454. void CodeGenFunction::EmitEndEHSpec(const Decl *D) {
  455. if (!CGM.getLangOpts().CXXExceptions)
  456. return;
  457. const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
  458. if (FD == 0)
  459. return;
  460. const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
  461. if (Proto == 0)
  462. return;
  463. ExceptionSpecificationType EST = Proto->getExceptionSpecType();
  464. if (isNoexceptExceptionSpec(EST)) {
  465. if (Proto->getNoexceptSpec(getContext()) == FunctionProtoType::NR_Nothrow) {
  466. EHStack.popTerminate();
  467. }
  468. } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
  469. EHFilterScope &filterScope = cast<EHFilterScope>(*EHStack.begin());
  470. emitFilterDispatchBlock(*this, filterScope);
  471. EHStack.popFilter();
  472. }
  473. }
  474. void CodeGenFunction::EmitCXXTryStmt(const CXXTryStmt &S) {
  475. EnterCXXTryStmt(S);
  476. EmitStmt(S.getTryBlock());
  477. ExitCXXTryStmt(S);
  478. }
  479. void CodeGenFunction::EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
  480. unsigned NumHandlers = S.getNumHandlers();
  481. EHCatchScope *CatchScope = EHStack.pushCatch(NumHandlers);
  482. for (unsigned I = 0; I != NumHandlers; ++I) {
  483. const CXXCatchStmt *C = S.getHandler(I);
  484. llvm::BasicBlock *Handler = createBasicBlock("catch");
  485. if (C->getExceptionDecl()) {
  486. // FIXME: Dropping the reference type on the type into makes it
  487. // impossible to correctly implement catch-by-reference
  488. // semantics for pointers. Unfortunately, this is what all
  489. // existing compilers do, and it's not clear that the standard
  490. // personality routine is capable of doing this right. See C++ DR 388:
  491. // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#388
  492. QualType CaughtType = C->getCaughtType();
  493. CaughtType = CaughtType.getNonReferenceType().getUnqualifiedType();
  494. llvm::Value *TypeInfo = 0;
  495. if (CaughtType->isObjCObjectPointerType())
  496. TypeInfo = CGM.getObjCRuntime().GetEHType(CaughtType);
  497. else
  498. TypeInfo = CGM.GetAddrOfRTTIDescriptor(CaughtType, /*ForEH=*/true);
  499. CatchScope->setHandler(I, TypeInfo, Handler);
  500. } else {
  501. // No exception decl indicates '...', a catch-all.
  502. CatchScope->setCatchAllHandler(I, Handler);
  503. }
  504. }
  505. }
  506. llvm::BasicBlock *
  507. CodeGenFunction::getEHDispatchBlock(EHScopeStack::stable_iterator si) {
  508. // The dispatch block for the end of the scope chain is a block that
  509. // just resumes unwinding.
  510. if (si == EHStack.stable_end())
  511. return getEHResumeBlock();
  512. // Otherwise, we should look at the actual scope.
  513. EHScope &scope = *EHStack.find(si);
  514. llvm::BasicBlock *dispatchBlock = scope.getCachedEHDispatchBlock();
  515. if (!dispatchBlock) {
  516. switch (scope.getKind()) {
  517. case EHScope::Catch: {
  518. // Apply a special case to a single catch-all.
  519. EHCatchScope &catchScope = cast<EHCatchScope>(scope);
  520. if (catchScope.getNumHandlers() == 1 &&
  521. catchScope.getHandler(0).isCatchAll()) {
  522. dispatchBlock = catchScope.getHandler(0).Block;
  523. // Otherwise, make a dispatch block.
  524. } else {
  525. dispatchBlock = createBasicBlock("catch.dispatch");
  526. }
  527. break;
  528. }
  529. case EHScope::Cleanup:
  530. dispatchBlock = createBasicBlock("ehcleanup");
  531. break;
  532. case EHScope::Filter:
  533. dispatchBlock = createBasicBlock("filter.dispatch");
  534. break;
  535. case EHScope::Terminate:
  536. dispatchBlock = getTerminateHandler();
  537. break;
  538. }
  539. scope.setCachedEHDispatchBlock(dispatchBlock);
  540. }
  541. return dispatchBlock;
  542. }
  543. /// Check whether this is a non-EH scope, i.e. a scope which doesn't
  544. /// affect exception handling. Currently, the only non-EH scopes are
  545. /// normal-only cleanup scopes.
  546. static bool isNonEHScope(const EHScope &S) {
  547. switch (S.getKind()) {
  548. case EHScope::Cleanup:
  549. return !cast<EHCleanupScope>(S).isEHCleanup();
  550. case EHScope::Filter:
  551. case EHScope::Catch:
  552. case EHScope::Terminate:
  553. return false;
  554. }
  555. llvm_unreachable("Invalid EHScope Kind!");
  556. }
  557. llvm::BasicBlock *CodeGenFunction::getInvokeDestImpl() {
  558. assert(EHStack.requiresLandingPad());
  559. assert(!EHStack.empty());
  560. if (!CGM.getLangOpts().Exceptions)
  561. return 0;
  562. // Check the innermost scope for a cached landing pad. If this is
  563. // a non-EH cleanup, we'll check enclosing scopes in EmitLandingPad.
  564. llvm::BasicBlock *LP = EHStack.begin()->getCachedLandingPad();
  565. if (LP) return LP;
  566. // Build the landing pad for this scope.
  567. LP = EmitLandingPad();
  568. assert(LP);
  569. // Cache the landing pad on the innermost scope. If this is a
  570. // non-EH scope, cache the landing pad on the enclosing scope, too.
  571. for (EHScopeStack::iterator ir = EHStack.begin(); true; ++ir) {
  572. ir->setCachedLandingPad(LP);
  573. if (!isNonEHScope(*ir)) break;
  574. }
  575. return LP;
  576. }
  577. // This code contains a hack to work around a design flaw in
  578. // LLVM's EH IR which breaks semantics after inlining. This same
  579. // hack is implemented in llvm-gcc.
  580. //
  581. // The LLVM EH abstraction is basically a thin veneer over the
  582. // traditional GCC zero-cost design: for each range of instructions
  583. // in the function, there is (at most) one "landing pad" with an
  584. // associated chain of EH actions. A language-specific personality
  585. // function interprets this chain of actions and (1) decides whether
  586. // or not to resume execution at the landing pad and (2) if so,
  587. // provides an integer indicating why it's stopping. In LLVM IR,
  588. // the association of a landing pad with a range of instructions is
  589. // achieved via an invoke instruction, the chain of actions becomes
  590. // the arguments to the @llvm.eh.selector call, and the selector
  591. // call returns the integer indicator. Other than the required
  592. // presence of two intrinsic function calls in the landing pad,
  593. // the IR exactly describes the layout of the output code.
  594. //
  595. // A principal advantage of this design is that it is completely
  596. // language-agnostic; in theory, the LLVM optimizers can treat
  597. // landing pads neutrally, and targets need only know how to lower
  598. // the intrinsics to have a functioning exceptions system (assuming
  599. // that platform exceptions follow something approximately like the
  600. // GCC design). Unfortunately, landing pads cannot be combined in a
  601. // language-agnostic way: given selectors A and B, there is no way
  602. // to make a single landing pad which faithfully represents the
  603. // semantics of propagating an exception first through A, then
  604. // through B, without knowing how the personality will interpret the
  605. // (lowered form of the) selectors. This means that inlining has no
  606. // choice but to crudely chain invokes (i.e., to ignore invokes in
  607. // the inlined function, but to turn all unwindable calls into
  608. // invokes), which is only semantically valid if every unwind stops
  609. // at every landing pad.
  610. //
  611. // Therefore, the invoke-inline hack is to guarantee that every
  612. // landing pad has a catch-all.
  613. enum CleanupHackLevel_t {
  614. /// A level of hack that requires that all landing pads have
  615. /// catch-alls.
  616. CHL_MandatoryCatchall,
  617. /// A level of hack that requires that all landing pads handle
  618. /// cleanups.
  619. CHL_MandatoryCleanup,
  620. /// No hacks at all; ideal IR generation.
  621. CHL_Ideal
  622. };
  623. const CleanupHackLevel_t CleanupHackLevel = CHL_MandatoryCleanup;
  624. llvm::BasicBlock *CodeGenFunction::EmitLandingPad() {
  625. assert(EHStack.requiresLandingPad());
  626. EHScope &innermostEHScope = *EHStack.find(EHStack.getInnermostEHScope());
  627. switch (innermostEHScope.getKind()) {
  628. case EHScope::Terminate:
  629. return getTerminateLandingPad();
  630. case EHScope::Catch:
  631. case EHScope::Cleanup:
  632. case EHScope::Filter:
  633. if (llvm::BasicBlock *lpad = innermostEHScope.getCachedLandingPad())
  634. return lpad;
  635. }
  636. // Save the current IR generation state.
  637. CGBuilderTy::InsertPoint savedIP = Builder.saveAndClearIP();
  638. const EHPersonality &personality = EHPersonality::get(getLangOpts());
  639. // Create and configure the landing pad.
  640. llvm::BasicBlock *lpad = createBasicBlock("lpad");
  641. EmitBlock(lpad);
  642. llvm::LandingPadInst *LPadInst =
  643. Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty, NULL),
  644. getOpaquePersonalityFn(CGM, personality), 0);
  645. llvm::Value *LPadExn = Builder.CreateExtractValue(LPadInst, 0);
  646. Builder.CreateStore(LPadExn, getExceptionSlot());
  647. llvm::Value *LPadSel = Builder.CreateExtractValue(LPadInst, 1);
  648. Builder.CreateStore(LPadSel, getEHSelectorSlot());
  649. // Save the exception pointer. It's safe to use a single exception
  650. // pointer per function because EH cleanups can never have nested
  651. // try/catches.
  652. // Build the landingpad instruction.
  653. // Accumulate all the handlers in scope.
  654. bool hasCatchAll = false;
  655. bool hasCleanup = false;
  656. bool hasFilter = false;
  657. SmallVector<llvm::Value*, 4> filterTypes;
  658. llvm::SmallPtrSet<llvm::Value*, 4> catchTypes;
  659. for (EHScopeStack::iterator I = EHStack.begin(), E = EHStack.end();
  660. I != E; ++I) {
  661. switch (I->getKind()) {
  662. case EHScope::Cleanup:
  663. // If we have a cleanup, remember that.
  664. hasCleanup = (hasCleanup || cast<EHCleanupScope>(*I).isEHCleanup());
  665. continue;
  666. case EHScope::Filter: {
  667. assert(I.next() == EHStack.end() && "EH filter is not end of EH stack");
  668. assert(!hasCatchAll && "EH filter reached after catch-all");
  669. // Filter scopes get added to the landingpad in weird ways.
  670. EHFilterScope &filter = cast<EHFilterScope>(*I);
  671. hasFilter = true;
  672. // Add all the filter values.
  673. for (unsigned i = 0, e = filter.getNumFilters(); i != e; ++i)
  674. filterTypes.push_back(filter.getFilter(i));
  675. goto done;
  676. }
  677. case EHScope::Terminate:
  678. // Terminate scopes are basically catch-alls.
  679. assert(!hasCatchAll);
  680. hasCatchAll = true;
  681. goto done;
  682. case EHScope::Catch:
  683. break;
  684. }
  685. EHCatchScope &catchScope = cast<EHCatchScope>(*I);
  686. for (unsigned hi = 0, he = catchScope.getNumHandlers(); hi != he; ++hi) {
  687. EHCatchScope::Handler handler = catchScope.getHandler(hi);
  688. // If this is a catch-all, register that and abort.
  689. if (!handler.Type) {
  690. assert(!hasCatchAll);
  691. hasCatchAll = true;
  692. goto done;
  693. }
  694. // Check whether we already have a handler for this type.
  695. if (catchTypes.insert(handler.Type))
  696. // If not, add it directly to the landingpad.
  697. LPadInst->addClause(handler.Type);
  698. }
  699. }
  700. done:
  701. // If we have a catch-all, add null to the landingpad.
  702. assert(!(hasCatchAll && hasFilter));
  703. if (hasCatchAll) {
  704. LPadInst->addClause(getCatchAllValue(*this));
  705. // If we have an EH filter, we need to add those handlers in the
  706. // right place in the landingpad, which is to say, at the end.
  707. } else if (hasFilter) {
  708. // Create a filter expression: a constant array indicating which filter
  709. // types there are. The personality routine only lands here if the filter
  710. // doesn't match.
  711. llvm::SmallVector<llvm::Constant*, 8> Filters;
  712. llvm::ArrayType *AType =
  713. llvm::ArrayType::get(!filterTypes.empty() ?
  714. filterTypes[0]->getType() : Int8PtrTy,
  715. filterTypes.size());
  716. for (unsigned i = 0, e = filterTypes.size(); i != e; ++i)
  717. Filters.push_back(cast<llvm::Constant>(filterTypes[i]));
  718. llvm::Constant *FilterArray = llvm::ConstantArray::get(AType, Filters);
  719. LPadInst->addClause(FilterArray);
  720. // Also check whether we need a cleanup.
  721. if (hasCleanup)
  722. LPadInst->setCleanup(true);
  723. // Otherwise, signal that we at least have cleanups.
  724. } else if (CleanupHackLevel == CHL_MandatoryCatchall || hasCleanup) {
  725. if (CleanupHackLevel == CHL_MandatoryCatchall)
  726. LPadInst->addClause(getCatchAllValue(*this));
  727. else
  728. LPadInst->setCleanup(true);
  729. }
  730. assert((LPadInst->getNumClauses() > 0 || LPadInst->isCleanup()) &&
  731. "landingpad instruction has no clauses!");
  732. // Tell the backend how to generate the landing pad.
  733. Builder.CreateBr(getEHDispatchBlock(EHStack.getInnermostEHScope()));
  734. // Restore the old IR generation state.
  735. Builder.restoreIP(savedIP);
  736. return lpad;
  737. }
  738. namespace {
  739. /// A cleanup to call __cxa_end_catch. In many cases, the caught
  740. /// exception type lets us state definitively that the thrown exception
  741. /// type does not have a destructor. In particular:
  742. /// - Catch-alls tell us nothing, so we have to conservatively
  743. /// assume that the thrown exception might have a destructor.
  744. /// - Catches by reference behave according to their base types.
  745. /// - Catches of non-record types will only trigger for exceptions
  746. /// of non-record types, which never have destructors.
  747. /// - Catches of record types can trigger for arbitrary subclasses
  748. /// of the caught type, so we have to assume the actual thrown
  749. /// exception type might have a throwing destructor, even if the
  750. /// caught type's destructor is trivial or nothrow.
  751. struct CallEndCatch : EHScopeStack::Cleanup {
  752. CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
  753. bool MightThrow;
  754. void Emit(CodeGenFunction &CGF, Flags flags) {
  755. if (!MightThrow) {
  756. CGF.Builder.CreateCall(getEndCatchFn(CGF))->setDoesNotThrow();
  757. return;
  758. }
  759. CGF.EmitCallOrInvoke(getEndCatchFn(CGF));
  760. }
  761. };
  762. }
  763. /// Emits a call to __cxa_begin_catch and enters a cleanup to call
  764. /// __cxa_end_catch.
  765. ///
  766. /// \param EndMightThrow - true if __cxa_end_catch might throw
  767. static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
  768. llvm::Value *Exn,
  769. bool EndMightThrow) {
  770. llvm::CallInst *Call = CGF.Builder.CreateCall(getBeginCatchFn(CGF), Exn);
  771. Call->setDoesNotThrow();
  772. CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
  773. return Call;
  774. }
  775. /// A "special initializer" callback for initializing a catch
  776. /// parameter during catch initialization.
  777. static void InitCatchParam(CodeGenFunction &CGF,
  778. const VarDecl &CatchParam,
  779. llvm::Value *ParamAddr) {
  780. // Load the exception from where the landing pad saved it.
  781. llvm::Value *Exn = CGF.getExceptionFromSlot();
  782. CanQualType CatchType =
  783. CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
  784. llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
  785. // If we're catching by reference, we can just cast the object
  786. // pointer to the appropriate pointer.
  787. if (isa<ReferenceType>(CatchType)) {
  788. QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
  789. bool EndCatchMightThrow = CaughtType->isRecordType();
  790. // __cxa_begin_catch returns the adjusted object pointer.
  791. llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
  792. // We have no way to tell the personality function that we're
  793. // catching by reference, so if we're catching a pointer,
  794. // __cxa_begin_catch will actually return that pointer by value.
  795. if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
  796. QualType PointeeType = PT->getPointeeType();
  797. // When catching by reference, generally we should just ignore
  798. // this by-value pointer and use the exception object instead.
  799. if (!PointeeType->isRecordType()) {
  800. // Exn points to the struct _Unwind_Exception header, which
  801. // we have to skip past in order to reach the exception data.
  802. unsigned HeaderSize =
  803. CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
  804. AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
  805. // However, if we're catching a pointer-to-record type that won't
  806. // work, because the personality function might have adjusted
  807. // the pointer. There's actually no way for us to fully satisfy
  808. // the language/ABI contract here: we can't use Exn because it
  809. // might have the wrong adjustment, but we can't use the by-value
  810. // pointer because it's off by a level of abstraction.
  811. //
  812. // The current solution is to dump the adjusted pointer into an
  813. // alloca, which breaks language semantics (because changing the
  814. // pointer doesn't change the exception) but at least works.
  815. // The better solution would be to filter out non-exact matches
  816. // and rethrow them, but this is tricky because the rethrow
  817. // really needs to be catchable by other sites at this landing
  818. // pad. The best solution is to fix the personality function.
  819. } else {
  820. // Pull the pointer for the reference type off.
  821. llvm::Type *PtrTy =
  822. cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
  823. // Create the temporary and write the adjusted pointer into it.
  824. llvm::Value *ExnPtrTmp = CGF.CreateTempAlloca(PtrTy, "exn.byref.tmp");
  825. llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
  826. CGF.Builder.CreateStore(Casted, ExnPtrTmp);
  827. // Bind the reference to the temporary.
  828. AdjustedExn = ExnPtrTmp;
  829. }
  830. }
  831. llvm::Value *ExnCast =
  832. CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
  833. CGF.Builder.CreateStore(ExnCast, ParamAddr);
  834. return;
  835. }
  836. // Non-aggregates (plus complexes).
  837. bool IsComplex = false;
  838. if (!CGF.hasAggregateLLVMType(CatchType) ||
  839. (IsComplex = CatchType->isAnyComplexType())) {
  840. llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
  841. // If the catch type is a pointer type, __cxa_begin_catch returns
  842. // the pointer by value.
  843. if (CatchType->hasPointerRepresentation()) {
  844. llvm::Value *CastExn =
  845. CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
  846. switch (CatchType.getQualifiers().getObjCLifetime()) {
  847. case Qualifiers::OCL_Strong:
  848. CastExn = CGF.EmitARCRetainNonBlock(CastExn);
  849. // fallthrough
  850. case Qualifiers::OCL_None:
  851. case Qualifiers::OCL_ExplicitNone:
  852. case Qualifiers::OCL_Autoreleasing:
  853. CGF.Builder.CreateStore(CastExn, ParamAddr);
  854. return;
  855. case Qualifiers::OCL_Weak:
  856. CGF.EmitARCInitWeak(ParamAddr, CastExn);
  857. return;
  858. }
  859. llvm_unreachable("bad ownership qualifier!");
  860. }
  861. // Otherwise, it returns a pointer into the exception object.
  862. llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
  863. llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
  864. if (IsComplex) {
  865. CGF.StoreComplexToAddr(CGF.LoadComplexFromAddr(Cast, /*volatile*/ false),
  866. ParamAddr, /*volatile*/ false);
  867. } else {
  868. unsigned Alignment =
  869. CGF.getContext().getDeclAlign(&CatchParam).getQuantity();
  870. llvm::Value *ExnLoad = CGF.Builder.CreateLoad(Cast, "exn.scalar");
  871. CGF.EmitStoreOfScalar(ExnLoad, ParamAddr, /*volatile*/ false, Alignment,
  872. CatchType);
  873. }
  874. return;
  875. }
  876. assert(isa<RecordType>(CatchType) && "unexpected catch type!");
  877. llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
  878. // Check for a copy expression. If we don't have a copy expression,
  879. // that means a trivial copy is okay.
  880. const Expr *copyExpr = CatchParam.getInit();
  881. if (!copyExpr) {
  882. llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true);
  883. llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
  884. CGF.EmitAggregateCopy(ParamAddr, adjustedExn, CatchType);
  885. return;
  886. }
  887. // We have to call __cxa_get_exception_ptr to get the adjusted
  888. // pointer before copying.
  889. llvm::CallInst *rawAdjustedExn =
  890. CGF.Builder.CreateCall(getGetExceptionPtrFn(CGF), Exn);
  891. rawAdjustedExn->setDoesNotThrow();
  892. // Cast that to the appropriate type.
  893. llvm::Value *adjustedExn = CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy);
  894. // The copy expression is defined in terms of an OpaqueValueExpr.
  895. // Find it and map it to the adjusted expression.
  896. CodeGenFunction::OpaqueValueMapping
  897. opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr),
  898. CGF.MakeAddrLValue(adjustedExn, CatchParam.getType()));
  899. // Call the copy ctor in a terminate scope.
  900. CGF.EHStack.pushTerminate();
  901. // Perform the copy construction.
  902. CharUnits Alignment = CGF.getContext().getDeclAlign(&CatchParam);
  903. CGF.EmitAggExpr(copyExpr,
  904. AggValueSlot::forAddr(ParamAddr, Alignment, Qualifiers(),
  905. AggValueSlot::IsNotDestructed,
  906. AggValueSlot::DoesNotNeedGCBarriers,
  907. AggValueSlot::IsNotAliased));
  908. // Leave the terminate scope.
  909. CGF.EHStack.popTerminate();
  910. // Undo the opaque value mapping.
  911. opaque.pop();
  912. // Finally we can call __cxa_begin_catch.
  913. CallBeginCatch(CGF, Exn, true);
  914. }
  915. /// Begins a catch statement by initializing the catch variable and
  916. /// calling __cxa_begin_catch.
  917. static void BeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *S) {
  918. // We have to be very careful with the ordering of cleanups here:
  919. // C++ [except.throw]p4:
  920. // The destruction [of the exception temporary] occurs
  921. // immediately after the destruction of the object declared in
  922. // the exception-declaration in the handler.
  923. //
  924. // So the precise ordering is:
  925. // 1. Construct catch variable.
  926. // 2. __cxa_begin_catch
  927. // 3. Enter __cxa_end_catch cleanup
  928. // 4. Enter dtor cleanup
  929. //
  930. // We do this by using a slightly abnormal initialization process.
  931. // Delegation sequence:
  932. // - ExitCXXTryStmt opens a RunCleanupsScope
  933. // - EmitAutoVarAlloca creates the variable and debug info
  934. // - InitCatchParam initializes the variable from the exception
  935. // - CallBeginCatch calls __cxa_begin_catch
  936. // - CallBeginCatch enters the __cxa_end_catch cleanup
  937. // - EmitAutoVarCleanups enters the variable destructor cleanup
  938. // - EmitCXXTryStmt emits the code for the catch body
  939. // - EmitCXXTryStmt close the RunCleanupsScope
  940. VarDecl *CatchParam = S->getExceptionDecl();
  941. if (!CatchParam) {
  942. llvm::Value *Exn = CGF.getExceptionFromSlot();
  943. CallBeginCatch(CGF, Exn, true);
  944. return;
  945. }
  946. // Emit the local.
  947. CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
  948. InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF));
  949. CGF.EmitAutoVarCleanups(var);
  950. }
  951. /// Emit the structure of the dispatch block for the given catch scope.
  952. /// It is an invariant that the dispatch block already exists.
  953. static void emitCatchDispatchBlock(CodeGenFunction &CGF,
  954. EHCatchScope &catchScope) {
  955. llvm::BasicBlock *dispatchBlock = catchScope.getCachedEHDispatchBlock();
  956. assert(dispatchBlock);
  957. // If there's only a single catch-all, getEHDispatchBlock returned
  958. // that catch-all as the dispatch block.
  959. if (catchScope.getNumHandlers() == 1 &&
  960. catchScope.getHandler(0).isCatchAll()) {
  961. assert(dispatchBlock == catchScope.getHandler(0).Block);
  962. return;
  963. }
  964. CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveIP();
  965. CGF.EmitBlockAfterUses(dispatchBlock);
  966. // Select the right handler.
  967. llvm::Value *llvm_eh_typeid_for =
  968. CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
  969. // Load the selector value.
  970. llvm::Value *selector = CGF.getSelectorFromSlot();
  971. // Test against each of the exception types we claim to catch.
  972. for (unsigned i = 0, e = catchScope.getNumHandlers(); ; ++i) {
  973. assert(i < e && "ran off end of handlers!");
  974. const EHCatchScope::Handler &handler = catchScope.getHandler(i);
  975. llvm::Value *typeValue = handler.Type;
  976. assert(typeValue && "fell into catch-all case!");
  977. typeValue = CGF.Builder.CreateBitCast(typeValue, CGF.Int8PtrTy);
  978. // Figure out the next block.
  979. bool nextIsEnd;
  980. llvm::BasicBlock *nextBlock;
  981. // If this is the last handler, we're at the end, and the next
  982. // block is the block for the enclosing EH scope.
  983. if (i + 1 == e) {
  984. nextBlock = CGF.getEHDispatchBlock(catchScope.getEnclosingEHScope());
  985. nextIsEnd = true;
  986. // If the next handler is a catch-all, we're at the end, and the
  987. // next block is that handler.
  988. } else if (catchScope.getHandler(i+1).isCatchAll()) {
  989. nextBlock = catchScope.getHandler(i+1).Block;
  990. nextIsEnd = true;
  991. // Otherwise, we're not at the end and we need a new block.
  992. } else {
  993. nextBlock = CGF.createBasicBlock("catch.fallthrough");
  994. nextIsEnd = false;
  995. }
  996. // Figure out the catch type's index in the LSDA's type table.
  997. llvm::CallInst *typeIndex =
  998. CGF.Builder.CreateCall(llvm_eh_typeid_for, typeValue);
  999. typeIndex->setDoesNotThrow();
  1000. llvm::Value *matchesTypeIndex =
  1001. CGF.Builder.CreateICmpEQ(selector, typeIndex, "matches");
  1002. CGF.Builder.CreateCondBr(matchesTypeIndex, handler.Block, nextBlock);
  1003. // If the next handler is a catch-all, we're completely done.
  1004. if (nextIsEnd) {
  1005. CGF.Builder.restoreIP(savedIP);
  1006. return;
  1007. }
  1008. // Otherwise we need to emit and continue at that block.
  1009. CGF.EmitBlock(nextBlock);
  1010. }
  1011. }
  1012. void CodeGenFunction::popCatchScope() {
  1013. EHCatchScope &catchScope = cast<EHCatchScope>(*EHStack.begin());
  1014. if (catchScope.hasEHBranches())
  1015. emitCatchDispatchBlock(*this, catchScope);
  1016. EHStack.popCatch();
  1017. }
  1018. void CodeGenFunction::ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
  1019. unsigned NumHandlers = S.getNumHandlers();
  1020. EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
  1021. assert(CatchScope.getNumHandlers() == NumHandlers);
  1022. // If the catch was not required, bail out now.
  1023. if (!CatchScope.hasEHBranches()) {
  1024. EHStack.popCatch();
  1025. return;
  1026. }
  1027. // Emit the structure of the EH dispatch for this catch.
  1028. emitCatchDispatchBlock(*this, CatchScope);
  1029. // Copy the handler blocks off before we pop the EH stack. Emitting
  1030. // the handlers might scribble on this memory.
  1031. SmallVector<EHCatchScope::Handler, 8> Handlers(NumHandlers);
  1032. memcpy(Handlers.data(), CatchScope.begin(),
  1033. NumHandlers * sizeof(EHCatchScope::Handler));
  1034. EHStack.popCatch();
  1035. // The fall-through block.
  1036. llvm::BasicBlock *ContBB = createBasicBlock("try.cont");
  1037. // We just emitted the body of the try; jump to the continue block.
  1038. if (HaveInsertPoint())
  1039. Builder.CreateBr(ContBB);
  1040. // Determine if we need an implicit rethrow for all these catch handlers;
  1041. // see the comment below.
  1042. bool doImplicitRethrow = false;
  1043. if (IsFnTryBlock)
  1044. doImplicitRethrow = isa<CXXDestructorDecl>(CurCodeDecl) ||
  1045. isa<CXXConstructorDecl>(CurCodeDecl);
  1046. // Perversely, we emit the handlers backwards precisely because we
  1047. // want them to appear in source order. In all of these cases, the
  1048. // catch block will have exactly one predecessor, which will be a
  1049. // particular block in the catch dispatch. However, in the case of
  1050. // a catch-all, one of the dispatch blocks will branch to two
  1051. // different handlers, and EmitBlockAfterUses will cause the second
  1052. // handler to be moved before the first.
  1053. for (unsigned I = NumHandlers; I != 0; --I) {
  1054. llvm::BasicBlock *CatchBlock = Handlers[I-1].Block;
  1055. EmitBlockAfterUses(CatchBlock);
  1056. // Catch the exception if this isn't a catch-all.
  1057. const CXXCatchStmt *C = S.getHandler(I-1);
  1058. // Enter a cleanup scope, including the catch variable and the
  1059. // end-catch.
  1060. RunCleanupsScope CatchScope(*this);
  1061. // Initialize the catch variable and set up the cleanups.
  1062. BeginCatch(*this, C);
  1063. // Perform the body of the catch.
  1064. EmitStmt(C->getHandlerBlock());
  1065. // [except.handle]p11:
  1066. // The currently handled exception is rethrown if control
  1067. // reaches the end of a handler of the function-try-block of a
  1068. // constructor or destructor.
  1069. // It is important that we only do this on fallthrough and not on
  1070. // return. Note that it's illegal to put a return in a
  1071. // constructor function-try-block's catch handler (p14), so this
  1072. // really only applies to destructors.
  1073. if (doImplicitRethrow && HaveInsertPoint()) {
  1074. EmitCallOrInvoke(getReThrowFn(*this));
  1075. Builder.CreateUnreachable();
  1076. Builder.ClearInsertionPoint();
  1077. }
  1078. // Fall out through the catch cleanups.
  1079. CatchScope.ForceCleanup();
  1080. // Branch out of the try.
  1081. if (HaveInsertPoint())
  1082. Builder.CreateBr(ContBB);
  1083. }
  1084. EmitBlock(ContBB);
  1085. }
  1086. namespace {
  1087. struct CallEndCatchForFinally : EHScopeStack::Cleanup {
  1088. llvm::Value *ForEHVar;
  1089. llvm::Value *EndCatchFn;
  1090. CallEndCatchForFinally(llvm::Value *ForEHVar, llvm::Value *EndCatchFn)
  1091. : ForEHVar(ForEHVar), EndCatchFn(EndCatchFn) {}
  1092. void Emit(CodeGenFunction &CGF, Flags flags) {
  1093. llvm::BasicBlock *EndCatchBB = CGF.createBasicBlock("finally.endcatch");
  1094. llvm::BasicBlock *CleanupContBB =
  1095. CGF.createBasicBlock("finally.cleanup.cont");
  1096. llvm::Value *ShouldEndCatch =
  1097. CGF.Builder.CreateLoad(ForEHVar, "finally.endcatch");
  1098. CGF.Builder.CreateCondBr(ShouldEndCatch, EndCatchBB, CleanupContBB);
  1099. CGF.EmitBlock(EndCatchBB);
  1100. CGF.EmitCallOrInvoke(EndCatchFn); // catch-all, so might throw
  1101. CGF.EmitBlock(CleanupContBB);
  1102. }
  1103. };
  1104. struct PerformFinally : EHScopeStack::Cleanup {
  1105. const Stmt *Body;
  1106. llvm::Value *ForEHVar;
  1107. llvm::Value *EndCatchFn;
  1108. llvm::Value *RethrowFn;
  1109. llvm::Value *SavedExnVar;
  1110. PerformFinally(const Stmt *Body, llvm::Value *ForEHVar,
  1111. llvm::Value *EndCatchFn,
  1112. llvm::Value *RethrowFn, llvm::Value *SavedExnVar)
  1113. : Body(Body), ForEHVar(ForEHVar), EndCatchFn(EndCatchFn),
  1114. RethrowFn(RethrowFn), SavedExnVar(SavedExnVar) {}
  1115. void Emit(CodeGenFunction &CGF, Flags flags) {
  1116. // Enter a cleanup to call the end-catch function if one was provided.
  1117. if (EndCatchFn)
  1118. CGF.EHStack.pushCleanup<CallEndCatchForFinally>(NormalAndEHCleanup,
  1119. ForEHVar, EndCatchFn);
  1120. // Save the current cleanup destination in case there are
  1121. // cleanups in the finally block.
  1122. llvm::Value *SavedCleanupDest =
  1123. CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot(),
  1124. "cleanup.dest.saved");
  1125. // Emit the finally block.
  1126. CGF.EmitStmt(Body);
  1127. // If the end of the finally is reachable, check whether this was
  1128. // for EH. If so, rethrow.
  1129. if (CGF.HaveInsertPoint()) {
  1130. llvm::BasicBlock *RethrowBB = CGF.createBasicBlock("finally.rethrow");
  1131. llvm::BasicBlock *ContBB = CGF.createBasicBlock("finally.cont");
  1132. llvm::Value *ShouldRethrow =
  1133. CGF.Builder.CreateLoad(ForEHVar, "finally.shouldthrow");
  1134. CGF.Builder.CreateCondBr(ShouldRethrow, RethrowBB, ContBB);
  1135. CGF.EmitBlock(RethrowBB);
  1136. if (SavedExnVar) {
  1137. CGF.EmitCallOrInvoke(RethrowFn, CGF.Builder.CreateLoad(SavedExnVar));
  1138. } else {
  1139. CGF.EmitCallOrInvoke(RethrowFn);
  1140. }
  1141. CGF.Builder.CreateUnreachable();
  1142. CGF.EmitBlock(ContBB);
  1143. // Restore the cleanup destination.
  1144. CGF.Builder.CreateStore(SavedCleanupDest,
  1145. CGF.getNormalCleanupDestSlot());
  1146. }
  1147. // Leave the end-catch cleanup. As an optimization, pretend that
  1148. // the fallthrough path was inaccessible; we've dynamically proven
  1149. // that we're not in the EH case along that path.
  1150. if (EndCatchFn) {
  1151. CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
  1152. CGF.PopCleanupBlock();
  1153. CGF.Builder.restoreIP(SavedIP);
  1154. }
  1155. // Now make sure we actually have an insertion point or the
  1156. // cleanup gods will hate us.
  1157. CGF.EnsureInsertPoint();
  1158. }
  1159. };
  1160. }
  1161. /// Enters a finally block for an implementation using zero-cost
  1162. /// exceptions. This is mostly general, but hard-codes some
  1163. /// language/ABI-specific behavior in the catch-all sections.
  1164. void CodeGenFunction::FinallyInfo::enter(CodeGenFunction &CGF,
  1165. const Stmt *body,
  1166. llvm::Constant *beginCatchFn,
  1167. llvm::Constant *endCatchFn,
  1168. llvm::Constant *rethrowFn) {
  1169. assert((beginCatchFn != 0) == (endCatchFn != 0) &&
  1170. "begin/end catch functions not paired");
  1171. assert(rethrowFn && "rethrow function is required");
  1172. BeginCatchFn = beginCatchFn;
  1173. // The rethrow function has one of the following two types:
  1174. // void (*)()
  1175. // void (*)(void*)
  1176. // In the latter case we need to pass it the exception object.
  1177. // But we can't use the exception slot because the @finally might
  1178. // have a landing pad (which would overwrite the exception slot).
  1179. llvm::FunctionType *rethrowFnTy =
  1180. cast<llvm::FunctionType>(
  1181. cast<llvm::PointerType>(rethrowFn->getType())->getElementType());
  1182. SavedExnVar = 0;
  1183. if (rethrowFnTy->getNumParams())
  1184. SavedExnVar = CGF.CreateTempAlloca(CGF.Int8PtrTy, "finally.exn");
  1185. // A finally block is a statement which must be executed on any edge
  1186. // out of a given scope. Unlike a cleanup, the finally block may
  1187. // contain arbitrary control flow leading out of itself. In
  1188. // addition, finally blocks should always be executed, even if there
  1189. // are no catch handlers higher on the stack. Therefore, we
  1190. // surround the protected scope with a combination of a normal
  1191. // cleanup (to catch attempts to break out of the block via normal
  1192. // control flow) and an EH catch-all (semantically "outside" any try
  1193. // statement to which the finally block might have been attached).
  1194. // The finally block itself is generated in the context of a cleanup
  1195. // which conditionally leaves the catch-all.
  1196. // Jump destination for performing the finally block on an exception
  1197. // edge. We'll never actually reach this block, so unreachable is
  1198. // fine.
  1199. RethrowDest = CGF.getJumpDestInCurrentScope(CGF.getUnreachableBlock());
  1200. // Whether the finally block is being executed for EH purposes.
  1201. ForEHVar = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), "finally.for-eh");
  1202. CGF.Builder.CreateStore(CGF.Builder.getFalse(), ForEHVar);
  1203. // Enter a normal cleanup which will perform the @finally block.
  1204. CGF.EHStack.pushCleanup<PerformFinally>(NormalCleanup, body,
  1205. ForEHVar, endCatchFn,
  1206. rethrowFn, SavedExnVar);
  1207. // Enter a catch-all scope.
  1208. llvm::BasicBlock *catchBB = CGF.createBasicBlock("finally.catchall");
  1209. EHCatchScope *catchScope = CGF.EHStack.pushCatch(1);
  1210. catchScope->setCatchAllHandler(0, catchBB);
  1211. }
  1212. void CodeGenFunction::FinallyInfo::exit(CodeGenFunction &CGF) {
  1213. // Leave the finally catch-all.
  1214. EHCatchScope &catchScope = cast<EHCatchScope>(*CGF.EHStack.begin());
  1215. llvm::BasicBlock *catchBB = catchScope.getHandler(0).Block;
  1216. CGF.popCatchScope();
  1217. // If there are any references to the catch-all block, emit it.
  1218. if (catchBB->use_empty()) {
  1219. delete catchBB;
  1220. } else {
  1221. CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveAndClearIP();
  1222. CGF.EmitBlock(catchBB);
  1223. llvm::Value *exn = 0;
  1224. // If there's a begin-catch function, call it.
  1225. if (BeginCatchFn) {
  1226. exn = CGF.getExceptionFromSlot();
  1227. CGF.Builder.CreateCall(BeginCatchFn, exn)->setDoesNotThrow();
  1228. }
  1229. // If we need to remember the exception pointer to rethrow later, do so.
  1230. if (SavedExnVar) {
  1231. if (!exn) exn = CGF.getExceptionFromSlot();
  1232. CGF.Builder.CreateStore(exn, SavedExnVar);
  1233. }
  1234. // Tell the cleanups in the finally block that we're do this for EH.
  1235. CGF.Builder.CreateStore(CGF.Builder.getTrue(), ForEHVar);
  1236. // Thread a jump through the finally cleanup.
  1237. CGF.EmitBranchThroughCleanup(RethrowDest);
  1238. CGF.Builder.restoreIP(savedIP);
  1239. }
  1240. // Finally, leave the @finally cleanup.
  1241. CGF.PopCleanupBlock();
  1242. }
  1243. llvm::BasicBlock *CodeGenFunction::getTerminateLandingPad() {
  1244. if (TerminateLandingPad)
  1245. return TerminateLandingPad;
  1246. CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
  1247. // This will get inserted at the end of the function.
  1248. TerminateLandingPad = createBasicBlock("terminate.lpad");
  1249. Builder.SetInsertPoint(TerminateLandingPad);
  1250. // Tell the backend that this is a landing pad.
  1251. const EHPersonality &Personality = EHPersonality::get(CGM.getLangOpts());
  1252. llvm::LandingPadInst *LPadInst =
  1253. Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty, NULL),
  1254. getOpaquePersonalityFn(CGM, Personality), 0);
  1255. LPadInst->addClause(getCatchAllValue(*this));
  1256. llvm::CallInst *TerminateCall = Builder.CreateCall(getTerminateFn(*this));
  1257. TerminateCall->setDoesNotReturn();
  1258. TerminateCall->setDoesNotThrow();
  1259. Builder.CreateUnreachable();
  1260. // Restore the saved insertion state.
  1261. Builder.restoreIP(SavedIP);
  1262. return TerminateLandingPad;
  1263. }
  1264. llvm::BasicBlock *CodeGenFunction::getTerminateHandler() {
  1265. if (TerminateHandler)
  1266. return TerminateHandler;
  1267. CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
  1268. // Set up the terminate handler. This block is inserted at the very
  1269. // end of the function by FinishFunction.
  1270. TerminateHandler = createBasicBlock("terminate.handler");
  1271. Builder.SetInsertPoint(TerminateHandler);
  1272. llvm::CallInst *TerminateCall = Builder.CreateCall(getTerminateFn(*this));
  1273. TerminateCall->setDoesNotReturn();
  1274. TerminateCall->setDoesNotThrow();
  1275. Builder.CreateUnreachable();
  1276. // Restore the saved insertion state.
  1277. Builder.restoreIP(SavedIP);
  1278. return TerminateHandler;
  1279. }
  1280. llvm::BasicBlock *CodeGenFunction::getEHResumeBlock() {
  1281. if (EHResumeBlock) return EHResumeBlock;
  1282. CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
  1283. // We emit a jump to a notional label at the outermost unwind state.
  1284. EHResumeBlock = createBasicBlock("eh.resume");
  1285. Builder.SetInsertPoint(EHResumeBlock);
  1286. const EHPersonality &Personality = EHPersonality::get(CGM.getLangOpts());
  1287. // This can always be a call because we necessarily didn't find
  1288. // anything on the EH stack which needs our help.
  1289. const char *RethrowName = Personality.CatchallRethrowFn;
  1290. if (RethrowName != 0) {
  1291. Builder.CreateCall(getCatchallRethrowFn(*this, RethrowName),
  1292. getExceptionFromSlot())
  1293. ->setDoesNotReturn();
  1294. } else {
  1295. switch (CleanupHackLevel) {
  1296. case CHL_MandatoryCatchall:
  1297. // In mandatory-catchall mode, we need to use
  1298. // _Unwind_Resume_or_Rethrow, or whatever the personality's
  1299. // equivalent is.
  1300. Builder.CreateCall(getUnwindResumeOrRethrowFn(),
  1301. getExceptionFromSlot())
  1302. ->setDoesNotReturn();
  1303. break;
  1304. case CHL_MandatoryCleanup: {
  1305. // In mandatory-cleanup mode, we should use 'resume'.
  1306. // Recreate the landingpad's return value for the 'resume' instruction.
  1307. llvm::Value *Exn = getExceptionFromSlot();
  1308. llvm::Value *Sel = getSelectorFromSlot();
  1309. llvm::Type *LPadType = llvm::StructType::get(Exn->getType(),
  1310. Sel->getType(), NULL);
  1311. llvm::Value *LPadVal = llvm::UndefValue::get(LPadType);
  1312. LPadVal = Builder.CreateInsertValue(LPadVal, Exn, 0, "lpad.val");
  1313. LPadVal = Builder.CreateInsertValue(LPadVal, Sel, 1, "lpad.val");
  1314. Builder.CreateResume(LPadVal);
  1315. Builder.restoreIP(SavedIP);
  1316. return EHResumeBlock;
  1317. }
  1318. case CHL_Ideal:
  1319. // In an idealized mode where we don't have to worry about the
  1320. // optimizer combining landing pads, we should just use
  1321. // _Unwind_Resume (or the personality's equivalent).
  1322. Builder.CreateCall(getUnwindResumeFn(), getExceptionFromSlot())
  1323. ->setDoesNotReturn();
  1324. break;
  1325. }
  1326. }
  1327. Builder.CreateUnreachable();
  1328. Builder.restoreIP(SavedIP);
  1329. return EHResumeBlock;
  1330. }