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 questionable.
45 // This code uses code from the llvm compiler-rt project and the llvm
46 // Kaleidoscope project.
48 //===----------------------------------------------------------------------===//
50 #include "llvm/LLVMContext.h"
51 #include "llvm/DerivedTypes.h"
52 #include "llvm/ExecutionEngine/ExecutionEngine.h"
53 #include "llvm/ExecutionEngine/JIT.h"
54 #include "llvm/Module.h"
55 #include "llvm/PassManager.h"
56 #include "llvm/Intrinsics.h"
57 #include "llvm/Analysis/Verifier.h"
58 #include "llvm/Target/TargetData.h"
59 #include "llvm/Target/TargetSelect.h"
60 #include "llvm/Target/TargetOptions.h"
61 #include "llvm/Transforms/Scalar.h"
62 #include "llvm/Support/IRBuilder.h"
63 #include "llvm/Support/Dwarf.h"
65 // FIXME: Although all systems tested with (Linux, OS X), do not need this
66 // header file included. A user on ubuntu reported, undefined symbols
67 // for stderr, and fprintf, and the addition of this include fixed the
68 // issue for them. Given that LLVM's best practices include the goal
69 // of reducing the number of redundant header files included, the
70 // correct solution would be to find out why these symbols are not
71 // defined for the system in question, and fix the issue by finding out
72 // which LLVM header file, if any, would include these symbols.
79 #ifndef USE_GLOBAL_STR_CONSTS
80 #define USE_GLOBAL_STR_CONSTS true
83 // System C++ ABI unwind types from:
84 // http://refspecs.freestandards.org/abi-eh-1.21.html
90 _URC_FOREIGN_EXCEPTION_CAUGHT = 1,
91 _URC_FATAL_PHASE2_ERROR = 2,
92 _URC_FATAL_PHASE1_ERROR = 3,
94 _URC_END_OF_STACK = 5,
95 _URC_HANDLER_FOUND = 6,
96 _URC_INSTALL_CONTEXT = 7,
97 _URC_CONTINUE_UNWIND = 8
98 } _Unwind_Reason_Code;
101 _UA_SEARCH_PHASE = 1,
102 _UA_CLEANUP_PHASE = 2,
103 _UA_HANDLER_FRAME = 4,
104 _UA_FORCE_UNWIND = 8,
105 _UA_END_OF_STACK = 16
108 struct _Unwind_Exception;
110 typedef void (*_Unwind_Exception_Cleanup_Fn) (_Unwind_Reason_Code,
111 struct _Unwind_Exception *);
113 struct _Unwind_Exception {
114 uint64_t exception_class;
115 _Unwind_Exception_Cleanup_Fn exception_cleanup;
120 // @@@ The IA-64 ABI says that this structure must be double-word aligned.
121 // Taking that literally does not make much sense generically. Instead
122 // we provide the maximum alignment required by any type for the machine.
123 } __attribute__((__aligned__));
125 struct _Unwind_Context;
126 typedef struct _Unwind_Context *_Unwind_Context_t;
128 extern const uint8_t *_Unwind_GetLanguageSpecificData (_Unwind_Context_t c);
129 extern uintptr_t _Unwind_GetGR (_Unwind_Context_t c, int i);
130 extern void _Unwind_SetGR (_Unwind_Context_t c, int i, uintptr_t n);
131 extern void _Unwind_SetIP (_Unwind_Context_t, uintptr_t new_value);
132 extern uintptr_t _Unwind_GetIP (_Unwind_Context_t context);
133 extern uintptr_t _Unwind_GetRegionStart (_Unwind_Context_t context);
141 /// This is our simplistic type info
142 struct OurExceptionType_t {
148 /// This is our Exception class which relies on a negative offset to calculate
149 /// pointers to its instances from pointers to its unwindException member.
151 /// Note: The above unwind.h defines struct _Unwind_Exception to be aligned
152 /// on a double word boundary. This is necessary to match the standard:
153 /// http://refspecs.freestandards.org/abi-eh-1.21.html
154 struct OurBaseException_t {
155 struct OurExceptionType_t type;
157 // Note: This is properly aligned in unwind.h
158 struct _Unwind_Exception unwindException;
162 // Note: Not needed since we are C++
163 typedef struct OurBaseException_t OurException;
164 typedef struct _Unwind_Exception OurUnwindException;
167 // Various globals used to support typeinfo and generatted exceptions in
171 static std::map<std::string, llvm::Value*> namedValues;
173 int64_t ourBaseFromUnwindOffset;
175 const unsigned char ourBaseExcpClassChars[] =
176 {'o', 'b', 'j', '\0', 'b', 'a', 's', '\0'};
179 static uint64_t ourBaseExceptionClass = 0;
181 static std::vector<std::string> ourTypeInfoNames;
182 static std::map<int, std::string> ourTypeInfoNamesIndex;
184 static llvm::StructType *ourTypeInfoType;
185 static llvm::StructType *ourExceptionType;
186 static llvm::StructType *ourUnwindExceptionType;
188 static llvm::ConstantInt *ourExceptionNotThrownState;
189 static llvm::ConstantInt *ourExceptionThrownState;
190 static llvm::ConstantInt *ourExceptionCaughtState;
192 typedef std::vector<std::string> ArgNames;
193 typedef std::vector<llvm::Type*> ArgTypes;
196 // Code Generation Utilities
199 /// Utility used to create a function, both declarations and definitions
200 /// @param module for module instance
201 /// @param retType function return type
202 /// @param theArgTypes function's ordered argument types
203 /// @param theArgNames function's ordered arguments needed if use of this
204 /// function corresponds to a function definition. Use empty
205 /// aggregate for function declarations.
206 /// @param functName function name
207 /// @param linkage function linkage
208 /// @param declarationOnly for function declarations
209 /// @param isVarArg function uses vararg arguments
210 /// @returns function instance
211 llvm::Function *createFunction(llvm::Module &module,
213 const ArgTypes &theArgTypes,
214 const ArgNames &theArgNames,
215 const std::string &functName,
216 llvm::GlobalValue::LinkageTypes linkage,
217 bool declarationOnly,
219 llvm::FunctionType *functType =
220 llvm::FunctionType::get(retType, theArgTypes, isVarArg);
221 llvm::Function *ret =
222 llvm::Function::Create(functType, linkage, functName, &module);
223 if (!ret || declarationOnly)
228 for (llvm::Function::arg_iterator argIndex = ret->arg_begin();
229 i != theArgNames.size();
232 argIndex->setName(theArgNames[i]);
233 namedValues[theArgNames[i]] = argIndex;
240 /// Create an alloca instruction in the entry block of
241 /// the parent function. This is used for mutable variables etc.
242 /// @param function parent instance
243 /// @param varName stack variable name
244 /// @param type stack variable type
245 /// @param initWith optional constant initialization value
246 /// @returns AllocaInst instance
247 static llvm::AllocaInst *createEntryBlockAlloca(llvm::Function &function,
248 const std::string &varName,
250 llvm::Constant *initWith = 0) {
251 llvm::BasicBlock &block = function.getEntryBlock();
252 llvm::IRBuilder<> tmp(&block, block.begin());
253 llvm::AllocaInst *ret = tmp.CreateAlloca(type, 0, varName.c_str());
256 tmp.CreateStore(initWith, ret);
263 // Code Generation Utilities End
267 // Runtime C Library functions
270 // Note: using an extern "C" block so that static functions can be used
273 // Note: Better ways to decide on bit width
275 /// Prints a 32 bit number, according to the format, to stderr.
276 /// @param intToPrint integer to print
277 /// @param format printf like format to use when printing
278 void print32Int(int intToPrint, const char *format) {
280 // Note: No NULL check
281 fprintf(stderr, format, intToPrint);
284 // Note: No NULL check
285 fprintf(stderr, "::print32Int(...):NULL arg.\n");
290 // Note: Better ways to decide on bit width
292 /// Prints a 64 bit number, according to the format, to stderr.
293 /// @param intToPrint integer to print
294 /// @param format printf like format to use when printing
295 void print64Int(long int intToPrint, const char *format) {
297 // Note: No NULL check
298 fprintf(stderr, format, intToPrint);
301 // Note: No NULL check
302 fprintf(stderr, "::print64Int(...):NULL arg.\n");
307 /// Prints a C string to stderr
308 /// @param toPrint string to print
309 void printStr(char *toPrint) {
311 fprintf(stderr, "%s", toPrint);
314 fprintf(stderr, "::printStr(...):NULL arg.\n");
319 /// Deletes the true previosly allocated exception whose address
320 /// is calculated from the supplied OurBaseException_t::unwindException
321 /// member address. Handles (ignores), NULL pointers.
322 /// @param expToDelete exception to delete
323 void deleteOurException(OurUnwindException *expToDelete) {
326 "deleteOurException(...).\n");
330 (expToDelete->exception_class == ourBaseExceptionClass)) {
332 free(((char*) expToDelete) + ourBaseFromUnwindOffset);
337 /// This function is the struct _Unwind_Exception API mandated delete function
338 /// used by foreign exception handlers when deleting our exception
339 /// (OurException), instances.
340 /// @param reason @link http://refspecs.freestandards.org/abi-eh-1.21.html
342 /// @param expToDelete exception instance to delete
343 void deleteFromUnwindOurException(_Unwind_Reason_Code reason,
344 OurUnwindException *expToDelete) {
347 "deleteFromUnwindOurException(...).\n");
350 deleteOurException(expToDelete);
354 /// Creates (allocates on the heap), an exception (OurException instance),
355 /// of the supplied type info type.
356 /// @param type type info type
357 OurUnwindException *createOurException(int type) {
358 size_t size = sizeof(OurException);
359 OurException *ret = (OurException*) memset(malloc(size), 0, size);
360 (ret->type).type = type;
361 (ret->unwindException).exception_class = ourBaseExceptionClass;
362 (ret->unwindException).exception_cleanup = deleteFromUnwindOurException;
364 return(&(ret->unwindException));
368 /// Read a uleb128 encoded value and advance pointer
369 /// See Variable Length Data in:
370 /// @link http://dwarfstd.org/Dwarf3.pdf @unlink
371 /// @param data reference variable holding memory pointer to decode from
372 /// @returns decoded value
373 static uintptr_t readULEB128(const uint8_t **data) {
374 uintptr_t result = 0;
377 const uint8_t *p = *data;
381 result |= (byte & 0x7f) << shift;
392 /// Read a sleb128 encoded value and advance pointer
393 /// See Variable Length Data in:
394 /// @link http://dwarfstd.org/Dwarf3.pdf @unlink
395 /// @param data reference variable holding memory pointer to decode from
396 /// @returns decoded value
397 static uintptr_t readSLEB128(const uint8_t **data) {
398 uintptr_t result = 0;
401 const uint8_t *p = *data;
405 result |= (byte & 0x7f) << shift;
412 if ((byte & 0x40) && (shift < (sizeof(result) << 3))) {
413 result |= (~0 << shift);
420 /// Read a pointer encoded value and advance pointer
421 /// See Variable Length Data in:
422 /// @link http://dwarfstd.org/Dwarf3.pdf @unlink
423 /// @param data reference variable holding memory pointer to decode from
424 /// @param encoding dwarf encoding type
425 /// @returns decoded value
426 static uintptr_t readEncodedPointer(const uint8_t **data, uint8_t encoding) {
427 uintptr_t result = 0;
428 const uint8_t *p = *data;
430 if (encoding == llvm::dwarf::DW_EH_PE_omit)
434 switch (encoding & 0x0F) {
435 case llvm::dwarf::DW_EH_PE_absptr:
436 result = *((uintptr_t*)p);
437 p += sizeof(uintptr_t);
439 case llvm::dwarf::DW_EH_PE_uleb128:
440 result = readULEB128(&p);
442 // Note: This case has not been tested
443 case llvm::dwarf::DW_EH_PE_sleb128:
444 result = readSLEB128(&p);
446 case llvm::dwarf::DW_EH_PE_udata2:
447 result = *((uint16_t*)p);
448 p += sizeof(uint16_t);
450 case llvm::dwarf::DW_EH_PE_udata4:
451 result = *((uint32_t*)p);
452 p += sizeof(uint32_t);
454 case llvm::dwarf::DW_EH_PE_udata8:
455 result = *((uint64_t*)p);
456 p += sizeof(uint64_t);
458 case llvm::dwarf::DW_EH_PE_sdata2:
459 result = *((int16_t*)p);
460 p += sizeof(int16_t);
462 case llvm::dwarf::DW_EH_PE_sdata4:
463 result = *((int32_t*)p);
464 p += sizeof(int32_t);
466 case llvm::dwarf::DW_EH_PE_sdata8:
467 result = *((int64_t*)p);
468 p += sizeof(int64_t);
476 // then add relative offset
477 switch (encoding & 0x70) {
478 case llvm::dwarf::DW_EH_PE_absptr:
481 case llvm::dwarf::DW_EH_PE_pcrel:
482 result += (uintptr_t)(*data);
484 case llvm::dwarf::DW_EH_PE_textrel:
485 case llvm::dwarf::DW_EH_PE_datarel:
486 case llvm::dwarf::DW_EH_PE_funcrel:
487 case llvm::dwarf::DW_EH_PE_aligned:
494 // then apply indirection
495 if (encoding & llvm::dwarf::DW_EH_PE_indirect) {
496 result = *((uintptr_t*)result);
505 /// Deals with Dwarf actions matching our type infos
506 /// (OurExceptionType_t instances). Returns whether or not a dwarf emitted
507 /// action matches the supplied exception type. If such a match succeeds,
508 /// the resultAction argument will be set with > 0 index value. Only
509 /// corresponding llvm.eh.selector type info arguments, cleanup arguments
510 /// are supported. Filters are not supported.
511 /// See Variable Length Data in:
512 /// @link http://dwarfstd.org/Dwarf3.pdf @unlink
513 /// Also see @link http://refspecs.freestandards.org/abi-eh-1.21.html @unlink
514 /// @param resultAction reference variable which will be set with result
515 /// @param classInfo our array of type info pointers (to globals)
516 /// @param actionEntry index into above type info array or 0 (clean up).
517 /// We do not support filters.
518 /// @param exceptionClass exception class (_Unwind_Exception::exception_class)
519 /// of thrown exception.
520 /// @param exceptionObject thrown _Unwind_Exception instance.
521 /// @returns whether or not a type info was found. False is returned if only
522 /// a cleanup was found
523 static bool handleActionValue(int64_t *resultAction,
524 struct OurExceptionType_t **classInfo,
525 uintptr_t actionEntry,
526 uint64_t exceptionClass,
527 struct _Unwind_Exception *exceptionObject) {
532 (exceptionClass != ourBaseExceptionClass))
535 struct OurBaseException_t *excp = (struct OurBaseException_t*)
536 (((char*) exceptionObject) + ourBaseFromUnwindOffset);
537 struct OurExceptionType_t *excpType = &(excp->type);
538 int type = excpType->type;
542 "handleActionValue(...): exceptionObject = <%p>, "
548 const uint8_t *actionPos = (uint8_t*) actionEntry,
550 int64_t typeOffset = 0,
553 for (int i = 0; true; ++i) {
554 // Each emitted dwarf action corresponds to a 2 tuple of
555 // type info address offset, and action offset to the next
557 typeOffset = readSLEB128(&actionPos);
558 tempActionPos = actionPos;
559 actionOffset = readSLEB128(&tempActionPos);
563 "handleActionValue(...):typeOffset: <%lld>, "
564 "actionOffset: <%lld>.\n",
568 assert((typeOffset >= 0) &&
569 "handleActionValue(...):filters are not supported.");
571 // Note: A typeOffset == 0 implies that a cleanup llvm.eh.selector
572 // argument has been matched.
573 if ((typeOffset > 0) &&
574 (type == (classInfo[-typeOffset])->type)) {
577 "handleActionValue(...):actionValue <%d> found.\n",
580 *resultAction = i + 1;
587 "handleActionValue(...):actionValue not found.\n");
592 actionPos += actionOffset;
599 /// Deals with the Language specific data portion of the emitted dwarf code.
600 /// See @link http://refspecs.freestandards.org/abi-eh-1.21.html @unlink
601 /// @param version unsupported (ignored), unwind version
602 /// @param lsda language specific data area
603 /// @param _Unwind_Action actions minimally supported unwind stage
604 /// (forced specifically not supported)
605 /// @param exceptionClass exception class (_Unwind_Exception::exception_class)
606 /// of thrown exception.
607 /// @param exceptionObject thrown _Unwind_Exception instance.
608 /// @param context unwind system context
609 /// @returns minimally supported unwinding control indicator
610 static _Unwind_Reason_Code handleLsda(int version,
612 _Unwind_Action actions,
613 uint64_t exceptionClass,
614 struct _Unwind_Exception *exceptionObject,
615 _Unwind_Context_t context) {
616 _Unwind_Reason_Code ret = _URC_CONTINUE_UNWIND;
623 "handleLsda(...):lsda is non-zero.\n");
626 // Get the current instruction pointer and offset it before next
627 // instruction in the current frame which threw the exception.
628 uintptr_t pc = _Unwind_GetIP(context)-1;
630 // Get beginning current frame's code (as defined by the
631 // emitted dwarf code)
632 uintptr_t funcStart = _Unwind_GetRegionStart(context);
633 uintptr_t pcOffset = pc - funcStart;
634 struct OurExceptionType_t **classInfo = NULL;
636 // Note: See JITDwarfEmitter::EmitExceptionTable(...) for corresponding
639 // Parse LSDA header.
640 uint8_t lpStartEncoding = *lsda++;
642 if (lpStartEncoding != llvm::dwarf::DW_EH_PE_omit) {
643 readEncodedPointer(&lsda, lpStartEncoding);
646 uint8_t ttypeEncoding = *lsda++;
647 uintptr_t classInfoOffset;
649 if (ttypeEncoding != llvm::dwarf::DW_EH_PE_omit) {
650 // Calculate type info locations in emitted dwarf code which
651 // were flagged by type info arguments to llvm.eh.selector
653 classInfoOffset = readULEB128(&lsda);
654 classInfo = (struct OurExceptionType_t**) (lsda + classInfoOffset);
657 // Walk call-site table looking for range that
658 // includes current PC.
660 uint8_t callSiteEncoding = *lsda++;
661 uint32_t callSiteTableLength = readULEB128(&lsda);
662 const uint8_t *callSiteTableStart = lsda;
663 const uint8_t *callSiteTableEnd = callSiteTableStart +
665 const uint8_t *actionTableStart = callSiteTableEnd;
666 const uint8_t *callSitePtr = callSiteTableStart;
668 bool foreignException = false;
670 while (callSitePtr < callSiteTableEnd) {
671 uintptr_t start = readEncodedPointer(&callSitePtr,
673 uintptr_t length = readEncodedPointer(&callSitePtr,
675 uintptr_t landingPad = readEncodedPointer(&callSitePtr,
678 // Note: Action value
679 uintptr_t actionEntry = readULEB128(&callSitePtr);
681 if (exceptionClass != ourBaseExceptionClass) {
682 // We have been notified of a foreign exception being thrown,
683 // and we therefore need to execute cleanup landing pads
685 foreignException = true;
688 if (landingPad == 0) {
691 "handleLsda(...): No landing pad found.\n");
694 continue; // no landing pad for this entry
698 actionEntry += ((uintptr_t) actionTableStart) - 1;
703 "handleLsda(...):No action table found.\n");
707 bool exceptionMatched = false;
709 if ((start <= pcOffset) && (pcOffset < (start + length))) {
712 "handleLsda(...): Landing pad found.\n");
714 int64_t actionValue = 0;
717 exceptionMatched = handleActionValue(&actionValue,
724 if (!(actions & _UA_SEARCH_PHASE)) {
727 "handleLsda(...): installed landing pad "
731 // Found landing pad for the PC.
732 // Set Instruction Pointer to so we re-enter function
733 // at landing pad. The landing pad is created by the
734 // compiler to take two parameters in registers.
735 _Unwind_SetGR(context,
736 __builtin_eh_return_data_regno(0),
737 (uintptr_t)exceptionObject);
739 // Note: this virtual register directly corresponds
740 // to the return of the llvm.eh.selector intrinsic
741 if (!actionEntry || !exceptionMatched) {
742 // We indicate cleanup only
743 _Unwind_SetGR(context,
744 __builtin_eh_return_data_regno(1),
748 // Matched type info index of llvm.eh.selector intrinsic
750 _Unwind_SetGR(context,
751 __builtin_eh_return_data_regno(1),
755 // To execute landing pad set here
756 _Unwind_SetIP(context, funcStart + landingPad);
757 ret = _URC_INSTALL_CONTEXT;
759 else if (exceptionMatched) {
762 "handleLsda(...): setting handler found.\n");
764 ret = _URC_HANDLER_FOUND;
767 // Note: Only non-clean up handlers are marked as
768 // found. Otherwise the clean up handlers will be
769 // re-found and executed during the clean up
773 "handleLsda(...): cleanup handler found.\n");
785 /// This is the personality function which is embedded (dwarf emitted), in the
786 /// dwarf unwind info block. Again see: JITDwarfEmitter.cpp.
787 /// See @link http://refspecs.freestandards.org/abi-eh-1.21.html @unlink
788 /// @param version unsupported (ignored), unwind version
789 /// @param _Unwind_Action actions minimally supported unwind stage
790 /// (forced specifically not supported)
791 /// @param exceptionClass exception class (_Unwind_Exception::exception_class)
792 /// of thrown exception.
793 /// @param exceptionObject thrown _Unwind_Exception instance.
794 /// @param context unwind system context
795 /// @returns minimally supported unwinding control indicator
796 _Unwind_Reason_Code ourPersonality(int version,
797 _Unwind_Action actions,
798 uint64_t exceptionClass,
799 struct _Unwind_Exception *exceptionObject,
800 _Unwind_Context_t context) {
803 "We are in ourPersonality(...):actions is <%d>.\n",
806 if (actions & _UA_SEARCH_PHASE) {
807 fprintf(stderr, "ourPersonality(...):In search phase.\n");
810 fprintf(stderr, "ourPersonality(...):In non-search phase.\n");
814 const uint8_t *lsda = _Unwind_GetLanguageSpecificData(context);
818 "ourPersonality(...):lsda = <%p>.\n",
822 // The real work of the personality function is captured here
823 return(handleLsda(version,
832 /// Generates our _Unwind_Exception class from a given character array.
833 /// thereby handling arbitrary lengths (not in standard), and handling
835 /// See @link http://refspecs.freestandards.org/abi-eh-1.21.html @unlink
836 /// @param classChars char array to encode. NULL values not checkedf
837 /// @param classCharsSize number of chars in classChars. Value is not checked.
838 /// @returns class value
839 uint64_t genClass(const unsigned char classChars[], size_t classCharsSize)
841 uint64_t ret = classChars[0];
843 for (unsigned i = 1; i < classCharsSize; ++i) {
845 ret += classChars[i];
854 // Runtime C Library functions End
858 // Code generation functions
861 /// Generates code to print given constant string
862 /// @param context llvm context
863 /// @param module code for module instance
864 /// @param builder builder instance
865 /// @param toPrint string to print
866 /// @param useGlobal A value of true (default) indicates a GlobalValue is
867 /// generated, and is used to hold the constant string. A value of
868 /// false indicates that the constant string will be stored on the
870 void generateStringPrint(llvm::LLVMContext &context,
871 llvm::Module &module,
872 llvm::IRBuilder<> &builder,
874 bool useGlobal = true) {
875 llvm::Function *printFunct = module.getFunction("printStr");
877 llvm::Value *stringVar;
878 llvm::Constant *stringConstant =
879 llvm::ConstantArray::get(context, toPrint);
882 // Note: Does not work without allocation
884 new llvm::GlobalVariable(module,
885 stringConstant->getType(),
887 llvm::GlobalValue::LinkerPrivateLinkage,
892 stringVar = builder.CreateAlloca(stringConstant->getType());
893 builder.CreateStore(stringConstant, stringVar);
897 builder.CreatePointerCast(stringVar,
898 builder.getInt8PtrTy());
899 builder.CreateCall(printFunct, cast);
903 /// Generates code to print given runtime integer according to constant
904 /// string format, and a given print function.
905 /// @param context llvm context
906 /// @param module code for module instance
907 /// @param builder builder instance
908 /// @param printFunct function used to "print" integer
909 /// @param toPrint string to print
910 /// @param format printf like formating string for print
911 /// @param useGlobal A value of true (default) indicates a GlobalValue is
912 /// generated, and is used to hold the constant string. A value of
913 /// false indicates that the constant string will be stored on the
915 void generateIntegerPrint(llvm::LLVMContext &context,
916 llvm::Module &module,
917 llvm::IRBuilder<> &builder,
918 llvm::Function &printFunct,
919 llvm::Value &toPrint,
921 bool useGlobal = true) {
922 llvm::Constant *stringConstant = llvm::ConstantArray::get(context, format);
923 llvm::Value *stringVar;
926 // Note: Does not seem to work without allocation
928 new llvm::GlobalVariable(module,
929 stringConstant->getType(),
931 llvm::GlobalValue::LinkerPrivateLinkage,
936 stringVar = builder.CreateAlloca(stringConstant->getType());
937 builder.CreateStore(stringConstant, stringVar);
941 builder.CreateBitCast(stringVar,
942 builder.getInt8PtrTy());
943 builder.CreateCall2(&printFunct, &toPrint, cast);
947 /// Generates code to handle finally block type semantics: always runs
948 /// regardless of whether a thrown exception is passing through or the
949 /// parent function is simply exiting. In addition to printing some state
950 /// to stderr, this code will resume the exception handling--runs the
951 /// unwind resume block, if the exception has not been previously caught
952 /// by a catch clause, and will otherwise execute the end block (terminator
953 /// block). In addition this function creates the corresponding function's
954 /// stack storage for the exception pointer and catch flag status.
955 /// @param context llvm context
956 /// @param module code for module instance
957 /// @param builder builder instance
958 /// @param toAddTo parent function to add block to
959 /// @param blockName block name of new "finally" block.
960 /// @param functionId output id used for printing
961 /// @param terminatorBlock terminator "end" block
962 /// @param unwindResumeBlock unwind resume block
963 /// @param exceptionCaughtFlag reference exception caught/thrown status storage
964 /// @param exceptionStorage reference to exception pointer storage
965 /// @returns newly created block
966 static llvm::BasicBlock *createFinallyBlock(llvm::LLVMContext &context,
967 llvm::Module &module,
968 llvm::IRBuilder<> &builder,
969 llvm::Function &toAddTo,
970 std::string &blockName,
971 std::string &functionId,
972 llvm::BasicBlock &terminatorBlock,
973 llvm::BasicBlock &unwindResumeBlock,
974 llvm::Value **exceptionCaughtFlag,
975 llvm::Value **exceptionStorage) {
976 assert(exceptionCaughtFlag &&
977 "ExceptionDemo::createFinallyBlock(...):exceptionCaughtFlag "
979 assert(exceptionStorage &&
980 "ExceptionDemo::createFinallyBlock(...):exceptionStorage "
983 *exceptionCaughtFlag =
984 createEntryBlockAlloca(toAddTo,
986 ourExceptionNotThrownState->getType(),
987 ourExceptionNotThrownState);
989 llvm::PointerType *exceptionStorageType = builder.getInt8PtrTy();
991 createEntryBlockAlloca(toAddTo,
993 exceptionStorageType,
994 llvm::ConstantPointerNull::get(
995 exceptionStorageType));
997 llvm::BasicBlock *ret = llvm::BasicBlock::Create(context,
1001 builder.SetInsertPoint(ret);
1003 std::ostringstream bufferToPrint;
1004 bufferToPrint << "Gen: Executing finally block "
1005 << blockName << " in " << functionId << "\n";
1006 generateStringPrint(context,
1009 bufferToPrint.str(),
1010 USE_GLOBAL_STR_CONSTS);
1012 llvm::SwitchInst *theSwitch =
1013 builder.CreateSwitch(builder.CreateLoad(*exceptionCaughtFlag),
1016 theSwitch->addCase(ourExceptionCaughtState, &terminatorBlock);
1017 theSwitch->addCase(ourExceptionThrownState, &unwindResumeBlock);
1023 /// Generates catch block semantics which print a string to indicate type of
1024 /// catch executed, sets an exception caught flag, and executes passed in
1025 /// end block (terminator block).
1026 /// @param context llvm context
1027 /// @param module code for module instance
1028 /// @param builder builder instance
1029 /// @param toAddTo parent function to add block to
1030 /// @param blockName block name of new "catch" block.
1031 /// @param functionId output id used for printing
1032 /// @param terminatorBlock terminator "end" block
1033 /// @param exceptionCaughtFlag exception caught/thrown status
1034 /// @returns newly created block
1035 static llvm::BasicBlock *createCatchBlock(llvm::LLVMContext &context,
1036 llvm::Module &module,
1037 llvm::IRBuilder<> &builder,
1038 llvm::Function &toAddTo,
1039 std::string &blockName,
1040 std::string &functionId,
1041 llvm::BasicBlock &terminatorBlock,
1042 llvm::Value &exceptionCaughtFlag) {
1044 llvm::BasicBlock *ret = llvm::BasicBlock::Create(context,
1048 builder.SetInsertPoint(ret);
1050 std::ostringstream bufferToPrint;
1051 bufferToPrint << "Gen: Executing catch block "
1056 generateStringPrint(context,
1059 bufferToPrint.str(),
1060 USE_GLOBAL_STR_CONSTS);
1061 builder.CreateStore(ourExceptionCaughtState, &exceptionCaughtFlag);
1062 builder.CreateBr(&terminatorBlock);
1068 /// Generates a function which invokes a function (toInvoke) and, whose
1069 /// unwind block will "catch" the type info types correspondingly held in the
1070 /// exceptionTypesToCatch argument. If the toInvoke function throws an
1071 /// exception which does not match any type info types contained in
1072 /// exceptionTypesToCatch, the generated code will call _Unwind_Resume
1073 /// with the raised exception. On the other hand the generated code will
1074 /// normally exit if the toInvoke function does not throw an exception.
1075 /// The generated "finally" block is always run regardless of the cause of
1076 /// the generated function exit.
1077 /// The generated function is returned after being verified.
1078 /// @param module code for module instance
1079 /// @param builder builder instance
1080 /// @param fpm a function pass manager holding optional IR to IR
1082 /// @param toInvoke inner function to invoke
1083 /// @param ourId id used to printing purposes
1084 /// @param numExceptionsToCatch length of exceptionTypesToCatch array
1085 /// @param exceptionTypesToCatch array of type info types to "catch"
1086 /// @returns generated function
1088 llvm::Function *createCatchWrappedInvokeFunction(llvm::Module &module,
1089 llvm::IRBuilder<> &builder,
1090 llvm::FunctionPassManager &fpm,
1091 llvm::Function &toInvoke,
1093 unsigned numExceptionsToCatch,
1094 unsigned exceptionTypesToCatch[]) {
1096 llvm::LLVMContext &context = module.getContext();
1097 llvm::Function *toPrint32Int = module.getFunction("print32Int");
1100 argTypes.push_back(builder.getInt32Ty());
1103 argNames.push_back("exceptTypeToThrow");
1105 llvm::Function *ret = createFunction(module,
1106 builder.getVoidTy(),
1110 llvm::Function::ExternalLinkage,
1114 // Block which calls invoke
1115 llvm::BasicBlock *entryBlock = llvm::BasicBlock::Create(context,
1118 // Normal block for invoke
1119 llvm::BasicBlock *normalBlock = llvm::BasicBlock::Create(context,
1122 // Unwind block for invoke
1123 llvm::BasicBlock *exceptionBlock =
1124 llvm::BasicBlock::Create(context, "exception", ret);
1126 // Block which routes exception to correct catch handler block
1127 llvm::BasicBlock *exceptionRouteBlock =
1128 llvm::BasicBlock::Create(context, "exceptionRoute", ret);
1130 // Foreign exception handler
1131 llvm::BasicBlock *externalExceptionBlock =
1132 llvm::BasicBlock::Create(context, "externalException", ret);
1134 // Block which calls _Unwind_Resume
1135 llvm::BasicBlock *unwindResumeBlock =
1136 llvm::BasicBlock::Create(context, "unwindResume", ret);
1138 // Clean up block which delete exception if needed
1139 llvm::BasicBlock *endBlock =
1140 llvm::BasicBlock::Create(context, "end", ret);
1142 std::string nextName;
1143 std::vector<llvm::BasicBlock*> catchBlocks(numExceptionsToCatch);
1144 llvm::Value *exceptionCaughtFlag = NULL;
1145 llvm::Value *exceptionStorage = NULL;
1147 // Finally block which will branch to unwindResumeBlock if
1148 // exception is not caught. Initializes/allocates stack locations.
1149 llvm::BasicBlock *finallyBlock = createFinallyBlock(context,
1153 nextName = "finally",
1157 &exceptionCaughtFlag,
1160 for (unsigned i = 0; i < numExceptionsToCatch; ++i) {
1161 nextName = ourTypeInfoNames[exceptionTypesToCatch[i]];
1163 // One catch block per type info to be caught
1164 catchBlocks[i] = createCatchBlock(context,
1171 *exceptionCaughtFlag);
1176 builder.SetInsertPoint(entryBlock);
1178 std::vector<llvm::Value*> args;
1179 args.push_back(namedValues["exceptTypeToThrow"]);
1180 builder.CreateInvoke(&toInvoke,
1187 builder.SetInsertPoint(endBlock);
1189 generateStringPrint(context,
1192 "Gen: In end block: exiting in " + ourId + ".\n",
1193 USE_GLOBAL_STR_CONSTS);
1194 llvm::Function *deleteOurException =
1195 module.getFunction("deleteOurException");
1197 // Note: function handles NULL exceptions
1198 builder.CreateCall(deleteOurException,
1199 builder.CreateLoad(exceptionStorage));
1200 builder.CreateRetVoid();
1204 builder.SetInsertPoint(normalBlock);
1206 generateStringPrint(context,
1209 "Gen: No exception in " + ourId + "!\n",
1210 USE_GLOBAL_STR_CONSTS);
1212 // Finally block is always called
1213 builder.CreateBr(finallyBlock);
1215 // Unwind Resume Block
1217 builder.SetInsertPoint(unwindResumeBlock);
1219 llvm::Function *resumeOurException =
1220 module.getFunction("_Unwind_Resume");
1221 builder.CreateCall(resumeOurException,
1222 builder.CreateLoad(exceptionStorage));
1223 builder.CreateUnreachable();
1227 builder.SetInsertPoint(exceptionBlock);
1229 llvm::Function *ehException = module.getFunction("llvm.eh.exception");
1231 // Retrieve thrown exception
1232 llvm::Value *unwindException = builder.CreateCall(ehException);
1234 // Store exception and flag
1235 builder.CreateStore(unwindException, exceptionStorage);
1236 builder.CreateStore(ourExceptionThrownState, exceptionCaughtFlag);
1237 llvm::Function *personality = module.getFunction("ourPersonality");
1238 llvm::Value *functPtr =
1239 builder.CreatePointerCast(personality,
1240 builder.getInt8PtrTy());
1243 args.push_back(unwindException);
1244 args.push_back(functPtr);
1246 // Note: Skipping index 0
1247 for (unsigned i = 0; i < numExceptionsToCatch; ++i) {
1248 // Set up type infos to be caught
1249 args.push_back(module.getGlobalVariable(
1250 ourTypeInfoNames[exceptionTypesToCatch[i]]));
1253 args.push_back(llvm::ConstantInt::get(builder.getInt32Ty(), 0));
1255 llvm::Function *ehSelector = module.getFunction("llvm.eh.selector");
1257 // Set up this exeption block as the landing pad which will handle
1258 // given type infos. See case Intrinsic::eh_selector in
1259 // SelectionDAGBuilder::visitIntrinsicCall(...) and AddCatchInfo(...)
1260 // implemented in FunctionLoweringInfo.cpp to see how the implementation
1261 // handles this call. This landing pad (this exception block), will be
1262 // called either because it nees to cleanup (call finally) or a type
1263 // info was found which matched the thrown exception.
1264 llvm::Value *retTypeInfoIndex = builder.CreateCall(ehSelector, args);
1266 // Retrieve exception_class member from thrown exception
1267 // (_Unwind_Exception instance). This member tells us whether or not
1268 // the exception is foreign.
1269 llvm::Value *unwindExceptionClass =
1270 builder.CreateLoad(builder.CreateStructGEP(
1271 builder.CreatePointerCast(unwindException,
1272 ourUnwindExceptionType->getPointerTo()),
1275 // Branch to the externalExceptionBlock if the exception is foreign or
1276 // to a catch router if not. Either way the finally block will be run.
1277 builder.CreateCondBr(builder.CreateICmpEQ(unwindExceptionClass,
1278 llvm::ConstantInt::get(builder.getInt64Ty(),
1279 ourBaseExceptionClass)),
1280 exceptionRouteBlock,
1281 externalExceptionBlock);
1283 // External Exception Block
1285 builder.SetInsertPoint(externalExceptionBlock);
1287 generateStringPrint(context,
1290 "Gen: Foreign exception received.\n",
1291 USE_GLOBAL_STR_CONSTS);
1293 // Branch to the finally block
1294 builder.CreateBr(finallyBlock);
1296 // Exception Route Block
1298 builder.SetInsertPoint(exceptionRouteBlock);
1300 // Casts exception pointer (_Unwind_Exception instance) to parent
1301 // (OurException instance).
1303 // Note: ourBaseFromUnwindOffset is usually negative
1304 llvm::Value *typeInfoThrown =
1305 builder.CreatePointerCast(builder.CreateConstGEP1_64(unwindException,
1306 ourBaseFromUnwindOffset),
1307 ourExceptionType->getPointerTo());
1309 // Retrieve thrown exception type info type
1311 // Note: Index is not relative to pointer but instead to structure
1312 // unlike a true getelementptr (GEP) instruction
1313 typeInfoThrown = builder.CreateStructGEP(typeInfoThrown, 0);
1315 llvm::Value *typeInfoThrownType =
1316 builder.CreateStructGEP(typeInfoThrown, 0);
1318 generateIntegerPrint(context,
1322 *(builder.CreateLoad(typeInfoThrownType)),
1323 "Gen: Exception type <%d> received (stack unwound) "
1327 USE_GLOBAL_STR_CONSTS);
1329 // Route to matched type info catch block or run cleanup finally block
1330 llvm::SwitchInst *switchToCatchBlock =
1331 builder.CreateSwitch(retTypeInfoIndex,
1333 numExceptionsToCatch);
1335 unsigned nextTypeToCatch;
1337 for (unsigned i = 1; i <= numExceptionsToCatch; ++i) {
1338 nextTypeToCatch = i - 1;
1339 switchToCatchBlock->addCase(llvm::ConstantInt::get(
1340 llvm::Type::getInt32Ty(context), i),
1341 catchBlocks[nextTypeToCatch]);
1344 llvm::verifyFunction(*ret);
1351 /// Generates function which throws either an exception matched to a runtime
1352 /// determined type info type (argument to generated function), or if this
1353 /// runtime value matches nativeThrowType, throws a foreign exception by
1354 /// calling nativeThrowFunct.
1355 /// @param module code for module instance
1356 /// @param builder builder instance
1357 /// @param fpm a function pass manager holding optional IR to IR
1359 /// @param ourId id used to printing purposes
1360 /// @param nativeThrowType a runtime argument of this value results in
1361 /// nativeThrowFunct being called to generate/throw exception.
1362 /// @param nativeThrowFunct function which will throw a foreign exception
1363 /// if the above nativeThrowType matches generated function's arg.
1364 /// @returns generated function
1366 llvm::Function *createThrowExceptionFunction(llvm::Module &module,
1367 llvm::IRBuilder<> &builder,
1368 llvm::FunctionPassManager &fpm,
1370 int32_t nativeThrowType,
1371 llvm::Function &nativeThrowFunct) {
1372 llvm::LLVMContext &context = module.getContext();
1373 namedValues.clear();
1374 ArgTypes unwindArgTypes;
1375 unwindArgTypes.push_back(builder.getInt32Ty());
1376 ArgNames unwindArgNames;
1377 unwindArgNames.push_back("exceptTypeToThrow");
1379 llvm::Function *ret = createFunction(module,
1380 builder.getVoidTy(),
1384 llvm::Function::ExternalLinkage,
1388 // Throws either one of our exception or a native C++ exception depending
1389 // on a runtime argument value containing a type info type.
1390 llvm::BasicBlock *entryBlock = llvm::BasicBlock::Create(context,
1393 // Throws a foreign exception
1394 llvm::BasicBlock *nativeThrowBlock =
1395 llvm::BasicBlock::Create(context,
1398 // Throws one of our Exceptions
1399 llvm::BasicBlock *generatedThrowBlock =
1400 llvm::BasicBlock::Create(context,
1403 // Retrieved runtime type info type to throw
1404 llvm::Value *exceptionType = namedValues["exceptTypeToThrow"];
1406 // nativeThrowBlock block
1408 builder.SetInsertPoint(nativeThrowBlock);
1410 // Throws foreign exception
1411 builder.CreateCall(&nativeThrowFunct, exceptionType);
1412 builder.CreateUnreachable();
1416 builder.SetInsertPoint(entryBlock);
1418 llvm::Function *toPrint32Int = module.getFunction("print32Int");
1419 generateIntegerPrint(context,
1424 "\nGen: About to throw exception type <%d> in " +
1427 USE_GLOBAL_STR_CONSTS);
1429 // Switches on runtime type info type value to determine whether or not
1430 // a foreign exception is thrown. Defaults to throwing one of our
1431 // generated exceptions.
1432 llvm::SwitchInst *theSwitch = builder.CreateSwitch(exceptionType,
1433 generatedThrowBlock,
1436 theSwitch->addCase(llvm::ConstantInt::get(llvm::Type::getInt32Ty(context),
1440 // generatedThrow block
1442 builder.SetInsertPoint(generatedThrowBlock);
1444 llvm::Function *createOurException =
1445 module.getFunction("createOurException");
1446 llvm::Function *raiseOurException =
1447 module.getFunction("_Unwind_RaiseException");
1449 // Creates exception to throw with runtime type info type.
1450 llvm::Value *exception =
1451 builder.CreateCall(createOurException,
1452 namedValues["exceptTypeToThrow"]);
1454 // Throw generated Exception
1455 builder.CreateCall(raiseOurException, exception);
1456 builder.CreateUnreachable();
1458 llvm::verifyFunction(*ret);
1464 static void createStandardUtilityFunctions(unsigned numTypeInfos,
1465 llvm::Module &module,
1466 llvm::IRBuilder<> &builder);
1468 /// Creates test code by generating and organizing these functions into the
1469 /// test case. The test case consists of an outer function setup to invoke
1470 /// an inner function within an environment having multiple catch and single
1471 /// finally blocks. This inner function is also setup to invoke a throw
1472 /// function within an evironment similar in nature to the outer function's
1473 /// catch and finally blocks. Each of these two functions catch mutually
1474 /// exclusive subsets (even or odd) of the type info types configured
1475 /// for this this. All generated functions have a runtime argument which
1476 /// holds a type info type to throw that each function takes and passes it
1477 /// to the inner one if such a inner function exists. This type info type is
1478 /// looked at by the generated throw function to see whether or not it should
1479 /// throw a generated exception with the same type info type, or instead call
1480 /// a supplied a function which in turn will throw a foreign exception.
1481 /// @param module code for module instance
1482 /// @param builder builder instance
1483 /// @param fpm a function pass manager holding optional IR to IR
1485 /// @param nativeThrowFunctName name of external function which will throw
1486 /// a foreign exception
1487 /// @returns outermost generated test function.
1488 llvm::Function *createUnwindExceptionTest(llvm::Module &module,
1489 llvm::IRBuilder<> &builder,
1490 llvm::FunctionPassManager &fpm,
1491 std::string nativeThrowFunctName) {
1492 // Number of type infos to generate
1493 unsigned numTypeInfos = 6;
1495 // Initialze intrisics and external functions to use along with exception
1496 // and type info globals.
1497 createStandardUtilityFunctions(numTypeInfos,
1500 llvm::Function *nativeThrowFunct =
1501 module.getFunction(nativeThrowFunctName);
1503 // Create exception throw function using the value ~0 to cause
1504 // foreign exceptions to be thrown.
1505 llvm::Function *throwFunct =
1506 createThrowExceptionFunction(module,
1512 // Inner function will catch even type infos
1513 unsigned innerExceptionTypesToCatch[] = {6, 2, 4};
1514 size_t numExceptionTypesToCatch = sizeof(innerExceptionTypesToCatch) /
1517 // Generate inner function.
1518 llvm::Function *innerCatchFunct =
1519 createCatchWrappedInvokeFunction(module,
1524 numExceptionTypesToCatch,
1525 innerExceptionTypesToCatch);
1527 // Outer function will catch odd type infos
1528 unsigned outerExceptionTypesToCatch[] = {3, 1, 5};
1529 numExceptionTypesToCatch = sizeof(outerExceptionTypesToCatch) /
1532 // Generate outer function
1533 llvm::Function *outerCatchFunct =
1534 createCatchWrappedInvokeFunction(module,
1539 numExceptionTypesToCatch,
1540 outerExceptionTypesToCatch);
1542 // Return outer function to run
1543 return(outerCatchFunct);
1547 /// Represents our foreign exceptions
1548 class OurCppRunException : public std::runtime_error {
1550 OurCppRunException(const std::string reason) :
1551 std::runtime_error(reason) {}
1553 OurCppRunException (const OurCppRunException &toCopy) :
1554 std::runtime_error(toCopy) {}
1556 OurCppRunException &operator = (const OurCppRunException &toCopy) {
1557 return(reinterpret_cast<OurCppRunException&>(
1558 std::runtime_error::operator=(toCopy)));
1561 ~OurCppRunException (void) throw () {}
1565 /// Throws foreign C++ exception.
1566 /// @param ignoreIt unused parameter that allows function to match implied
1567 /// generated function contract.
1569 void throwCppException (int32_t ignoreIt) {
1570 throw(OurCppRunException("thrown by throwCppException(...)"));
1573 typedef void (*OurExceptionThrowFunctType) (int32_t typeToThrow);
1575 /// This is a test harness which runs test by executing generated
1576 /// function with a type info type to throw. Harness wraps the execution
1577 /// of generated function in a C++ try catch clause.
1578 /// @param engine execution engine to use for executing generated function.
1579 /// This demo program expects this to be a JIT instance for demo
1581 /// @param function generated test function to run
1582 /// @param typeToThrow type info type of generated exception to throw, or
1583 /// indicator to cause foreign exception to be thrown.
1585 void runExceptionThrow(llvm::ExecutionEngine *engine,
1586 llvm::Function *function,
1587 int32_t typeToThrow) {
1589 // Find test's function pointer
1590 OurExceptionThrowFunctType functPtr =
1591 reinterpret_cast<OurExceptionThrowFunctType>(
1592 reinterpret_cast<intptr_t>(engine->getPointerToFunction(function)));
1596 (*functPtr)(typeToThrow);
1598 catch (OurCppRunException exc) {
1599 // Catch foreign C++ exception
1601 "\nrunExceptionThrow(...):In C++ catch OurCppRunException "
1602 "with reason: %s.\n",
1606 // Catch all exceptions including our generated ones. I'm not sure
1607 // why this latter functionality should work, as it seems that
1608 // our exceptions should be foreign to C++ (the _Unwind_Exception::
1609 // exception_class should be different from the one used by C++), and
1610 // therefore C++ should ignore the generated exceptions.
1613 "\nrunExceptionThrow(...):In C++ catch all.\n");
1618 // End test functions
1621 typedef llvm::ArrayRef<llvm::Type*> TypeArray;
1623 /// This initialization routine creates type info globals and
1624 /// adds external function declarations to module.
1625 /// @param numTypeInfos number of linear type info associated type info types
1626 /// to create as GlobalVariable instances, starting with the value 1.
1627 /// @param module code for module instance
1628 /// @param builder builder instance
1629 static void createStandardUtilityFunctions(unsigned numTypeInfos,
1630 llvm::Module &module,
1631 llvm::IRBuilder<> &builder) {
1633 llvm::LLVMContext &context = module.getContext();
1635 // Exception initializations
1637 // Setup exception catch state
1638 ourExceptionNotThrownState =
1639 llvm::ConstantInt::get(llvm::Type::getInt8Ty(context), 0),
1640 ourExceptionThrownState =
1641 llvm::ConstantInt::get(llvm::Type::getInt8Ty(context), 1),
1642 ourExceptionCaughtState =
1643 llvm::ConstantInt::get(llvm::Type::getInt8Ty(context), 2),
1647 // Create our type info type
1648 ourTypeInfoType = llvm::StructType::get(context,
1649 TypeArray(builder.getInt32Ty()));
1650 // Create OurException type
1651 ourExceptionType = llvm::StructType::get(context,
1652 TypeArray(ourTypeInfoType));
1654 // Create portion of _Unwind_Exception type
1656 // Note: Declaring only a portion of the _Unwind_Exception struct.
1657 // Does this cause problems?
1658 ourUnwindExceptionType =
1659 llvm::StructType::get(context,
1660 TypeArray(builder.getInt64Ty()));
1662 struct OurBaseException_t dummyException;
1664 // Calculate offset of OurException::unwindException member.
1665 ourBaseFromUnwindOffset = ((uintptr_t) &dummyException) -
1666 ((uintptr_t) &(dummyException.unwindException));
1670 "createStandardUtilityFunctions(...):ourBaseFromUnwindOffset "
1671 "= %lld, sizeof(struct OurBaseException_t) - "
1672 "sizeof(struct _Unwind_Exception) = %lu.\n",
1673 ourBaseFromUnwindOffset,
1674 sizeof(struct OurBaseException_t) -
1675 sizeof(struct _Unwind_Exception));
1678 size_t numChars = sizeof(ourBaseExcpClassChars) / sizeof(char);
1680 // Create our _Unwind_Exception::exception_class value
1681 ourBaseExceptionClass = genClass(ourBaseExcpClassChars, numChars);
1685 std::string baseStr = "typeInfo", typeInfoName;
1686 std::ostringstream typeInfoNameBuilder;
1687 std::vector<llvm::Constant*> structVals;
1689 llvm::Constant *nextStruct;
1690 llvm::GlobalVariable *nextGlobal = NULL;
1692 // Generate each type info
1694 // Note: First type info is not used.
1695 for (unsigned i = 0; i <= numTypeInfos; ++i) {
1697 structVals.push_back(llvm::ConstantInt::get(builder.getInt32Ty(), i));
1698 nextStruct = llvm::ConstantStruct::get(ourTypeInfoType, structVals);
1700 typeInfoNameBuilder.str("");
1701 typeInfoNameBuilder << baseStr << i;
1702 typeInfoName = typeInfoNameBuilder.str();
1704 // Note: Does not seem to work without allocation
1706 new llvm::GlobalVariable(module,
1709 llvm::GlobalValue::ExternalLinkage,
1713 ourTypeInfoNames.push_back(typeInfoName);
1714 ourTypeInfoNamesIndex[i] = typeInfoName;
1719 llvm::Function *funct = NULL;
1723 llvm::Type *retType = builder.getVoidTy();
1726 argTypes.push_back(builder.getInt32Ty());
1727 argTypes.push_back(builder.getInt8PtrTy());
1731 createFunction(module,
1736 llvm::Function::ExternalLinkage,
1742 retType = builder.getVoidTy();
1745 argTypes.push_back(builder.getInt64Ty());
1746 argTypes.push_back(builder.getInt8PtrTy());
1750 createFunction(module,
1755 llvm::Function::ExternalLinkage,
1761 retType = builder.getVoidTy();
1764 argTypes.push_back(builder.getInt8PtrTy());
1768 createFunction(module,
1773 llvm::Function::ExternalLinkage,
1777 // throwCppException
1779 retType = builder.getVoidTy();
1782 argTypes.push_back(builder.getInt32Ty());
1786 createFunction(module,
1790 "throwCppException",
1791 llvm::Function::ExternalLinkage,
1795 // deleteOurException
1797 retType = builder.getVoidTy();
1800 argTypes.push_back(builder.getInt8PtrTy());
1804 createFunction(module,
1808 "deleteOurException",
1809 llvm::Function::ExternalLinkage,
1813 // createOurException
1815 retType = builder.getInt8PtrTy();
1818 argTypes.push_back(builder.getInt32Ty());
1822 createFunction(module,
1826 "createOurException",
1827 llvm::Function::ExternalLinkage,
1831 // _Unwind_RaiseException
1833 retType = builder.getInt32Ty();
1836 argTypes.push_back(builder.getInt8PtrTy());
1840 funct = createFunction(module,
1844 "_Unwind_RaiseException",
1845 llvm::Function::ExternalLinkage,
1849 funct->addFnAttr(llvm::Attribute::NoReturn);
1853 retType = builder.getInt32Ty();
1856 argTypes.push_back(builder.getInt8PtrTy());
1860 funct = createFunction(module,
1865 llvm::Function::ExternalLinkage,
1869 funct->addFnAttr(llvm::Attribute::NoReturn);
1873 retType = builder.getInt32Ty();
1876 argTypes.push_back(builder.getInt32Ty());
1877 argTypes.push_back(builder.getInt32Ty());
1878 argTypes.push_back(builder.getInt64Ty());
1879 argTypes.push_back(builder.getInt8PtrTy());
1880 argTypes.push_back(builder.getInt8PtrTy());
1884 createFunction(module,
1889 llvm::Function::ExternalLinkage,
1893 // llvm.eh.selector intrinsic
1895 getDeclaration(&module, llvm::Intrinsic::eh_selector);
1897 // llvm.eh.exception intrinsic
1899 getDeclaration(&module, llvm::Intrinsic::eh_exception);
1901 // llvm.eh.typeid.for intrinsic
1903 getDeclaration(&module, llvm::Intrinsic::eh_typeid_for);
1907 //===----------------------------------------------------------------------===//
1908 // Main test driver code.
1909 //===----------------------------------------------------------------------===//
1911 /// Demo main routine which takes the type info types to throw. A test will
1912 /// be run for each given type info type. While type info types with the value
1913 /// of -1 will trigger a foreign C++ exception to be thrown; type info types
1914 /// <= 6 and >= 1 will be caught by test functions; and type info types > 6
1915 /// will result in exceptions which pass through to the test harness. All other
1916 /// type info types are not supported and could cause a crash.
1917 int main(int argc, char *argv[]) {
1920 "\nUsage: ExceptionDemo <exception type to throw> "
1921 "[<type 2>...<type n>].\n"
1922 " Each type must have the value of 1 - 6 for "
1923 "generated exceptions to be caught;\n"
1924 " the value -1 for foreign C++ exceptions to be "
1925 "generated and thrown;\n"
1926 " or the values > 6 for exceptions to be ignored.\n"
1927 "\nTry: ExceptionDemo 2 3 7 -1\n"
1928 " for a full test.\n\n");
1932 // If not set, exception handling will not be turned on
1933 llvm::JITExceptionHandling = true;
1935 llvm::InitializeNativeTarget();
1936 llvm::LLVMContext &context = llvm::getGlobalContext();
1937 llvm::IRBuilder<> theBuilder(context);
1939 // Make the module, which holds all the code.
1940 llvm::Module *module = new llvm::Module("my cool jit", context);
1942 // Build engine with JIT
1943 llvm::EngineBuilder factory(module);
1944 factory.setEngineKind(llvm::EngineKind::JIT);
1945 factory.setAllocateGVsWithCode(false);
1946 llvm::ExecutionEngine *executionEngine = factory.create();
1949 llvm::FunctionPassManager fpm(module);
1951 // Set up the optimizer pipeline.
1952 // Start with registering info about how the
1953 // target lays out data structures.
1954 fpm.add(new llvm::TargetData(*executionEngine->getTargetData()));
1956 // Optimizations turned on
1957 #ifdef ADD_OPT_PASSES
1959 // Basic AliasAnslysis support for GVN.
1960 fpm.add(llvm::createBasicAliasAnalysisPass());
1962 // Promote allocas to registers.
1963 fpm.add(llvm::createPromoteMemoryToRegisterPass());
1965 // Do simple "peephole" optimizations and bit-twiddling optzns.
1966 fpm.add(llvm::createInstructionCombiningPass());
1968 // Reassociate expressions.
1969 fpm.add(llvm::createReassociatePass());
1971 // Eliminate Common SubExpressions.
1972 fpm.add(llvm::createGVNPass());
1974 // Simplify the control flow graph (deleting unreachable
1976 fpm.add(llvm::createCFGSimplificationPass());
1977 #endif // ADD_OPT_PASSES
1979 fpm.doInitialization();
1981 // Generate test code using function throwCppException(...) as
1982 // the function which throws foreign exceptions.
1983 llvm::Function *toRun =
1984 createUnwindExceptionTest(*module,
1987 "throwCppException");
1989 fprintf(stderr, "\nBegin module dump:\n\n");
1993 fprintf(stderr, "\nEnd module dump:\n");
1995 fprintf(stderr, "\n\nBegin Test:\n");
1997 for (int i = 1; i < argc; ++i) {
1998 // Run test for each argument whose value is the exception
2000 runExceptionThrow(executionEngine,
2002 (unsigned) strtoul(argv[i], NULL, 10));
2005 fprintf(stderr, "\nEnd Test:\n\n");
2008 delete executionEngine;