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
717 if (!(actions & _UA_SEARCH_PHASE)) {
720 "handleLsda(...): installed landing pad "
724 // Found landing pad for the PC.
725 // Set Instruction Pointer to so we re-enter function
726 // at landing pad. The landing pad is created by the
727 // compiler to take two parameters in registers.
728 _Unwind_SetGR(context,
729 __builtin_eh_return_data_regno(0),
730 (uintptr_t)exceptionObject);
732 // Note: this virtual register directly corresponds
733 // to the return of the llvm.eh.selector intrinsic
734 if (!actionEntry || !exceptionMatched) {
735 // We indicate cleanup only
736 _Unwind_SetGR(context,
737 __builtin_eh_return_data_regno(1),
741 // Matched type info index of llvm.eh.selector intrinsic
743 _Unwind_SetGR(context,
744 __builtin_eh_return_data_regno(1),
748 // To execute landing pad set here
749 _Unwind_SetIP(context, funcStart + landingPad);
750 ret = _URC_INSTALL_CONTEXT;
752 else if (exceptionMatched) {
755 "handleLsda(...): setting handler found.\n");
757 ret = _URC_HANDLER_FOUND;
760 // Note: Only non-clean up handlers are marked as
761 // found. Otherwise the clean up handlers will be
762 // re-found and executed during the clean up
766 "handleLsda(...): cleanup handler found.\n");
778 /// This is the personality function which is embedded (dwarf emitted), in the
779 /// dwarf unwind info block. Again see: JITDwarfEmitter.cpp.
780 /// See @link http://refspecs.freestandards.org/abi-eh-1.21.html @unlink
781 /// @param version unsupported (ignored), unwind version
782 /// @param _Unwind_Action actions minimally supported unwind stage
783 /// (forced specifically not supported)
784 /// @param exceptionClass exception class (_Unwind_Exception::exception_class)
785 /// of thrown exception.
786 /// @param exceptionObject thrown _Unwind_Exception instance.
787 /// @param context unwind system context
788 /// @returns minimally supported unwinding control indicator
789 _Unwind_Reason_Code ourPersonality(int version,
790 _Unwind_Action actions,
791 uint64_t exceptionClass,
792 struct _Unwind_Exception* exceptionObject,
793 _Unwind_Context_t context) {
796 "We are in ourPersonality(...):actions is <%d>.\n",
799 if (actions & _UA_SEARCH_PHASE) {
800 fprintf(stderr, "ourPersonality(...):In search phase.\n");
803 fprintf(stderr, "ourPersonality(...):In non-search phase.\n");
807 const uint8_t* lsda = _Unwind_GetLanguageSpecificData(context);
811 "ourPersonality(...):lsda = <%p>.\n",
815 // The real work of the personality function is captured here
816 return(handleLsda(version,
825 /// Generates our _Unwind_Exception class from a given character array.
826 /// thereby handling arbitrary lengths (not in standard), and handling
828 /// See @link http://refspecs.freestandards.org/abi-eh-1.21.html @unlink
829 /// @param classChars char array to encode. NULL values not checkedf
830 /// @param classCharsSize number of chars in classChars. Value is not checked.
831 /// @returns class value
832 uint64_t genClass(const unsigned char classChars[], size_t classCharsSize)
834 uint64_t ret = classChars[0];
836 for (unsigned i = 1; i < classCharsSize; ++i) {
838 ret += classChars[i];
847 // Runtime C Library functions End
851 // Code generation functions
854 /// Generates code to print given constant string
855 /// @param context llvm context
856 /// @param module code for module instance
857 /// @param builder builder instance
858 /// @param toPrint string to print
859 /// @param useGlobal A value of true (default) indicates a GlobalValue is
860 /// generated, and is used to hold the constant string. A value of
861 /// false indicates that the constant string will be stored on the
863 void generateStringPrint(llvm::LLVMContext& context,
864 llvm::Module& module,
865 llvm::IRBuilder<>& builder,
867 bool useGlobal = true) {
868 llvm::Function *printFunct = module.getFunction("printStr");
870 llvm::Value *stringVar;
871 llvm::Constant* stringConstant =
872 llvm::ConstantArray::get(context, toPrint);
875 // Note: Does not work without allocation
877 new llvm::GlobalVariable(module,
878 stringConstant->getType(),
880 llvm::GlobalValue::LinkerPrivateLinkage,
885 stringVar = builder.CreateAlloca(stringConstant->getType());
886 builder.CreateStore(stringConstant, stringVar);
890 builder.CreatePointerCast(stringVar,
891 builder.getInt8Ty()->getPointerTo());
892 builder.CreateCall(printFunct, cast);
896 /// Generates code to print given runtime integer according to constant
897 /// string format, and a given print function.
898 /// @param context llvm context
899 /// @param module code for module instance
900 /// @param builder builder instance
901 /// @param printFunct function used to "print" integer
902 /// @param toPrint string to print
903 /// @param format printf like formating string for print
904 /// @param useGlobal A value of true (default) indicates a GlobalValue is
905 /// generated, and is used to hold the constant string. A value of
906 /// false indicates that the constant string will be stored on the
908 void generateIntegerPrint(llvm::LLVMContext& context,
909 llvm::Module& module,
910 llvm::IRBuilder<>& builder,
911 llvm::Function& printFunct,
912 llvm::Value& toPrint,
914 bool useGlobal = true) {
915 llvm::Constant *stringConstant = llvm::ConstantArray::get(context, format);
916 llvm::Value *stringVar;
919 // Note: Does not seem to work without allocation
921 new llvm::GlobalVariable(module,
922 stringConstant->getType(),
924 llvm::GlobalValue::LinkerPrivateLinkage,
929 stringVar = builder.CreateAlloca(stringConstant->getType());
930 builder.CreateStore(stringConstant, stringVar);
934 builder.CreateBitCast(stringVar,
935 builder.getInt8Ty()->getPointerTo());
936 builder.CreateCall2(&printFunct, &toPrint, cast);
940 /// Generates code to handle finally block type semantics: always runs
941 /// regardless of whether a thrown exception is passing through or the
942 /// parent function is simply exiting. In addition to printing some state
943 /// to stderr, this code will resume the exception handling--runs the
944 /// unwind resume block, if the exception has not been previously caught
945 /// by a catch clause, and will otherwise execute the end block (terminator
946 /// block). In addition this function creates the corresponding function's
947 /// stack storage for the exception pointer and catch flag status.
948 /// @param context llvm context
949 /// @param module code for module instance
950 /// @param builder builder instance
951 /// @param toAddTo parent function to add block to
952 /// @param blockName block name of new "finally" block.
953 /// @param functionId output id used for printing
954 /// @param terminatorBlock terminator "end" block
955 /// @param unwindResumeBlock unwind resume block
956 /// @param exceptionCaughtFlag reference exception caught/thrown status storage
957 /// @param exceptionStorage reference to exception pointer storage
958 /// @returns newly created block
959 static llvm::BasicBlock* createFinallyBlock(llvm::LLVMContext& context,
960 llvm::Module& module,
961 llvm::IRBuilder<>& builder,
962 llvm::Function& toAddTo,
963 std::string& blockName,
964 std::string& functionId,
965 llvm::BasicBlock& terminatorBlock,
966 llvm::BasicBlock& unwindResumeBlock,
967 llvm::Value** exceptionCaughtFlag,
968 llvm::Value** exceptionStorage) {
969 assert(exceptionCaughtFlag &&
970 "ExceptionDemo::createFinallyBlock(...):exceptionCaughtFlag "
972 assert(exceptionStorage &&
973 "ExceptionDemo::createFinallyBlock(...):exceptionStorage "
976 *exceptionCaughtFlag =
977 createEntryBlockAlloca(toAddTo,
979 ourExceptionNotThrownState->getType(),
980 ourExceptionNotThrownState);
982 const llvm::PointerType* exceptionStorageType =
983 builder.getInt8Ty()->getPointerTo();
985 createEntryBlockAlloca(toAddTo,
987 exceptionStorageType,
988 llvm::ConstantPointerNull::get(
989 exceptionStorageType));
991 llvm::BasicBlock *ret = llvm::BasicBlock::Create(context,
995 builder.SetInsertPoint(ret);
997 std::ostringstream bufferToPrint;
998 bufferToPrint << "Gen: Executing finally block "
999 << blockName << " in " << functionId << "\n";
1000 generateStringPrint(context,
1003 bufferToPrint.str(),
1004 USE_GLOBAL_STR_CONSTS);
1006 llvm::SwitchInst* theSwitch =
1007 builder.CreateSwitch(builder.CreateLoad(*exceptionCaughtFlag),
1010 theSwitch->addCase(ourExceptionCaughtState, &terminatorBlock);
1011 theSwitch->addCase(ourExceptionThrownState, &unwindResumeBlock);
1017 /// Generates catch block semantics which print a string to indicate type of
1018 /// catch executed, sets an exception caught flag, and executes passed in
1019 /// end block (terminator block).
1020 /// @param context llvm context
1021 /// @param module code for module instance
1022 /// @param builder builder instance
1023 /// @param toAddTo parent function to add block to
1024 /// @param blockName block name of new "catch" block.
1025 /// @param functionId output id used for printing
1026 /// @param terminatorBlock terminator "end" block
1027 /// @param exceptionCaughtFlag exception caught/thrown status
1028 /// @returns newly created block
1029 static llvm::BasicBlock* createCatchBlock(llvm::LLVMContext& context,
1030 llvm::Module& module,
1031 llvm::IRBuilder<>& builder,
1032 llvm::Function& toAddTo,
1033 std::string& blockName,
1034 std::string& functionId,
1035 llvm::BasicBlock& terminatorBlock,
1036 llvm::Value& exceptionCaughtFlag) {
1038 llvm::BasicBlock *ret = llvm::BasicBlock::Create(context,
1042 builder.SetInsertPoint(ret);
1044 std::ostringstream bufferToPrint;
1045 bufferToPrint << "Gen: Executing catch block "
1050 generateStringPrint(context,
1053 bufferToPrint.str(),
1054 USE_GLOBAL_STR_CONSTS);
1055 builder.CreateStore(ourExceptionCaughtState, &exceptionCaughtFlag);
1056 builder.CreateBr(&terminatorBlock);
1062 /// Generates a function which invokes a function (toInvoke) and, whose
1063 /// unwind block will "catch" the type info types correspondingly held in the
1064 /// exceptionTypesToCatch argument. If the toInvoke function throws an
1065 /// exception which does not match any type info types contained in
1066 /// exceptionTypesToCatch, the generated code will call _Unwind_Resume
1067 /// with the raised exception. On the other hand the generated code will
1068 /// normally exit if the toInvoke function does not throw an exception.
1069 /// The generated "finally" block is always run regardless of the cause of
1070 /// the generated function exit.
1071 /// The generated function is returned after being verified.
1072 /// @param module code for module instance
1073 /// @param builder builder instance
1074 /// @param fpm a function pass manager holding optional IR to IR
1076 /// @param toInvoke inner function to invoke
1077 /// @param ourId id used to printing purposes
1078 /// @param numExceptionsToCatch length of exceptionTypesToCatch array
1079 /// @param exceptionTypesToCatch array of type info types to "catch"
1080 /// @returns generated function
1082 llvm::Function* createCatchWrappedInvokeFunction(llvm::Module& module,
1083 llvm::IRBuilder<>& builder,
1084 llvm::FunctionPassManager& fpm,
1085 llvm::Function& toInvoke,
1087 unsigned numExceptionsToCatch,
1088 unsigned exceptionTypesToCatch[]) {
1090 llvm::LLVMContext& context = module.getContext();
1091 llvm::Function *toPrint32Int = module.getFunction("print32Int");
1094 argTypes.push_back(builder.getInt32Ty());
1097 argNames.push_back("exceptTypeToThrow");
1099 llvm::Function* ret = createFunction(module,
1100 builder.getVoidTy(),
1104 llvm::Function::ExternalLinkage,
1108 // Block which calls invoke
1109 llvm::BasicBlock *entryBlock = llvm::BasicBlock::Create(context,
1112 // Normal block for invoke
1113 llvm::BasicBlock *normalBlock = llvm::BasicBlock::Create(context,
1116 // Unwind block for invoke
1117 llvm::BasicBlock *exceptionBlock =
1118 llvm::BasicBlock::Create(context, "exception", ret);
1120 // Block which routes exception to correct catch handler block
1121 llvm::BasicBlock *exceptionRouteBlock =
1122 llvm::BasicBlock::Create(context, "exceptionRoute", ret);
1124 // Foreign exception handler
1125 llvm::BasicBlock *externalExceptionBlock =
1126 llvm::BasicBlock::Create(context, "externalException", ret);
1128 // Block which calls _Unwind_Resume
1129 llvm::BasicBlock *unwindResumeBlock =
1130 llvm::BasicBlock::Create(context, "unwindResume", ret);
1132 // Clean up block which delete exception if needed
1133 llvm::BasicBlock *endBlock =
1134 llvm::BasicBlock::Create(context, "end", ret);
1136 std::string nextName;
1137 std::vector<llvm::BasicBlock*> catchBlocks(numExceptionsToCatch);
1138 llvm::Value* exceptionCaughtFlag = NULL;
1139 llvm::Value* exceptionStorage = NULL;
1141 // Finally block which will branch to unwindResumeBlock if
1142 // exception is not caught. Initializes/allocates stack locations.
1143 llvm::BasicBlock* finallyBlock = createFinallyBlock(context,
1147 nextName = "finally",
1151 &exceptionCaughtFlag,
1154 for (unsigned i = 0; i < numExceptionsToCatch; ++i) {
1155 nextName = ourTypeInfoNames[exceptionTypesToCatch[i]];
1157 // One catch block per type info to be caught
1158 catchBlocks[i] = createCatchBlock(context,
1165 *exceptionCaughtFlag);
1170 builder.SetInsertPoint(entryBlock);
1172 std::vector<llvm::Value*> args;
1173 args.push_back(namedValues["exceptTypeToThrow"]);
1174 builder.CreateInvoke(&toInvoke,
1182 builder.SetInsertPoint(endBlock);
1184 generateStringPrint(context,
1187 "Gen: In end block: exiting in " + ourId + ".\n",
1188 USE_GLOBAL_STR_CONSTS);
1189 llvm::Function *deleteOurException =
1190 module.getFunction("deleteOurException");
1192 // Note: function handles NULL exceptions
1193 builder.CreateCall(deleteOurException,
1194 builder.CreateLoad(exceptionStorage));
1195 builder.CreateRetVoid();
1199 builder.SetInsertPoint(normalBlock);
1201 generateStringPrint(context,
1204 "Gen: No exception in " + ourId + "!\n",
1205 USE_GLOBAL_STR_CONSTS);
1207 // Finally block is always called
1208 builder.CreateBr(finallyBlock);
1210 // Unwind Resume Block
1212 builder.SetInsertPoint(unwindResumeBlock);
1214 llvm::Function *resumeOurException =
1215 module.getFunction("_Unwind_Resume");
1216 builder.CreateCall(resumeOurException,
1217 builder.CreateLoad(exceptionStorage));
1218 builder.CreateUnreachable();
1222 builder.SetInsertPoint(exceptionBlock);
1224 llvm::Function *ehException = module.getFunction("llvm.eh.exception");
1226 // Retrieve thrown exception
1227 llvm::Value* unwindException = builder.CreateCall(ehException);
1229 // Store exception and flag
1230 builder.CreateStore(unwindException, exceptionStorage);
1231 builder.CreateStore(ourExceptionThrownState, exceptionCaughtFlag);
1232 llvm::Function *personality = module.getFunction("ourPersonality");
1233 llvm::Value* functPtr =
1234 builder.CreatePointerCast(personality,
1235 builder.getInt8Ty()->getPointerTo());
1238 args.push_back(unwindException);
1239 args.push_back(functPtr);
1241 // Note: Skipping index 0
1242 for (unsigned i = 0; i < numExceptionsToCatch; ++i) {
1243 // Set up type infos to be caught
1244 args.push_back(module.getGlobalVariable(
1245 ourTypeInfoNames[exceptionTypesToCatch[i]]));
1248 args.push_back(llvm::ConstantInt::get(builder.getInt32Ty(), 0));
1250 llvm::Function *ehSelector = module.getFunction("llvm.eh.selector");
1252 // Set up this exeption block as the landing pad which will handle
1253 // given type infos. See case Intrinsic::eh_selector in
1254 // SelectionDAGBuilder::visitIntrinsicCall(...) and AddCatchInfo(...)
1255 // implemented in FunctionLoweringInfo.cpp to see how the implementation
1256 // handles this call. This landing pad (this exception block), will be
1257 // called either because it nees to cleanup (call finally) or a type
1258 // info was found which matched the thrown exception.
1259 llvm::Value* retTypeInfoIndex = builder.CreateCall(ehSelector,
1263 // Retrieve exception_class member from thrown exception
1264 // (_Unwind_Exception instance). This member tells us whether or not
1265 // the exception is foreign.
1266 llvm::Value* unwindExceptionClass =
1267 builder.CreateLoad(builder.CreateStructGEP(
1268 builder.CreatePointerCast(unwindException,
1269 ourUnwindExceptionType->getPointerTo()),
1272 // Branch to the externalExceptionBlock if the exception is foreign or
1273 // to a catch router if not. Either way the finally block will be run.
1274 builder.CreateCondBr(builder.CreateICmpEQ(unwindExceptionClass,
1275 llvm::ConstantInt::get(builder.getInt64Ty(),
1276 ourBaseExceptionClass)),
1277 exceptionRouteBlock,
1278 externalExceptionBlock);
1280 // External Exception Block
1282 builder.SetInsertPoint(externalExceptionBlock);
1284 generateStringPrint(context,
1287 "Gen: Foreign exception received.\n",
1288 USE_GLOBAL_STR_CONSTS);
1290 // Branch to the finally block
1291 builder.CreateBr(finallyBlock);
1293 // Exception Route Block
1295 builder.SetInsertPoint(exceptionRouteBlock);
1297 // Casts exception pointer (_Unwind_Exception instance) to parent
1298 // (OurException instance).
1300 // Note: ourBaseFromUnwindOffset is usually negative
1301 llvm::Value* typeInfoThrown =
1302 builder.CreatePointerCast(builder.CreateConstGEP1_64(unwindException,
1303 ourBaseFromUnwindOffset),
1304 ourExceptionType->getPointerTo());
1306 // Retrieve thrown exception type info type
1308 // Note: Index is not relative to pointer but instead to structure
1309 // unlike a true getelementptr (GEP) instruction
1310 typeInfoThrown = builder.CreateStructGEP(typeInfoThrown, 0);
1312 llvm::Value* typeInfoThrownType =
1313 builder.CreateStructGEP(typeInfoThrown, 0);
1315 generateIntegerPrint(context,
1319 *(builder.CreateLoad(typeInfoThrownType)),
1320 "Gen: Exception type <%d> received (stack unwound) "
1324 USE_GLOBAL_STR_CONSTS);
1326 // Route to matched type info catch block or run cleanup finally block
1327 llvm::SwitchInst* switchToCatchBlock =
1328 builder.CreateSwitch(retTypeInfoIndex,
1330 numExceptionsToCatch);
1332 unsigned nextTypeToCatch;
1334 for (unsigned i = 1; i <= numExceptionsToCatch; ++i) {
1335 nextTypeToCatch = i - 1;
1336 switchToCatchBlock->addCase(llvm::ConstantInt::get(
1337 llvm::Type::getInt32Ty(context), i),
1338 catchBlocks[nextTypeToCatch]);
1341 llvm::verifyFunction(*ret);
1348 /// Generates function which throws either an exception matched to a runtime
1349 /// determined type info type (argument to generated function), or if this
1350 /// runtime value matches nativeThrowType, throws a foreign exception by
1351 /// calling nativeThrowFunct.
1352 /// @param module code for module instance
1353 /// @param builder builder instance
1354 /// @param fpm a function pass manager holding optional IR to IR
1356 /// @param ourId id used to printing purposes
1357 /// @param nativeThrowType a runtime argument of this value results in
1358 /// nativeThrowFunct being called to generate/throw exception.
1359 /// @param nativeThrowFunct function which will throw a foreign exception
1360 /// if the above nativeThrowType matches generated function's arg.
1361 /// @returns generated function
1363 llvm::Function* createThrowExceptionFunction(llvm::Module& module,
1364 llvm::IRBuilder<>& builder,
1365 llvm::FunctionPassManager& fpm,
1367 int32_t nativeThrowType,
1368 llvm::Function& nativeThrowFunct) {
1369 llvm::LLVMContext& context = module.getContext();
1370 namedValues.clear();
1371 ArgTypes unwindArgTypes;
1372 unwindArgTypes.push_back(builder.getInt32Ty());
1373 ArgNames unwindArgNames;
1374 unwindArgNames.push_back("exceptTypeToThrow");
1376 llvm::Function *ret = createFunction(module,
1377 builder.getVoidTy(),
1381 llvm::Function::ExternalLinkage,
1385 // Throws either one of our exception or a native C++ exception depending
1386 // on a runtime argument value containing a type info type.
1387 llvm::BasicBlock *entryBlock = llvm::BasicBlock::Create(context,
1390 // Throws a foreign exception
1391 llvm::BasicBlock *nativeThrowBlock =
1392 llvm::BasicBlock::Create(context,
1395 // Throws one of our Exceptions
1396 llvm::BasicBlock *generatedThrowBlock =
1397 llvm::BasicBlock::Create(context,
1400 // Retrieved runtime type info type to throw
1401 llvm::Value* exceptionType = namedValues["exceptTypeToThrow"];
1403 // nativeThrowBlock block
1405 builder.SetInsertPoint(nativeThrowBlock);
1407 // Throws foreign exception
1408 builder.CreateCall(&nativeThrowFunct, exceptionType);
1409 builder.CreateUnreachable();
1413 builder.SetInsertPoint(entryBlock);
1415 llvm::Function *toPrint32Int = module.getFunction("print32Int");
1416 generateIntegerPrint(context,
1421 "\nGen: About to throw exception type <%d> in " +
1424 USE_GLOBAL_STR_CONSTS);
1426 // Switches on runtime type info type value to determine whether or not
1427 // a foreign exception is thrown. Defaults to throwing one of our
1428 // generated exceptions.
1429 llvm::SwitchInst* theSwitch = builder.CreateSwitch(exceptionType,
1430 generatedThrowBlock,
1433 theSwitch->addCase(llvm::ConstantInt::get(llvm::Type::getInt32Ty(context),
1437 // generatedThrow block
1439 builder.SetInsertPoint(generatedThrowBlock);
1441 llvm::Function *createOurException =
1442 module.getFunction("createOurException");
1443 llvm::Function *raiseOurException =
1444 module.getFunction("_Unwind_RaiseException");
1446 // Creates exception to throw with runtime type info type.
1447 llvm::Value* exception =
1448 builder.CreateCall(createOurException,
1449 namedValues["exceptTypeToThrow"]);
1451 // Throw generated Exception
1452 builder.CreateCall(raiseOurException, exception);
1453 builder.CreateUnreachable();
1455 llvm::verifyFunction(*ret);
1461 static void createStandardUtilityFunctions(unsigned numTypeInfos,
1462 llvm::Module& module,
1463 llvm::IRBuilder<>& builder);
1465 /// Creates test code by generating and organizing these functions into the
1466 /// test case. The test case consists of an outer function setup to invoke
1467 /// an inner function within an environment having multiple catch and single
1468 /// finally blocks. This inner function is also setup to invoke a throw
1469 /// function within an evironment similar in nature to the outer function's
1470 /// catch and finally blocks. Each of these two functions catch mutually
1471 /// exclusive subsets (even or odd) of the type info types configured
1472 /// for this this. All generated functions have a runtime argument which
1473 /// holds a type info type to throw that each function takes and passes it
1474 /// to the inner one if such a inner function exists. This type info type is
1475 /// looked at by the generated throw function to see whether or not it should
1476 /// throw a generated exception with the same type info type, or instead call
1477 /// a supplied a function which in turn will throw a foreign exception.
1478 /// @param module code for module instance
1479 /// @param builder builder instance
1480 /// @param fpm a function pass manager holding optional IR to IR
1482 /// @param nativeThrowFunctName name of external function which will throw
1483 /// a foreign exception
1484 /// @returns outermost generated test function.
1485 llvm::Function* createUnwindExceptionTest(llvm::Module& module,
1486 llvm::IRBuilder<>& builder,
1487 llvm::FunctionPassManager& fpm,
1488 std::string nativeThrowFunctName) {
1489 // Number of type infos to generate
1490 unsigned numTypeInfos = 6;
1492 // Initialze intrisics and external functions to use along with exception
1493 // and type info globals.
1494 createStandardUtilityFunctions(numTypeInfos,
1497 llvm::Function *nativeThrowFunct =
1498 module.getFunction(nativeThrowFunctName);
1500 // Create exception throw function using the value ~0 to cause
1501 // foreign exceptions to be thrown.
1502 llvm::Function* throwFunct =
1503 createThrowExceptionFunction(module,
1509 // Inner function will catch even type infos
1510 unsigned innerExceptionTypesToCatch[] = {6, 2, 4};
1511 size_t numExceptionTypesToCatch = sizeof(innerExceptionTypesToCatch) /
1514 // Generate inner function.
1515 llvm::Function* innerCatchFunct =
1516 createCatchWrappedInvokeFunction(module,
1521 numExceptionTypesToCatch,
1522 innerExceptionTypesToCatch);
1524 // Outer function will catch odd type infos
1525 unsigned outerExceptionTypesToCatch[] = {3, 1, 5};
1526 numExceptionTypesToCatch = sizeof(outerExceptionTypesToCatch) /
1529 // Generate outer function
1530 llvm::Function* outerCatchFunct =
1531 createCatchWrappedInvokeFunction(module,
1536 numExceptionTypesToCatch,
1537 outerExceptionTypesToCatch);
1539 // Return outer function to run
1540 return(outerCatchFunct);
1544 /// Represents our foreign exceptions
1545 class OurCppRunException : public std::runtime_error {
1547 OurCppRunException(const std::string reason) :
1548 std::runtime_error(reason) {}
1550 OurCppRunException (const OurCppRunException& toCopy) :
1551 std::runtime_error(toCopy) {}
1553 OurCppRunException& operator = (const OurCppRunException& toCopy) {
1554 return(reinterpret_cast<OurCppRunException&>(
1555 std::runtime_error::operator=(toCopy)));
1558 ~OurCppRunException (void) throw () {}
1562 /// Throws foreign C++ exception.
1563 /// @param ignoreIt unused parameter that allows function to match implied
1564 /// generated function contract.
1566 void throwCppException (int32_t ignoreIt) {
1567 throw(OurCppRunException("thrown by throwCppException(...)"));
1570 typedef void (*OurExceptionThrowFunctType) (int32_t typeToThrow);
1572 /// This is a test harness which runs test by executing generated
1573 /// function with a type info type to throw. Harness wraps the excecution
1574 /// of generated function in a C++ try catch clause.
1575 /// @param engine execution engine to use for executing generated function.
1576 /// This demo program expects this to be a JIT instance for demo
1578 /// @param function generated test function to run
1579 /// @param typeToThrow type info type of generated exception to throw, or
1580 /// indicator to cause foreign exception to be thrown.
1582 void runExceptionThrow(llvm::ExecutionEngine* engine,
1583 llvm::Function* function,
1584 int32_t typeToThrow) {
1586 // Find test's function pointer
1587 OurExceptionThrowFunctType functPtr =
1588 reinterpret_cast<OurExceptionThrowFunctType>(
1589 reinterpret_cast<intptr_t>(engine->getPointerToFunction(function)));
1593 (*functPtr)(typeToThrow);
1595 catch (OurCppRunException exc) {
1596 // Catch foreign C++ exception
1598 "\nrunExceptionThrow(...):In C++ catch OurCppRunException "
1599 "with reason: %s.\n",
1603 // Catch all exceptions including our generated ones. I'm not sure
1604 // why this latter functionality should work, as it seems that
1605 // our exceptions should be foreign to C++ (the _Unwind_Exception::
1606 // exception_class should be different from the one used by C++), and
1607 // therefore C++ should ignore the generated exceptions.
1610 "\nrunExceptionThrow(...):In C++ catch all.\n");
1615 // End test functions
1618 typedef llvm::ArrayRef<const llvm::Type*> TypeArray;
1620 /// This initialization routine creates type info globals and
1621 /// adds external function declarations to module.
1622 /// @param numTypeInfos number of linear type info associated type info types
1623 /// to create as GlobalVariable instances, starting with the value 1.
1624 /// @param module code for module instance
1625 /// @param builder builder instance
1626 static void createStandardUtilityFunctions(unsigned numTypeInfos,
1627 llvm::Module& module,
1628 llvm::IRBuilder<>& builder) {
1630 llvm::LLVMContext& context = module.getContext();
1632 // Exception initializations
1634 // Setup exception catch state
1635 ourExceptionNotThrownState =
1636 llvm::ConstantInt::get(llvm::Type::getInt8Ty(context), 0),
1637 ourExceptionThrownState =
1638 llvm::ConstantInt::get(llvm::Type::getInt8Ty(context), 1),
1639 ourExceptionCaughtState =
1640 llvm::ConstantInt::get(llvm::Type::getInt8Ty(context), 2),
1644 // Create our type info type
1645 ourTypeInfoType = llvm::StructType::get(context,
1646 TypeArray(builder.getInt32Ty()));
1648 // Create OurException type
1649 ourExceptionType = llvm::StructType::get(context,
1650 TypeArray(ourTypeInfoType));
1652 // Create portion of _Unwind_Exception type
1654 // Note: Declaring only a portion of the _Unwind_Exception struct.
1655 // Does this cause problems?
1656 ourUnwindExceptionType =
1657 llvm::StructType::get(context, TypeArray(builder.getInt64Ty()));
1658 struct OurBaseException_t dummyException;
1660 // Calculate offset of OurException::unwindException member.
1661 ourBaseFromUnwindOffset = ((uintptr_t) &dummyException) -
1662 ((uintptr_t) &(dummyException.unwindException));
1666 "createStandardUtilityFunctions(...):ourBaseFromUnwindOffset "
1667 "= %lld, sizeof(struct OurBaseException_t) - "
1668 "sizeof(struct _Unwind_Exception) = %lu.\n",
1669 ourBaseFromUnwindOffset,
1670 sizeof(struct OurBaseException_t) -
1671 sizeof(struct _Unwind_Exception));
1674 size_t numChars = sizeof(ourBaseExcpClassChars) / sizeof(char);
1676 // Create our _Unwind_Exception::exception_class value
1677 ourBaseExceptionClass = genClass(ourBaseExcpClassChars, numChars);
1681 std::string baseStr = "typeInfo", typeInfoName;
1682 std::ostringstream typeInfoNameBuilder;
1683 std::vector<llvm::Constant*> structVals;
1685 llvm::Constant *nextStruct;
1686 llvm::GlobalVariable* nextGlobal = NULL;
1688 // Generate each type info
1690 // Note: First type info is not used.
1691 for (unsigned i = 0; i <= numTypeInfos; ++i) {
1693 structVals.push_back(llvm::ConstantInt::get(builder.getInt32Ty(), i));
1694 nextStruct = llvm::ConstantStruct::get(ourTypeInfoType, structVals);
1696 typeInfoNameBuilder.str("");
1697 typeInfoNameBuilder << baseStr << i;
1698 typeInfoName = typeInfoNameBuilder.str();
1700 // Note: Does not seem to work without allocation
1702 new llvm::GlobalVariable(module,
1705 llvm::GlobalValue::ExternalLinkage,
1709 ourTypeInfoNames.push_back(typeInfoName);
1710 ourTypeInfoNamesIndex[i] = typeInfoName;
1715 llvm::Function* funct = NULL;
1719 const llvm::Type* retType = builder.getVoidTy();
1722 argTypes.push_back(builder.getInt32Ty());
1723 argTypes.push_back(builder.getInt8Ty()->getPointerTo());
1727 createFunction(module,
1732 llvm::Function::ExternalLinkage,
1738 retType = builder.getVoidTy();
1741 argTypes.push_back(builder.getInt64Ty());
1742 argTypes.push_back(builder.getInt8Ty()->getPointerTo());
1746 createFunction(module,
1751 llvm::Function::ExternalLinkage,
1757 retType = builder.getVoidTy();
1760 argTypes.push_back(builder.getInt8Ty()->getPointerTo());
1764 createFunction(module,
1769 llvm::Function::ExternalLinkage,
1773 // throwCppException
1775 retType = builder.getVoidTy();
1778 argTypes.push_back(builder.getInt32Ty());
1782 createFunction(module,
1786 "throwCppException",
1787 llvm::Function::ExternalLinkage,
1791 // deleteOurException
1793 retType = builder.getVoidTy();
1796 argTypes.push_back(builder.getInt8Ty()->getPointerTo());
1800 createFunction(module,
1804 "deleteOurException",
1805 llvm::Function::ExternalLinkage,
1809 // createOurException
1811 retType = builder.getInt8Ty()->getPointerTo();
1814 argTypes.push_back(builder.getInt32Ty());
1818 createFunction(module,
1822 "createOurException",
1823 llvm::Function::ExternalLinkage,
1827 // _Unwind_RaiseException
1829 retType = builder.getInt32Ty();
1832 argTypes.push_back(builder.getInt8Ty()->getPointerTo());
1836 funct = createFunction(module,
1840 "_Unwind_RaiseException",
1841 llvm::Function::ExternalLinkage,
1845 funct->addFnAttr(llvm::Attribute::NoReturn);
1849 retType = builder.getInt32Ty();
1852 argTypes.push_back(builder.getInt8Ty()->getPointerTo());
1856 funct = createFunction(module,
1861 llvm::Function::ExternalLinkage,
1865 funct->addFnAttr(llvm::Attribute::NoReturn);
1869 retType = builder.getInt32Ty();
1872 argTypes.push_back(builder.getInt32Ty());
1873 argTypes.push_back(builder.getInt32Ty());
1874 argTypes.push_back(builder.getInt64Ty());
1875 argTypes.push_back(builder.getInt8Ty()->getPointerTo());
1876 argTypes.push_back(builder.getInt8Ty()->getPointerTo());
1880 createFunction(module,
1885 llvm::Function::ExternalLinkage,
1889 // llvm.eh.selector intrinsic
1891 getDeclaration(&module, llvm::Intrinsic::eh_selector);
1893 // llvm.eh.exception intrinsic
1895 getDeclaration(&module, llvm::Intrinsic::eh_exception);
1897 // llvm.eh.typeid.for intrinsic
1899 getDeclaration(&module, llvm::Intrinsic::eh_typeid_for);
1903 //===----------------------------------------------------------------------===//
1904 // Main test driver code.
1905 //===----------------------------------------------------------------------===//
1907 /// Demo main routine which takes the type info types to throw. A test will
1908 /// be run for each given type info type. While type info types with the value
1909 /// of -1 will trigger a foreign C++ exception to be thrown; type info types
1910 /// <= 6 and >= 1 will be caught by test functions; and type info types > 6
1911 /// will result in exceptions which pass through to the test harness. All other
1912 /// type info types are not supported and could cause a crash.
1913 int main(int argc, char* argv[]) {
1916 "\nUsage: ExceptionDemo <exception type to throw> "
1917 "[<type 2>...<type n>].\n"
1918 " Each type must have the value of 1 - 6 for "
1919 "generated exceptions to be caught;\n"
1920 " the value -1 for foreign C++ exceptions to be "
1921 "generated and thrown;\n"
1922 " or the values > 6 for exceptions to be ignored.\n"
1923 "\nTry: ExceptionDemo 2 3 7 -1\n"
1924 " for a full test.\n\n");
1928 // If not set, exception handling will not be turned on
1929 llvm::JITExceptionHandling = true;
1931 llvm::InitializeNativeTarget();
1932 llvm::LLVMContext& context = llvm::getGlobalContext();
1933 llvm::IRBuilder<> theBuilder(context);
1935 // Make the module, which holds all the code.
1936 llvm::Module* module = new llvm::Module("my cool jit", context);
1938 // Build engine with JIT
1939 llvm::EngineBuilder factory(module);
1940 factory.setEngineKind(llvm::EngineKind::JIT);
1941 factory.setAllocateGVsWithCode(false);
1942 llvm::ExecutionEngine* executionEngine = factory.create();
1945 llvm::FunctionPassManager fpm(module);
1947 // Set up the optimizer pipeline.
1948 // Start with registering info about how the
1949 // target lays out data structures.
1950 fpm.add(new llvm::TargetData(*executionEngine->getTargetData()));
1952 // Optimizations turned on
1953 #ifdef ADD_OPT_PASSES
1955 // Basic AliasAnslysis support for GVN.
1956 fpm.add(llvm::createBasicAliasAnalysisPass());
1958 // Promote allocas to registers.
1959 fpm.add(llvm::createPromoteMemoryToRegisterPass());
1961 // Do simple "peephole" optimizations and bit-twiddling optzns.
1962 fpm.add(llvm::createInstructionCombiningPass());
1964 // Reassociate expressions.
1965 fpm.add(llvm::createReassociatePass());
1967 // Eliminate Common SubExpressions.
1968 fpm.add(llvm::createGVNPass());
1970 // Simplify the control flow graph (deleting unreachable
1972 fpm.add(llvm::createCFGSimplificationPass());
1973 #endif // ADD_OPT_PASSES
1975 fpm.doInitialization();
1977 // Generate test code using function throwCppException(...) as
1978 // the function which throws foreign exceptions.
1979 llvm::Function* toRun =
1980 createUnwindExceptionTest(*module,
1983 "throwCppException");
1985 fprintf(stderr, "\nBegin module dump:\n\n");
1989 fprintf(stderr, "\nEnd module dump:\n");
1991 fprintf(stderr, "\n\nBegin Test:\n");
1993 for (int i = 1; i < argc; ++i) {
1994 // Run test for each argument whose value is the exception
1996 runExceptionThrow(executionEngine,
1998 (unsigned) strtoul(argv[i], NULL, 10));
2001 fprintf(stderr, "\nEnd Test:\n\n");
2004 delete executionEngine;