1 //===-- ExceptionDemo.cpp - An example using llvm Exceptions --------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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
27 // causes a usage to be printed to stderr
29 // ExceptionDemo 2 3 7 -1
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
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)
46 // This code uses code from the llvm compiler-rt project and the llvm
47 // Kaleidoscope project.
49 //===----------------------------------------------------------------------===//
51 #include "llvm/ADT/STLExtras.h"
52 #include "llvm/IR/Verifier.h"
53 #include "llvm/ExecutionEngine/MCJIT.h"
54 #include "llvm/ExecutionEngine/SectionMemoryManager.h"
55 #include "llvm/IR/DataLayout.h"
56 #include "llvm/IR/DerivedTypes.h"
57 #include "llvm/IR/IRBuilder.h"
58 #include "llvm/IR/Intrinsics.h"
59 #include "llvm/IR/LLVMContext.h"
60 #include "llvm/IR/LegacyPassManager.h"
61 #include "llvm/IR/Module.h"
62 #include "llvm/Support/Dwarf.h"
63 #include "llvm/Support/TargetSelect.h"
64 #include "llvm/Target/TargetOptions.h"
65 #include "llvm/Transforms/Scalar.h"
67 // FIXME: Although all systems tested with (Linux, OS X), do not need this
68 // header file included. A user on ubuntu reported, undefined symbols
69 // for stderr, and fprintf, and the addition of this include fixed the
70 // issue for them. Given that LLVM's best practices include the goal
71 // of reducing the number of redundant header files included, the
72 // correct solution would be to find out why these symbols are not
73 // defined for the system in question, and fix the issue by finding out
74 // which LLVM header file, if any, would include these symbols.
81 #ifndef USE_GLOBAL_STR_CONSTS
82 #define USE_GLOBAL_STR_CONSTS true
85 // System C++ ABI unwind types from:
86 // http://mentorembedded.github.com/cxx-abi/abi-eh.html (v1.22)
92 _URC_FOREIGN_EXCEPTION_CAUGHT = 1,
93 _URC_FATAL_PHASE2_ERROR = 2,
94 _URC_FATAL_PHASE1_ERROR = 3,
96 _URC_END_OF_STACK = 5,
97 _URC_HANDLER_FOUND = 6,
98 _URC_INSTALL_CONTEXT = 7,
99 _URC_CONTINUE_UNWIND = 8
100 } _Unwind_Reason_Code;
103 _UA_SEARCH_PHASE = 1,
104 _UA_CLEANUP_PHASE = 2,
105 _UA_HANDLER_FRAME = 4,
106 _UA_FORCE_UNWIND = 8,
107 _UA_END_OF_STACK = 16
110 struct _Unwind_Exception;
112 typedef void (*_Unwind_Exception_Cleanup_Fn) (_Unwind_Reason_Code,
113 struct _Unwind_Exception *);
115 struct _Unwind_Exception {
116 uint64_t exception_class;
117 _Unwind_Exception_Cleanup_Fn exception_cleanup;
122 // @@@ The IA-64 ABI says that this structure must be double-word aligned.
123 // Taking that literally does not make much sense generically. Instead
124 // we provide the maximum alignment required by any type for the machine.
125 } __attribute__((__aligned__));
127 struct _Unwind_Context;
128 typedef struct _Unwind_Context *_Unwind_Context_t;
130 extern const uint8_t *_Unwind_GetLanguageSpecificData (_Unwind_Context_t c);
131 extern uintptr_t _Unwind_GetGR (_Unwind_Context_t c, int i);
132 extern void _Unwind_SetGR (_Unwind_Context_t c, int i, uintptr_t n);
133 extern void _Unwind_SetIP (_Unwind_Context_t, uintptr_t new_value);
134 extern uintptr_t _Unwind_GetIP (_Unwind_Context_t context);
135 extern uintptr_t _Unwind_GetRegionStart (_Unwind_Context_t context);
143 /// This is our simplistic type info
144 struct OurExceptionType_t {
150 /// This is our Exception class which relies on a negative offset to calculate
151 /// pointers to its instances from pointers to its unwindException member.
153 /// Note: The above unwind.h defines struct _Unwind_Exception to be aligned
154 /// on a double word boundary. This is necessary to match the standard:
155 /// http://mentorembedded.github.com/cxx-abi/abi-eh.html
156 struct OurBaseException_t {
157 struct OurExceptionType_t type;
159 // Note: This is properly aligned in unwind.h
160 struct _Unwind_Exception unwindException;
164 // Note: Not needed since we are C++
165 typedef struct OurBaseException_t OurException;
166 typedef struct _Unwind_Exception OurUnwindException;
169 // Various globals used to support typeinfo and generatted exceptions in
173 static std::map<std::string, llvm::Value*> namedValues;
175 int64_t ourBaseFromUnwindOffset;
177 const unsigned char ourBaseExcpClassChars[] =
178 {'o', 'b', 'j', '\0', 'b', 'a', 's', '\0'};
181 static uint64_t ourBaseExceptionClass = 0;
183 static std::vector<std::string> ourTypeInfoNames;
184 static std::map<int, std::string> ourTypeInfoNamesIndex;
186 static llvm::StructType *ourTypeInfoType;
187 static llvm::StructType *ourCaughtResultType;
188 static llvm::StructType *ourExceptionType;
189 static llvm::StructType *ourUnwindExceptionType;
191 static llvm::ConstantInt *ourExceptionNotThrownState;
192 static llvm::ConstantInt *ourExceptionThrownState;
193 static llvm::ConstantInt *ourExceptionCaughtState;
195 typedef std::vector<std::string> ArgNames;
196 typedef std::vector<llvm::Type*> ArgTypes;
199 // Code Generation Utilities
202 /// Utility used to create a function, both declarations and definitions
203 /// @param module for module instance
204 /// @param retType function return type
205 /// @param theArgTypes function's ordered argument types
206 /// @param theArgNames function's ordered arguments needed if use of this
207 /// function corresponds to a function definition. Use empty
208 /// aggregate for function declarations.
209 /// @param functName function name
210 /// @param linkage function linkage
211 /// @param declarationOnly for function declarations
212 /// @param isVarArg function uses vararg arguments
213 /// @returns function instance
214 llvm::Function *createFunction(llvm::Module &module,
216 const ArgTypes &theArgTypes,
217 const ArgNames &theArgNames,
218 const std::string &functName,
219 llvm::GlobalValue::LinkageTypes linkage,
220 bool declarationOnly,
222 llvm::FunctionType *functType =
223 llvm::FunctionType::get(retType, theArgTypes, isVarArg);
224 llvm::Function *ret =
225 llvm::Function::Create(functType, linkage, functName, &module);
226 if (!ret || declarationOnly)
231 for (llvm::Function::arg_iterator argIndex = ret->arg_begin();
232 i != theArgNames.size();
235 argIndex->setName(theArgNames[i]);
236 namedValues[theArgNames[i]] = argIndex;
243 /// Create an alloca instruction in the entry block of
244 /// the parent function. This is used for mutable variables etc.
245 /// @param function parent instance
246 /// @param varName stack variable name
247 /// @param type stack variable type
248 /// @param initWith optional constant initialization value
249 /// @returns AllocaInst instance
250 static llvm::AllocaInst *createEntryBlockAlloca(llvm::Function &function,
251 const std::string &varName,
253 llvm::Constant *initWith = 0) {
254 llvm::BasicBlock &block = function.getEntryBlock();
255 llvm::IRBuilder<> tmp(&block, block.begin());
256 llvm::AllocaInst *ret = tmp.CreateAlloca(type, 0, varName.c_str());
259 tmp.CreateStore(initWith, ret);
266 // Code Generation Utilities End
270 // Runtime C Library functions
273 // Note: using an extern "C" block so that static functions can be used
276 // Note: Better ways to decide on bit width
278 /// Prints a 32 bit number, according to the format, to stderr.
279 /// @param intToPrint integer to print
280 /// @param format printf like format to use when printing
281 void print32Int(int intToPrint, const char *format) {
283 // Note: No NULL check
284 fprintf(stderr, format, intToPrint);
287 // Note: No NULL check
288 fprintf(stderr, "::print32Int(...):NULL arg.\n");
293 // Note: Better ways to decide on bit width
295 /// Prints a 64 bit number, according to the format, to stderr.
296 /// @param intToPrint integer to print
297 /// @param format printf like format to use when printing
298 void print64Int(long int intToPrint, const char *format) {
300 // Note: No NULL check
301 fprintf(stderr, format, intToPrint);
304 // Note: No NULL check
305 fprintf(stderr, "::print64Int(...):NULL arg.\n");
310 /// Prints a C string to stderr
311 /// @param toPrint string to print
312 void printStr(char *toPrint) {
314 fprintf(stderr, "%s", toPrint);
317 fprintf(stderr, "::printStr(...):NULL arg.\n");
322 /// Deletes the true previosly allocated exception whose address
323 /// is calculated from the supplied OurBaseException_t::unwindException
324 /// member address. Handles (ignores), NULL pointers.
325 /// @param expToDelete exception to delete
326 void deleteOurException(OurUnwindException *expToDelete) {
329 "deleteOurException(...).\n");
333 (expToDelete->exception_class == ourBaseExceptionClass)) {
335 free(((char*) expToDelete) + ourBaseFromUnwindOffset);
340 /// This function is the struct _Unwind_Exception API mandated delete function
341 /// used by foreign exception handlers when deleting our exception
342 /// (OurException), instances.
343 /// @param reason See @link http://mentorembedded.github.com/cxx-abi/abi-eh.html
345 /// @param expToDelete exception instance to delete
346 void deleteFromUnwindOurException(_Unwind_Reason_Code reason,
347 OurUnwindException *expToDelete) {
350 "deleteFromUnwindOurException(...).\n");
353 deleteOurException(expToDelete);
357 /// Creates (allocates on the heap), an exception (OurException instance),
358 /// of the supplied type info type.
359 /// @param type type info type
360 OurUnwindException *createOurException(int type) {
361 size_t size = sizeof(OurException);
362 OurException *ret = (OurException*) memset(malloc(size), 0, size);
363 (ret->type).type = type;
364 (ret->unwindException).exception_class = ourBaseExceptionClass;
365 (ret->unwindException).exception_cleanup = deleteFromUnwindOurException;
367 return(&(ret->unwindException));
371 /// Read a uleb128 encoded value and advance pointer
372 /// See Variable Length Data in:
373 /// @link http://dwarfstd.org/Dwarf3.pdf @unlink
374 /// @param data reference variable holding memory pointer to decode from
375 /// @returns decoded value
376 static uintptr_t readULEB128(const uint8_t **data) {
377 uintptr_t result = 0;
380 const uint8_t *p = *data;
384 result |= (byte & 0x7f) << shift;
395 /// Read a sleb128 encoded value and advance pointer
396 /// See Variable Length Data in:
397 /// @link http://dwarfstd.org/Dwarf3.pdf @unlink
398 /// @param data reference variable holding memory pointer to decode from
399 /// @returns decoded value
400 static uintptr_t readSLEB128(const uint8_t **data) {
401 uintptr_t result = 0;
404 const uint8_t *p = *data;
408 result |= (byte & 0x7f) << shift;
415 if ((byte & 0x40) && (shift < (sizeof(result) << 3))) {
416 result |= (~0 << shift);
422 unsigned getEncodingSize(uint8_t Encoding) {
423 if (Encoding == llvm::dwarf::DW_EH_PE_omit)
426 switch (Encoding & 0x0F) {
427 case llvm::dwarf::DW_EH_PE_absptr:
428 return sizeof(uintptr_t);
429 case llvm::dwarf::DW_EH_PE_udata2:
430 return sizeof(uint16_t);
431 case llvm::dwarf::DW_EH_PE_udata4:
432 return sizeof(uint32_t);
433 case llvm::dwarf::DW_EH_PE_udata8:
434 return sizeof(uint64_t);
435 case llvm::dwarf::DW_EH_PE_sdata2:
436 return sizeof(int16_t);
437 case llvm::dwarf::DW_EH_PE_sdata4:
438 return sizeof(int32_t);
439 case llvm::dwarf::DW_EH_PE_sdata8:
440 return sizeof(int64_t);
447 /// Read a pointer encoded value and advance pointer
448 /// See Variable Length Data in:
449 /// @link http://dwarfstd.org/Dwarf3.pdf @unlink
450 /// @param data reference variable holding memory pointer to decode from
451 /// @param encoding dwarf encoding type
452 /// @returns decoded value
453 static uintptr_t readEncodedPointer(const uint8_t **data, uint8_t encoding) {
454 uintptr_t result = 0;
455 const uint8_t *p = *data;
457 if (encoding == llvm::dwarf::DW_EH_PE_omit)
461 switch (encoding & 0x0F) {
462 case llvm::dwarf::DW_EH_PE_absptr:
463 result = *((uintptr_t*)p);
464 p += sizeof(uintptr_t);
466 case llvm::dwarf::DW_EH_PE_uleb128:
467 result = readULEB128(&p);
469 // Note: This case has not been tested
470 case llvm::dwarf::DW_EH_PE_sleb128:
471 result = readSLEB128(&p);
473 case llvm::dwarf::DW_EH_PE_udata2:
474 result = *((uint16_t*)p);
475 p += sizeof(uint16_t);
477 case llvm::dwarf::DW_EH_PE_udata4:
478 result = *((uint32_t*)p);
479 p += sizeof(uint32_t);
481 case llvm::dwarf::DW_EH_PE_udata8:
482 result = *((uint64_t*)p);
483 p += sizeof(uint64_t);
485 case llvm::dwarf::DW_EH_PE_sdata2:
486 result = *((int16_t*)p);
487 p += sizeof(int16_t);
489 case llvm::dwarf::DW_EH_PE_sdata4:
490 result = *((int32_t*)p);
491 p += sizeof(int32_t);
493 case llvm::dwarf::DW_EH_PE_sdata8:
494 result = *((int64_t*)p);
495 p += sizeof(int64_t);
503 // then add relative offset
504 switch (encoding & 0x70) {
505 case llvm::dwarf::DW_EH_PE_absptr:
508 case llvm::dwarf::DW_EH_PE_pcrel:
509 result += (uintptr_t)(*data);
511 case llvm::dwarf::DW_EH_PE_textrel:
512 case llvm::dwarf::DW_EH_PE_datarel:
513 case llvm::dwarf::DW_EH_PE_funcrel:
514 case llvm::dwarf::DW_EH_PE_aligned:
521 // then apply indirection
522 if (encoding & llvm::dwarf::DW_EH_PE_indirect) {
523 result = *((uintptr_t*)result);
532 /// Deals with Dwarf actions matching our type infos
533 /// (OurExceptionType_t instances). Returns whether or not a dwarf emitted
534 /// action matches the supplied exception type. If such a match succeeds,
535 /// the resultAction argument will be set with > 0 index value. Only
536 /// corresponding llvm.eh.selector type info arguments, cleanup arguments
537 /// are supported. Filters are not supported.
538 /// See Variable Length Data in:
539 /// @link http://dwarfstd.org/Dwarf3.pdf @unlink
540 /// Also see @link http://mentorembedded.github.com/cxx-abi/abi-eh.html @unlink
541 /// @param resultAction reference variable which will be set with result
542 /// @param classInfo our array of type info pointers (to globals)
543 /// @param actionEntry index into above type info array or 0 (clean up).
544 /// We do not support filters.
545 /// @param exceptionClass exception class (_Unwind_Exception::exception_class)
546 /// of thrown exception.
547 /// @param exceptionObject thrown _Unwind_Exception instance.
548 /// @returns whether or not a type info was found. False is returned if only
549 /// a cleanup was found
550 static bool handleActionValue(int64_t *resultAction,
551 uint8_t TTypeEncoding,
552 const uint8_t *ClassInfo,
553 uintptr_t actionEntry,
554 uint64_t exceptionClass,
555 struct _Unwind_Exception *exceptionObject) {
560 (exceptionClass != ourBaseExceptionClass))
563 struct OurBaseException_t *excp = (struct OurBaseException_t*)
564 (((char*) exceptionObject) + ourBaseFromUnwindOffset);
565 struct OurExceptionType_t *excpType = &(excp->type);
566 int type = excpType->type;
570 "handleActionValue(...): exceptionObject = <%p>, "
576 const uint8_t *actionPos = (uint8_t*) actionEntry,
578 int64_t typeOffset = 0,
581 for (int i = 0; true; ++i) {
582 // Each emitted dwarf action corresponds to a 2 tuple of
583 // type info address offset, and action offset to the next
585 typeOffset = readSLEB128(&actionPos);
586 tempActionPos = actionPos;
587 actionOffset = readSLEB128(&tempActionPos);
591 "handleActionValue(...):typeOffset: <%lld>, "
592 "actionOffset: <%lld>.\n",
596 assert((typeOffset >= 0) &&
597 "handleActionValue(...):filters are not supported.");
599 // Note: A typeOffset == 0 implies that a cleanup llvm.eh.selector
600 // argument has been matched.
601 if (typeOffset > 0) {
604 "handleActionValue(...):actionValue <%d> found.\n",
607 unsigned EncSize = getEncodingSize(TTypeEncoding);
608 const uint8_t *EntryP = ClassInfo - typeOffset * EncSize;
609 uintptr_t P = readEncodedPointer(&EntryP, TTypeEncoding);
610 struct OurExceptionType_t *ThisClassInfo =
611 reinterpret_cast<struct OurExceptionType_t *>(P);
612 if (ThisClassInfo->type == type) {
613 *resultAction = i + 1;
621 "handleActionValue(...):actionValue not found.\n");
626 actionPos += actionOffset;
633 /// Deals with the Language specific data portion of the emitted dwarf code.
634 /// See @link http://mentorembedded.github.com/cxx-abi/abi-eh.html @unlink
635 /// @param version unsupported (ignored), unwind version
636 /// @param lsda language specific data area
637 /// @param _Unwind_Action actions minimally supported unwind stage
638 /// (forced specifically not supported)
639 /// @param exceptionClass exception class (_Unwind_Exception::exception_class)
640 /// of thrown exception.
641 /// @param exceptionObject thrown _Unwind_Exception instance.
642 /// @param context unwind system context
643 /// @returns minimally supported unwinding control indicator
644 static _Unwind_Reason_Code handleLsda(int version,
646 _Unwind_Action actions,
647 uint64_t exceptionClass,
648 struct _Unwind_Exception *exceptionObject,
649 _Unwind_Context_t context) {
650 _Unwind_Reason_Code ret = _URC_CONTINUE_UNWIND;
657 "handleLsda(...):lsda is non-zero.\n");
660 // Get the current instruction pointer and offset it before next
661 // instruction in the current frame which threw the exception.
662 uintptr_t pc = _Unwind_GetIP(context)-1;
664 // Get beginning current frame's code (as defined by the
665 // emitted dwarf code)
666 uintptr_t funcStart = _Unwind_GetRegionStart(context);
667 uintptr_t pcOffset = pc - funcStart;
668 const uint8_t *ClassInfo = NULL;
670 // Note: See JITDwarfEmitter::EmitExceptionTable(...) for corresponding
673 // Parse LSDA header.
674 uint8_t lpStartEncoding = *lsda++;
676 if (lpStartEncoding != llvm::dwarf::DW_EH_PE_omit) {
677 readEncodedPointer(&lsda, lpStartEncoding);
680 uint8_t ttypeEncoding = *lsda++;
681 uintptr_t classInfoOffset;
683 if (ttypeEncoding != llvm::dwarf::DW_EH_PE_omit) {
684 // Calculate type info locations in emitted dwarf code which
685 // were flagged by type info arguments to llvm.eh.selector
687 classInfoOffset = readULEB128(&lsda);
688 ClassInfo = lsda + classInfoOffset;
691 // Walk call-site table looking for range that
692 // includes current PC.
694 uint8_t callSiteEncoding = *lsda++;
695 uint32_t callSiteTableLength = readULEB128(&lsda);
696 const uint8_t *callSiteTableStart = lsda;
697 const uint8_t *callSiteTableEnd = callSiteTableStart +
699 const uint8_t *actionTableStart = callSiteTableEnd;
700 const uint8_t *callSitePtr = callSiteTableStart;
702 while (callSitePtr < callSiteTableEnd) {
703 uintptr_t start = readEncodedPointer(&callSitePtr,
705 uintptr_t length = readEncodedPointer(&callSitePtr,
707 uintptr_t landingPad = readEncodedPointer(&callSitePtr,
710 // Note: Action value
711 uintptr_t actionEntry = readULEB128(&callSitePtr);
713 if (exceptionClass != ourBaseExceptionClass) {
714 // We have been notified of a foreign exception being thrown,
715 // and we therefore need to execute cleanup landing pads
719 if (landingPad == 0) {
722 "handleLsda(...): No landing pad found.\n");
725 continue; // no landing pad for this entry
729 actionEntry += ((uintptr_t) actionTableStart) - 1;
734 "handleLsda(...):No action table found.\n");
738 bool exceptionMatched = false;
740 if ((start <= pcOffset) && (pcOffset < (start + length))) {
743 "handleLsda(...): Landing pad found.\n");
745 int64_t actionValue = 0;
748 exceptionMatched = handleActionValue(&actionValue,
756 if (!(actions & _UA_SEARCH_PHASE)) {
759 "handleLsda(...): installed landing pad "
763 // Found landing pad for the PC.
764 // Set Instruction Pointer to so we re-enter function
765 // at landing pad. The landing pad is created by the
766 // compiler to take two parameters in registers.
767 _Unwind_SetGR(context,
768 __builtin_eh_return_data_regno(0),
769 (uintptr_t)exceptionObject);
771 // Note: this virtual register directly corresponds
772 // to the return of the llvm.eh.selector intrinsic
773 if (!actionEntry || !exceptionMatched) {
774 // We indicate cleanup only
775 _Unwind_SetGR(context,
776 __builtin_eh_return_data_regno(1),
780 // Matched type info index of llvm.eh.selector intrinsic
782 _Unwind_SetGR(context,
783 __builtin_eh_return_data_regno(1),
787 // To execute landing pad set here
788 _Unwind_SetIP(context, funcStart + landingPad);
789 ret = _URC_INSTALL_CONTEXT;
791 else if (exceptionMatched) {
794 "handleLsda(...): setting handler found.\n");
796 ret = _URC_HANDLER_FOUND;
799 // Note: Only non-clean up handlers are marked as
800 // found. Otherwise the clean up handlers will be
801 // re-found and executed during the clean up
805 "handleLsda(...): cleanup handler found.\n");
817 /// This is the personality function which is embedded (dwarf emitted), in the
818 /// dwarf unwind info block. Again see: JITDwarfEmitter.cpp.
819 /// See @link http://mentorembedded.github.com/cxx-abi/abi-eh.html @unlink
820 /// @param version unsupported (ignored), unwind version
821 /// @param _Unwind_Action actions minimally supported unwind stage
822 /// (forced specifically not supported)
823 /// @param exceptionClass exception class (_Unwind_Exception::exception_class)
824 /// of thrown exception.
825 /// @param exceptionObject thrown _Unwind_Exception instance.
826 /// @param context unwind system context
827 /// @returns minimally supported unwinding control indicator
828 _Unwind_Reason_Code ourPersonality(int version,
829 _Unwind_Action actions,
830 uint64_t exceptionClass,
831 struct _Unwind_Exception *exceptionObject,
832 _Unwind_Context_t context) {
835 "We are in ourPersonality(...):actions is <%d>.\n",
838 if (actions & _UA_SEARCH_PHASE) {
839 fprintf(stderr, "ourPersonality(...):In search phase.\n");
842 fprintf(stderr, "ourPersonality(...):In non-search phase.\n");
846 const uint8_t *lsda = _Unwind_GetLanguageSpecificData(context);
850 "ourPersonality(...):lsda = <%p>.\n",
854 // The real work of the personality function is captured here
855 return(handleLsda(version,
864 /// Generates our _Unwind_Exception class from a given character array.
865 /// thereby handling arbitrary lengths (not in standard), and handling
867 /// See @link http://mentorembedded.github.com/cxx-abi/abi-eh.html @unlink
868 /// @param classChars char array to encode. NULL values not checkedf
869 /// @param classCharsSize number of chars in classChars. Value is not checked.
870 /// @returns class value
871 uint64_t genClass(const unsigned char classChars[], size_t classCharsSize)
873 uint64_t ret = classChars[0];
875 for (unsigned i = 1; i < classCharsSize; ++i) {
877 ret += classChars[i];
886 // Runtime C Library functions End
890 // Code generation functions
893 /// Generates code to print given constant string
894 /// @param context llvm context
895 /// @param module code for module instance
896 /// @param builder builder instance
897 /// @param toPrint string to print
898 /// @param useGlobal A value of true (default) indicates a GlobalValue is
899 /// generated, and is used to hold the constant string. A value of
900 /// false indicates that the constant string will be stored on the
902 void generateStringPrint(llvm::LLVMContext &context,
903 llvm::Module &module,
904 llvm::IRBuilder<> &builder,
906 bool useGlobal = true) {
907 llvm::Function *printFunct = module.getFunction("printStr");
909 llvm::Value *stringVar;
910 llvm::Constant *stringConstant =
911 llvm::ConstantDataArray::getString(context, toPrint);
914 // Note: Does not work without allocation
916 new llvm::GlobalVariable(module,
917 stringConstant->getType(),
919 llvm::GlobalValue::PrivateLinkage,
924 stringVar = builder.CreateAlloca(stringConstant->getType());
925 builder.CreateStore(stringConstant, stringVar);
928 llvm::Value *cast = builder.CreatePointerCast(stringVar,
929 builder.getInt8PtrTy());
930 builder.CreateCall(printFunct, cast);
934 /// Generates code to print given runtime integer according to constant
935 /// string format, and a given print function.
936 /// @param context llvm context
937 /// @param module code for module instance
938 /// @param builder builder instance
939 /// @param printFunct function used to "print" integer
940 /// @param toPrint string to print
941 /// @param format printf like formating string for print
942 /// @param useGlobal A value of true (default) indicates a GlobalValue is
943 /// generated, and is used to hold the constant string. A value of
944 /// false indicates that the constant string will be stored on the
946 void generateIntegerPrint(llvm::LLVMContext &context,
947 llvm::Module &module,
948 llvm::IRBuilder<> &builder,
949 llvm::Function &printFunct,
950 llvm::Value &toPrint,
952 bool useGlobal = true) {
953 llvm::Constant *stringConstant =
954 llvm::ConstantDataArray::getString(context, format);
955 llvm::Value *stringVar;
958 // Note: Does not seem to work without allocation
960 new llvm::GlobalVariable(module,
961 stringConstant->getType(),
963 llvm::GlobalValue::PrivateLinkage,
968 stringVar = builder.CreateAlloca(stringConstant->getType());
969 builder.CreateStore(stringConstant, stringVar);
972 llvm::Value *cast = builder.CreateBitCast(stringVar,
973 builder.getInt8PtrTy());
974 builder.CreateCall2(&printFunct, &toPrint, cast);
978 /// Generates code to handle finally block type semantics: always runs
979 /// regardless of whether a thrown exception is passing through or the
980 /// parent function is simply exiting. In addition to printing some state
981 /// to stderr, this code will resume the exception handling--runs the
982 /// unwind resume block, if the exception has not been previously caught
983 /// by a catch clause, and will otherwise execute the end block (terminator
984 /// block). In addition this function creates the corresponding function's
985 /// stack storage for the exception pointer and catch flag status.
986 /// @param context llvm context
987 /// @param module code for module instance
988 /// @param builder builder instance
989 /// @param toAddTo parent function to add block to
990 /// @param blockName block name of new "finally" block.
991 /// @param functionId output id used for printing
992 /// @param terminatorBlock terminator "end" block
993 /// @param unwindResumeBlock unwind resume block
994 /// @param exceptionCaughtFlag reference exception caught/thrown status storage
995 /// @param exceptionStorage reference to exception pointer storage
996 /// @param caughtResultStorage reference to landingpad result storage
997 /// @returns newly created block
998 static llvm::BasicBlock *createFinallyBlock(llvm::LLVMContext &context,
999 llvm::Module &module,
1000 llvm::IRBuilder<> &builder,
1001 llvm::Function &toAddTo,
1002 std::string &blockName,
1003 std::string &functionId,
1004 llvm::BasicBlock &terminatorBlock,
1005 llvm::BasicBlock &unwindResumeBlock,
1006 llvm::Value **exceptionCaughtFlag,
1007 llvm::Value **exceptionStorage,
1008 llvm::Value **caughtResultStorage) {
1009 assert(exceptionCaughtFlag &&
1010 "ExceptionDemo::createFinallyBlock(...):exceptionCaughtFlag "
1012 assert(exceptionStorage &&
1013 "ExceptionDemo::createFinallyBlock(...):exceptionStorage "
1015 assert(caughtResultStorage &&
1016 "ExceptionDemo::createFinallyBlock(...):caughtResultStorage "
1019 *exceptionCaughtFlag = createEntryBlockAlloca(toAddTo,
1021 ourExceptionNotThrownState->getType(),
1022 ourExceptionNotThrownState);
1024 llvm::PointerType *exceptionStorageType = builder.getInt8PtrTy();
1025 *exceptionStorage = createEntryBlockAlloca(toAddTo,
1027 exceptionStorageType,
1028 llvm::ConstantPointerNull::get(
1029 exceptionStorageType));
1030 *caughtResultStorage = createEntryBlockAlloca(toAddTo,
1031 "caughtResultStorage",
1032 ourCaughtResultType,
1033 llvm::ConstantAggregateZero::get(
1034 ourCaughtResultType));
1036 llvm::BasicBlock *ret = llvm::BasicBlock::Create(context,
1040 builder.SetInsertPoint(ret);
1042 std::ostringstream bufferToPrint;
1043 bufferToPrint << "Gen: Executing finally block "
1044 << blockName << " in " << functionId << "\n";
1045 generateStringPrint(context,
1048 bufferToPrint.str(),
1049 USE_GLOBAL_STR_CONSTS);
1051 llvm::SwitchInst *theSwitch = builder.CreateSwitch(builder.CreateLoad(
1052 *exceptionCaughtFlag),
1055 theSwitch->addCase(ourExceptionCaughtState, &terminatorBlock);
1056 theSwitch->addCase(ourExceptionThrownState, &unwindResumeBlock);
1062 /// Generates catch block semantics which print a string to indicate type of
1063 /// catch executed, sets an exception caught flag, and executes passed in
1064 /// end block (terminator block).
1065 /// @param context llvm context
1066 /// @param module code for module instance
1067 /// @param builder builder instance
1068 /// @param toAddTo parent function to add block to
1069 /// @param blockName block name of new "catch" block.
1070 /// @param functionId output id used for printing
1071 /// @param terminatorBlock terminator "end" block
1072 /// @param exceptionCaughtFlag exception caught/thrown status
1073 /// @returns newly created block
1074 static llvm::BasicBlock *createCatchBlock(llvm::LLVMContext &context,
1075 llvm::Module &module,
1076 llvm::IRBuilder<> &builder,
1077 llvm::Function &toAddTo,
1078 std::string &blockName,
1079 std::string &functionId,
1080 llvm::BasicBlock &terminatorBlock,
1081 llvm::Value &exceptionCaughtFlag) {
1083 llvm::BasicBlock *ret = llvm::BasicBlock::Create(context,
1087 builder.SetInsertPoint(ret);
1089 std::ostringstream bufferToPrint;
1090 bufferToPrint << "Gen: Executing catch block "
1095 generateStringPrint(context,
1098 bufferToPrint.str(),
1099 USE_GLOBAL_STR_CONSTS);
1100 builder.CreateStore(ourExceptionCaughtState, &exceptionCaughtFlag);
1101 builder.CreateBr(&terminatorBlock);
1107 /// Generates a function which invokes a function (toInvoke) and, whose
1108 /// unwind block will "catch" the type info types correspondingly held in the
1109 /// exceptionTypesToCatch argument. If the toInvoke function throws an
1110 /// exception which does not match any type info types contained in
1111 /// exceptionTypesToCatch, the generated code will call _Unwind_Resume
1112 /// with the raised exception. On the other hand the generated code will
1113 /// normally exit if the toInvoke function does not throw an exception.
1114 /// The generated "finally" block is always run regardless of the cause of
1115 /// the generated function exit.
1116 /// The generated function is returned after being verified.
1117 /// @param module code for module instance
1118 /// @param builder builder instance
1119 /// @param fpm a function pass manager holding optional IR to IR
1121 /// @param toInvoke inner function to invoke
1122 /// @param ourId id used to printing purposes
1123 /// @param numExceptionsToCatch length of exceptionTypesToCatch array
1124 /// @param exceptionTypesToCatch array of type info types to "catch"
1125 /// @returns generated function
1126 static llvm::Function *createCatchWrappedInvokeFunction(
1127 llvm::Module &module, llvm::IRBuilder<> &builder,
1128 llvm::legacy::FunctionPassManager &fpm, llvm::Function &toInvoke,
1129 std::string ourId, unsigned numExceptionsToCatch,
1130 unsigned exceptionTypesToCatch[]) {
1132 llvm::LLVMContext &context = module.getContext();
1133 llvm::Function *toPrint32Int = module.getFunction("print32Int");
1136 argTypes.push_back(builder.getInt32Ty());
1139 argNames.push_back("exceptTypeToThrow");
1141 llvm::Function *ret = createFunction(module,
1142 builder.getVoidTy(),
1146 llvm::Function::ExternalLinkage,
1150 // Block which calls invoke
1151 llvm::BasicBlock *entryBlock = llvm::BasicBlock::Create(context,
1154 // Normal block for invoke
1155 llvm::BasicBlock *normalBlock = llvm::BasicBlock::Create(context,
1158 // Unwind block for invoke
1159 llvm::BasicBlock *exceptionBlock = llvm::BasicBlock::Create(context,
1163 // Block which routes exception to correct catch handler block
1164 llvm::BasicBlock *exceptionRouteBlock = llvm::BasicBlock::Create(context,
1168 // Foreign exception handler
1169 llvm::BasicBlock *externalExceptionBlock = llvm::BasicBlock::Create(context,
1170 "externalException",
1173 // Block which calls _Unwind_Resume
1174 llvm::BasicBlock *unwindResumeBlock = llvm::BasicBlock::Create(context,
1178 // Clean up block which delete exception if needed
1179 llvm::BasicBlock *endBlock = llvm::BasicBlock::Create(context, "end", ret);
1181 std::string nextName;
1182 std::vector<llvm::BasicBlock*> catchBlocks(numExceptionsToCatch);
1183 llvm::Value *exceptionCaughtFlag = NULL;
1184 llvm::Value *exceptionStorage = NULL;
1185 llvm::Value *caughtResultStorage = NULL;
1187 // Finally block which will branch to unwindResumeBlock if
1188 // exception is not caught. Initializes/allocates stack locations.
1189 llvm::BasicBlock *finallyBlock = createFinallyBlock(context,
1193 nextName = "finally",
1197 &exceptionCaughtFlag,
1199 &caughtResultStorage
1202 for (unsigned i = 0; i < numExceptionsToCatch; ++i) {
1203 nextName = ourTypeInfoNames[exceptionTypesToCatch[i]];
1205 // One catch block per type info to be caught
1206 catchBlocks[i] = createCatchBlock(context,
1213 *exceptionCaughtFlag);
1218 builder.SetInsertPoint(entryBlock);
1220 std::vector<llvm::Value*> args;
1221 args.push_back(namedValues["exceptTypeToThrow"]);
1222 builder.CreateInvoke(&toInvoke,
1229 builder.SetInsertPoint(endBlock);
1231 generateStringPrint(context,
1234 "Gen: In end block: exiting in " + ourId + ".\n",
1235 USE_GLOBAL_STR_CONSTS);
1236 llvm::Function *deleteOurException = module.getFunction("deleteOurException");
1238 // Note: function handles NULL exceptions
1239 builder.CreateCall(deleteOurException,
1240 builder.CreateLoad(exceptionStorage));
1241 builder.CreateRetVoid();
1245 builder.SetInsertPoint(normalBlock);
1247 generateStringPrint(context,
1250 "Gen: No exception in " + ourId + "!\n",
1251 USE_GLOBAL_STR_CONSTS);
1253 // Finally block is always called
1254 builder.CreateBr(finallyBlock);
1256 // Unwind Resume Block
1258 builder.SetInsertPoint(unwindResumeBlock);
1260 builder.CreateResume(builder.CreateLoad(caughtResultStorage));
1264 builder.SetInsertPoint(exceptionBlock);
1266 llvm::Function *personality = module.getFunction("ourPersonality");
1268 llvm::LandingPadInst *caughtResult =
1269 builder.CreateLandingPad(ourCaughtResultType,
1271 numExceptionsToCatch,
1274 caughtResult->setCleanup(true);
1276 for (unsigned i = 0; i < numExceptionsToCatch; ++i) {
1277 // Set up type infos to be caught
1278 caughtResult->addClause(module.getGlobalVariable(
1279 ourTypeInfoNames[exceptionTypesToCatch[i]]));
1282 llvm::Value *unwindException = builder.CreateExtractValue(caughtResult, 0);
1283 llvm::Value *retTypeInfoIndex = builder.CreateExtractValue(caughtResult, 1);
1285 // FIXME: Redundant storage which, beyond utilizing value of
1286 // caughtResultStore for unwindException storage, may be alleviated
1287 // altogether with a block rearrangement
1288 builder.CreateStore(caughtResult, caughtResultStorage);
1289 builder.CreateStore(unwindException, exceptionStorage);
1290 builder.CreateStore(ourExceptionThrownState, exceptionCaughtFlag);
1292 // Retrieve exception_class member from thrown exception
1293 // (_Unwind_Exception instance). This member tells us whether or not
1294 // the exception is foreign.
1295 llvm::Value *unwindExceptionClass =
1296 builder.CreateLoad(builder.CreateStructGEP(
1297 ourUnwindExceptionType,
1298 builder.CreatePointerCast(unwindException,
1299 ourUnwindExceptionType->getPointerTo()),
1302 // Branch to the externalExceptionBlock if the exception is foreign or
1303 // to a catch router if not. Either way the finally block will be run.
1304 builder.CreateCondBr(builder.CreateICmpEQ(unwindExceptionClass,
1305 llvm::ConstantInt::get(builder.getInt64Ty(),
1306 ourBaseExceptionClass)),
1307 exceptionRouteBlock,
1308 externalExceptionBlock);
1310 // External Exception Block
1312 builder.SetInsertPoint(externalExceptionBlock);
1314 generateStringPrint(context,
1317 "Gen: Foreign exception received.\n",
1318 USE_GLOBAL_STR_CONSTS);
1320 // Branch to the finally block
1321 builder.CreateBr(finallyBlock);
1323 // Exception Route Block
1325 builder.SetInsertPoint(exceptionRouteBlock);
1327 // Casts exception pointer (_Unwind_Exception instance) to parent
1328 // (OurException instance).
1330 // Note: ourBaseFromUnwindOffset is usually negative
1331 llvm::Value *typeInfoThrown = builder.CreatePointerCast(
1332 builder.CreateConstGEP1_64(unwindException,
1333 ourBaseFromUnwindOffset),
1334 ourExceptionType->getPointerTo());
1336 // Retrieve thrown exception type info type
1338 // Note: Index is not relative to pointer but instead to structure
1339 // unlike a true getelementptr (GEP) instruction
1340 typeInfoThrown = builder.CreateStructGEP(ourExceptionType, typeInfoThrown, 0);
1342 llvm::Value *typeInfoThrownType =
1343 builder.CreateStructGEP(builder.getInt8PtrTy(), typeInfoThrown, 0);
1345 generateIntegerPrint(context,
1349 *(builder.CreateLoad(typeInfoThrownType)),
1350 "Gen: Exception type <%d> received (stack unwound) "
1354 USE_GLOBAL_STR_CONSTS);
1356 // Route to matched type info catch block or run cleanup finally block
1357 llvm::SwitchInst *switchToCatchBlock = builder.CreateSwitch(retTypeInfoIndex,
1359 numExceptionsToCatch);
1361 unsigned nextTypeToCatch;
1363 for (unsigned i = 1; i <= numExceptionsToCatch; ++i) {
1364 nextTypeToCatch = i - 1;
1365 switchToCatchBlock->addCase(llvm::ConstantInt::get(
1366 llvm::Type::getInt32Ty(context), i),
1367 catchBlocks[nextTypeToCatch]);
1370 llvm::verifyFunction(*ret);
1377 /// Generates function which throws either an exception matched to a runtime
1378 /// determined type info type (argument to generated function), or if this
1379 /// runtime value matches nativeThrowType, throws a foreign exception by
1380 /// calling nativeThrowFunct.
1381 /// @param module code for module instance
1382 /// @param builder builder instance
1383 /// @param fpm a function pass manager holding optional IR to IR
1385 /// @param ourId id used to printing purposes
1386 /// @param nativeThrowType a runtime argument of this value results in
1387 /// nativeThrowFunct being called to generate/throw exception.
1388 /// @param nativeThrowFunct function which will throw a foreign exception
1389 /// if the above nativeThrowType matches generated function's arg.
1390 /// @returns generated function
1391 static llvm::Function *
1392 createThrowExceptionFunction(llvm::Module &module, llvm::IRBuilder<> &builder,
1393 llvm::legacy::FunctionPassManager &fpm,
1394 std::string ourId, int32_t nativeThrowType,
1395 llvm::Function &nativeThrowFunct) {
1396 llvm::LLVMContext &context = module.getContext();
1397 namedValues.clear();
1398 ArgTypes unwindArgTypes;
1399 unwindArgTypes.push_back(builder.getInt32Ty());
1400 ArgNames unwindArgNames;
1401 unwindArgNames.push_back("exceptTypeToThrow");
1403 llvm::Function *ret = createFunction(module,
1404 builder.getVoidTy(),
1408 llvm::Function::ExternalLinkage,
1412 // Throws either one of our exception or a native C++ exception depending
1413 // on a runtime argument value containing a type info type.
1414 llvm::BasicBlock *entryBlock = llvm::BasicBlock::Create(context,
1417 // Throws a foreign exception
1418 llvm::BasicBlock *nativeThrowBlock = llvm::BasicBlock::Create(context,
1421 // Throws one of our Exceptions
1422 llvm::BasicBlock *generatedThrowBlock = llvm::BasicBlock::Create(context,
1425 // Retrieved runtime type info type to throw
1426 llvm::Value *exceptionType = namedValues["exceptTypeToThrow"];
1428 // nativeThrowBlock block
1430 builder.SetInsertPoint(nativeThrowBlock);
1432 // Throws foreign exception
1433 builder.CreateCall(&nativeThrowFunct, exceptionType);
1434 builder.CreateUnreachable();
1438 builder.SetInsertPoint(entryBlock);
1440 llvm::Function *toPrint32Int = module.getFunction("print32Int");
1441 generateIntegerPrint(context,
1446 "\nGen: About to throw exception type <%d> in " +
1449 USE_GLOBAL_STR_CONSTS);
1451 // Switches on runtime type info type value to determine whether or not
1452 // a foreign exception is thrown. Defaults to throwing one of our
1453 // generated exceptions.
1454 llvm::SwitchInst *theSwitch = builder.CreateSwitch(exceptionType,
1455 generatedThrowBlock,
1458 theSwitch->addCase(llvm::ConstantInt::get(llvm::Type::getInt32Ty(context),
1462 // generatedThrow block
1464 builder.SetInsertPoint(generatedThrowBlock);
1466 llvm::Function *createOurException = module.getFunction("createOurException");
1467 llvm::Function *raiseOurException = module.getFunction(
1468 "_Unwind_RaiseException");
1470 // Creates exception to throw with runtime type info type.
1471 llvm::Value *exception = builder.CreateCall(createOurException,
1472 namedValues["exceptTypeToThrow"]);
1474 // Throw generated Exception
1475 builder.CreateCall(raiseOurException, exception);
1476 builder.CreateUnreachable();
1478 llvm::verifyFunction(*ret);
1484 static void createStandardUtilityFunctions(unsigned numTypeInfos,
1485 llvm::Module &module,
1486 llvm::IRBuilder<> &builder);
1488 /// Creates test code by generating and organizing these functions into the
1489 /// test case. The test case consists of an outer function setup to invoke
1490 /// an inner function within an environment having multiple catch and single
1491 /// finally blocks. This inner function is also setup to invoke a throw
1492 /// function within an evironment similar in nature to the outer function's
1493 /// catch and finally blocks. Each of these two functions catch mutually
1494 /// exclusive subsets (even or odd) of the type info types configured
1495 /// for this this. All generated functions have a runtime argument which
1496 /// holds a type info type to throw that each function takes and passes it
1497 /// to the inner one if such a inner function exists. This type info type is
1498 /// looked at by the generated throw function to see whether or not it should
1499 /// throw a generated exception with the same type info type, or instead call
1500 /// a supplied a function which in turn will throw a foreign exception.
1501 /// @param module code for module instance
1502 /// @param builder builder instance
1503 /// @param fpm a function pass manager holding optional IR to IR
1505 /// @param nativeThrowFunctName name of external function which will throw
1506 /// a foreign exception
1507 /// @returns outermost generated test function.
1509 createUnwindExceptionTest(llvm::Module &module, llvm::IRBuilder<> &builder,
1510 llvm::legacy::FunctionPassManager &fpm,
1511 std::string nativeThrowFunctName) {
1512 // Number of type infos to generate
1513 unsigned numTypeInfos = 6;
1515 // Initialze intrisics and external functions to use along with exception
1516 // and type info globals.
1517 createStandardUtilityFunctions(numTypeInfos,
1520 llvm::Function *nativeThrowFunct = module.getFunction(nativeThrowFunctName);
1522 // Create exception throw function using the value ~0 to cause
1523 // foreign exceptions to be thrown.
1524 llvm::Function *throwFunct = createThrowExceptionFunction(module,
1530 // Inner function will catch even type infos
1531 unsigned innerExceptionTypesToCatch[] = {6, 2, 4};
1532 size_t numExceptionTypesToCatch = sizeof(innerExceptionTypesToCatch) /
1535 // Generate inner function.
1536 llvm::Function *innerCatchFunct = createCatchWrappedInvokeFunction(module,
1541 numExceptionTypesToCatch,
1542 innerExceptionTypesToCatch);
1544 // Outer function will catch odd type infos
1545 unsigned outerExceptionTypesToCatch[] = {3, 1, 5};
1546 numExceptionTypesToCatch = sizeof(outerExceptionTypesToCatch) /
1549 // Generate outer function
1550 llvm::Function *outerCatchFunct = createCatchWrappedInvokeFunction(module,
1555 numExceptionTypesToCatch,
1556 outerExceptionTypesToCatch);
1558 // Return outer function to run
1559 return(outerCatchFunct);
1563 /// Represents our foreign exceptions
1564 class OurCppRunException : public std::runtime_error {
1566 OurCppRunException(const std::string reason) :
1567 std::runtime_error(reason) {}
1569 OurCppRunException (const OurCppRunException &toCopy) :
1570 std::runtime_error(toCopy) {}
1572 OurCppRunException &operator = (const OurCppRunException &toCopy) {
1573 return(reinterpret_cast<OurCppRunException&>(
1574 std::runtime_error::operator=(toCopy)));
1577 ~OurCppRunException(void) throw() override {}
1579 } // end anonymous namespace
1581 /// Throws foreign C++ exception.
1582 /// @param ignoreIt unused parameter that allows function to match implied
1583 /// generated function contract.
1585 void throwCppException (int32_t ignoreIt) {
1586 throw(OurCppRunException("thrown by throwCppException(...)"));
1589 typedef void (*OurExceptionThrowFunctType) (int32_t typeToThrow);
1591 /// This is a test harness which runs test by executing generated
1592 /// function with a type info type to throw. Harness wraps the execution
1593 /// of generated function in a C++ try catch clause.
1594 /// @param engine execution engine to use for executing generated function.
1595 /// This demo program expects this to be a JIT instance for demo
1597 /// @param function generated test function to run
1598 /// @param typeToThrow type info type of generated exception to throw, or
1599 /// indicator to cause foreign exception to be thrown.
1601 void runExceptionThrow(llvm::ExecutionEngine *engine,
1602 llvm::Function *function,
1603 int32_t typeToThrow) {
1605 // Find test's function pointer
1606 OurExceptionThrowFunctType functPtr =
1607 reinterpret_cast<OurExceptionThrowFunctType>(
1608 reinterpret_cast<intptr_t>(engine->getPointerToFunction(function)));
1612 (*functPtr)(typeToThrow);
1614 catch (OurCppRunException exc) {
1615 // Catch foreign C++ exception
1617 "\nrunExceptionThrow(...):In C++ catch OurCppRunException "
1618 "with reason: %s.\n",
1622 // Catch all exceptions including our generated ones. This latter
1623 // functionality works according to the example in rules 1.6.4 of
1624 // http://mentorembedded.github.com/cxx-abi/abi-eh.html (v1.22),
1625 // given that these will be exceptions foreign to C++
1626 // (the _Unwind_Exception::exception_class should be different from
1627 // the one used by C++).
1629 "\nrunExceptionThrow(...):In C++ catch all.\n");
1634 // End test functions
1637 typedef llvm::ArrayRef<llvm::Type*> TypeArray;
1639 /// This initialization routine creates type info globals and
1640 /// adds external function declarations to module.
1641 /// @param numTypeInfos number of linear type info associated type info types
1642 /// to create as GlobalVariable instances, starting with the value 1.
1643 /// @param module code for module instance
1644 /// @param builder builder instance
1645 static void createStandardUtilityFunctions(unsigned numTypeInfos,
1646 llvm::Module &module,
1647 llvm::IRBuilder<> &builder) {
1649 llvm::LLVMContext &context = module.getContext();
1651 // Exception initializations
1653 // Setup exception catch state
1654 ourExceptionNotThrownState =
1655 llvm::ConstantInt::get(llvm::Type::getInt8Ty(context), 0),
1656 ourExceptionThrownState =
1657 llvm::ConstantInt::get(llvm::Type::getInt8Ty(context), 1),
1658 ourExceptionCaughtState =
1659 llvm::ConstantInt::get(llvm::Type::getInt8Ty(context), 2),
1663 // Create our type info type
1664 ourTypeInfoType = llvm::StructType::get(context,
1665 TypeArray(builder.getInt32Ty()));
1667 llvm::Type *caughtResultFieldTypes[] = {
1668 builder.getInt8PtrTy(),
1669 builder.getInt32Ty()
1672 // Create our landingpad result type
1673 ourCaughtResultType = llvm::StructType::get(context,
1674 TypeArray(caughtResultFieldTypes));
1676 // Create OurException type
1677 ourExceptionType = llvm::StructType::get(context,
1678 TypeArray(ourTypeInfoType));
1680 // Create portion of _Unwind_Exception type
1682 // Note: Declaring only a portion of the _Unwind_Exception struct.
1683 // Does this cause problems?
1684 ourUnwindExceptionType =
1685 llvm::StructType::get(context,
1686 TypeArray(builder.getInt64Ty()));
1688 struct OurBaseException_t dummyException;
1690 // Calculate offset of OurException::unwindException member.
1691 ourBaseFromUnwindOffset = ((uintptr_t) &dummyException) -
1692 ((uintptr_t) &(dummyException.unwindException));
1696 "createStandardUtilityFunctions(...):ourBaseFromUnwindOffset "
1697 "= %lld, sizeof(struct OurBaseException_t) - "
1698 "sizeof(struct _Unwind_Exception) = %lu.\n",
1699 ourBaseFromUnwindOffset,
1700 sizeof(struct OurBaseException_t) -
1701 sizeof(struct _Unwind_Exception));
1704 size_t numChars = sizeof(ourBaseExcpClassChars) / sizeof(char);
1706 // Create our _Unwind_Exception::exception_class value
1707 ourBaseExceptionClass = genClass(ourBaseExcpClassChars, numChars);
1711 std::string baseStr = "typeInfo", typeInfoName;
1712 std::ostringstream typeInfoNameBuilder;
1713 std::vector<llvm::Constant*> structVals;
1715 llvm::Constant *nextStruct;
1717 // Generate each type info
1719 // Note: First type info is not used.
1720 for (unsigned i = 0; i <= numTypeInfos; ++i) {
1722 structVals.push_back(llvm::ConstantInt::get(builder.getInt32Ty(), i));
1723 nextStruct = llvm::ConstantStruct::get(ourTypeInfoType, structVals);
1725 typeInfoNameBuilder.str("");
1726 typeInfoNameBuilder << baseStr << i;
1727 typeInfoName = typeInfoNameBuilder.str();
1729 // Note: Does not seem to work without allocation
1730 new llvm::GlobalVariable(module,
1733 llvm::GlobalValue::ExternalLinkage,
1737 ourTypeInfoNames.push_back(typeInfoName);
1738 ourTypeInfoNamesIndex[i] = typeInfoName;
1743 llvm::Function *funct = NULL;
1747 llvm::Type *retType = builder.getVoidTy();
1750 argTypes.push_back(builder.getInt32Ty());
1751 argTypes.push_back(builder.getInt8PtrTy());
1755 createFunction(module,
1760 llvm::Function::ExternalLinkage,
1766 retType = builder.getVoidTy();
1769 argTypes.push_back(builder.getInt64Ty());
1770 argTypes.push_back(builder.getInt8PtrTy());
1774 createFunction(module,
1779 llvm::Function::ExternalLinkage,
1785 retType = builder.getVoidTy();
1788 argTypes.push_back(builder.getInt8PtrTy());
1792 createFunction(module,
1797 llvm::Function::ExternalLinkage,
1801 // throwCppException
1803 retType = builder.getVoidTy();
1806 argTypes.push_back(builder.getInt32Ty());
1810 createFunction(module,
1814 "throwCppException",
1815 llvm::Function::ExternalLinkage,
1819 // deleteOurException
1821 retType = builder.getVoidTy();
1824 argTypes.push_back(builder.getInt8PtrTy());
1828 createFunction(module,
1832 "deleteOurException",
1833 llvm::Function::ExternalLinkage,
1837 // createOurException
1839 retType = builder.getInt8PtrTy();
1842 argTypes.push_back(builder.getInt32Ty());
1846 createFunction(module,
1850 "createOurException",
1851 llvm::Function::ExternalLinkage,
1855 // _Unwind_RaiseException
1857 retType = builder.getInt32Ty();
1860 argTypes.push_back(builder.getInt8PtrTy());
1864 funct = createFunction(module,
1868 "_Unwind_RaiseException",
1869 llvm::Function::ExternalLinkage,
1873 funct->setDoesNotReturn();
1877 retType = builder.getInt32Ty();
1880 argTypes.push_back(builder.getInt8PtrTy());
1884 funct = createFunction(module,
1889 llvm::Function::ExternalLinkage,
1893 funct->setDoesNotReturn();
1897 retType = builder.getInt32Ty();
1900 argTypes.push_back(builder.getInt32Ty());
1901 argTypes.push_back(builder.getInt32Ty());
1902 argTypes.push_back(builder.getInt64Ty());
1903 argTypes.push_back(builder.getInt8PtrTy());
1904 argTypes.push_back(builder.getInt8PtrTy());
1908 createFunction(module,
1913 llvm::Function::ExternalLinkage,
1917 // llvm.eh.typeid.for intrinsic
1919 getDeclaration(&module, llvm::Intrinsic::eh_typeid_for);
1923 //===----------------------------------------------------------------------===//
1924 // Main test driver code.
1925 //===----------------------------------------------------------------------===//
1927 /// Demo main routine which takes the type info types to throw. A test will
1928 /// be run for each given type info type. While type info types with the value
1929 /// of -1 will trigger a foreign C++ exception to be thrown; type info types
1930 /// <= 6 and >= 1 will be caught by test functions; and type info types > 6
1931 /// will result in exceptions which pass through to the test harness. All other
1932 /// type info types are not supported and could cause a crash.
1933 int main(int argc, char *argv[]) {
1936 "\nUsage: ExceptionDemo <exception type to throw> "
1937 "[<type 2>...<type n>].\n"
1938 " Each type must have the value of 1 - 6 for "
1939 "generated exceptions to be caught;\n"
1940 " the value -1 for foreign C++ exceptions to be "
1941 "generated and thrown;\n"
1942 " or the values > 6 for exceptions to be ignored.\n"
1943 "\nTry: ExceptionDemo 2 3 7 -1\n"
1944 " for a full test.\n\n");
1948 // If not set, exception handling will not be turned on
1949 llvm::TargetOptions Opts;
1951 llvm::InitializeNativeTarget();
1952 llvm::InitializeNativeTargetAsmPrinter();
1953 llvm::LLVMContext &context = llvm::getGlobalContext();
1954 llvm::IRBuilder<> theBuilder(context);
1956 // Make the module, which holds all the code.
1957 std::unique_ptr<llvm::Module> Owner =
1958 llvm::make_unique<llvm::Module>("my cool jit", context);
1959 llvm::Module *module = Owner.get();
1961 std::unique_ptr<llvm::RTDyldMemoryManager> MemMgr(new llvm::SectionMemoryManager());
1963 // Build engine with JIT
1964 llvm::EngineBuilder factory(std::move(Owner));
1965 factory.setEngineKind(llvm::EngineKind::JIT);
1966 factory.setTargetOptions(Opts);
1967 factory.setMCJITMemoryManager(std::move(MemMgr));
1968 llvm::ExecutionEngine *executionEngine = factory.create();
1971 llvm::legacy::FunctionPassManager fpm(module);
1973 // Set up the optimizer pipeline.
1974 // Start with registering info about how the
1975 // target lays out data structures.
1976 module->setDataLayout(*executionEngine->getDataLayout());
1978 // Optimizations turned on
1979 #ifdef ADD_OPT_PASSES
1981 // Basic AliasAnslysis support for GVN.
1982 fpm.add(llvm::createBasicAliasAnalysisPass());
1984 // Promote allocas to registers.
1985 fpm.add(llvm::createPromoteMemoryToRegisterPass());
1987 // Do simple "peephole" optimizations and bit-twiddling optzns.
1988 fpm.add(llvm::createInstructionCombiningPass());
1990 // Reassociate expressions.
1991 fpm.add(llvm::createReassociatePass());
1993 // Eliminate Common SubExpressions.
1994 fpm.add(llvm::createGVNPass());
1996 // Simplify the control flow graph (deleting unreachable
1998 fpm.add(llvm::createCFGSimplificationPass());
1999 #endif // ADD_OPT_PASSES
2001 fpm.doInitialization();
2003 // Generate test code using function throwCppException(...) as
2004 // the function which throws foreign exceptions.
2005 llvm::Function *toRun =
2006 createUnwindExceptionTest(*module,
2009 "throwCppException");
2011 executionEngine->finalizeObject();
2013 fprintf(stderr, "\nBegin module dump:\n\n");
2017 fprintf(stderr, "\nEnd module dump:\n");
2019 fprintf(stderr, "\n\nBegin Test:\n");
2021 for (int i = 1; i < argc; ++i) {
2022 // Run test for each argument whose value is the exception
2024 runExceptionThrow(executionEngine,
2026 (unsigned) strtoul(argv[i], NULL, 10));
2029 fprintf(stderr, "\nEnd Test:\n\n");
2032 delete executionEngine;