ExceptionDemo.cpp 70 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034
  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/LegacyPassManager.h"
  59. #include "llvm/IR/Module.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 llvm::Function *createCatchWrappedInvokeFunction(
  966. llvm::Module &module, llvm::IRBuilder<> &builder,
  967. llvm::legacy::FunctionPassManager &fpm, llvm::Function &toInvoke,
  968. std::string ourId, unsigned numExceptionsToCatch,
  969. unsigned exceptionTypesToCatch[]) {
  970. llvm::LLVMContext &context = module.getContext();
  971. llvm::Function *toPrint32Int = module.getFunction("print32Int");
  972. ArgTypes argTypes;
  973. argTypes.push_back(builder.getInt32Ty());
  974. ArgNames argNames;
  975. argNames.push_back("exceptTypeToThrow");
  976. llvm::Function *ret = createFunction(module,
  977. builder.getVoidTy(),
  978. argTypes,
  979. argNames,
  980. ourId,
  981. llvm::Function::ExternalLinkage,
  982. false,
  983. false);
  984. // Block which calls invoke
  985. llvm::BasicBlock *entryBlock = llvm::BasicBlock::Create(context,
  986. "entry",
  987. ret);
  988. // Normal block for invoke
  989. llvm::BasicBlock *normalBlock = llvm::BasicBlock::Create(context,
  990. "normal",
  991. ret);
  992. // Unwind block for invoke
  993. llvm::BasicBlock *exceptionBlock = llvm::BasicBlock::Create(context,
  994. "exception",
  995. ret);
  996. // Block which routes exception to correct catch handler block
  997. llvm::BasicBlock *exceptionRouteBlock = llvm::BasicBlock::Create(context,
  998. "exceptionRoute",
  999. ret);
  1000. // Foreign exception handler
  1001. llvm::BasicBlock *externalExceptionBlock = llvm::BasicBlock::Create(context,
  1002. "externalException",
  1003. ret);
  1004. // Block which calls _Unwind_Resume
  1005. llvm::BasicBlock *unwindResumeBlock = llvm::BasicBlock::Create(context,
  1006. "unwindResume",
  1007. ret);
  1008. // Clean up block which delete exception if needed
  1009. llvm::BasicBlock *endBlock = llvm::BasicBlock::Create(context, "end", ret);
  1010. std::string nextName;
  1011. std::vector<llvm::BasicBlock*> catchBlocks(numExceptionsToCatch);
  1012. llvm::Value *exceptionCaughtFlag = NULL;
  1013. llvm::Value *exceptionStorage = NULL;
  1014. llvm::Value *caughtResultStorage = NULL;
  1015. // Finally block which will branch to unwindResumeBlock if
  1016. // exception is not caught. Initializes/allocates stack locations.
  1017. llvm::BasicBlock *finallyBlock = createFinallyBlock(context,
  1018. module,
  1019. builder,
  1020. *ret,
  1021. nextName = "finally",
  1022. ourId,
  1023. *endBlock,
  1024. *unwindResumeBlock,
  1025. &exceptionCaughtFlag,
  1026. &exceptionStorage,
  1027. &caughtResultStorage
  1028. );
  1029. for (unsigned i = 0; i < numExceptionsToCatch; ++i) {
  1030. nextName = ourTypeInfoNames[exceptionTypesToCatch[i]];
  1031. // One catch block per type info to be caught
  1032. catchBlocks[i] = createCatchBlock(context,
  1033. module,
  1034. builder,
  1035. *ret,
  1036. nextName,
  1037. ourId,
  1038. *finallyBlock,
  1039. *exceptionCaughtFlag);
  1040. }
  1041. // Entry Block
  1042. builder.SetInsertPoint(entryBlock);
  1043. std::vector<llvm::Value*> args;
  1044. args.push_back(namedValues["exceptTypeToThrow"]);
  1045. builder.CreateInvoke(&toInvoke,
  1046. normalBlock,
  1047. exceptionBlock,
  1048. args);
  1049. // End Block
  1050. builder.SetInsertPoint(endBlock);
  1051. generateStringPrint(context,
  1052. module,
  1053. builder,
  1054. "Gen: In end block: exiting in " + ourId + ".\n",
  1055. USE_GLOBAL_STR_CONSTS);
  1056. llvm::Function *deleteOurException = module.getFunction("deleteOurException");
  1057. // Note: function handles NULL exceptions
  1058. builder.CreateCall(deleteOurException,
  1059. builder.CreateLoad(exceptionStorage));
  1060. builder.CreateRetVoid();
  1061. // Normal Block
  1062. builder.SetInsertPoint(normalBlock);
  1063. generateStringPrint(context,
  1064. module,
  1065. builder,
  1066. "Gen: No exception in " + ourId + "!\n",
  1067. USE_GLOBAL_STR_CONSTS);
  1068. // Finally block is always called
  1069. builder.CreateBr(finallyBlock);
  1070. // Unwind Resume Block
  1071. builder.SetInsertPoint(unwindResumeBlock);
  1072. builder.CreateResume(builder.CreateLoad(caughtResultStorage));
  1073. // Exception Block
  1074. builder.SetInsertPoint(exceptionBlock);
  1075. llvm::Function *personality = module.getFunction("ourPersonality");
  1076. llvm::LandingPadInst *caughtResult =
  1077. builder.CreateLandingPad(ourCaughtResultType,
  1078. personality,
  1079. numExceptionsToCatch,
  1080. "landingPad");
  1081. caughtResult->setCleanup(true);
  1082. for (unsigned i = 0; i < numExceptionsToCatch; ++i) {
  1083. // Set up type infos to be caught
  1084. caughtResult->addClause(module.getGlobalVariable(
  1085. ourTypeInfoNames[exceptionTypesToCatch[i]]));
  1086. }
  1087. llvm::Value *unwindException = builder.CreateExtractValue(caughtResult, 0);
  1088. llvm::Value *retTypeInfoIndex = builder.CreateExtractValue(caughtResult, 1);
  1089. // FIXME: Redundant storage which, beyond utilizing value of
  1090. // caughtResultStore for unwindException storage, may be alleviated
  1091. // altogether with a block rearrangement
  1092. builder.CreateStore(caughtResult, caughtResultStorage);
  1093. builder.CreateStore(unwindException, exceptionStorage);
  1094. builder.CreateStore(ourExceptionThrownState, exceptionCaughtFlag);
  1095. // Retrieve exception_class member from thrown exception
  1096. // (_Unwind_Exception instance). This member tells us whether or not
  1097. // the exception is foreign.
  1098. llvm::Value *unwindExceptionClass =
  1099. builder.CreateLoad(builder.CreateStructGEP(
  1100. builder.CreatePointerCast(unwindException,
  1101. ourUnwindExceptionType->getPointerTo()),
  1102. 0));
  1103. // Branch to the externalExceptionBlock if the exception is foreign or
  1104. // to a catch router if not. Either way the finally block will be run.
  1105. builder.CreateCondBr(builder.CreateICmpEQ(unwindExceptionClass,
  1106. llvm::ConstantInt::get(builder.getInt64Ty(),
  1107. ourBaseExceptionClass)),
  1108. exceptionRouteBlock,
  1109. externalExceptionBlock);
  1110. // External Exception Block
  1111. builder.SetInsertPoint(externalExceptionBlock);
  1112. generateStringPrint(context,
  1113. module,
  1114. builder,
  1115. "Gen: Foreign exception received.\n",
  1116. USE_GLOBAL_STR_CONSTS);
  1117. // Branch to the finally block
  1118. builder.CreateBr(finallyBlock);
  1119. // Exception Route Block
  1120. builder.SetInsertPoint(exceptionRouteBlock);
  1121. // Casts exception pointer (_Unwind_Exception instance) to parent
  1122. // (OurException instance).
  1123. //
  1124. // Note: ourBaseFromUnwindOffset is usually negative
  1125. llvm::Value *typeInfoThrown = builder.CreatePointerCast(
  1126. builder.CreateConstGEP1_64(unwindException,
  1127. ourBaseFromUnwindOffset),
  1128. ourExceptionType->getPointerTo());
  1129. // Retrieve thrown exception type info type
  1130. //
  1131. // Note: Index is not relative to pointer but instead to structure
  1132. // unlike a true getelementptr (GEP) instruction
  1133. typeInfoThrown = builder.CreateStructGEP(typeInfoThrown, 0);
  1134. llvm::Value *typeInfoThrownType =
  1135. builder.CreateStructGEP(typeInfoThrown, 0);
  1136. generateIntegerPrint(context,
  1137. module,
  1138. builder,
  1139. *toPrint32Int,
  1140. *(builder.CreateLoad(typeInfoThrownType)),
  1141. "Gen: Exception type <%d> received (stack unwound) "
  1142. " in " +
  1143. ourId +
  1144. ".\n",
  1145. USE_GLOBAL_STR_CONSTS);
  1146. // Route to matched type info catch block or run cleanup finally block
  1147. llvm::SwitchInst *switchToCatchBlock = builder.CreateSwitch(retTypeInfoIndex,
  1148. finallyBlock,
  1149. numExceptionsToCatch);
  1150. unsigned nextTypeToCatch;
  1151. for (unsigned i = 1; i <= numExceptionsToCatch; ++i) {
  1152. nextTypeToCatch = i - 1;
  1153. switchToCatchBlock->addCase(llvm::ConstantInt::get(
  1154. llvm::Type::getInt32Ty(context), i),
  1155. catchBlocks[nextTypeToCatch]);
  1156. }
  1157. llvm::verifyFunction(*ret);
  1158. fpm.run(*ret);
  1159. return(ret);
  1160. }
  1161. /// Generates function which throws either an exception matched to a runtime
  1162. /// determined type info type (argument to generated function), or if this
  1163. /// runtime value matches nativeThrowType, throws a foreign exception by
  1164. /// calling nativeThrowFunct.
  1165. /// @param module code for module instance
  1166. /// @param builder builder instance
  1167. /// @param fpm a function pass manager holding optional IR to IR
  1168. /// transformations
  1169. /// @param ourId id used to printing purposes
  1170. /// @param nativeThrowType a runtime argument of this value results in
  1171. /// nativeThrowFunct being called to generate/throw exception.
  1172. /// @param nativeThrowFunct function which will throw a foreign exception
  1173. /// if the above nativeThrowType matches generated function's arg.
  1174. /// @returns generated function
  1175. static llvm::Function *
  1176. createThrowExceptionFunction(llvm::Module &module, llvm::IRBuilder<> &builder,
  1177. llvm::legacy::FunctionPassManager &fpm,
  1178. std::string ourId, int32_t nativeThrowType,
  1179. llvm::Function &nativeThrowFunct) {
  1180. llvm::LLVMContext &context = module.getContext();
  1181. namedValues.clear();
  1182. ArgTypes unwindArgTypes;
  1183. unwindArgTypes.push_back(builder.getInt32Ty());
  1184. ArgNames unwindArgNames;
  1185. unwindArgNames.push_back("exceptTypeToThrow");
  1186. llvm::Function *ret = createFunction(module,
  1187. builder.getVoidTy(),
  1188. unwindArgTypes,
  1189. unwindArgNames,
  1190. ourId,
  1191. llvm::Function::ExternalLinkage,
  1192. false,
  1193. false);
  1194. // Throws either one of our exception or a native C++ exception depending
  1195. // on a runtime argument value containing a type info type.
  1196. llvm::BasicBlock *entryBlock = llvm::BasicBlock::Create(context,
  1197. "entry",
  1198. ret);
  1199. // Throws a foreign exception
  1200. llvm::BasicBlock *nativeThrowBlock = llvm::BasicBlock::Create(context,
  1201. "nativeThrow",
  1202. ret);
  1203. // Throws one of our Exceptions
  1204. llvm::BasicBlock *generatedThrowBlock = llvm::BasicBlock::Create(context,
  1205. "generatedThrow",
  1206. ret);
  1207. // Retrieved runtime type info type to throw
  1208. llvm::Value *exceptionType = namedValues["exceptTypeToThrow"];
  1209. // nativeThrowBlock block
  1210. builder.SetInsertPoint(nativeThrowBlock);
  1211. // Throws foreign exception
  1212. builder.CreateCall(&nativeThrowFunct, exceptionType);
  1213. builder.CreateUnreachable();
  1214. // entry block
  1215. builder.SetInsertPoint(entryBlock);
  1216. llvm::Function *toPrint32Int = module.getFunction("print32Int");
  1217. generateIntegerPrint(context,
  1218. module,
  1219. builder,
  1220. *toPrint32Int,
  1221. *exceptionType,
  1222. "\nGen: About to throw exception type <%d> in " +
  1223. ourId +
  1224. ".\n",
  1225. USE_GLOBAL_STR_CONSTS);
  1226. // Switches on runtime type info type value to determine whether or not
  1227. // a foreign exception is thrown. Defaults to throwing one of our
  1228. // generated exceptions.
  1229. llvm::SwitchInst *theSwitch = builder.CreateSwitch(exceptionType,
  1230. generatedThrowBlock,
  1231. 1);
  1232. theSwitch->addCase(llvm::ConstantInt::get(llvm::Type::getInt32Ty(context),
  1233. nativeThrowType),
  1234. nativeThrowBlock);
  1235. // generatedThrow block
  1236. builder.SetInsertPoint(generatedThrowBlock);
  1237. llvm::Function *createOurException = module.getFunction("createOurException");
  1238. llvm::Function *raiseOurException = module.getFunction(
  1239. "_Unwind_RaiseException");
  1240. // Creates exception to throw with runtime type info type.
  1241. llvm::Value *exception = builder.CreateCall(createOurException,
  1242. namedValues["exceptTypeToThrow"]);
  1243. // Throw generated Exception
  1244. builder.CreateCall(raiseOurException, exception);
  1245. builder.CreateUnreachable();
  1246. llvm::verifyFunction(*ret);
  1247. fpm.run(*ret);
  1248. return(ret);
  1249. }
  1250. static void createStandardUtilityFunctions(unsigned numTypeInfos,
  1251. llvm::Module &module,
  1252. llvm::IRBuilder<> &builder);
  1253. /// Creates test code by generating and organizing these functions into the
  1254. /// test case. The test case consists of an outer function setup to invoke
  1255. /// an inner function within an environment having multiple catch and single
  1256. /// finally blocks. This inner function is also setup to invoke a throw
  1257. /// function within an evironment similar in nature to the outer function's
  1258. /// catch and finally blocks. Each of these two functions catch mutually
  1259. /// exclusive subsets (even or odd) of the type info types configured
  1260. /// for this this. All generated functions have a runtime argument which
  1261. /// holds a type info type to throw that each function takes and passes it
  1262. /// to the inner one if such a inner function exists. This type info type is
  1263. /// looked at by the generated throw function to see whether or not it should
  1264. /// throw a generated exception with the same type info type, or instead call
  1265. /// a supplied a function which in turn will throw a foreign exception.
  1266. /// @param module code for module instance
  1267. /// @param builder builder instance
  1268. /// @param fpm a function pass manager holding optional IR to IR
  1269. /// transformations
  1270. /// @param nativeThrowFunctName name of external function which will throw
  1271. /// a foreign exception
  1272. /// @returns outermost generated test function.
  1273. llvm::Function *
  1274. createUnwindExceptionTest(llvm::Module &module, llvm::IRBuilder<> &builder,
  1275. llvm::legacy::FunctionPassManager &fpm,
  1276. std::string nativeThrowFunctName) {
  1277. // Number of type infos to generate
  1278. unsigned numTypeInfos = 6;
  1279. // Initialze intrisics and external functions to use along with exception
  1280. // and type info globals.
  1281. createStandardUtilityFunctions(numTypeInfos,
  1282. module,
  1283. builder);
  1284. llvm::Function *nativeThrowFunct = module.getFunction(nativeThrowFunctName);
  1285. // Create exception throw function using the value ~0 to cause
  1286. // foreign exceptions to be thrown.
  1287. llvm::Function *throwFunct = createThrowExceptionFunction(module,
  1288. builder,
  1289. fpm,
  1290. "throwFunct",
  1291. ~0,
  1292. *nativeThrowFunct);
  1293. // Inner function will catch even type infos
  1294. unsigned innerExceptionTypesToCatch[] = {6, 2, 4};
  1295. size_t numExceptionTypesToCatch = sizeof(innerExceptionTypesToCatch) /
  1296. sizeof(unsigned);
  1297. // Generate inner function.
  1298. llvm::Function *innerCatchFunct = createCatchWrappedInvokeFunction(module,
  1299. builder,
  1300. fpm,
  1301. *throwFunct,
  1302. "innerCatchFunct",
  1303. numExceptionTypesToCatch,
  1304. innerExceptionTypesToCatch);
  1305. // Outer function will catch odd type infos
  1306. unsigned outerExceptionTypesToCatch[] = {3, 1, 5};
  1307. numExceptionTypesToCatch = sizeof(outerExceptionTypesToCatch) /
  1308. sizeof(unsigned);
  1309. // Generate outer function
  1310. llvm::Function *outerCatchFunct = createCatchWrappedInvokeFunction(module,
  1311. builder,
  1312. fpm,
  1313. *innerCatchFunct,
  1314. "outerCatchFunct",
  1315. numExceptionTypesToCatch,
  1316. outerExceptionTypesToCatch);
  1317. // Return outer function to run
  1318. return(outerCatchFunct);
  1319. }
  1320. namespace {
  1321. /// Represents our foreign exceptions
  1322. class OurCppRunException : public std::runtime_error {
  1323. public:
  1324. OurCppRunException(const std::string reason) :
  1325. std::runtime_error(reason) {}
  1326. OurCppRunException (const OurCppRunException &toCopy) :
  1327. std::runtime_error(toCopy) {}
  1328. OurCppRunException &operator = (const OurCppRunException &toCopy) {
  1329. return(reinterpret_cast<OurCppRunException&>(
  1330. std::runtime_error::operator=(toCopy)));
  1331. }
  1332. virtual ~OurCppRunException (void) throw () {}
  1333. };
  1334. } // end anonymous namespace
  1335. /// Throws foreign C++ exception.
  1336. /// @param ignoreIt unused parameter that allows function to match implied
  1337. /// generated function contract.
  1338. extern "C"
  1339. void throwCppException (int32_t ignoreIt) {
  1340. throw(OurCppRunException("thrown by throwCppException(...)"));
  1341. }
  1342. typedef void (*OurExceptionThrowFunctType) (int32_t typeToThrow);
  1343. /// This is a test harness which runs test by executing generated
  1344. /// function with a type info type to throw. Harness wraps the execution
  1345. /// of generated function in a C++ try catch clause.
  1346. /// @param engine execution engine to use for executing generated function.
  1347. /// This demo program expects this to be a JIT instance for demo
  1348. /// purposes.
  1349. /// @param function generated test function to run
  1350. /// @param typeToThrow type info type of generated exception to throw, or
  1351. /// indicator to cause foreign exception to be thrown.
  1352. static
  1353. void runExceptionThrow(llvm::ExecutionEngine *engine,
  1354. llvm::Function *function,
  1355. int32_t typeToThrow) {
  1356. // Find test's function pointer
  1357. OurExceptionThrowFunctType functPtr =
  1358. reinterpret_cast<OurExceptionThrowFunctType>(
  1359. reinterpret_cast<intptr_t>(engine->getPointerToFunction(function)));
  1360. try {
  1361. // Run test
  1362. (*functPtr)(typeToThrow);
  1363. }
  1364. catch (OurCppRunException exc) {
  1365. // Catch foreign C++ exception
  1366. fprintf(stderr,
  1367. "\nrunExceptionThrow(...):In C++ catch OurCppRunException "
  1368. "with reason: %s.\n",
  1369. exc.what());
  1370. }
  1371. catch (...) {
  1372. // Catch all exceptions including our generated ones. This latter
  1373. // functionality works according to the example in rules 1.6.4 of
  1374. // http://mentorembedded.github.com/cxx-abi/abi-eh.html (v1.22),
  1375. // given that these will be exceptions foreign to C++
  1376. // (the _Unwind_Exception::exception_class should be different from
  1377. // the one used by C++).
  1378. fprintf(stderr,
  1379. "\nrunExceptionThrow(...):In C++ catch all.\n");
  1380. }
  1381. }
  1382. //
  1383. // End test functions
  1384. //
  1385. typedef llvm::ArrayRef<llvm::Type*> TypeArray;
  1386. /// This initialization routine creates type info globals and
  1387. /// adds external function declarations to module.
  1388. /// @param numTypeInfos number of linear type info associated type info types
  1389. /// to create as GlobalVariable instances, starting with the value 1.
  1390. /// @param module code for module instance
  1391. /// @param builder builder instance
  1392. static void createStandardUtilityFunctions(unsigned numTypeInfos,
  1393. llvm::Module &module,
  1394. llvm::IRBuilder<> &builder) {
  1395. llvm::LLVMContext &context = module.getContext();
  1396. // Exception initializations
  1397. // Setup exception catch state
  1398. ourExceptionNotThrownState =
  1399. llvm::ConstantInt::get(llvm::Type::getInt8Ty(context), 0),
  1400. ourExceptionThrownState =
  1401. llvm::ConstantInt::get(llvm::Type::getInt8Ty(context), 1),
  1402. ourExceptionCaughtState =
  1403. llvm::ConstantInt::get(llvm::Type::getInt8Ty(context), 2),
  1404. // Create our type info type
  1405. ourTypeInfoType = llvm::StructType::get(context,
  1406. TypeArray(builder.getInt32Ty()));
  1407. llvm::Type *caughtResultFieldTypes[] = {
  1408. builder.getInt8PtrTy(),
  1409. builder.getInt32Ty()
  1410. };
  1411. // Create our landingpad result type
  1412. ourCaughtResultType = llvm::StructType::get(context,
  1413. TypeArray(caughtResultFieldTypes));
  1414. // Create OurException type
  1415. ourExceptionType = llvm::StructType::get(context,
  1416. TypeArray(ourTypeInfoType));
  1417. // Create portion of _Unwind_Exception type
  1418. //
  1419. // Note: Declaring only a portion of the _Unwind_Exception struct.
  1420. // Does this cause problems?
  1421. ourUnwindExceptionType =
  1422. llvm::StructType::get(context,
  1423. TypeArray(builder.getInt64Ty()));
  1424. struct OurBaseException_t dummyException;
  1425. // Calculate offset of OurException::unwindException member.
  1426. ourBaseFromUnwindOffset = ((uintptr_t) &dummyException) -
  1427. ((uintptr_t) &(dummyException.unwindException));
  1428. #ifdef DEBUG
  1429. fprintf(stderr,
  1430. "createStandardUtilityFunctions(...):ourBaseFromUnwindOffset "
  1431. "= %lld, sizeof(struct OurBaseException_t) - "
  1432. "sizeof(struct _Unwind_Exception) = %lu.\n",
  1433. ourBaseFromUnwindOffset,
  1434. sizeof(struct OurBaseException_t) -
  1435. sizeof(struct _Unwind_Exception));
  1436. #endif
  1437. size_t numChars = sizeof(ourBaseExcpClassChars) / sizeof(char);
  1438. // Create our _Unwind_Exception::exception_class value
  1439. ourBaseExceptionClass = genClass(ourBaseExcpClassChars, numChars);
  1440. // Type infos
  1441. std::string baseStr = "typeInfo", typeInfoName;
  1442. std::ostringstream typeInfoNameBuilder;
  1443. std::vector<llvm::Constant*> structVals;
  1444. llvm::Constant *nextStruct;
  1445. // Generate each type info
  1446. //
  1447. // Note: First type info is not used.
  1448. for (unsigned i = 0; i <= numTypeInfos; ++i) {
  1449. structVals.clear();
  1450. structVals.push_back(llvm::ConstantInt::get(builder.getInt32Ty(), i));
  1451. nextStruct = llvm::ConstantStruct::get(ourTypeInfoType, structVals);
  1452. typeInfoNameBuilder.str("");
  1453. typeInfoNameBuilder << baseStr << i;
  1454. typeInfoName = typeInfoNameBuilder.str();
  1455. // Note: Does not seem to work without allocation
  1456. new llvm::GlobalVariable(module,
  1457. ourTypeInfoType,
  1458. true,
  1459. llvm::GlobalValue::ExternalLinkage,
  1460. nextStruct,
  1461. typeInfoName);
  1462. ourTypeInfoNames.push_back(typeInfoName);
  1463. ourTypeInfoNamesIndex[i] = typeInfoName;
  1464. }
  1465. ArgNames argNames;
  1466. ArgTypes argTypes;
  1467. llvm::Function *funct = NULL;
  1468. // print32Int
  1469. llvm::Type *retType = builder.getVoidTy();
  1470. argTypes.clear();
  1471. argTypes.push_back(builder.getInt32Ty());
  1472. argTypes.push_back(builder.getInt8PtrTy());
  1473. argNames.clear();
  1474. createFunction(module,
  1475. retType,
  1476. argTypes,
  1477. argNames,
  1478. "print32Int",
  1479. llvm::Function::ExternalLinkage,
  1480. true,
  1481. false);
  1482. // print64Int
  1483. retType = builder.getVoidTy();
  1484. argTypes.clear();
  1485. argTypes.push_back(builder.getInt64Ty());
  1486. argTypes.push_back(builder.getInt8PtrTy());
  1487. argNames.clear();
  1488. createFunction(module,
  1489. retType,
  1490. argTypes,
  1491. argNames,
  1492. "print64Int",
  1493. llvm::Function::ExternalLinkage,
  1494. true,
  1495. false);
  1496. // printStr
  1497. retType = builder.getVoidTy();
  1498. argTypes.clear();
  1499. argTypes.push_back(builder.getInt8PtrTy());
  1500. argNames.clear();
  1501. createFunction(module,
  1502. retType,
  1503. argTypes,
  1504. argNames,
  1505. "printStr",
  1506. llvm::Function::ExternalLinkage,
  1507. true,
  1508. false);
  1509. // throwCppException
  1510. retType = builder.getVoidTy();
  1511. argTypes.clear();
  1512. argTypes.push_back(builder.getInt32Ty());
  1513. argNames.clear();
  1514. createFunction(module,
  1515. retType,
  1516. argTypes,
  1517. argNames,
  1518. "throwCppException",
  1519. llvm::Function::ExternalLinkage,
  1520. true,
  1521. false);
  1522. // deleteOurException
  1523. retType = builder.getVoidTy();
  1524. argTypes.clear();
  1525. argTypes.push_back(builder.getInt8PtrTy());
  1526. argNames.clear();
  1527. createFunction(module,
  1528. retType,
  1529. argTypes,
  1530. argNames,
  1531. "deleteOurException",
  1532. llvm::Function::ExternalLinkage,
  1533. true,
  1534. false);
  1535. // createOurException
  1536. retType = builder.getInt8PtrTy();
  1537. argTypes.clear();
  1538. argTypes.push_back(builder.getInt32Ty());
  1539. argNames.clear();
  1540. createFunction(module,
  1541. retType,
  1542. argTypes,
  1543. argNames,
  1544. "createOurException",
  1545. llvm::Function::ExternalLinkage,
  1546. true,
  1547. false);
  1548. // _Unwind_RaiseException
  1549. retType = builder.getInt32Ty();
  1550. argTypes.clear();
  1551. argTypes.push_back(builder.getInt8PtrTy());
  1552. argNames.clear();
  1553. funct = createFunction(module,
  1554. retType,
  1555. argTypes,
  1556. argNames,
  1557. "_Unwind_RaiseException",
  1558. llvm::Function::ExternalLinkage,
  1559. true,
  1560. false);
  1561. funct->setDoesNotReturn();
  1562. // _Unwind_Resume
  1563. retType = builder.getInt32Ty();
  1564. argTypes.clear();
  1565. argTypes.push_back(builder.getInt8PtrTy());
  1566. argNames.clear();
  1567. funct = createFunction(module,
  1568. retType,
  1569. argTypes,
  1570. argNames,
  1571. "_Unwind_Resume",
  1572. llvm::Function::ExternalLinkage,
  1573. true,
  1574. false);
  1575. funct->setDoesNotReturn();
  1576. // ourPersonality
  1577. retType = builder.getInt32Ty();
  1578. argTypes.clear();
  1579. argTypes.push_back(builder.getInt32Ty());
  1580. argTypes.push_back(builder.getInt32Ty());
  1581. argTypes.push_back(builder.getInt64Ty());
  1582. argTypes.push_back(builder.getInt8PtrTy());
  1583. argTypes.push_back(builder.getInt8PtrTy());
  1584. argNames.clear();
  1585. createFunction(module,
  1586. retType,
  1587. argTypes,
  1588. argNames,
  1589. "ourPersonality",
  1590. llvm::Function::ExternalLinkage,
  1591. true,
  1592. false);
  1593. // llvm.eh.typeid.for intrinsic
  1594. getDeclaration(&module, llvm::Intrinsic::eh_typeid_for);
  1595. }
  1596. //===----------------------------------------------------------------------===//
  1597. // Main test driver code.
  1598. //===----------------------------------------------------------------------===//
  1599. /// Demo main routine which takes the type info types to throw. A test will
  1600. /// be run for each given type info type. While type info types with the value
  1601. /// of -1 will trigger a foreign C++ exception to be thrown; type info types
  1602. /// <= 6 and >= 1 will be caught by test functions; and type info types > 6
  1603. /// will result in exceptions which pass through to the test harness. All other
  1604. /// type info types are not supported and could cause a crash.
  1605. int main(int argc, char *argv[]) {
  1606. if (argc == 1) {
  1607. fprintf(stderr,
  1608. "\nUsage: ExceptionDemo <exception type to throw> "
  1609. "[<type 2>...<type n>].\n"
  1610. " Each type must have the value of 1 - 6 for "
  1611. "generated exceptions to be caught;\n"
  1612. " the value -1 for foreign C++ exceptions to be "
  1613. "generated and thrown;\n"
  1614. " or the values > 6 for exceptions to be ignored.\n"
  1615. "\nTry: ExceptionDemo 2 3 7 -1\n"
  1616. " for a full test.\n\n");
  1617. return(0);
  1618. }
  1619. // If not set, exception handling will not be turned on
  1620. llvm::TargetOptions Opts;
  1621. llvm::InitializeNativeTarget();
  1622. llvm::InitializeNativeTargetAsmPrinter();
  1623. llvm::LLVMContext &context = llvm::getGlobalContext();
  1624. llvm::IRBuilder<> theBuilder(context);
  1625. // Make the module, which holds all the code.
  1626. std::unique_ptr<llvm::Module> Owner =
  1627. llvm::make_unique<llvm::Module>("my cool jit", context);
  1628. llvm::Module *module = Owner.get();
  1629. std::unique_ptr<llvm::RTDyldMemoryManager> MemMgr(new llvm::SectionMemoryManager());
  1630. // Build engine with JIT
  1631. llvm::EngineBuilder factory(std::move(Owner));
  1632. factory.setEngineKind(llvm::EngineKind::JIT);
  1633. factory.setTargetOptions(Opts);
  1634. factory.setMCJITMemoryManager(std::move(MemMgr));
  1635. llvm::ExecutionEngine *executionEngine = factory.create();
  1636. {
  1637. llvm::legacy::FunctionPassManager fpm(module);
  1638. // Set up the optimizer pipeline.
  1639. // Start with registering info about how the
  1640. // target lays out data structures.
  1641. module->setDataLayout(executionEngine->getDataLayout());
  1642. fpm.add(new llvm::DataLayoutPass());
  1643. // Optimizations turned on
  1644. #ifdef ADD_OPT_PASSES
  1645. // Basic AliasAnslysis support for GVN.
  1646. fpm.add(llvm::createBasicAliasAnalysisPass());
  1647. // Promote allocas to registers.
  1648. fpm.add(llvm::createPromoteMemoryToRegisterPass());
  1649. // Do simple "peephole" optimizations and bit-twiddling optzns.
  1650. fpm.add(llvm::createInstructionCombiningPass());
  1651. // Reassociate expressions.
  1652. fpm.add(llvm::createReassociatePass());
  1653. // Eliminate Common SubExpressions.
  1654. fpm.add(llvm::createGVNPass());
  1655. // Simplify the control flow graph (deleting unreachable
  1656. // blocks, etc).
  1657. fpm.add(llvm::createCFGSimplificationPass());
  1658. #endif // ADD_OPT_PASSES
  1659. fpm.doInitialization();
  1660. // Generate test code using function throwCppException(...) as
  1661. // the function which throws foreign exceptions.
  1662. llvm::Function *toRun =
  1663. createUnwindExceptionTest(*module,
  1664. theBuilder,
  1665. fpm,
  1666. "throwCppException");
  1667. executionEngine->finalizeObject();
  1668. fprintf(stderr, "\nBegin module dump:\n\n");
  1669. module->dump();
  1670. fprintf(stderr, "\nEnd module dump:\n");
  1671. fprintf(stderr, "\n\nBegin Test:\n");
  1672. for (int i = 1; i < argc; ++i) {
  1673. // Run test for each argument whose value is the exception
  1674. // type to throw.
  1675. runExceptionThrow(executionEngine,
  1676. toRun,
  1677. (unsigned) strtoul(argv[i], NULL, 10));
  1678. }
  1679. fprintf(stderr, "\nEnd Test:\n\n");
  1680. }
  1681. delete executionEngine;
  1682. return 0;
  1683. }