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"
69 #ifndef USE_GLOBAL_STR_CONSTS
70 #define USE_GLOBAL_STR_CONSTS true
73 // System C++ ABI unwind types from:
74 // http://refspecs.freestandards.org/abi-eh-1.21.html
80 _URC_FOREIGN_EXCEPTION_CAUGHT = 1,
81 _URC_FATAL_PHASE2_ERROR = 2,
82 _URC_FATAL_PHASE1_ERROR = 3,
84 _URC_END_OF_STACK = 5,
85 _URC_HANDLER_FOUND = 6,
86 _URC_INSTALL_CONTEXT = 7,
87 _URC_CONTINUE_UNWIND = 8
88 } _Unwind_Reason_Code;
92 _UA_CLEANUP_PHASE = 2,
93 _UA_HANDLER_FRAME = 4,
98 struct _Unwind_Exception;
100 typedef void (*_Unwind_Exception_Cleanup_Fn) (_Unwind_Reason_Code,
101 struct _Unwind_Exception *);
103 struct _Unwind_Exception {
104 uint64_t exception_class;
105 _Unwind_Exception_Cleanup_Fn exception_cleanup;
110 // @@@ The IA-64 ABI says that this structure must be double-word aligned.
111 // Taking that literally does not make much sense generically. Instead
112 // we provide the maximum alignment required by any type for the machine.
113 } __attribute__((__aligned__));
115 struct _Unwind_Context;
116 typedef struct _Unwind_Context *_Unwind_Context_t;
118 extern const uint8_t *_Unwind_GetLanguageSpecificData (_Unwind_Context_t c);
119 extern uintptr_t _Unwind_GetGR (_Unwind_Context_t c, int i);
120 extern void _Unwind_SetGR (_Unwind_Context_t c, int i, uintptr_t n);
121 extern void _Unwind_SetIP (_Unwind_Context_t, uintptr_t new_value);
122 extern uintptr_t _Unwind_GetIP (_Unwind_Context_t context);
123 extern uintptr_t _Unwind_GetRegionStart (_Unwind_Context_t context);
131 /// This is our simplistic type info
132 struct OurExceptionType_t {
138 /// This is our Exception class which relies on a negative offset to calculate
139 /// pointers to its instances from pointers to its unwindException member.
141 /// Note: The above unwind.h defines struct _Unwind_Exception to be aligned
142 /// on a double word boundary. This is necessary to match the standard:
143 /// http://refspecs.freestandards.org/abi-eh-1.21.html
144 struct OurBaseException_t {
145 struct OurExceptionType_t type;
147 // Note: This is properly aligned in unwind.h
148 struct _Unwind_Exception unwindException;
152 // Note: Not needed since we are C++
153 typedef struct OurBaseException_t OurException;
154 typedef struct _Unwind_Exception OurUnwindException;
157 // Various globals used to support typeinfo and generatted exceptions in
161 static std::map<std::string, llvm::Value*> namedValues;
163 int64_t ourBaseFromUnwindOffset;
165 const unsigned char ourBaseExcpClassChars[] =
166 {'o', 'b', 'j', '\0', 'b', 'a', 's', '\0'};
169 static uint64_t ourBaseExceptionClass = 0;
171 static std::vector<std::string> ourTypeInfoNames;
172 static std::map<int, std::string> ourTypeInfoNamesIndex;
174 static llvm::StructType *ourTypeInfoType;
175 static llvm::StructType *ourExceptionType;
176 static llvm::StructType *ourUnwindExceptionType;
178 static llvm::ConstantInt *ourExceptionNotThrownState;
179 static llvm::ConstantInt *ourExceptionThrownState;
180 static llvm::ConstantInt *ourExceptionCaughtState;
182 typedef std::vector<std::string> ArgNames;
183 typedef std::vector<const llvm::Type*> ArgTypes;
186 // Code Generation Utilities
189 /// Utility used to create a function, both declarations and definitions
190 /// @param module for module instance
191 /// @param retType function return type
192 /// @param theArgTypes function's ordered argument types
193 /// @param theArgNames function's ordered arguments needed if use of this
194 /// function corresponds to a function definition. Use empty
195 /// aggregate for function declarations.
196 /// @param functName function name
197 /// @param linkage function linkage
198 /// @param declarationOnly for function declarations
199 /// @param isVarArg function uses vararg arguments
200 /// @returns function instance
201 llvm::Function *createFunction(llvm::Module &module,
202 const llvm::Type *retType,
203 const ArgTypes &theArgTypes,
204 const ArgNames &theArgNames,
205 const std::string &functName,
206 llvm::GlobalValue::LinkageTypes linkage,
207 bool declarationOnly,
209 llvm::FunctionType *functType =
210 llvm::FunctionType::get(retType, theArgTypes, isVarArg);
211 llvm::Function *ret =
212 llvm::Function::Create(functType, linkage, functName, &module);
213 if (!ret || declarationOnly)
218 for (llvm::Function::arg_iterator argIndex = ret->arg_begin();
219 i != theArgNames.size();
222 argIndex->setName(theArgNames[i]);
223 namedValues[theArgNames[i]] = argIndex;
230 /// Create an alloca instruction in the entry block of
231 /// the parent function. This is used for mutable variables etc.
232 /// @param function parent instance
233 /// @param varName stack variable name
234 /// @param type stack variable type
235 /// @param initWith optional constant initialization value
236 /// @returns AllocaInst instance
237 static llvm::AllocaInst *createEntryBlockAlloca(llvm::Function &function,
238 const std::string &varName,
239 const llvm::Type *type,
240 llvm::Constant *initWith = 0) {
241 llvm::BasicBlock &block = function.getEntryBlock();
242 llvm::IRBuilder<> tmp(&block, block.begin());
243 llvm::AllocaInst *ret = tmp.CreateAlloca(type, 0, varName.c_str());
246 tmp.CreateStore(initWith, ret);
253 // Code Generation Utilities End
257 // Runtime C Library functions
260 // Note: using an extern "C" block so that static functions can be used
263 // Note: Better ways to decide on bit width
265 /// Prints a 32 bit number, according to the format, to stderr.
266 /// @param intToPrint integer to print
267 /// @param format printf like format to use when printing
268 void print32Int(int intToPrint, const char *format) {
270 // Note: No NULL check
271 fprintf(stderr, format, intToPrint);
274 // Note: No NULL check
275 fprintf(stderr, "::print32Int(...):NULL arg.\n");
280 // Note: Better ways to decide on bit width
282 /// Prints a 64 bit number, according to the format, to stderr.
283 /// @param intToPrint integer to print
284 /// @param format printf like format to use when printing
285 void print64Int(long int intToPrint, const char *format) {
287 // Note: No NULL check
288 fprintf(stderr, format, intToPrint);
291 // Note: No NULL check
292 fprintf(stderr, "::print64Int(...):NULL arg.\n");
297 /// Prints a C string to stderr
298 /// @param toPrint string to print
299 void printStr(char *toPrint) {
301 fprintf(stderr, "%s", toPrint);
304 fprintf(stderr, "::printStr(...):NULL arg.\n");
309 /// Deletes the true previosly allocated exception whose address
310 /// is calculated from the supplied OurBaseException_t::unwindException
311 /// member address. Handles (ignores), NULL pointers.
312 /// @param expToDelete exception to delete
313 void deleteOurException(OurUnwindException *expToDelete) {
316 "deleteOurException(...).\n");
320 (expToDelete->exception_class == ourBaseExceptionClass)) {
322 free(((char*) expToDelete) + ourBaseFromUnwindOffset);
327 /// This function is the struct _Unwind_Exception API mandated delete function
328 /// used by foreign exception handlers when deleting our exception
329 /// (OurException), instances.
330 /// @param reason @link http://refspecs.freestandards.org/abi-eh-1.21.html
332 /// @param expToDelete exception instance to delete
333 void deleteFromUnwindOurException(_Unwind_Reason_Code reason,
334 OurUnwindException *expToDelete) {
337 "deleteFromUnwindOurException(...).\n");
340 deleteOurException(expToDelete);
344 /// Creates (allocates on the heap), an exception (OurException instance),
345 /// of the supplied type info type.
346 /// @param type type info type
347 OurUnwindException *createOurException(int type) {
348 size_t size = sizeof(OurException);
349 OurException *ret = (OurException*) memset(malloc(size), 0, size);
350 (ret->type).type = type;
351 (ret->unwindException).exception_class = ourBaseExceptionClass;
352 (ret->unwindException).exception_cleanup = deleteFromUnwindOurException;
354 return(&(ret->unwindException));
358 /// Read a uleb128 encoded value and advance pointer
359 /// See Variable Length Data in:
360 /// @link http://dwarfstd.org/Dwarf3.pdf @unlink
361 /// @param data reference variable holding memory pointer to decode from
362 /// @returns decoded value
363 static uintptr_t readULEB128(const uint8_t **data) {
364 uintptr_t result = 0;
367 const uint8_t *p = *data;
371 result |= (byte & 0x7f) << shift;
382 /// Read a sleb128 encoded value and advance pointer
383 /// See Variable Length Data in:
384 /// @link http://dwarfstd.org/Dwarf3.pdf @unlink
385 /// @param data reference variable holding memory pointer to decode from
386 /// @returns decoded value
387 static uintptr_t readSLEB128(const uint8_t **data) {
388 uintptr_t result = 0;
391 const uint8_t *p = *data;
395 result |= (byte & 0x7f) << shift;
402 if ((byte & 0x40) && (shift < (sizeof(result) << 3))) {
403 result |= (~0 << shift);
410 /// Read a pointer encoded value and advance pointer
411 /// See Variable Length Data in:
412 /// @link http://dwarfstd.org/Dwarf3.pdf @unlink
413 /// @param data reference variable holding memory pointer to decode from
414 /// @param encoding dwarf encoding type
415 /// @returns decoded value
416 static uintptr_t readEncodedPointer(const uint8_t **data, uint8_t encoding) {
417 uintptr_t result = 0;
418 const uint8_t *p = *data;
420 if (encoding == llvm::dwarf::DW_EH_PE_omit)
424 switch (encoding & 0x0F) {
425 case llvm::dwarf::DW_EH_PE_absptr:
426 result = *((uintptr_t*)p);
427 p += sizeof(uintptr_t);
429 case llvm::dwarf::DW_EH_PE_uleb128:
430 result = readULEB128(&p);
432 // Note: This case has not been tested
433 case llvm::dwarf::DW_EH_PE_sleb128:
434 result = readSLEB128(&p);
436 case llvm::dwarf::DW_EH_PE_udata2:
437 result = *((uint16_t*)p);
438 p += sizeof(uint16_t);
440 case llvm::dwarf::DW_EH_PE_udata4:
441 result = *((uint32_t*)p);
442 p += sizeof(uint32_t);
444 case llvm::dwarf::DW_EH_PE_udata8:
445 result = *((uint64_t*)p);
446 p += sizeof(uint64_t);
448 case llvm::dwarf::DW_EH_PE_sdata2:
449 result = *((int16_t*)p);
450 p += sizeof(int16_t);
452 case llvm::dwarf::DW_EH_PE_sdata4:
453 result = *((int32_t*)p);
454 p += sizeof(int32_t);
456 case llvm::dwarf::DW_EH_PE_sdata8:
457 result = *((int64_t*)p);
458 p += sizeof(int64_t);
466 // then add relative offset
467 switch (encoding & 0x70) {
468 case llvm::dwarf::DW_EH_PE_absptr:
471 case llvm::dwarf::DW_EH_PE_pcrel:
472 result += (uintptr_t)(*data);
474 case llvm::dwarf::DW_EH_PE_textrel:
475 case llvm::dwarf::DW_EH_PE_datarel:
476 case llvm::dwarf::DW_EH_PE_funcrel:
477 case llvm::dwarf::DW_EH_PE_aligned:
484 // then apply indirection
485 if (encoding & llvm::dwarf::DW_EH_PE_indirect) {
486 result = *((uintptr_t*)result);
495 /// Deals with Dwarf actions matching our type infos
496 /// (OurExceptionType_t instances). Returns whether or not a dwarf emitted
497 /// action matches the supplied exception type. If such a match succeeds,
498 /// the resultAction argument will be set with > 0 index value. Only
499 /// corresponding llvm.eh.selector type info arguments, cleanup arguments
500 /// are supported. Filters are not supported.
501 /// See Variable Length Data in:
502 /// @link http://dwarfstd.org/Dwarf3.pdf @unlink
503 /// Also see @link http://refspecs.freestandards.org/abi-eh-1.21.html @unlink
504 /// @param resultAction reference variable which will be set with result
505 /// @param classInfo our array of type info pointers (to globals)
506 /// @param actionEntry index into above type info array or 0 (clean up).
507 /// We do not support filters.
508 /// @param exceptionClass exception class (_Unwind_Exception::exception_class)
509 /// of thrown exception.
510 /// @param exceptionObject thrown _Unwind_Exception instance.
511 /// @returns whether or not a type info was found. False is returned if only
512 /// a cleanup was found
513 static bool handleActionValue(int64_t *resultAction,
514 struct OurExceptionType_t **classInfo,
515 uintptr_t actionEntry,
516 uint64_t exceptionClass,
517 struct _Unwind_Exception *exceptionObject) {
522 (exceptionClass != ourBaseExceptionClass))
525 struct OurBaseException_t *excp = (struct OurBaseException_t*)
526 (((char*) exceptionObject) + ourBaseFromUnwindOffset);
527 struct OurExceptionType_t *excpType = &(excp->type);
528 int type = excpType->type;
532 "handleActionValue(...): exceptionObject = <%p>, "
538 const uint8_t *actionPos = (uint8_t*) actionEntry,
540 int64_t typeOffset = 0,
543 for (int i = 0; true; ++i) {
544 // Each emitted dwarf action corresponds to a 2 tuple of
545 // type info address offset, and action offset to the next
547 typeOffset = readSLEB128(&actionPos);
548 tempActionPos = actionPos;
549 actionOffset = readSLEB128(&tempActionPos);
553 "handleActionValue(...):typeOffset: <%lld>, "
554 "actionOffset: <%lld>.\n",
558 assert((typeOffset >= 0) &&
559 "handleActionValue(...):filters are not supported.");
561 // Note: A typeOffset == 0 implies that a cleanup llvm.eh.selector
562 // argument has been matched.
563 if ((typeOffset > 0) &&
564 (type == (classInfo[-typeOffset])->type)) {
567 "handleActionValue(...):actionValue <%d> found.\n",
570 *resultAction = i + 1;
577 "handleActionValue(...):actionValue not found.\n");
582 actionPos += actionOffset;
589 /// Deals with the Language specific data portion of the emitted dwarf code.
590 /// See @link http://refspecs.freestandards.org/abi-eh-1.21.html @unlink
591 /// @param version unsupported (ignored), unwind version
592 /// @param lsda language specific data area
593 /// @param _Unwind_Action actions minimally supported unwind stage
594 /// (forced specifically not supported)
595 /// @param exceptionClass exception class (_Unwind_Exception::exception_class)
596 /// of thrown exception.
597 /// @param exceptionObject thrown _Unwind_Exception instance.
598 /// @param context unwind system context
599 /// @returns minimally supported unwinding control indicator
600 static _Unwind_Reason_Code handleLsda(int version,
602 _Unwind_Action actions,
603 uint64_t exceptionClass,
604 struct _Unwind_Exception *exceptionObject,
605 _Unwind_Context_t context) {
606 _Unwind_Reason_Code ret = _URC_CONTINUE_UNWIND;
613 "handleLsda(...):lsda is non-zero.\n");
616 // Get the current instruction pointer and offset it before next
617 // instruction in the current frame which threw the exception.
618 uintptr_t pc = _Unwind_GetIP(context)-1;
620 // Get beginning current frame's code (as defined by the
621 // emitted dwarf code)
622 uintptr_t funcStart = _Unwind_GetRegionStart(context);
623 uintptr_t pcOffset = pc - funcStart;
624 struct OurExceptionType_t **classInfo = NULL;
626 // Note: See JITDwarfEmitter::EmitExceptionTable(...) for corresponding
629 // Parse LSDA header.
630 uint8_t lpStartEncoding = *lsda++;
632 if (lpStartEncoding != llvm::dwarf::DW_EH_PE_omit) {
633 readEncodedPointer(&lsda, lpStartEncoding);
636 uint8_t ttypeEncoding = *lsda++;
637 uintptr_t classInfoOffset;
639 if (ttypeEncoding != llvm::dwarf::DW_EH_PE_omit) {
640 // Calculate type info locations in emitted dwarf code which
641 // were flagged by type info arguments to llvm.eh.selector
643 classInfoOffset = readULEB128(&lsda);
644 classInfo = (struct OurExceptionType_t**) (lsda + classInfoOffset);
647 // Walk call-site table looking for range that
648 // includes current PC.
650 uint8_t callSiteEncoding = *lsda++;
651 uint32_t callSiteTableLength = readULEB128(&lsda);
652 const uint8_t *callSiteTableStart = lsda;
653 const uint8_t *callSiteTableEnd = callSiteTableStart +
655 const uint8_t *actionTableStart = callSiteTableEnd;
656 const uint8_t *callSitePtr = callSiteTableStart;
658 bool foreignException = false;
660 while (callSitePtr < callSiteTableEnd) {
661 uintptr_t start = readEncodedPointer(&callSitePtr,
663 uintptr_t length = readEncodedPointer(&callSitePtr,
665 uintptr_t landingPad = readEncodedPointer(&callSitePtr,
668 // Note: Action value
669 uintptr_t actionEntry = readULEB128(&callSitePtr);
671 if (exceptionClass != ourBaseExceptionClass) {
672 // We have been notified of a foreign exception being thrown,
673 // and we therefore need to execute cleanup landing pads
675 foreignException = true;
678 if (landingPad == 0) {
681 "handleLsda(...): No landing pad found.\n");
684 continue; // no landing pad for this entry
688 actionEntry += ((uintptr_t) actionTableStart) - 1;
693 "handleLsda(...):No action table found.\n");
697 bool exceptionMatched = false;
699 if ((start <= pcOffset) && (pcOffset < (start + length))) {
702 "handleLsda(...): Landing pad found.\n");
704 int64_t actionValue = 0;
707 exceptionMatched = handleActionValue(&actionValue,
714 if (!(actions & _UA_SEARCH_PHASE)) {
717 "handleLsda(...): installed landing pad "
721 // Found landing pad for the PC.
722 // Set Instruction Pointer to so we re-enter function
723 // at landing pad. The landing pad is created by the
724 // compiler to take two parameters in registers.
725 _Unwind_SetGR(context,
726 __builtin_eh_return_data_regno(0),
727 (uintptr_t)exceptionObject);
729 // Note: this virtual register directly corresponds
730 // to the return of the llvm.eh.selector intrinsic
731 if (!actionEntry || !exceptionMatched) {
732 // We indicate cleanup only
733 _Unwind_SetGR(context,
734 __builtin_eh_return_data_regno(1),
738 // Matched type info index of llvm.eh.selector intrinsic
740 _Unwind_SetGR(context,
741 __builtin_eh_return_data_regno(1),
745 // To execute landing pad set here
746 _Unwind_SetIP(context, funcStart + landingPad);
747 ret = _URC_INSTALL_CONTEXT;
749 else if (exceptionMatched) {
752 "handleLsda(...): setting handler found.\n");
754 ret = _URC_HANDLER_FOUND;
757 // Note: Only non-clean up handlers are marked as
758 // found. Otherwise the clean up handlers will be
759 // re-found and executed during the clean up
763 "handleLsda(...): cleanup handler found.\n");
775 /// This is the personality function which is embedded (dwarf emitted), in the
776 /// dwarf unwind info block. Again see: JITDwarfEmitter.cpp.
777 /// See @link http://refspecs.freestandards.org/abi-eh-1.21.html @unlink
778 /// @param version unsupported (ignored), unwind version
779 /// @param _Unwind_Action actions minimally supported unwind stage
780 /// (forced specifically not supported)
781 /// @param exceptionClass exception class (_Unwind_Exception::exception_class)
782 /// of thrown exception.
783 /// @param exceptionObject thrown _Unwind_Exception instance.
784 /// @param context unwind system context
785 /// @returns minimally supported unwinding control indicator
786 _Unwind_Reason_Code ourPersonality(int version,
787 _Unwind_Action actions,
788 uint64_t exceptionClass,
789 struct _Unwind_Exception *exceptionObject,
790 _Unwind_Context_t context) {
793 "We are in ourPersonality(...):actions is <%d>.\n",
796 if (actions & _UA_SEARCH_PHASE) {
797 fprintf(stderr, "ourPersonality(...):In search phase.\n");
800 fprintf(stderr, "ourPersonality(...):In non-search phase.\n");
804 const uint8_t *lsda = _Unwind_GetLanguageSpecificData(context);
808 "ourPersonality(...):lsda = <%p>.\n",
812 // The real work of the personality function is captured here
813 return(handleLsda(version,
822 /// Generates our _Unwind_Exception class from a given character array.
823 /// thereby handling arbitrary lengths (not in standard), and handling
825 /// See @link http://refspecs.freestandards.org/abi-eh-1.21.html @unlink
826 /// @param classChars char array to encode. NULL values not checkedf
827 /// @param classCharsSize number of chars in classChars. Value is not checked.
828 /// @returns class value
829 uint64_t genClass(const unsigned char classChars[], size_t classCharsSize)
831 uint64_t ret = classChars[0];
833 for (unsigned i = 1; i < classCharsSize; ++i) {
835 ret += classChars[i];
844 // Runtime C Library functions End
848 // Code generation functions
851 /// Generates code to print given constant string
852 /// @param context llvm context
853 /// @param module code for module instance
854 /// @param builder builder instance
855 /// @param toPrint string to print
856 /// @param useGlobal A value of true (default) indicates a GlobalValue is
857 /// generated, and is used to hold the constant string. A value of
858 /// false indicates that the constant string will be stored on the
860 void generateStringPrint(llvm::LLVMContext &context,
861 llvm::Module &module,
862 llvm::IRBuilder<> &builder,
864 bool useGlobal = true) {
865 llvm::Function *printFunct = module.getFunction("printStr");
867 llvm::Value *stringVar;
868 llvm::Constant *stringConstant =
869 llvm::ConstantArray::get(context, toPrint);
872 // Note: Does not work without allocation
874 new llvm::GlobalVariable(module,
875 stringConstant->getType(),
877 llvm::GlobalValue::LinkerPrivateLinkage,
882 stringVar = builder.CreateAlloca(stringConstant->getType());
883 builder.CreateStore(stringConstant, stringVar);
887 builder.CreatePointerCast(stringVar,
888 builder.getInt8Ty()->getPointerTo());
889 builder.CreateCall(printFunct, cast);
893 /// Generates code to print given runtime integer according to constant
894 /// string format, and a given print function.
895 /// @param context llvm context
896 /// @param module code for module instance
897 /// @param builder builder instance
898 /// @param printFunct function used to "print" integer
899 /// @param toPrint string to print
900 /// @param format printf like formating string for print
901 /// @param useGlobal A value of true (default) indicates a GlobalValue is
902 /// generated, and is used to hold the constant string. A value of
903 /// false indicates that the constant string will be stored on the
905 void generateIntegerPrint(llvm::LLVMContext &context,
906 llvm::Module &module,
907 llvm::IRBuilder<> &builder,
908 llvm::Function &printFunct,
909 llvm::Value &toPrint,
911 bool useGlobal = true) {
912 llvm::Constant *stringConstant = llvm::ConstantArray::get(context, format);
913 llvm::Value *stringVar;
916 // Note: Does not seem to work without allocation
918 new llvm::GlobalVariable(module,
919 stringConstant->getType(),
921 llvm::GlobalValue::LinkerPrivateLinkage,
926 stringVar = builder.CreateAlloca(stringConstant->getType());
927 builder.CreateStore(stringConstant, stringVar);
931 builder.CreateBitCast(stringVar,
932 builder.getInt8Ty()->getPointerTo());
933 builder.CreateCall2(&printFunct, &toPrint, cast);
937 /// Generates code to handle finally block type semantics: always runs
938 /// regardless of whether a thrown exception is passing through or the
939 /// parent function is simply exiting. In addition to printing some state
940 /// to stderr, this code will resume the exception handling--runs the
941 /// unwind resume block, if the exception has not been previously caught
942 /// by a catch clause, and will otherwise execute the end block (terminator
943 /// block). In addition this function creates the corresponding function's
944 /// stack storage for the exception pointer and catch flag status.
945 /// @param context llvm context
946 /// @param module code for module instance
947 /// @param builder builder instance
948 /// @param toAddTo parent function to add block to
949 /// @param blockName block name of new "finally" block.
950 /// @param functionId output id used for printing
951 /// @param terminatorBlock terminator "end" block
952 /// @param unwindResumeBlock unwind resume block
953 /// @param exceptionCaughtFlag reference exception caught/thrown status storage
954 /// @param exceptionStorage reference to exception pointer storage
955 /// @returns newly created block
956 static llvm::BasicBlock *createFinallyBlock(llvm::LLVMContext &context,
957 llvm::Module &module,
958 llvm::IRBuilder<> &builder,
959 llvm::Function &toAddTo,
960 std::string &blockName,
961 std::string &functionId,
962 llvm::BasicBlock &terminatorBlock,
963 llvm::BasicBlock &unwindResumeBlock,
964 llvm::Value **exceptionCaughtFlag,
965 llvm::Value **exceptionStorage) {
966 assert(exceptionCaughtFlag &&
967 "ExceptionDemo::createFinallyBlock(...):exceptionCaughtFlag "
969 assert(exceptionStorage &&
970 "ExceptionDemo::createFinallyBlock(...):exceptionStorage "
973 *exceptionCaughtFlag =
974 createEntryBlockAlloca(toAddTo,
976 ourExceptionNotThrownState->getType(),
977 ourExceptionNotThrownState);
979 const llvm::PointerType *exceptionStorageType =
980 builder.getInt8Ty()->getPointerTo();
982 createEntryBlockAlloca(toAddTo,
984 exceptionStorageType,
985 llvm::ConstantPointerNull::get(
986 exceptionStorageType));
988 llvm::BasicBlock *ret = llvm::BasicBlock::Create(context,
992 builder.SetInsertPoint(ret);
994 std::ostringstream bufferToPrint;
995 bufferToPrint << "Gen: Executing finally block "
996 << blockName << " in " << functionId << "\n";
997 generateStringPrint(context,
1000 bufferToPrint.str(),
1001 USE_GLOBAL_STR_CONSTS);
1003 llvm::SwitchInst *theSwitch =
1004 builder.CreateSwitch(builder.CreateLoad(*exceptionCaughtFlag),
1007 theSwitch->addCase(ourExceptionCaughtState, &terminatorBlock);
1008 theSwitch->addCase(ourExceptionThrownState, &unwindResumeBlock);
1014 /// Generates catch block semantics which print a string to indicate type of
1015 /// catch executed, sets an exception caught flag, and executes passed in
1016 /// end block (terminator block).
1017 /// @param context llvm context
1018 /// @param module code for module instance
1019 /// @param builder builder instance
1020 /// @param toAddTo parent function to add block to
1021 /// @param blockName block name of new "catch" block.
1022 /// @param functionId output id used for printing
1023 /// @param terminatorBlock terminator "end" block
1024 /// @param exceptionCaughtFlag exception caught/thrown status
1025 /// @returns newly created block
1026 static llvm::BasicBlock *createCatchBlock(llvm::LLVMContext &context,
1027 llvm::Module &module,
1028 llvm::IRBuilder<> &builder,
1029 llvm::Function &toAddTo,
1030 std::string &blockName,
1031 std::string &functionId,
1032 llvm::BasicBlock &terminatorBlock,
1033 llvm::Value &exceptionCaughtFlag) {
1035 llvm::BasicBlock *ret = llvm::BasicBlock::Create(context,
1039 builder.SetInsertPoint(ret);
1041 std::ostringstream bufferToPrint;
1042 bufferToPrint << "Gen: Executing catch block "
1047 generateStringPrint(context,
1050 bufferToPrint.str(),
1051 USE_GLOBAL_STR_CONSTS);
1052 builder.CreateStore(ourExceptionCaughtState, &exceptionCaughtFlag);
1053 builder.CreateBr(&terminatorBlock);
1059 /// Generates a function which invokes a function (toInvoke) and, whose
1060 /// unwind block will "catch" the type info types correspondingly held in the
1061 /// exceptionTypesToCatch argument. If the toInvoke function throws an
1062 /// exception which does not match any type info types contained in
1063 /// exceptionTypesToCatch, the generated code will call _Unwind_Resume
1064 /// with the raised exception. On the other hand the generated code will
1065 /// normally exit if the toInvoke function does not throw an exception.
1066 /// The generated "finally" block is always run regardless of the cause of
1067 /// the generated function exit.
1068 /// The generated function is returned after being verified.
1069 /// @param module code for module instance
1070 /// @param builder builder instance
1071 /// @param fpm a function pass manager holding optional IR to IR
1073 /// @param toInvoke inner function to invoke
1074 /// @param ourId id used to printing purposes
1075 /// @param numExceptionsToCatch length of exceptionTypesToCatch array
1076 /// @param exceptionTypesToCatch array of type info types to "catch"
1077 /// @returns generated function
1079 llvm::Function *createCatchWrappedInvokeFunction(llvm::Module &module,
1080 llvm::IRBuilder<> &builder,
1081 llvm::FunctionPassManager &fpm,
1082 llvm::Function &toInvoke,
1084 unsigned numExceptionsToCatch,
1085 unsigned exceptionTypesToCatch[]) {
1087 llvm::LLVMContext &context = module.getContext();
1088 llvm::Function *toPrint32Int = module.getFunction("print32Int");
1091 argTypes.push_back(builder.getInt32Ty());
1094 argNames.push_back("exceptTypeToThrow");
1096 llvm::Function *ret = createFunction(module,
1097 builder.getVoidTy(),
1101 llvm::Function::ExternalLinkage,
1105 // Block which calls invoke
1106 llvm::BasicBlock *entryBlock = llvm::BasicBlock::Create(context,
1109 // Normal block for invoke
1110 llvm::BasicBlock *normalBlock = llvm::BasicBlock::Create(context,
1113 // Unwind block for invoke
1114 llvm::BasicBlock *exceptionBlock =
1115 llvm::BasicBlock::Create(context, "exception", ret);
1117 // Block which routes exception to correct catch handler block
1118 llvm::BasicBlock *exceptionRouteBlock =
1119 llvm::BasicBlock::Create(context, "exceptionRoute", ret);
1121 // Foreign exception handler
1122 llvm::BasicBlock *externalExceptionBlock =
1123 llvm::BasicBlock::Create(context, "externalException", ret);
1125 // Block which calls _Unwind_Resume
1126 llvm::BasicBlock *unwindResumeBlock =
1127 llvm::BasicBlock::Create(context, "unwindResume", ret);
1129 // Clean up block which delete exception if needed
1130 llvm::BasicBlock *endBlock =
1131 llvm::BasicBlock::Create(context, "end", ret);
1133 std::string nextName;
1134 std::vector<llvm::BasicBlock*> catchBlocks(numExceptionsToCatch);
1135 llvm::Value *exceptionCaughtFlag = NULL;
1136 llvm::Value *exceptionStorage = NULL;
1138 // Finally block which will branch to unwindResumeBlock if
1139 // exception is not caught. Initializes/allocates stack locations.
1140 llvm::BasicBlock *finallyBlock = createFinallyBlock(context,
1144 nextName = "finally",
1148 &exceptionCaughtFlag,
1151 for (unsigned i = 0; i < numExceptionsToCatch; ++i) {
1152 nextName = ourTypeInfoNames[exceptionTypesToCatch[i]];
1154 // One catch block per type info to be caught
1155 catchBlocks[i] = createCatchBlock(context,
1162 *exceptionCaughtFlag);
1167 builder.SetInsertPoint(entryBlock);
1169 std::vector<llvm::Value*> args;
1170 args.push_back(namedValues["exceptTypeToThrow"]);
1171 builder.CreateInvoke(&toInvoke,
1179 builder.SetInsertPoint(endBlock);
1181 generateStringPrint(context,
1184 "Gen: In end block: exiting in " + ourId + ".\n",
1185 USE_GLOBAL_STR_CONSTS);
1186 llvm::Function *deleteOurException =
1187 module.getFunction("deleteOurException");
1189 // Note: function handles NULL exceptions
1190 builder.CreateCall(deleteOurException,
1191 builder.CreateLoad(exceptionStorage));
1192 builder.CreateRetVoid();
1196 builder.SetInsertPoint(normalBlock);
1198 generateStringPrint(context,
1201 "Gen: No exception in " + ourId + "!\n",
1202 USE_GLOBAL_STR_CONSTS);
1204 // Finally block is always called
1205 builder.CreateBr(finallyBlock);
1207 // Unwind Resume Block
1209 builder.SetInsertPoint(unwindResumeBlock);
1211 llvm::Function *resumeOurException =
1212 module.getFunction("_Unwind_Resume");
1213 builder.CreateCall(resumeOurException,
1214 builder.CreateLoad(exceptionStorage));
1215 builder.CreateUnreachable();
1219 builder.SetInsertPoint(exceptionBlock);
1221 llvm::Function *ehException = module.getFunction("llvm.eh.exception");
1223 // Retrieve thrown exception
1224 llvm::Value *unwindException = builder.CreateCall(ehException);
1226 // Store exception and flag
1227 builder.CreateStore(unwindException, exceptionStorage);
1228 builder.CreateStore(ourExceptionThrownState, exceptionCaughtFlag);
1229 llvm::Function *personality = module.getFunction("ourPersonality");
1230 llvm::Value *functPtr =
1231 builder.CreatePointerCast(personality,
1232 builder.getInt8Ty()->getPointerTo());
1235 args.push_back(unwindException);
1236 args.push_back(functPtr);
1238 // Note: Skipping index 0
1239 for (unsigned i = 0; i < numExceptionsToCatch; ++i) {
1240 // Set up type infos to be caught
1241 args.push_back(module.getGlobalVariable(
1242 ourTypeInfoNames[exceptionTypesToCatch[i]]));
1245 args.push_back(llvm::ConstantInt::get(builder.getInt32Ty(), 0));
1247 llvm::Function *ehSelector = module.getFunction("llvm.eh.selector");
1249 // Set up this exeption block as the landing pad which will handle
1250 // given type infos. See case Intrinsic::eh_selector in
1251 // SelectionDAGBuilder::visitIntrinsicCall(...) and AddCatchInfo(...)
1252 // implemented in FunctionLoweringInfo.cpp to see how the implementation
1253 // handles this call. This landing pad (this exception block), will be
1254 // called either because it nees to cleanup (call finally) or a type
1255 // info was found which matched the thrown exception.
1256 llvm::Value *retTypeInfoIndex = builder.CreateCall(ehSelector,
1260 // Retrieve exception_class member from thrown exception
1261 // (_Unwind_Exception instance). This member tells us whether or not
1262 // the exception is foreign.
1263 llvm::Value *unwindExceptionClass =
1264 builder.CreateLoad(builder.CreateStructGEP(
1265 builder.CreatePointerCast(unwindException,
1266 ourUnwindExceptionType->getPointerTo()),
1269 // Branch to the externalExceptionBlock if the exception is foreign or
1270 // to a catch router if not. Either way the finally block will be run.
1271 builder.CreateCondBr(builder.CreateICmpEQ(unwindExceptionClass,
1272 llvm::ConstantInt::get(builder.getInt64Ty(),
1273 ourBaseExceptionClass)),
1274 exceptionRouteBlock,
1275 externalExceptionBlock);
1277 // External Exception Block
1279 builder.SetInsertPoint(externalExceptionBlock);
1281 generateStringPrint(context,
1284 "Gen: Foreign exception received.\n",
1285 USE_GLOBAL_STR_CONSTS);
1287 // Branch to the finally block
1288 builder.CreateBr(finallyBlock);
1290 // Exception Route Block
1292 builder.SetInsertPoint(exceptionRouteBlock);
1294 // Casts exception pointer (_Unwind_Exception instance) to parent
1295 // (OurException instance).
1297 // Note: ourBaseFromUnwindOffset is usually negative
1298 llvm::Value *typeInfoThrown =
1299 builder.CreatePointerCast(builder.CreateConstGEP1_64(unwindException,
1300 ourBaseFromUnwindOffset),
1301 ourExceptionType->getPointerTo());
1303 // Retrieve thrown exception type info type
1305 // Note: Index is not relative to pointer but instead to structure
1306 // unlike a true getelementptr (GEP) instruction
1307 typeInfoThrown = builder.CreateStructGEP(typeInfoThrown, 0);
1309 llvm::Value *typeInfoThrownType =
1310 builder.CreateStructGEP(typeInfoThrown, 0);
1312 generateIntegerPrint(context,
1316 *(builder.CreateLoad(typeInfoThrownType)),
1317 "Gen: Exception type <%d> received (stack unwound) "
1321 USE_GLOBAL_STR_CONSTS);
1323 // Route to matched type info catch block or run cleanup finally block
1324 llvm::SwitchInst *switchToCatchBlock =
1325 builder.CreateSwitch(retTypeInfoIndex,
1327 numExceptionsToCatch);
1329 unsigned nextTypeToCatch;
1331 for (unsigned i = 1; i <= numExceptionsToCatch; ++i) {
1332 nextTypeToCatch = i - 1;
1333 switchToCatchBlock->addCase(llvm::ConstantInt::get(
1334 llvm::Type::getInt32Ty(context), i),
1335 catchBlocks[nextTypeToCatch]);
1338 llvm::verifyFunction(*ret);
1345 /// Generates function which throws either an exception matched to a runtime
1346 /// determined type info type (argument to generated function), or if this
1347 /// runtime value matches nativeThrowType, throws a foreign exception by
1348 /// calling nativeThrowFunct.
1349 /// @param module code for module instance
1350 /// @param builder builder instance
1351 /// @param fpm a function pass manager holding optional IR to IR
1353 /// @param ourId id used to printing purposes
1354 /// @param nativeThrowType a runtime argument of this value results in
1355 /// nativeThrowFunct being called to generate/throw exception.
1356 /// @param nativeThrowFunct function which will throw a foreign exception
1357 /// if the above nativeThrowType matches generated function's arg.
1358 /// @returns generated function
1360 llvm::Function *createThrowExceptionFunction(llvm::Module &module,
1361 llvm::IRBuilder<> &builder,
1362 llvm::FunctionPassManager &fpm,
1364 int32_t nativeThrowType,
1365 llvm::Function &nativeThrowFunct) {
1366 llvm::LLVMContext &context = module.getContext();
1367 namedValues.clear();
1368 ArgTypes unwindArgTypes;
1369 unwindArgTypes.push_back(builder.getInt32Ty());
1370 ArgNames unwindArgNames;
1371 unwindArgNames.push_back("exceptTypeToThrow");
1373 llvm::Function *ret = createFunction(module,
1374 builder.getVoidTy(),
1378 llvm::Function::ExternalLinkage,
1382 // Throws either one of our exception or a native C++ exception depending
1383 // on a runtime argument value containing a type info type.
1384 llvm::BasicBlock *entryBlock = llvm::BasicBlock::Create(context,
1387 // Throws a foreign exception
1388 llvm::BasicBlock *nativeThrowBlock =
1389 llvm::BasicBlock::Create(context,
1392 // Throws one of our Exceptions
1393 llvm::BasicBlock *generatedThrowBlock =
1394 llvm::BasicBlock::Create(context,
1397 // Retrieved runtime type info type to throw
1398 llvm::Value *exceptionType = namedValues["exceptTypeToThrow"];
1400 // nativeThrowBlock block
1402 builder.SetInsertPoint(nativeThrowBlock);
1404 // Throws foreign exception
1405 builder.CreateCall(&nativeThrowFunct, exceptionType);
1406 builder.CreateUnreachable();
1410 builder.SetInsertPoint(entryBlock);
1412 llvm::Function *toPrint32Int = module.getFunction("print32Int");
1413 generateIntegerPrint(context,
1418 "\nGen: About to throw exception type <%d> in " +
1421 USE_GLOBAL_STR_CONSTS);
1423 // Switches on runtime type info type value to determine whether or not
1424 // a foreign exception is thrown. Defaults to throwing one of our
1425 // generated exceptions.
1426 llvm::SwitchInst *theSwitch = builder.CreateSwitch(exceptionType,
1427 generatedThrowBlock,
1430 theSwitch->addCase(llvm::ConstantInt::get(llvm::Type::getInt32Ty(context),
1434 // generatedThrow block
1436 builder.SetInsertPoint(generatedThrowBlock);
1438 llvm::Function *createOurException =
1439 module.getFunction("createOurException");
1440 llvm::Function *raiseOurException =
1441 module.getFunction("_Unwind_RaiseException");
1443 // Creates exception to throw with runtime type info type.
1444 llvm::Value *exception =
1445 builder.CreateCall(createOurException,
1446 namedValues["exceptTypeToThrow"]);
1448 // Throw generated Exception
1449 builder.CreateCall(raiseOurException, exception);
1450 builder.CreateUnreachable();
1452 llvm::verifyFunction(*ret);
1458 static void createStandardUtilityFunctions(unsigned numTypeInfos,
1459 llvm::Module &module,
1460 llvm::IRBuilder<> &builder);
1462 /// Creates test code by generating and organizing these functions into the
1463 /// test case. The test case consists of an outer function setup to invoke
1464 /// an inner function within an environment having multiple catch and single
1465 /// finally blocks. This inner function is also setup to invoke a throw
1466 /// function within an evironment similar in nature to the outer function's
1467 /// catch and finally blocks. Each of these two functions catch mutually
1468 /// exclusive subsets (even or odd) of the type info types configured
1469 /// for this this. All generated functions have a runtime argument which
1470 /// holds a type info type to throw that each function takes and passes it
1471 /// to the inner one if such a inner function exists. This type info type is
1472 /// looked at by the generated throw function to see whether or not it should
1473 /// throw a generated exception with the same type info type, or instead call
1474 /// a supplied a function which in turn will throw a foreign exception.
1475 /// @param module code for module instance
1476 /// @param builder builder instance
1477 /// @param fpm a function pass manager holding optional IR to IR
1479 /// @param nativeThrowFunctName name of external function which will throw
1480 /// a foreign exception
1481 /// @returns outermost generated test function.
1482 llvm::Function *createUnwindExceptionTest(llvm::Module &module,
1483 llvm::IRBuilder<> &builder,
1484 llvm::FunctionPassManager &fpm,
1485 std::string nativeThrowFunctName) {
1486 // Number of type infos to generate
1487 unsigned numTypeInfos = 6;
1489 // Initialze intrisics and external functions to use along with exception
1490 // and type info globals.
1491 createStandardUtilityFunctions(numTypeInfos,
1494 llvm::Function *nativeThrowFunct =
1495 module.getFunction(nativeThrowFunctName);
1497 // Create exception throw function using the value ~0 to cause
1498 // foreign exceptions to be thrown.
1499 llvm::Function *throwFunct =
1500 createThrowExceptionFunction(module,
1506 // Inner function will catch even type infos
1507 unsigned innerExceptionTypesToCatch[] = {6, 2, 4};
1508 size_t numExceptionTypesToCatch = sizeof(innerExceptionTypesToCatch) /
1511 // Generate inner function.
1512 llvm::Function *innerCatchFunct =
1513 createCatchWrappedInvokeFunction(module,
1518 numExceptionTypesToCatch,
1519 innerExceptionTypesToCatch);
1521 // Outer function will catch odd type infos
1522 unsigned outerExceptionTypesToCatch[] = {3, 1, 5};
1523 numExceptionTypesToCatch = sizeof(outerExceptionTypesToCatch) /
1526 // Generate outer function
1527 llvm::Function *outerCatchFunct =
1528 createCatchWrappedInvokeFunction(module,
1533 numExceptionTypesToCatch,
1534 outerExceptionTypesToCatch);
1536 // Return outer function to run
1537 return(outerCatchFunct);
1541 /// Represents our foreign exceptions
1542 class OurCppRunException : public std::runtime_error {
1544 OurCppRunException(const std::string reason) :
1545 std::runtime_error(reason) {}
1547 OurCppRunException (const OurCppRunException &toCopy) :
1548 std::runtime_error(toCopy) {}
1550 OurCppRunException &operator = (const OurCppRunException &toCopy) {
1551 return(reinterpret_cast<OurCppRunException&>(
1552 std::runtime_error::operator=(toCopy)));
1555 ~OurCppRunException (void) throw () {}
1559 /// Throws foreign C++ exception.
1560 /// @param ignoreIt unused parameter that allows function to match implied
1561 /// generated function contract.
1563 void throwCppException (int32_t ignoreIt) {
1564 throw(OurCppRunException("thrown by throwCppException(...)"));
1567 typedef void (*OurExceptionThrowFunctType) (int32_t typeToThrow);
1569 /// This is a test harness which runs test by executing generated
1570 /// function with a type info type to throw. Harness wraps the excecution
1571 /// of generated function in a C++ try catch clause.
1572 /// @param engine execution engine to use for executing generated function.
1573 /// This demo program expects this to be a JIT instance for demo
1575 /// @param function generated test function to run
1576 /// @param typeToThrow type info type of generated exception to throw, or
1577 /// indicator to cause foreign exception to be thrown.
1579 void runExceptionThrow(llvm::ExecutionEngine *engine,
1580 llvm::Function *function,
1581 int32_t typeToThrow) {
1583 // Find test's function pointer
1584 OurExceptionThrowFunctType functPtr =
1585 reinterpret_cast<OurExceptionThrowFunctType>(
1586 reinterpret_cast<intptr_t>(engine->getPointerToFunction(function)));
1590 (*functPtr)(typeToThrow);
1592 catch (OurCppRunException exc) {
1593 // Catch foreign C++ exception
1595 "\nrunExceptionThrow(...):In C++ catch OurCppRunException "
1596 "with reason: %s.\n",
1600 // Catch all exceptions including our generated ones. I'm not sure
1601 // why this latter functionality should work, as it seems that
1602 // our exceptions should be foreign to C++ (the _Unwind_Exception::
1603 // exception_class should be different from the one used by C++), and
1604 // therefore C++ should ignore the generated exceptions.
1607 "\nrunExceptionThrow(...):In C++ catch all.\n");
1612 // End test functions
1615 typedef llvm::ArrayRef<const llvm::Type*> TypeArray;
1617 /// This initialization routine creates type info globals and
1618 /// adds external function declarations to module.
1619 /// @param numTypeInfos number of linear type info associated type info types
1620 /// to create as GlobalVariable instances, starting with the value 1.
1621 /// @param module code for module instance
1622 /// @param builder builder instance
1623 static void createStandardUtilityFunctions(unsigned numTypeInfos,
1624 llvm::Module &module,
1625 llvm::IRBuilder<> &builder) {
1627 llvm::LLVMContext &context = module.getContext();
1629 // Exception initializations
1631 // Setup exception catch state
1632 ourExceptionNotThrownState =
1633 llvm::ConstantInt::get(llvm::Type::getInt8Ty(context), 0),
1634 ourExceptionThrownState =
1635 llvm::ConstantInt::get(llvm::Type::getInt8Ty(context), 1),
1636 ourExceptionCaughtState =
1637 llvm::ConstantInt::get(llvm::Type::getInt8Ty(context), 2),
1641 // Create our type info type
1642 ourTypeInfoType = llvm::StructType::get(context,
1643 TypeArray(builder.getInt32Ty()));
1645 // Create OurException type
1646 ourExceptionType = llvm::StructType::get(context,
1647 TypeArray(ourTypeInfoType));
1649 // Create portion of _Unwind_Exception type
1651 // Note: Declaring only a portion of the _Unwind_Exception struct.
1652 // Does this cause problems?
1653 ourUnwindExceptionType =
1654 llvm::StructType::get(context, TypeArray(builder.getInt64Ty()));
1655 struct OurBaseException_t dummyException;
1657 // Calculate offset of OurException::unwindException member.
1658 ourBaseFromUnwindOffset = ((uintptr_t) &dummyException) -
1659 ((uintptr_t) &(dummyException.unwindException));
1663 "createStandardUtilityFunctions(...):ourBaseFromUnwindOffset "
1664 "= %lld, sizeof(struct OurBaseException_t) - "
1665 "sizeof(struct _Unwind_Exception) = %lu.\n",
1666 ourBaseFromUnwindOffset,
1667 sizeof(struct OurBaseException_t) -
1668 sizeof(struct _Unwind_Exception));
1671 size_t numChars = sizeof(ourBaseExcpClassChars) / sizeof(char);
1673 // Create our _Unwind_Exception::exception_class value
1674 ourBaseExceptionClass = genClass(ourBaseExcpClassChars, numChars);
1678 std::string baseStr = "typeInfo", typeInfoName;
1679 std::ostringstream typeInfoNameBuilder;
1680 std::vector<llvm::Constant*> structVals;
1682 llvm::Constant *nextStruct;
1683 llvm::GlobalVariable *nextGlobal = NULL;
1685 // Generate each type info
1687 // Note: First type info is not used.
1688 for (unsigned i = 0; i <= numTypeInfos; ++i) {
1690 structVals.push_back(llvm::ConstantInt::get(builder.getInt32Ty(), i));
1691 nextStruct = llvm::ConstantStruct::get(ourTypeInfoType, structVals);
1693 typeInfoNameBuilder.str("");
1694 typeInfoNameBuilder << baseStr << i;
1695 typeInfoName = typeInfoNameBuilder.str();
1697 // Note: Does not seem to work without allocation
1699 new llvm::GlobalVariable(module,
1702 llvm::GlobalValue::ExternalLinkage,
1706 ourTypeInfoNames.push_back(typeInfoName);
1707 ourTypeInfoNamesIndex[i] = typeInfoName;
1712 llvm::Function *funct = NULL;
1716 const llvm::Type *retType = builder.getVoidTy();
1719 argTypes.push_back(builder.getInt32Ty());
1720 argTypes.push_back(builder.getInt8Ty()->getPointerTo());
1724 createFunction(module,
1729 llvm::Function::ExternalLinkage,
1735 retType = builder.getVoidTy();
1738 argTypes.push_back(builder.getInt64Ty());
1739 argTypes.push_back(builder.getInt8Ty()->getPointerTo());
1743 createFunction(module,
1748 llvm::Function::ExternalLinkage,
1754 retType = builder.getVoidTy();
1757 argTypes.push_back(builder.getInt8Ty()->getPointerTo());
1761 createFunction(module,
1766 llvm::Function::ExternalLinkage,
1770 // throwCppException
1772 retType = builder.getVoidTy();
1775 argTypes.push_back(builder.getInt32Ty());
1779 createFunction(module,
1783 "throwCppException",
1784 llvm::Function::ExternalLinkage,
1788 // deleteOurException
1790 retType = builder.getVoidTy();
1793 argTypes.push_back(builder.getInt8Ty()->getPointerTo());
1797 createFunction(module,
1801 "deleteOurException",
1802 llvm::Function::ExternalLinkage,
1806 // createOurException
1808 retType = builder.getInt8Ty()->getPointerTo();
1811 argTypes.push_back(builder.getInt32Ty());
1815 createFunction(module,
1819 "createOurException",
1820 llvm::Function::ExternalLinkage,
1824 // _Unwind_RaiseException
1826 retType = builder.getInt32Ty();
1829 argTypes.push_back(builder.getInt8Ty()->getPointerTo());
1833 funct = createFunction(module,
1837 "_Unwind_RaiseException",
1838 llvm::Function::ExternalLinkage,
1842 funct->addFnAttr(llvm::Attribute::NoReturn);
1846 retType = builder.getInt32Ty();
1849 argTypes.push_back(builder.getInt8Ty()->getPointerTo());
1853 funct = createFunction(module,
1858 llvm::Function::ExternalLinkage,
1862 funct->addFnAttr(llvm::Attribute::NoReturn);
1866 retType = builder.getInt32Ty();
1869 argTypes.push_back(builder.getInt32Ty());
1870 argTypes.push_back(builder.getInt32Ty());
1871 argTypes.push_back(builder.getInt64Ty());
1872 argTypes.push_back(builder.getInt8Ty()->getPointerTo());
1873 argTypes.push_back(builder.getInt8Ty()->getPointerTo());
1877 createFunction(module,
1882 llvm::Function::ExternalLinkage,
1886 // llvm.eh.selector intrinsic
1888 getDeclaration(&module, llvm::Intrinsic::eh_selector);
1890 // llvm.eh.exception intrinsic
1892 getDeclaration(&module, llvm::Intrinsic::eh_exception);
1894 // llvm.eh.typeid.for intrinsic
1896 getDeclaration(&module, llvm::Intrinsic::eh_typeid_for);
1900 //===----------------------------------------------------------------------===//
1901 // Main test driver code.
1902 //===----------------------------------------------------------------------===//
1904 /// Demo main routine which takes the type info types to throw. A test will
1905 /// be run for each given type info type. While type info types with the value
1906 /// of -1 will trigger a foreign C++ exception to be thrown; type info types
1907 /// <= 6 and >= 1 will be caught by test functions; and type info types > 6
1908 /// will result in exceptions which pass through to the test harness. All other
1909 /// type info types are not supported and could cause a crash.
1910 int main(int argc, char *argv[]) {
1913 "\nUsage: ExceptionDemo <exception type to throw> "
1914 "[<type 2>...<type n>].\n"
1915 " Each type must have the value of 1 - 6 for "
1916 "generated exceptions to be caught;\n"
1917 " the value -1 for foreign C++ exceptions to be "
1918 "generated and thrown;\n"
1919 " or the values > 6 for exceptions to be ignored.\n"
1920 "\nTry: ExceptionDemo 2 3 7 -1\n"
1921 " for a full test.\n\n");
1925 // If not set, exception handling will not be turned on
1926 llvm::JITExceptionHandling = true;
1928 llvm::InitializeNativeTarget();
1929 llvm::LLVMContext &context = llvm::getGlobalContext();
1930 llvm::IRBuilder<> theBuilder(context);
1932 // Make the module, which holds all the code.
1933 llvm::Module *module = new llvm::Module("my cool jit", context);
1935 // Build engine with JIT
1936 llvm::EngineBuilder factory(module);
1937 factory.setEngineKind(llvm::EngineKind::JIT);
1938 factory.setAllocateGVsWithCode(false);
1939 llvm::ExecutionEngine *executionEngine = factory.create();
1942 llvm::FunctionPassManager fpm(module);
1944 // Set up the optimizer pipeline.
1945 // Start with registering info about how the
1946 // target lays out data structures.
1947 fpm.add(new llvm::TargetData(*executionEngine->getTargetData()));
1949 // Optimizations turned on
1950 #ifdef ADD_OPT_PASSES
1952 // Basic AliasAnslysis support for GVN.
1953 fpm.add(llvm::createBasicAliasAnalysisPass());
1955 // Promote allocas to registers.
1956 fpm.add(llvm::createPromoteMemoryToRegisterPass());
1958 // Do simple "peephole" optimizations and bit-twiddling optzns.
1959 fpm.add(llvm::createInstructionCombiningPass());
1961 // Reassociate expressions.
1962 fpm.add(llvm::createReassociatePass());
1964 // Eliminate Common SubExpressions.
1965 fpm.add(llvm::createGVNPass());
1967 // Simplify the control flow graph (deleting unreachable
1969 fpm.add(llvm::createCFGSimplificationPass());
1970 #endif // ADD_OPT_PASSES
1972 fpm.doInitialization();
1974 // Generate test code using function throwCppException(...) as
1975 // the function which throws foreign exceptions.
1976 llvm::Function *toRun =
1977 createUnwindExceptionTest(*module,
1980 "throwCppException");
1982 fprintf(stderr, "\nBegin module dump:\n\n");
1986 fprintf(stderr, "\nEnd module dump:\n");
1988 fprintf(stderr, "\n\nBegin Test:\n");
1990 for (int i = 1; i < argc; ++i) {
1991 // Run test for each argument whose value is the exception
1993 runExceptionThrow(executionEngine,
1995 (unsigned) strtoul(argv[i], NULL, 10));
1998 fprintf(stderr, "\nEnd Test:\n\n");
2001 delete executionEngine;