ExceptionDemo.cpp 71 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039
  1. //===-- ExceptionDemo.cpp - An example using llvm 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. // Demo program which implements an example LLVM exception implementation, and
  11. // shows several test cases including the handling of foreign exceptions.
  12. // It is run with type info types arguments to throw. A test will
  13. // be run for each given type info type. While type info types with the value
  14. // of -1 will trigger a foreign C++ exception to be thrown; type info types
  15. // <= 6 and >= 1 will cause the associated generated exceptions to be thrown
  16. // and caught by generated test functions; and type info types > 6
  17. // will result in exceptions which pass through to the test harness. All other
  18. // type info types are not supported and could cause a crash. In all cases,
  19. // the "finally" blocks of every generated test functions will executed
  20. // regardless of whether or not that test function ignores or catches the
  21. // thrown exception.
  22. //
  23. // examples:
  24. //
  25. // ExceptionDemo
  26. //
  27. // causes a usage to be printed to stderr
  28. //
  29. // ExceptionDemo 2 3 7 -1
  30. //
  31. // results in the following cases:
  32. // - Value 2 causes an exception with a type info type of 2 to be
  33. // thrown and caught by an inner generated test function.
  34. // - Value 3 causes an exception with a type info type of 3 to be
  35. // thrown and caught by an outer generated test function.
  36. // - Value 7 causes an exception with a type info type of 7 to be
  37. // thrown and NOT be caught by any generated function.
  38. // - Value -1 causes a foreign C++ exception to be thrown and not be
  39. // caught by any generated function
  40. //
  41. // Cases -1 and 7 are caught by a C++ test harness where the validity of
  42. // of a C++ catch(...) clause catching a generated exception with a
  43. // type info type of 7 is explained by: example in rules 1.6.4 in
  44. // http://mentorembedded.github.com/cxx-abi/abi-eh.html (v1.22)
  45. //
  46. // This code uses code from the llvm compiler-rt project and the llvm
  47. // Kaleidoscope project.
  48. //
  49. //===----------------------------------------------------------------------===//
  50. #include "llvm/IR/Verifier.h"
  51. #include "llvm/ExecutionEngine/MCJIT.h"
  52. #include "llvm/ExecutionEngine/SectionMemoryManager.h"
  53. #include "llvm/IR/DataLayout.h"
  54. #include "llvm/IR/DerivedTypes.h"
  55. #include "llvm/IR/IRBuilder.h"
  56. #include "llvm/IR/Intrinsics.h"
  57. #include "llvm/IR/LLVMContext.h"
  58. #include "llvm/IR/Module.h"
  59. #include "llvm/PassManager.h"
  60. #include "llvm/Support/Dwarf.h"
  61. #include "llvm/Support/TargetSelect.h"
  62. #include "llvm/Target/TargetOptions.h"
  63. #include "llvm/Transforms/Scalar.h"
  64. // FIXME: Although all systems tested with (Linux, OS X), do not need this
  65. // header file included. A user on ubuntu reported, undefined symbols
  66. // for stderr, and fprintf, and the addition of this include fixed the
  67. // issue for them. Given that LLVM's best practices include the goal
  68. // of reducing the number of redundant header files included, the
  69. // correct solution would be to find out why these symbols are not
  70. // defined for the system in question, and fix the issue by finding out
  71. // which LLVM header file, if any, would include these symbols.
  72. #include <cstdio>
  73. #include <sstream>
  74. #include <stdexcept>
  75. #ifndef USE_GLOBAL_STR_CONSTS
  76. #define USE_GLOBAL_STR_CONSTS true
  77. #endif
  78. // System C++ ABI unwind types from:
  79. // http://mentorembedded.github.com/cxx-abi/abi-eh.html (v1.22)
  80. extern "C" {
  81. typedef enum {
  82. _URC_NO_REASON = 0,
  83. _URC_FOREIGN_EXCEPTION_CAUGHT = 1,
  84. _URC_FATAL_PHASE2_ERROR = 2,
  85. _URC_FATAL_PHASE1_ERROR = 3,
  86. _URC_NORMAL_STOP = 4,
  87. _URC_END_OF_STACK = 5,
  88. _URC_HANDLER_FOUND = 6,
  89. _URC_INSTALL_CONTEXT = 7,
  90. _URC_CONTINUE_UNWIND = 8
  91. } _Unwind_Reason_Code;
  92. typedef enum {
  93. _UA_SEARCH_PHASE = 1,
  94. _UA_CLEANUP_PHASE = 2,
  95. _UA_HANDLER_FRAME = 4,
  96. _UA_FORCE_UNWIND = 8,
  97. _UA_END_OF_STACK = 16
  98. } _Unwind_Action;
  99. struct _Unwind_Exception;
  100. typedef void (*_Unwind_Exception_Cleanup_Fn) (_Unwind_Reason_Code,
  101. struct _Unwind_Exception *);
  102. struct _Unwind_Exception {
  103. uint64_t exception_class;
  104. _Unwind_Exception_Cleanup_Fn exception_cleanup;
  105. uintptr_t private_1;
  106. uintptr_t private_2;
  107. // @@@ The IA-64 ABI says that this structure must be double-word aligned.
  108. // Taking that literally does not make much sense generically. Instead
  109. // we provide the maximum alignment required by any type for the machine.
  110. } __attribute__((__aligned__));
  111. struct _Unwind_Context;
  112. typedef struct _Unwind_Context *_Unwind_Context_t;
  113. extern const uint8_t *_Unwind_GetLanguageSpecificData (_Unwind_Context_t c);
  114. extern uintptr_t _Unwind_GetGR (_Unwind_Context_t c, int i);
  115. extern void _Unwind_SetGR (_Unwind_Context_t c, int i, uintptr_t n);
  116. extern void _Unwind_SetIP (_Unwind_Context_t, uintptr_t new_value);
  117. extern uintptr_t _Unwind_GetIP (_Unwind_Context_t context);
  118. extern uintptr_t _Unwind_GetRegionStart (_Unwind_Context_t context);
  119. } // extern "C"
  120. //
  121. // Example types
  122. //
  123. /// This is our simplistic type info
  124. struct OurExceptionType_t {
  125. /// type info type
  126. int type;
  127. };
  128. /// This is our Exception class which relies on a negative offset to calculate
  129. /// pointers to its instances from pointers to its unwindException member.
  130. ///
  131. /// Note: The above unwind.h defines struct _Unwind_Exception to be aligned
  132. /// on a double word boundary. This is necessary to match the standard:
  133. /// http://mentorembedded.github.com/cxx-abi/abi-eh.html
  134. struct OurBaseException_t {
  135. struct OurExceptionType_t type;
  136. // Note: This is properly aligned in unwind.h
  137. struct _Unwind_Exception unwindException;
  138. };
  139. // Note: Not needed since we are C++
  140. typedef struct OurBaseException_t OurException;
  141. typedef struct _Unwind_Exception OurUnwindException;
  142. //
  143. // Various globals used to support typeinfo and generatted exceptions in
  144. // general
  145. //
  146. static std::map<std::string, llvm::Value*> namedValues;
  147. int64_t ourBaseFromUnwindOffset;
  148. const unsigned char ourBaseExcpClassChars[] =
  149. {'o', 'b', 'j', '\0', 'b', 'a', 's', '\0'};
  150. static uint64_t ourBaseExceptionClass = 0;
  151. static std::vector<std::string> ourTypeInfoNames;
  152. static std::map<int, std::string> ourTypeInfoNamesIndex;
  153. static llvm::StructType *ourTypeInfoType;
  154. static llvm::StructType *ourCaughtResultType;
  155. static llvm::StructType *ourExceptionType;
  156. static llvm::StructType *ourUnwindExceptionType;
  157. static llvm::ConstantInt *ourExceptionNotThrownState;
  158. static llvm::ConstantInt *ourExceptionThrownState;
  159. static llvm::ConstantInt *ourExceptionCaughtState;
  160. typedef std::vector<std::string> ArgNames;
  161. typedef std::vector<llvm::Type*> ArgTypes;
  162. //
  163. // Code Generation Utilities
  164. //
  165. /// Utility used to create a function, both declarations and definitions
  166. /// @param module for module instance
  167. /// @param retType function return type
  168. /// @param theArgTypes function's ordered argument types
  169. /// @param theArgNames function's ordered arguments needed if use of this
  170. /// function corresponds to a function definition. Use empty
  171. /// aggregate for function declarations.
  172. /// @param functName function name
  173. /// @param linkage function linkage
  174. /// @param declarationOnly for function declarations
  175. /// @param isVarArg function uses vararg arguments
  176. /// @returns function instance
  177. llvm::Function *createFunction(llvm::Module &module,
  178. llvm::Type *retType,
  179. const ArgTypes &theArgTypes,
  180. const ArgNames &theArgNames,
  181. const std::string &functName,
  182. llvm::GlobalValue::LinkageTypes linkage,
  183. bool declarationOnly,
  184. bool isVarArg) {
  185. llvm::FunctionType *functType =
  186. llvm::FunctionType::get(retType, theArgTypes, isVarArg);
  187. llvm::Function *ret =
  188. llvm::Function::Create(functType, linkage, functName, &module);
  189. if (!ret || declarationOnly)
  190. return(ret);
  191. namedValues.clear();
  192. unsigned i = 0;
  193. for (llvm::Function::arg_iterator argIndex = ret->arg_begin();
  194. i != theArgNames.size();
  195. ++argIndex, ++i) {
  196. argIndex->setName(theArgNames[i]);
  197. namedValues[theArgNames[i]] = argIndex;
  198. }
  199. return(ret);
  200. }
  201. /// Create an alloca instruction in the entry block of
  202. /// the parent function. This is used for mutable variables etc.
  203. /// @param function parent instance
  204. /// @param varName stack variable name
  205. /// @param type stack variable type
  206. /// @param initWith optional constant initialization value
  207. /// @returns AllocaInst instance
  208. static llvm::AllocaInst *createEntryBlockAlloca(llvm::Function &function,
  209. const std::string &varName,
  210. llvm::Type *type,
  211. llvm::Constant *initWith = 0) {
  212. llvm::BasicBlock &block = function.getEntryBlock();
  213. llvm::IRBuilder<> tmp(&block, block.begin());
  214. llvm::AllocaInst *ret = tmp.CreateAlloca(type, 0, varName.c_str());
  215. if (initWith)
  216. tmp.CreateStore(initWith, ret);
  217. return(ret);
  218. }
  219. //
  220. // Code Generation Utilities End
  221. //
  222. //
  223. // Runtime C Library functions
  224. //
  225. // Note: using an extern "C" block so that static functions can be used
  226. extern "C" {
  227. // Note: Better ways to decide on bit width
  228. //
  229. /// Prints a 32 bit number, according to the format, to stderr.
  230. /// @param intToPrint integer to print
  231. /// @param format printf like format to use when printing
  232. void print32Int(int intToPrint, const char *format) {
  233. if (format) {
  234. // Note: No NULL check
  235. fprintf(stderr, format, intToPrint);
  236. }
  237. else {
  238. // Note: No NULL check
  239. fprintf(stderr, "::print32Int(...):NULL arg.\n");
  240. }
  241. }
  242. // Note: Better ways to decide on bit width
  243. //
  244. /// Prints a 64 bit number, according to the format, to stderr.
  245. /// @param intToPrint integer to print
  246. /// @param format printf like format to use when printing
  247. void print64Int(long int intToPrint, const char *format) {
  248. if (format) {
  249. // Note: No NULL check
  250. fprintf(stderr, format, intToPrint);
  251. }
  252. else {
  253. // Note: No NULL check
  254. fprintf(stderr, "::print64Int(...):NULL arg.\n");
  255. }
  256. }
  257. /// Prints a C string to stderr
  258. /// @param toPrint string to print
  259. void printStr(char *toPrint) {
  260. if (toPrint) {
  261. fprintf(stderr, "%s", toPrint);
  262. }
  263. else {
  264. fprintf(stderr, "::printStr(...):NULL arg.\n");
  265. }
  266. }
  267. /// Deletes the true previosly allocated exception whose address
  268. /// is calculated from the supplied OurBaseException_t::unwindException
  269. /// member address. Handles (ignores), NULL pointers.
  270. /// @param expToDelete exception to delete
  271. void deleteOurException(OurUnwindException *expToDelete) {
  272. #ifdef DEBUG
  273. fprintf(stderr,
  274. "deleteOurException(...).\n");
  275. #endif
  276. if (expToDelete &&
  277. (expToDelete->exception_class == ourBaseExceptionClass)) {
  278. free(((char*) expToDelete) + ourBaseFromUnwindOffset);
  279. }
  280. }
  281. /// This function is the struct _Unwind_Exception API mandated delete function
  282. /// used by foreign exception handlers when deleting our exception
  283. /// (OurException), instances.
  284. /// @param reason See @link http://mentorembedded.github.com/cxx-abi/abi-eh.html
  285. /// @unlink
  286. /// @param expToDelete exception instance to delete
  287. void deleteFromUnwindOurException(_Unwind_Reason_Code reason,
  288. OurUnwindException *expToDelete) {
  289. #ifdef DEBUG
  290. fprintf(stderr,
  291. "deleteFromUnwindOurException(...).\n");
  292. #endif
  293. deleteOurException(expToDelete);
  294. }
  295. /// Creates (allocates on the heap), an exception (OurException instance),
  296. /// of the supplied type info type.
  297. /// @param type type info type
  298. OurUnwindException *createOurException(int type) {
  299. size_t size = sizeof(OurException);
  300. OurException *ret = (OurException*) memset(malloc(size), 0, size);
  301. (ret->type).type = type;
  302. (ret->unwindException).exception_class = ourBaseExceptionClass;
  303. (ret->unwindException).exception_cleanup = deleteFromUnwindOurException;
  304. return(&(ret->unwindException));
  305. }
  306. /// Read a uleb128 encoded value and advance pointer
  307. /// See Variable Length Data in:
  308. /// @link http://dwarfstd.org/Dwarf3.pdf @unlink
  309. /// @param data reference variable holding memory pointer to decode from
  310. /// @returns decoded value
  311. static uintptr_t readULEB128(const uint8_t **data) {
  312. uintptr_t result = 0;
  313. uintptr_t shift = 0;
  314. unsigned char byte;
  315. const uint8_t *p = *data;
  316. do {
  317. byte = *p++;
  318. result |= (byte & 0x7f) << shift;
  319. shift += 7;
  320. }
  321. while (byte & 0x80);
  322. *data = p;
  323. return result;
  324. }
  325. /// Read a sleb128 encoded value and advance pointer
  326. /// See Variable Length Data in:
  327. /// @link http://dwarfstd.org/Dwarf3.pdf @unlink
  328. /// @param data reference variable holding memory pointer to decode from
  329. /// @returns decoded value
  330. static uintptr_t readSLEB128(const uint8_t **data) {
  331. uintptr_t result = 0;
  332. uintptr_t shift = 0;
  333. unsigned char byte;
  334. const uint8_t *p = *data;
  335. do {
  336. byte = *p++;
  337. result |= (byte & 0x7f) << shift;
  338. shift += 7;
  339. }
  340. while (byte & 0x80);
  341. *data = p;
  342. if ((byte & 0x40) && (shift < (sizeof(result) << 3))) {
  343. result |= (~0 << shift);
  344. }
  345. return result;
  346. }
  347. unsigned getEncodingSize(uint8_t Encoding) {
  348. if (Encoding == llvm::dwarf::DW_EH_PE_omit)
  349. return 0;
  350. switch (Encoding & 0x0F) {
  351. case llvm::dwarf::DW_EH_PE_absptr:
  352. return sizeof(uintptr_t);
  353. case llvm::dwarf::DW_EH_PE_udata2:
  354. return sizeof(uint16_t);
  355. case llvm::dwarf::DW_EH_PE_udata4:
  356. return sizeof(uint32_t);
  357. case llvm::dwarf::DW_EH_PE_udata8:
  358. return sizeof(uint64_t);
  359. case llvm::dwarf::DW_EH_PE_sdata2:
  360. return sizeof(int16_t);
  361. case llvm::dwarf::DW_EH_PE_sdata4:
  362. return sizeof(int32_t);
  363. case llvm::dwarf::DW_EH_PE_sdata8:
  364. return sizeof(int64_t);
  365. default:
  366. // not supported
  367. abort();
  368. }
  369. }
  370. /// Read a pointer encoded value and advance pointer
  371. /// See Variable Length Data in:
  372. /// @link http://dwarfstd.org/Dwarf3.pdf @unlink
  373. /// @param data reference variable holding memory pointer to decode from
  374. /// @param encoding dwarf encoding type
  375. /// @returns decoded value
  376. static uintptr_t readEncodedPointer(const uint8_t **data, uint8_t encoding) {
  377. uintptr_t result = 0;
  378. const uint8_t *p = *data;
  379. if (encoding == llvm::dwarf::DW_EH_PE_omit)
  380. return(result);
  381. // first get value
  382. switch (encoding & 0x0F) {
  383. case llvm::dwarf::DW_EH_PE_absptr:
  384. result = *((uintptr_t*)p);
  385. p += sizeof(uintptr_t);
  386. break;
  387. case llvm::dwarf::DW_EH_PE_uleb128:
  388. result = readULEB128(&p);
  389. break;
  390. // Note: This case has not been tested
  391. case llvm::dwarf::DW_EH_PE_sleb128:
  392. result = readSLEB128(&p);
  393. break;
  394. case llvm::dwarf::DW_EH_PE_udata2:
  395. result = *((uint16_t*)p);
  396. p += sizeof(uint16_t);
  397. break;
  398. case llvm::dwarf::DW_EH_PE_udata4:
  399. result = *((uint32_t*)p);
  400. p += sizeof(uint32_t);
  401. break;
  402. case llvm::dwarf::DW_EH_PE_udata8:
  403. result = *((uint64_t*)p);
  404. p += sizeof(uint64_t);
  405. break;
  406. case llvm::dwarf::DW_EH_PE_sdata2:
  407. result = *((int16_t*)p);
  408. p += sizeof(int16_t);
  409. break;
  410. case llvm::dwarf::DW_EH_PE_sdata4:
  411. result = *((int32_t*)p);
  412. p += sizeof(int32_t);
  413. break;
  414. case llvm::dwarf::DW_EH_PE_sdata8:
  415. result = *((int64_t*)p);
  416. p += sizeof(int64_t);
  417. break;
  418. default:
  419. // not supported
  420. abort();
  421. break;
  422. }
  423. // then add relative offset
  424. switch (encoding & 0x70) {
  425. case llvm::dwarf::DW_EH_PE_absptr:
  426. // do nothing
  427. break;
  428. case llvm::dwarf::DW_EH_PE_pcrel:
  429. result += (uintptr_t)(*data);
  430. break;
  431. case llvm::dwarf::DW_EH_PE_textrel:
  432. case llvm::dwarf::DW_EH_PE_datarel:
  433. case llvm::dwarf::DW_EH_PE_funcrel:
  434. case llvm::dwarf::DW_EH_PE_aligned:
  435. default:
  436. // not supported
  437. abort();
  438. break;
  439. }
  440. // then apply indirection
  441. if (encoding & llvm::dwarf::DW_EH_PE_indirect) {
  442. result = *((uintptr_t*)result);
  443. }
  444. *data = p;
  445. return result;
  446. }
  447. /// Deals with Dwarf actions matching our type infos
  448. /// (OurExceptionType_t instances). Returns whether or not a dwarf emitted
  449. /// action matches the supplied exception type. If such a match succeeds,
  450. /// the resultAction argument will be set with > 0 index value. Only
  451. /// corresponding llvm.eh.selector type info arguments, cleanup arguments
  452. /// are supported. Filters are not supported.
  453. /// See Variable Length Data in:
  454. /// @link http://dwarfstd.org/Dwarf3.pdf @unlink
  455. /// Also see @link http://mentorembedded.github.com/cxx-abi/abi-eh.html @unlink
  456. /// @param resultAction reference variable which will be set with result
  457. /// @param classInfo our array of type info pointers (to globals)
  458. /// @param actionEntry index into above type info array or 0 (clean up).
  459. /// We do not support filters.
  460. /// @param exceptionClass exception class (_Unwind_Exception::exception_class)
  461. /// of thrown exception.
  462. /// @param exceptionObject thrown _Unwind_Exception instance.
  463. /// @returns whether or not a type info was found. False is returned if only
  464. /// a cleanup was found
  465. static bool handleActionValue(int64_t *resultAction,
  466. uint8_t TTypeEncoding,
  467. const uint8_t *ClassInfo,
  468. uintptr_t actionEntry,
  469. uint64_t exceptionClass,
  470. struct _Unwind_Exception *exceptionObject) {
  471. bool ret = false;
  472. if (!resultAction ||
  473. !exceptionObject ||
  474. (exceptionClass != ourBaseExceptionClass))
  475. return(ret);
  476. struct OurBaseException_t *excp = (struct OurBaseException_t*)
  477. (((char*) exceptionObject) + ourBaseFromUnwindOffset);
  478. struct OurExceptionType_t *excpType = &(excp->type);
  479. int type = excpType->type;
  480. #ifdef DEBUG
  481. fprintf(stderr,
  482. "handleActionValue(...): exceptionObject = <%p>, "
  483. "excp = <%p>.\n",
  484. exceptionObject,
  485. excp);
  486. #endif
  487. const uint8_t *actionPos = (uint8_t*) actionEntry,
  488. *tempActionPos;
  489. int64_t typeOffset = 0,
  490. actionOffset;
  491. for (int i = 0; true; ++i) {
  492. // Each emitted dwarf action corresponds to a 2 tuple of
  493. // type info address offset, and action offset to the next
  494. // emitted action.
  495. typeOffset = readSLEB128(&actionPos);
  496. tempActionPos = actionPos;
  497. actionOffset = readSLEB128(&tempActionPos);
  498. #ifdef DEBUG
  499. fprintf(stderr,
  500. "handleActionValue(...):typeOffset: <%lld>, "
  501. "actionOffset: <%lld>.\n",
  502. typeOffset,
  503. actionOffset);
  504. #endif
  505. assert((typeOffset >= 0) &&
  506. "handleActionValue(...):filters are not supported.");
  507. // Note: A typeOffset == 0 implies that a cleanup llvm.eh.selector
  508. // argument has been matched.
  509. if (typeOffset > 0) {
  510. #ifdef DEBUG
  511. fprintf(stderr,
  512. "handleActionValue(...):actionValue <%d> found.\n",
  513. i);
  514. #endif
  515. unsigned EncSize = getEncodingSize(TTypeEncoding);
  516. const uint8_t *EntryP = ClassInfo - typeOffset * EncSize;
  517. uintptr_t P = readEncodedPointer(&EntryP, TTypeEncoding);
  518. struct OurExceptionType_t *ThisClassInfo =
  519. reinterpret_cast<struct OurExceptionType_t *>(P);
  520. if (ThisClassInfo->type == type) {
  521. *resultAction = i + 1;
  522. ret = true;
  523. break;
  524. }
  525. }
  526. #ifdef DEBUG
  527. fprintf(stderr,
  528. "handleActionValue(...):actionValue not found.\n");
  529. #endif
  530. if (!actionOffset)
  531. break;
  532. actionPos += actionOffset;
  533. }
  534. return(ret);
  535. }
  536. /// Deals with the Language specific data portion of the emitted dwarf code.
  537. /// See @link http://mentorembedded.github.com/cxx-abi/abi-eh.html @unlink
  538. /// @param version unsupported (ignored), unwind version
  539. /// @param lsda language specific data area
  540. /// @param _Unwind_Action actions minimally supported unwind stage
  541. /// (forced specifically not supported)
  542. /// @param exceptionClass exception class (_Unwind_Exception::exception_class)
  543. /// of thrown exception.
  544. /// @param exceptionObject thrown _Unwind_Exception instance.
  545. /// @param context unwind system context
  546. /// @returns minimally supported unwinding control indicator
  547. static _Unwind_Reason_Code handleLsda(int version,
  548. const uint8_t *lsda,
  549. _Unwind_Action actions,
  550. uint64_t exceptionClass,
  551. struct _Unwind_Exception *exceptionObject,
  552. _Unwind_Context_t context) {
  553. _Unwind_Reason_Code ret = _URC_CONTINUE_UNWIND;
  554. if (!lsda)
  555. return(ret);
  556. #ifdef DEBUG
  557. fprintf(stderr,
  558. "handleLsda(...):lsda is non-zero.\n");
  559. #endif
  560. // Get the current instruction pointer and offset it before next
  561. // instruction in the current frame which threw the exception.
  562. uintptr_t pc = _Unwind_GetIP(context)-1;
  563. // Get beginning current frame's code (as defined by the
  564. // emitted dwarf code)
  565. uintptr_t funcStart = _Unwind_GetRegionStart(context);
  566. uintptr_t pcOffset = pc - funcStart;
  567. const uint8_t *ClassInfo = NULL;
  568. // Note: See JITDwarfEmitter::EmitExceptionTable(...) for corresponding
  569. // dwarf emission
  570. // Parse LSDA header.
  571. uint8_t lpStartEncoding = *lsda++;
  572. if (lpStartEncoding != llvm::dwarf::DW_EH_PE_omit) {
  573. readEncodedPointer(&lsda, lpStartEncoding);
  574. }
  575. uint8_t ttypeEncoding = *lsda++;
  576. uintptr_t classInfoOffset;
  577. if (ttypeEncoding != llvm::dwarf::DW_EH_PE_omit) {
  578. // Calculate type info locations in emitted dwarf code which
  579. // were flagged by type info arguments to llvm.eh.selector
  580. // intrinsic
  581. classInfoOffset = readULEB128(&lsda);
  582. ClassInfo = lsda + classInfoOffset;
  583. }
  584. // Walk call-site table looking for range that
  585. // includes current PC.
  586. uint8_t callSiteEncoding = *lsda++;
  587. uint32_t callSiteTableLength = readULEB128(&lsda);
  588. const uint8_t *callSiteTableStart = lsda;
  589. const uint8_t *callSiteTableEnd = callSiteTableStart +
  590. callSiteTableLength;
  591. const uint8_t *actionTableStart = callSiteTableEnd;
  592. const uint8_t *callSitePtr = callSiteTableStart;
  593. while (callSitePtr < callSiteTableEnd) {
  594. uintptr_t start = readEncodedPointer(&callSitePtr,
  595. callSiteEncoding);
  596. uintptr_t length = readEncodedPointer(&callSitePtr,
  597. callSiteEncoding);
  598. uintptr_t landingPad = readEncodedPointer(&callSitePtr,
  599. callSiteEncoding);
  600. // Note: Action value
  601. uintptr_t actionEntry = readULEB128(&callSitePtr);
  602. if (exceptionClass != ourBaseExceptionClass) {
  603. // We have been notified of a foreign exception being thrown,
  604. // and we therefore need to execute cleanup landing pads
  605. actionEntry = 0;
  606. }
  607. if (landingPad == 0) {
  608. #ifdef DEBUG
  609. fprintf(stderr,
  610. "handleLsda(...): No landing pad found.\n");
  611. #endif
  612. continue; // no landing pad for this entry
  613. }
  614. if (actionEntry) {
  615. actionEntry += ((uintptr_t) actionTableStart) - 1;
  616. }
  617. else {
  618. #ifdef DEBUG
  619. fprintf(stderr,
  620. "handleLsda(...):No action table found.\n");
  621. #endif
  622. }
  623. bool exceptionMatched = false;
  624. if ((start <= pcOffset) && (pcOffset < (start + length))) {
  625. #ifdef DEBUG
  626. fprintf(stderr,
  627. "handleLsda(...): Landing pad found.\n");
  628. #endif
  629. int64_t actionValue = 0;
  630. if (actionEntry) {
  631. exceptionMatched = handleActionValue(&actionValue,
  632. ttypeEncoding,
  633. ClassInfo,
  634. actionEntry,
  635. exceptionClass,
  636. exceptionObject);
  637. }
  638. if (!(actions & _UA_SEARCH_PHASE)) {
  639. #ifdef DEBUG
  640. fprintf(stderr,
  641. "handleLsda(...): installed landing pad "
  642. "context.\n");
  643. #endif
  644. // Found landing pad for the PC.
  645. // Set Instruction Pointer to so we re-enter function
  646. // at landing pad. The landing pad is created by the
  647. // compiler to take two parameters in registers.
  648. _Unwind_SetGR(context,
  649. __builtin_eh_return_data_regno(0),
  650. (uintptr_t)exceptionObject);
  651. // Note: this virtual register directly corresponds
  652. // to the return of the llvm.eh.selector intrinsic
  653. if (!actionEntry || !exceptionMatched) {
  654. // We indicate cleanup only
  655. _Unwind_SetGR(context,
  656. __builtin_eh_return_data_regno(1),
  657. 0);
  658. }
  659. else {
  660. // Matched type info index of llvm.eh.selector intrinsic
  661. // passed here.
  662. _Unwind_SetGR(context,
  663. __builtin_eh_return_data_regno(1),
  664. actionValue);
  665. }
  666. // To execute landing pad set here
  667. _Unwind_SetIP(context, funcStart + landingPad);
  668. ret = _URC_INSTALL_CONTEXT;
  669. }
  670. else if (exceptionMatched) {
  671. #ifdef DEBUG
  672. fprintf(stderr,
  673. "handleLsda(...): setting handler found.\n");
  674. #endif
  675. ret = _URC_HANDLER_FOUND;
  676. }
  677. else {
  678. // Note: Only non-clean up handlers are marked as
  679. // found. Otherwise the clean up handlers will be
  680. // re-found and executed during the clean up
  681. // phase.
  682. #ifdef DEBUG
  683. fprintf(stderr,
  684. "handleLsda(...): cleanup handler found.\n");
  685. #endif
  686. }
  687. break;
  688. }
  689. }
  690. return(ret);
  691. }
  692. /// This is the personality function which is embedded (dwarf emitted), in the
  693. /// dwarf unwind info block. Again see: JITDwarfEmitter.cpp.
  694. /// See @link http://mentorembedded.github.com/cxx-abi/abi-eh.html @unlink
  695. /// @param version unsupported (ignored), unwind version
  696. /// @param _Unwind_Action actions minimally supported unwind stage
  697. /// (forced specifically not supported)
  698. /// @param exceptionClass exception class (_Unwind_Exception::exception_class)
  699. /// of thrown exception.
  700. /// @param exceptionObject thrown _Unwind_Exception instance.
  701. /// @param context unwind system context
  702. /// @returns minimally supported unwinding control indicator
  703. _Unwind_Reason_Code ourPersonality(int version,
  704. _Unwind_Action actions,
  705. uint64_t exceptionClass,
  706. struct _Unwind_Exception *exceptionObject,
  707. _Unwind_Context_t context) {
  708. #ifdef DEBUG
  709. fprintf(stderr,
  710. "We are in ourPersonality(...):actions is <%d>.\n",
  711. actions);
  712. if (actions & _UA_SEARCH_PHASE) {
  713. fprintf(stderr, "ourPersonality(...):In search phase.\n");
  714. }
  715. else {
  716. fprintf(stderr, "ourPersonality(...):In non-search phase.\n");
  717. }
  718. #endif
  719. const uint8_t *lsda = _Unwind_GetLanguageSpecificData(context);
  720. #ifdef DEBUG
  721. fprintf(stderr,
  722. "ourPersonality(...):lsda = <%p>.\n",
  723. lsda);
  724. #endif
  725. // The real work of the personality function is captured here
  726. return(handleLsda(version,
  727. lsda,
  728. actions,
  729. exceptionClass,
  730. exceptionObject,
  731. context));
  732. }
  733. /// Generates our _Unwind_Exception class from a given character array.
  734. /// thereby handling arbitrary lengths (not in standard), and handling
  735. /// embedded \0s.
  736. /// See @link http://mentorembedded.github.com/cxx-abi/abi-eh.html @unlink
  737. /// @param classChars char array to encode. NULL values not checkedf
  738. /// @param classCharsSize number of chars in classChars. Value is not checked.
  739. /// @returns class value
  740. uint64_t genClass(const unsigned char classChars[], size_t classCharsSize)
  741. {
  742. uint64_t ret = classChars[0];
  743. for (unsigned i = 1; i < classCharsSize; ++i) {
  744. ret <<= 8;
  745. ret += classChars[i];
  746. }
  747. return(ret);
  748. }
  749. } // extern "C"
  750. //
  751. // Runtime C Library functions End
  752. //
  753. //
  754. // Code generation functions
  755. //
  756. /// Generates code to print given constant string
  757. /// @param context llvm context
  758. /// @param module code for module instance
  759. /// @param builder builder instance
  760. /// @param toPrint string to print
  761. /// @param useGlobal A value of true (default) indicates a GlobalValue is
  762. /// generated, and is used to hold the constant string. A value of
  763. /// false indicates that the constant string will be stored on the
  764. /// stack.
  765. void generateStringPrint(llvm::LLVMContext &context,
  766. llvm::Module &module,
  767. llvm::IRBuilder<> &builder,
  768. std::string toPrint,
  769. bool useGlobal = true) {
  770. llvm::Function *printFunct = module.getFunction("printStr");
  771. llvm::Value *stringVar;
  772. llvm::Constant *stringConstant =
  773. llvm::ConstantDataArray::getString(context, toPrint);
  774. if (useGlobal) {
  775. // Note: Does not work without allocation
  776. stringVar =
  777. new llvm::GlobalVariable(module,
  778. stringConstant->getType(),
  779. true,
  780. llvm::GlobalValue::PrivateLinkage,
  781. stringConstant,
  782. "");
  783. }
  784. else {
  785. stringVar = builder.CreateAlloca(stringConstant->getType());
  786. builder.CreateStore(stringConstant, stringVar);
  787. }
  788. llvm::Value *cast = builder.CreatePointerCast(stringVar,
  789. builder.getInt8PtrTy());
  790. builder.CreateCall(printFunct, cast);
  791. }
  792. /// Generates code to print given runtime integer according to constant
  793. /// string format, and a given print function.
  794. /// @param context llvm context
  795. /// @param module code for module instance
  796. /// @param builder builder instance
  797. /// @param printFunct function used to "print" integer
  798. /// @param toPrint string to print
  799. /// @param format printf like formating string for print
  800. /// @param useGlobal A value of true (default) indicates a GlobalValue is
  801. /// generated, and is used to hold the constant string. A value of
  802. /// false indicates that the constant string will be stored on the
  803. /// stack.
  804. void generateIntegerPrint(llvm::LLVMContext &context,
  805. llvm::Module &module,
  806. llvm::IRBuilder<> &builder,
  807. llvm::Function &printFunct,
  808. llvm::Value &toPrint,
  809. std::string format,
  810. bool useGlobal = true) {
  811. llvm::Constant *stringConstant =
  812. llvm::ConstantDataArray::getString(context, format);
  813. llvm::Value *stringVar;
  814. if (useGlobal) {
  815. // Note: Does not seem to work without allocation
  816. stringVar =
  817. new llvm::GlobalVariable(module,
  818. stringConstant->getType(),
  819. true,
  820. llvm::GlobalValue::PrivateLinkage,
  821. stringConstant,
  822. "");
  823. }
  824. else {
  825. stringVar = builder.CreateAlloca(stringConstant->getType());
  826. builder.CreateStore(stringConstant, stringVar);
  827. }
  828. llvm::Value *cast = builder.CreateBitCast(stringVar,
  829. builder.getInt8PtrTy());
  830. builder.CreateCall2(&printFunct, &toPrint, cast);
  831. }
  832. /// Generates code to handle finally block type semantics: always runs
  833. /// regardless of whether a thrown exception is passing through or the
  834. /// parent function is simply exiting. In addition to printing some state
  835. /// to stderr, this code will resume the exception handling--runs the
  836. /// unwind resume block, if the exception has not been previously caught
  837. /// by a catch clause, and will otherwise execute the end block (terminator
  838. /// block). In addition this function creates the corresponding function's
  839. /// stack storage for the exception pointer and catch flag status.
  840. /// @param context llvm context
  841. /// @param module code for module instance
  842. /// @param builder builder instance
  843. /// @param toAddTo parent function to add block to
  844. /// @param blockName block name of new "finally" block.
  845. /// @param functionId output id used for printing
  846. /// @param terminatorBlock terminator "end" block
  847. /// @param unwindResumeBlock unwind resume block
  848. /// @param exceptionCaughtFlag reference exception caught/thrown status storage
  849. /// @param exceptionStorage reference to exception pointer storage
  850. /// @param caughtResultStorage reference to landingpad result storage
  851. /// @returns newly created block
  852. static llvm::BasicBlock *createFinallyBlock(llvm::LLVMContext &context,
  853. llvm::Module &module,
  854. llvm::IRBuilder<> &builder,
  855. llvm::Function &toAddTo,
  856. std::string &blockName,
  857. std::string &functionId,
  858. llvm::BasicBlock &terminatorBlock,
  859. llvm::BasicBlock &unwindResumeBlock,
  860. llvm::Value **exceptionCaughtFlag,
  861. llvm::Value **exceptionStorage,
  862. llvm::Value **caughtResultStorage) {
  863. assert(exceptionCaughtFlag &&
  864. "ExceptionDemo::createFinallyBlock(...):exceptionCaughtFlag "
  865. "is NULL");
  866. assert(exceptionStorage &&
  867. "ExceptionDemo::createFinallyBlock(...):exceptionStorage "
  868. "is NULL");
  869. assert(caughtResultStorage &&
  870. "ExceptionDemo::createFinallyBlock(...):caughtResultStorage "
  871. "is NULL");
  872. *exceptionCaughtFlag = createEntryBlockAlloca(toAddTo,
  873. "exceptionCaught",
  874. ourExceptionNotThrownState->getType(),
  875. ourExceptionNotThrownState);
  876. llvm::PointerType *exceptionStorageType = builder.getInt8PtrTy();
  877. *exceptionStorage = createEntryBlockAlloca(toAddTo,
  878. "exceptionStorage",
  879. exceptionStorageType,
  880. llvm::ConstantPointerNull::get(
  881. exceptionStorageType));
  882. *caughtResultStorage = createEntryBlockAlloca(toAddTo,
  883. "caughtResultStorage",
  884. ourCaughtResultType,
  885. llvm::ConstantAggregateZero::get(
  886. ourCaughtResultType));
  887. llvm::BasicBlock *ret = llvm::BasicBlock::Create(context,
  888. blockName,
  889. &toAddTo);
  890. builder.SetInsertPoint(ret);
  891. std::ostringstream bufferToPrint;
  892. bufferToPrint << "Gen: Executing finally block "
  893. << blockName << " in " << functionId << "\n";
  894. generateStringPrint(context,
  895. module,
  896. builder,
  897. bufferToPrint.str(),
  898. USE_GLOBAL_STR_CONSTS);
  899. llvm::SwitchInst *theSwitch = builder.CreateSwitch(builder.CreateLoad(
  900. *exceptionCaughtFlag),
  901. &terminatorBlock,
  902. 2);
  903. theSwitch->addCase(ourExceptionCaughtState, &terminatorBlock);
  904. theSwitch->addCase(ourExceptionThrownState, &unwindResumeBlock);
  905. return(ret);
  906. }
  907. /// Generates catch block semantics which print a string to indicate type of
  908. /// catch executed, sets an exception caught flag, and executes passed in
  909. /// end block (terminator block).
  910. /// @param context llvm context
  911. /// @param module code for module instance
  912. /// @param builder builder instance
  913. /// @param toAddTo parent function to add block to
  914. /// @param blockName block name of new "catch" block.
  915. /// @param functionId output id used for printing
  916. /// @param terminatorBlock terminator "end" block
  917. /// @param exceptionCaughtFlag exception caught/thrown status
  918. /// @returns newly created block
  919. static llvm::BasicBlock *createCatchBlock(llvm::LLVMContext &context,
  920. llvm::Module &module,
  921. llvm::IRBuilder<> &builder,
  922. llvm::Function &toAddTo,
  923. std::string &blockName,
  924. std::string &functionId,
  925. llvm::BasicBlock &terminatorBlock,
  926. llvm::Value &exceptionCaughtFlag) {
  927. llvm::BasicBlock *ret = llvm::BasicBlock::Create(context,
  928. blockName,
  929. &toAddTo);
  930. builder.SetInsertPoint(ret);
  931. std::ostringstream bufferToPrint;
  932. bufferToPrint << "Gen: Executing catch block "
  933. << blockName
  934. << " in "
  935. << functionId
  936. << std::endl;
  937. generateStringPrint(context,
  938. module,
  939. builder,
  940. bufferToPrint.str(),
  941. USE_GLOBAL_STR_CONSTS);
  942. builder.CreateStore(ourExceptionCaughtState, &exceptionCaughtFlag);
  943. builder.CreateBr(&terminatorBlock);
  944. return(ret);
  945. }
  946. /// Generates a function which invokes a function (toInvoke) and, whose
  947. /// unwind block will "catch" the type info types correspondingly held in the
  948. /// exceptionTypesToCatch argument. If the toInvoke function throws an
  949. /// exception which does not match any type info types contained in
  950. /// exceptionTypesToCatch, the generated code will call _Unwind_Resume
  951. /// with the raised exception. On the other hand the generated code will
  952. /// normally exit if the toInvoke function does not throw an exception.
  953. /// The generated "finally" block is always run regardless of the cause of
  954. /// the generated function exit.
  955. /// The generated function is returned after being verified.
  956. /// @param module code for module instance
  957. /// @param builder builder instance
  958. /// @param fpm a function pass manager holding optional IR to IR
  959. /// transformations
  960. /// @param toInvoke inner function to invoke
  961. /// @param ourId id used to printing purposes
  962. /// @param numExceptionsToCatch length of exceptionTypesToCatch array
  963. /// @param exceptionTypesToCatch array of type info types to "catch"
  964. /// @returns generated function
  965. static
  966. llvm::Function *createCatchWrappedInvokeFunction(llvm::Module &module,
  967. llvm::IRBuilder<> &builder,
  968. llvm::FunctionPassManager &fpm,
  969. llvm::Function &toInvoke,
  970. std::string ourId,
  971. unsigned numExceptionsToCatch,
  972. unsigned exceptionTypesToCatch[]) {
  973. llvm::LLVMContext &context = module.getContext();
  974. llvm::Function *toPrint32Int = module.getFunction("print32Int");
  975. ArgTypes argTypes;
  976. argTypes.push_back(builder.getInt32Ty());
  977. ArgNames argNames;
  978. argNames.push_back("exceptTypeToThrow");
  979. llvm::Function *ret = createFunction(module,
  980. builder.getVoidTy(),
  981. argTypes,
  982. argNames,
  983. ourId,
  984. llvm::Function::ExternalLinkage,
  985. false,
  986. false);
  987. // Block which calls invoke
  988. llvm::BasicBlock *entryBlock = llvm::BasicBlock::Create(context,
  989. "entry",
  990. ret);
  991. // Normal block for invoke
  992. llvm::BasicBlock *normalBlock = llvm::BasicBlock::Create(context,
  993. "normal",
  994. ret);
  995. // Unwind block for invoke
  996. llvm::BasicBlock *exceptionBlock = llvm::BasicBlock::Create(context,
  997. "exception",
  998. ret);
  999. // Block which routes exception to correct catch handler block
  1000. llvm::BasicBlock *exceptionRouteBlock = llvm::BasicBlock::Create(context,
  1001. "exceptionRoute",
  1002. ret);
  1003. // Foreign exception handler
  1004. llvm::BasicBlock *externalExceptionBlock = llvm::BasicBlock::Create(context,
  1005. "externalException",
  1006. ret);
  1007. // Block which calls _Unwind_Resume
  1008. llvm::BasicBlock *unwindResumeBlock = llvm::BasicBlock::Create(context,
  1009. "unwindResume",
  1010. ret);
  1011. // Clean up block which delete exception if needed
  1012. llvm::BasicBlock *endBlock = llvm::BasicBlock::Create(context, "end", ret);
  1013. std::string nextName;
  1014. std::vector<llvm::BasicBlock*> catchBlocks(numExceptionsToCatch);
  1015. llvm::Value *exceptionCaughtFlag = NULL;
  1016. llvm::Value *exceptionStorage = NULL;
  1017. llvm::Value *caughtResultStorage = NULL;
  1018. // Finally block which will branch to unwindResumeBlock if
  1019. // exception is not caught. Initializes/allocates stack locations.
  1020. llvm::BasicBlock *finallyBlock = createFinallyBlock(context,
  1021. module,
  1022. builder,
  1023. *ret,
  1024. nextName = "finally",
  1025. ourId,
  1026. *endBlock,
  1027. *unwindResumeBlock,
  1028. &exceptionCaughtFlag,
  1029. &exceptionStorage,
  1030. &caughtResultStorage
  1031. );
  1032. for (unsigned i = 0; i < numExceptionsToCatch; ++i) {
  1033. nextName = ourTypeInfoNames[exceptionTypesToCatch[i]];
  1034. // One catch block per type info to be caught
  1035. catchBlocks[i] = createCatchBlock(context,
  1036. module,
  1037. builder,
  1038. *ret,
  1039. nextName,
  1040. ourId,
  1041. *finallyBlock,
  1042. *exceptionCaughtFlag);
  1043. }
  1044. // Entry Block
  1045. builder.SetInsertPoint(entryBlock);
  1046. std::vector<llvm::Value*> args;
  1047. args.push_back(namedValues["exceptTypeToThrow"]);
  1048. builder.CreateInvoke(&toInvoke,
  1049. normalBlock,
  1050. exceptionBlock,
  1051. args);
  1052. // End Block
  1053. builder.SetInsertPoint(endBlock);
  1054. generateStringPrint(context,
  1055. module,
  1056. builder,
  1057. "Gen: In end block: exiting in " + ourId + ".\n",
  1058. USE_GLOBAL_STR_CONSTS);
  1059. llvm::Function *deleteOurException = module.getFunction("deleteOurException");
  1060. // Note: function handles NULL exceptions
  1061. builder.CreateCall(deleteOurException,
  1062. builder.CreateLoad(exceptionStorage));
  1063. builder.CreateRetVoid();
  1064. // Normal Block
  1065. builder.SetInsertPoint(normalBlock);
  1066. generateStringPrint(context,
  1067. module,
  1068. builder,
  1069. "Gen: No exception in " + ourId + "!\n",
  1070. USE_GLOBAL_STR_CONSTS);
  1071. // Finally block is always called
  1072. builder.CreateBr(finallyBlock);
  1073. // Unwind Resume Block
  1074. builder.SetInsertPoint(unwindResumeBlock);
  1075. builder.CreateResume(builder.CreateLoad(caughtResultStorage));
  1076. // Exception Block
  1077. builder.SetInsertPoint(exceptionBlock);
  1078. llvm::Function *personality = module.getFunction("ourPersonality");
  1079. llvm::LandingPadInst *caughtResult =
  1080. builder.CreateLandingPad(ourCaughtResultType,
  1081. personality,
  1082. numExceptionsToCatch,
  1083. "landingPad");
  1084. caughtResult->setCleanup(true);
  1085. for (unsigned i = 0; i < numExceptionsToCatch; ++i) {
  1086. // Set up type infos to be caught
  1087. caughtResult->addClause(module.getGlobalVariable(
  1088. ourTypeInfoNames[exceptionTypesToCatch[i]]));
  1089. }
  1090. llvm::Value *unwindException = builder.CreateExtractValue(caughtResult, 0);
  1091. llvm::Value *retTypeInfoIndex = builder.CreateExtractValue(caughtResult, 1);
  1092. // FIXME: Redundant storage which, beyond utilizing value of
  1093. // caughtResultStore for unwindException storage, may be alleviated
  1094. // altogether with a block rearrangement
  1095. builder.CreateStore(caughtResult, caughtResultStorage);
  1096. builder.CreateStore(unwindException, exceptionStorage);
  1097. builder.CreateStore(ourExceptionThrownState, exceptionCaughtFlag);
  1098. // Retrieve exception_class member from thrown exception
  1099. // (_Unwind_Exception instance). This member tells us whether or not
  1100. // the exception is foreign.
  1101. llvm::Value *unwindExceptionClass =
  1102. builder.CreateLoad(builder.CreateStructGEP(
  1103. builder.CreatePointerCast(unwindException,
  1104. ourUnwindExceptionType->getPointerTo()),
  1105. 0));
  1106. // Branch to the externalExceptionBlock if the exception is foreign or
  1107. // to a catch router if not. Either way the finally block will be run.
  1108. builder.CreateCondBr(builder.CreateICmpEQ(unwindExceptionClass,
  1109. llvm::ConstantInt::get(builder.getInt64Ty(),
  1110. ourBaseExceptionClass)),
  1111. exceptionRouteBlock,
  1112. externalExceptionBlock);
  1113. // External Exception Block
  1114. builder.SetInsertPoint(externalExceptionBlock);
  1115. generateStringPrint(context,
  1116. module,
  1117. builder,
  1118. "Gen: Foreign exception received.\n",
  1119. USE_GLOBAL_STR_CONSTS);
  1120. // Branch to the finally block
  1121. builder.CreateBr(finallyBlock);
  1122. // Exception Route Block
  1123. builder.SetInsertPoint(exceptionRouteBlock);
  1124. // Casts exception pointer (_Unwind_Exception instance) to parent
  1125. // (OurException instance).
  1126. //
  1127. // Note: ourBaseFromUnwindOffset is usually negative
  1128. llvm::Value *typeInfoThrown = builder.CreatePointerCast(
  1129. builder.CreateConstGEP1_64(unwindException,
  1130. ourBaseFromUnwindOffset),
  1131. ourExceptionType->getPointerTo());
  1132. // Retrieve thrown exception type info type
  1133. //
  1134. // Note: Index is not relative to pointer but instead to structure
  1135. // unlike a true getelementptr (GEP) instruction
  1136. typeInfoThrown = builder.CreateStructGEP(typeInfoThrown, 0);
  1137. llvm::Value *typeInfoThrownType =
  1138. builder.CreateStructGEP(typeInfoThrown, 0);
  1139. generateIntegerPrint(context,
  1140. module,
  1141. builder,
  1142. *toPrint32Int,
  1143. *(builder.CreateLoad(typeInfoThrownType)),
  1144. "Gen: Exception type <%d> received (stack unwound) "
  1145. " in " +
  1146. ourId +
  1147. ".\n",
  1148. USE_GLOBAL_STR_CONSTS);
  1149. // Route to matched type info catch block or run cleanup finally block
  1150. llvm::SwitchInst *switchToCatchBlock = builder.CreateSwitch(retTypeInfoIndex,
  1151. finallyBlock,
  1152. numExceptionsToCatch);
  1153. unsigned nextTypeToCatch;
  1154. for (unsigned i = 1; i <= numExceptionsToCatch; ++i) {
  1155. nextTypeToCatch = i - 1;
  1156. switchToCatchBlock->addCase(llvm::ConstantInt::get(
  1157. llvm::Type::getInt32Ty(context), i),
  1158. catchBlocks[nextTypeToCatch]);
  1159. }
  1160. llvm::verifyFunction(*ret);
  1161. fpm.run(*ret);
  1162. return(ret);
  1163. }
  1164. /// Generates function which throws either an exception matched to a runtime
  1165. /// determined type info type (argument to generated function), or if this
  1166. /// runtime value matches nativeThrowType, throws a foreign exception by
  1167. /// calling nativeThrowFunct.
  1168. /// @param module code for module instance
  1169. /// @param builder builder instance
  1170. /// @param fpm a function pass manager holding optional IR to IR
  1171. /// transformations
  1172. /// @param ourId id used to printing purposes
  1173. /// @param nativeThrowType a runtime argument of this value results in
  1174. /// nativeThrowFunct being called to generate/throw exception.
  1175. /// @param nativeThrowFunct function which will throw a foreign exception
  1176. /// if the above nativeThrowType matches generated function's arg.
  1177. /// @returns generated function
  1178. static
  1179. llvm::Function *createThrowExceptionFunction(llvm::Module &module,
  1180. llvm::IRBuilder<> &builder,
  1181. llvm::FunctionPassManager &fpm,
  1182. std::string ourId,
  1183. int32_t nativeThrowType,
  1184. llvm::Function &nativeThrowFunct) {
  1185. llvm::LLVMContext &context = module.getContext();
  1186. namedValues.clear();
  1187. ArgTypes unwindArgTypes;
  1188. unwindArgTypes.push_back(builder.getInt32Ty());
  1189. ArgNames unwindArgNames;
  1190. unwindArgNames.push_back("exceptTypeToThrow");
  1191. llvm::Function *ret = createFunction(module,
  1192. builder.getVoidTy(),
  1193. unwindArgTypes,
  1194. unwindArgNames,
  1195. ourId,
  1196. llvm::Function::ExternalLinkage,
  1197. false,
  1198. false);
  1199. // Throws either one of our exception or a native C++ exception depending
  1200. // on a runtime argument value containing a type info type.
  1201. llvm::BasicBlock *entryBlock = llvm::BasicBlock::Create(context,
  1202. "entry",
  1203. ret);
  1204. // Throws a foreign exception
  1205. llvm::BasicBlock *nativeThrowBlock = llvm::BasicBlock::Create(context,
  1206. "nativeThrow",
  1207. ret);
  1208. // Throws one of our Exceptions
  1209. llvm::BasicBlock *generatedThrowBlock = llvm::BasicBlock::Create(context,
  1210. "generatedThrow",
  1211. ret);
  1212. // Retrieved runtime type info type to throw
  1213. llvm::Value *exceptionType = namedValues["exceptTypeToThrow"];
  1214. // nativeThrowBlock block
  1215. builder.SetInsertPoint(nativeThrowBlock);
  1216. // Throws foreign exception
  1217. builder.CreateCall(&nativeThrowFunct, exceptionType);
  1218. builder.CreateUnreachable();
  1219. // entry block
  1220. builder.SetInsertPoint(entryBlock);
  1221. llvm::Function *toPrint32Int = module.getFunction("print32Int");
  1222. generateIntegerPrint(context,
  1223. module,
  1224. builder,
  1225. *toPrint32Int,
  1226. *exceptionType,
  1227. "\nGen: About to throw exception type <%d> in " +
  1228. ourId +
  1229. ".\n",
  1230. USE_GLOBAL_STR_CONSTS);
  1231. // Switches on runtime type info type value to determine whether or not
  1232. // a foreign exception is thrown. Defaults to throwing one of our
  1233. // generated exceptions.
  1234. llvm::SwitchInst *theSwitch = builder.CreateSwitch(exceptionType,
  1235. generatedThrowBlock,
  1236. 1);
  1237. theSwitch->addCase(llvm::ConstantInt::get(llvm::Type::getInt32Ty(context),
  1238. nativeThrowType),
  1239. nativeThrowBlock);
  1240. // generatedThrow block
  1241. builder.SetInsertPoint(generatedThrowBlock);
  1242. llvm::Function *createOurException = module.getFunction("createOurException");
  1243. llvm::Function *raiseOurException = module.getFunction(
  1244. "_Unwind_RaiseException");
  1245. // Creates exception to throw with runtime type info type.
  1246. llvm::Value *exception = builder.CreateCall(createOurException,
  1247. namedValues["exceptTypeToThrow"]);
  1248. // Throw generated Exception
  1249. builder.CreateCall(raiseOurException, exception);
  1250. builder.CreateUnreachable();
  1251. llvm::verifyFunction(*ret);
  1252. fpm.run(*ret);
  1253. return(ret);
  1254. }
  1255. static void createStandardUtilityFunctions(unsigned numTypeInfos,
  1256. llvm::Module &module,
  1257. llvm::IRBuilder<> &builder);
  1258. /// Creates test code by generating and organizing these functions into the
  1259. /// test case. The test case consists of an outer function setup to invoke
  1260. /// an inner function within an environment having multiple catch and single
  1261. /// finally blocks. This inner function is also setup to invoke a throw
  1262. /// function within an evironment similar in nature to the outer function's
  1263. /// catch and finally blocks. Each of these two functions catch mutually
  1264. /// exclusive subsets (even or odd) of the type info types configured
  1265. /// for this this. All generated functions have a runtime argument which
  1266. /// holds a type info type to throw that each function takes and passes it
  1267. /// to the inner one if such a inner function exists. This type info type is
  1268. /// looked at by the generated throw function to see whether or not it should
  1269. /// throw a generated exception with the same type info type, or instead call
  1270. /// a supplied a function which in turn will throw a foreign exception.
  1271. /// @param module code for module instance
  1272. /// @param builder builder instance
  1273. /// @param fpm a function pass manager holding optional IR to IR
  1274. /// transformations
  1275. /// @param nativeThrowFunctName name of external function which will throw
  1276. /// a foreign exception
  1277. /// @returns outermost generated test function.
  1278. llvm::Function *createUnwindExceptionTest(llvm::Module &module,
  1279. llvm::IRBuilder<> &builder,
  1280. llvm::FunctionPassManager &fpm,
  1281. std::string nativeThrowFunctName) {
  1282. // Number of type infos to generate
  1283. unsigned numTypeInfos = 6;
  1284. // Initialze intrisics and external functions to use along with exception
  1285. // and type info globals.
  1286. createStandardUtilityFunctions(numTypeInfos,
  1287. module,
  1288. builder);
  1289. llvm::Function *nativeThrowFunct = module.getFunction(nativeThrowFunctName);
  1290. // Create exception throw function using the value ~0 to cause
  1291. // foreign exceptions to be thrown.
  1292. llvm::Function *throwFunct = createThrowExceptionFunction(module,
  1293. builder,
  1294. fpm,
  1295. "throwFunct",
  1296. ~0,
  1297. *nativeThrowFunct);
  1298. // Inner function will catch even type infos
  1299. unsigned innerExceptionTypesToCatch[] = {6, 2, 4};
  1300. size_t numExceptionTypesToCatch = sizeof(innerExceptionTypesToCatch) /
  1301. sizeof(unsigned);
  1302. // Generate inner function.
  1303. llvm::Function *innerCatchFunct = createCatchWrappedInvokeFunction(module,
  1304. builder,
  1305. fpm,
  1306. *throwFunct,
  1307. "innerCatchFunct",
  1308. numExceptionTypesToCatch,
  1309. innerExceptionTypesToCatch);
  1310. // Outer function will catch odd type infos
  1311. unsigned outerExceptionTypesToCatch[] = {3, 1, 5};
  1312. numExceptionTypesToCatch = sizeof(outerExceptionTypesToCatch) /
  1313. sizeof(unsigned);
  1314. // Generate outer function
  1315. llvm::Function *outerCatchFunct = createCatchWrappedInvokeFunction(module,
  1316. builder,
  1317. fpm,
  1318. *innerCatchFunct,
  1319. "outerCatchFunct",
  1320. numExceptionTypesToCatch,
  1321. outerExceptionTypesToCatch);
  1322. // Return outer function to run
  1323. return(outerCatchFunct);
  1324. }
  1325. namespace {
  1326. /// Represents our foreign exceptions
  1327. class OurCppRunException : public std::runtime_error {
  1328. public:
  1329. OurCppRunException(const std::string reason) :
  1330. std::runtime_error(reason) {}
  1331. OurCppRunException (const OurCppRunException &toCopy) :
  1332. std::runtime_error(toCopy) {}
  1333. OurCppRunException &operator = (const OurCppRunException &toCopy) {
  1334. return(reinterpret_cast<OurCppRunException&>(
  1335. std::runtime_error::operator=(toCopy)));
  1336. }
  1337. virtual ~OurCppRunException (void) throw () {}
  1338. };
  1339. } // end anonymous namespace
  1340. /// Throws foreign C++ exception.
  1341. /// @param ignoreIt unused parameter that allows function to match implied
  1342. /// generated function contract.
  1343. extern "C"
  1344. void throwCppException (int32_t ignoreIt) {
  1345. throw(OurCppRunException("thrown by throwCppException(...)"));
  1346. }
  1347. typedef void (*OurExceptionThrowFunctType) (int32_t typeToThrow);
  1348. /// This is a test harness which runs test by executing generated
  1349. /// function with a type info type to throw. Harness wraps the execution
  1350. /// of generated function in a C++ try catch clause.
  1351. /// @param engine execution engine to use for executing generated function.
  1352. /// This demo program expects this to be a JIT instance for demo
  1353. /// purposes.
  1354. /// @param function generated test function to run
  1355. /// @param typeToThrow type info type of generated exception to throw, or
  1356. /// indicator to cause foreign exception to be thrown.
  1357. static
  1358. void runExceptionThrow(llvm::ExecutionEngine *engine,
  1359. llvm::Function *function,
  1360. int32_t typeToThrow) {
  1361. // Find test's function pointer
  1362. OurExceptionThrowFunctType functPtr =
  1363. reinterpret_cast<OurExceptionThrowFunctType>(
  1364. reinterpret_cast<intptr_t>(engine->getPointerToFunction(function)));
  1365. try {
  1366. // Run test
  1367. (*functPtr)(typeToThrow);
  1368. }
  1369. catch (OurCppRunException exc) {
  1370. // Catch foreign C++ exception
  1371. fprintf(stderr,
  1372. "\nrunExceptionThrow(...):In C++ catch OurCppRunException "
  1373. "with reason: %s.\n",
  1374. exc.what());
  1375. }
  1376. catch (...) {
  1377. // Catch all exceptions including our generated ones. This latter
  1378. // functionality works according to the example in rules 1.6.4 of
  1379. // http://mentorembedded.github.com/cxx-abi/abi-eh.html (v1.22),
  1380. // given that these will be exceptions foreign to C++
  1381. // (the _Unwind_Exception::exception_class should be different from
  1382. // the one used by C++).
  1383. fprintf(stderr,
  1384. "\nrunExceptionThrow(...):In C++ catch all.\n");
  1385. }
  1386. }
  1387. //
  1388. // End test functions
  1389. //
  1390. typedef llvm::ArrayRef<llvm::Type*> TypeArray;
  1391. /// This initialization routine creates type info globals and
  1392. /// adds external function declarations to module.
  1393. /// @param numTypeInfos number of linear type info associated type info types
  1394. /// to create as GlobalVariable instances, starting with the value 1.
  1395. /// @param module code for module instance
  1396. /// @param builder builder instance
  1397. static void createStandardUtilityFunctions(unsigned numTypeInfos,
  1398. llvm::Module &module,
  1399. llvm::IRBuilder<> &builder) {
  1400. llvm::LLVMContext &context = module.getContext();
  1401. // Exception initializations
  1402. // Setup exception catch state
  1403. ourExceptionNotThrownState =
  1404. llvm::ConstantInt::get(llvm::Type::getInt8Ty(context), 0),
  1405. ourExceptionThrownState =
  1406. llvm::ConstantInt::get(llvm::Type::getInt8Ty(context), 1),
  1407. ourExceptionCaughtState =
  1408. llvm::ConstantInt::get(llvm::Type::getInt8Ty(context), 2),
  1409. // Create our type info type
  1410. ourTypeInfoType = llvm::StructType::get(context,
  1411. TypeArray(builder.getInt32Ty()));
  1412. llvm::Type *caughtResultFieldTypes[] = {
  1413. builder.getInt8PtrTy(),
  1414. builder.getInt32Ty()
  1415. };
  1416. // Create our landingpad result type
  1417. ourCaughtResultType = llvm::StructType::get(context,
  1418. TypeArray(caughtResultFieldTypes));
  1419. // Create OurException type
  1420. ourExceptionType = llvm::StructType::get(context,
  1421. TypeArray(ourTypeInfoType));
  1422. // Create portion of _Unwind_Exception type
  1423. //
  1424. // Note: Declaring only a portion of the _Unwind_Exception struct.
  1425. // Does this cause problems?
  1426. ourUnwindExceptionType =
  1427. llvm::StructType::get(context,
  1428. TypeArray(builder.getInt64Ty()));
  1429. struct OurBaseException_t dummyException;
  1430. // Calculate offset of OurException::unwindException member.
  1431. ourBaseFromUnwindOffset = ((uintptr_t) &dummyException) -
  1432. ((uintptr_t) &(dummyException.unwindException));
  1433. #ifdef DEBUG
  1434. fprintf(stderr,
  1435. "createStandardUtilityFunctions(...):ourBaseFromUnwindOffset "
  1436. "= %lld, sizeof(struct OurBaseException_t) - "
  1437. "sizeof(struct _Unwind_Exception) = %lu.\n",
  1438. ourBaseFromUnwindOffset,
  1439. sizeof(struct OurBaseException_t) -
  1440. sizeof(struct _Unwind_Exception));
  1441. #endif
  1442. size_t numChars = sizeof(ourBaseExcpClassChars) / sizeof(char);
  1443. // Create our _Unwind_Exception::exception_class value
  1444. ourBaseExceptionClass = genClass(ourBaseExcpClassChars, numChars);
  1445. // Type infos
  1446. std::string baseStr = "typeInfo", typeInfoName;
  1447. std::ostringstream typeInfoNameBuilder;
  1448. std::vector<llvm::Constant*> structVals;
  1449. llvm::Constant *nextStruct;
  1450. // Generate each type info
  1451. //
  1452. // Note: First type info is not used.
  1453. for (unsigned i = 0; i <= numTypeInfos; ++i) {
  1454. structVals.clear();
  1455. structVals.push_back(llvm::ConstantInt::get(builder.getInt32Ty(), i));
  1456. nextStruct = llvm::ConstantStruct::get(ourTypeInfoType, structVals);
  1457. typeInfoNameBuilder.str("");
  1458. typeInfoNameBuilder << baseStr << i;
  1459. typeInfoName = typeInfoNameBuilder.str();
  1460. // Note: Does not seem to work without allocation
  1461. new llvm::GlobalVariable(module,
  1462. ourTypeInfoType,
  1463. true,
  1464. llvm::GlobalValue::ExternalLinkage,
  1465. nextStruct,
  1466. typeInfoName);
  1467. ourTypeInfoNames.push_back(typeInfoName);
  1468. ourTypeInfoNamesIndex[i] = typeInfoName;
  1469. }
  1470. ArgNames argNames;
  1471. ArgTypes argTypes;
  1472. llvm::Function *funct = NULL;
  1473. // print32Int
  1474. llvm::Type *retType = builder.getVoidTy();
  1475. argTypes.clear();
  1476. argTypes.push_back(builder.getInt32Ty());
  1477. argTypes.push_back(builder.getInt8PtrTy());
  1478. argNames.clear();
  1479. createFunction(module,
  1480. retType,
  1481. argTypes,
  1482. argNames,
  1483. "print32Int",
  1484. llvm::Function::ExternalLinkage,
  1485. true,
  1486. false);
  1487. // print64Int
  1488. retType = builder.getVoidTy();
  1489. argTypes.clear();
  1490. argTypes.push_back(builder.getInt64Ty());
  1491. argTypes.push_back(builder.getInt8PtrTy());
  1492. argNames.clear();
  1493. createFunction(module,
  1494. retType,
  1495. argTypes,
  1496. argNames,
  1497. "print64Int",
  1498. llvm::Function::ExternalLinkage,
  1499. true,
  1500. false);
  1501. // printStr
  1502. retType = builder.getVoidTy();
  1503. argTypes.clear();
  1504. argTypes.push_back(builder.getInt8PtrTy());
  1505. argNames.clear();
  1506. createFunction(module,
  1507. retType,
  1508. argTypes,
  1509. argNames,
  1510. "printStr",
  1511. llvm::Function::ExternalLinkage,
  1512. true,
  1513. false);
  1514. // throwCppException
  1515. retType = builder.getVoidTy();
  1516. argTypes.clear();
  1517. argTypes.push_back(builder.getInt32Ty());
  1518. argNames.clear();
  1519. createFunction(module,
  1520. retType,
  1521. argTypes,
  1522. argNames,
  1523. "throwCppException",
  1524. llvm::Function::ExternalLinkage,
  1525. true,
  1526. false);
  1527. // deleteOurException
  1528. retType = builder.getVoidTy();
  1529. argTypes.clear();
  1530. argTypes.push_back(builder.getInt8PtrTy());
  1531. argNames.clear();
  1532. createFunction(module,
  1533. retType,
  1534. argTypes,
  1535. argNames,
  1536. "deleteOurException",
  1537. llvm::Function::ExternalLinkage,
  1538. true,
  1539. false);
  1540. // createOurException
  1541. retType = builder.getInt8PtrTy();
  1542. argTypes.clear();
  1543. argTypes.push_back(builder.getInt32Ty());
  1544. argNames.clear();
  1545. createFunction(module,
  1546. retType,
  1547. argTypes,
  1548. argNames,
  1549. "createOurException",
  1550. llvm::Function::ExternalLinkage,
  1551. true,
  1552. false);
  1553. // _Unwind_RaiseException
  1554. retType = builder.getInt32Ty();
  1555. argTypes.clear();
  1556. argTypes.push_back(builder.getInt8PtrTy());
  1557. argNames.clear();
  1558. funct = createFunction(module,
  1559. retType,
  1560. argTypes,
  1561. argNames,
  1562. "_Unwind_RaiseException",
  1563. llvm::Function::ExternalLinkage,
  1564. true,
  1565. false);
  1566. funct->setDoesNotReturn();
  1567. // _Unwind_Resume
  1568. retType = builder.getInt32Ty();
  1569. argTypes.clear();
  1570. argTypes.push_back(builder.getInt8PtrTy());
  1571. argNames.clear();
  1572. funct = createFunction(module,
  1573. retType,
  1574. argTypes,
  1575. argNames,
  1576. "_Unwind_Resume",
  1577. llvm::Function::ExternalLinkage,
  1578. true,
  1579. false);
  1580. funct->setDoesNotReturn();
  1581. // ourPersonality
  1582. retType = builder.getInt32Ty();
  1583. argTypes.clear();
  1584. argTypes.push_back(builder.getInt32Ty());
  1585. argTypes.push_back(builder.getInt32Ty());
  1586. argTypes.push_back(builder.getInt64Ty());
  1587. argTypes.push_back(builder.getInt8PtrTy());
  1588. argTypes.push_back(builder.getInt8PtrTy());
  1589. argNames.clear();
  1590. createFunction(module,
  1591. retType,
  1592. argTypes,
  1593. argNames,
  1594. "ourPersonality",
  1595. llvm::Function::ExternalLinkage,
  1596. true,
  1597. false);
  1598. // llvm.eh.typeid.for intrinsic
  1599. getDeclaration(&module, llvm::Intrinsic::eh_typeid_for);
  1600. }
  1601. //===----------------------------------------------------------------------===//
  1602. // Main test driver code.
  1603. //===----------------------------------------------------------------------===//
  1604. /// Demo main routine which takes the type info types to throw. A test will
  1605. /// be run for each given type info type. While type info types with the value
  1606. /// of -1 will trigger a foreign C++ exception to be thrown; type info types
  1607. /// <= 6 and >= 1 will be caught by test functions; and type info types > 6
  1608. /// will result in exceptions which pass through to the test harness. All other
  1609. /// type info types are not supported and could cause a crash.
  1610. int main(int argc, char *argv[]) {
  1611. if (argc == 1) {
  1612. fprintf(stderr,
  1613. "\nUsage: ExceptionDemo <exception type to throw> "
  1614. "[<type 2>...<type n>].\n"
  1615. " Each type must have the value of 1 - 6 for "
  1616. "generated exceptions to be caught;\n"
  1617. " the value -1 for foreign C++ exceptions to be "
  1618. "generated and thrown;\n"
  1619. " or the values > 6 for exceptions to be ignored.\n"
  1620. "\nTry: ExceptionDemo 2 3 7 -1\n"
  1621. " for a full test.\n\n");
  1622. return(0);
  1623. }
  1624. // If not set, exception handling will not be turned on
  1625. llvm::TargetOptions Opts;
  1626. llvm::InitializeNativeTarget();
  1627. llvm::InitializeNativeTargetAsmPrinter();
  1628. llvm::LLVMContext &context = llvm::getGlobalContext();
  1629. llvm::IRBuilder<> theBuilder(context);
  1630. // Make the module, which holds all the code.
  1631. llvm::Module *module = new llvm::Module("my cool jit", context);
  1632. llvm::RTDyldMemoryManager *MemMgr = new llvm::SectionMemoryManager();
  1633. // Build engine with JIT
  1634. llvm::EngineBuilder factory(module);
  1635. factory.setEngineKind(llvm::EngineKind::JIT);
  1636. factory.setAllocateGVsWithCode(false);
  1637. factory.setTargetOptions(Opts);
  1638. factory.setMCJITMemoryManager(MemMgr);
  1639. factory.setUseMCJIT(true);
  1640. llvm::ExecutionEngine *executionEngine = factory.create();
  1641. {
  1642. llvm::FunctionPassManager fpm(module);
  1643. // Set up the optimizer pipeline.
  1644. // Start with registering info about how the
  1645. // target lays out data structures.
  1646. module->setDataLayout(executionEngine->getDataLayout());
  1647. fpm.add(new llvm::DataLayoutPass(module));
  1648. // Optimizations turned on
  1649. #ifdef ADD_OPT_PASSES
  1650. // Basic AliasAnslysis support for GVN.
  1651. fpm.add(llvm::createBasicAliasAnalysisPass());
  1652. // Promote allocas to registers.
  1653. fpm.add(llvm::createPromoteMemoryToRegisterPass());
  1654. // Do simple "peephole" optimizations and bit-twiddling optzns.
  1655. fpm.add(llvm::createInstructionCombiningPass());
  1656. // Reassociate expressions.
  1657. fpm.add(llvm::createReassociatePass());
  1658. // Eliminate Common SubExpressions.
  1659. fpm.add(llvm::createGVNPass());
  1660. // Simplify the control flow graph (deleting unreachable
  1661. // blocks, etc).
  1662. fpm.add(llvm::createCFGSimplificationPass());
  1663. #endif // ADD_OPT_PASSES
  1664. fpm.doInitialization();
  1665. // Generate test code using function throwCppException(...) as
  1666. // the function which throws foreign exceptions.
  1667. llvm::Function *toRun =
  1668. createUnwindExceptionTest(*module,
  1669. theBuilder,
  1670. fpm,
  1671. "throwCppException");
  1672. executionEngine->finalizeObject();
  1673. fprintf(stderr, "\nBegin module dump:\n\n");
  1674. module->dump();
  1675. fprintf(stderr, "\nEnd module dump:\n");
  1676. fprintf(stderr, "\n\nBegin Test:\n");
  1677. for (int i = 1; i < argc; ++i) {
  1678. // Run test for each argument whose value is the exception
  1679. // type to throw.
  1680. runExceptionThrow(executionEngine,
  1681. toRun,
  1682. (unsigned) strtoul(argv[i], NULL, 10));
  1683. }
  1684. fprintf(stderr, "\nEnd Test:\n\n");
  1685. }
  1686. delete executionEngine;
  1687. return 0;
  1688. }