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/TargetOptions.h"
60 #include "llvm/Transforms/Scalar.h"
61 #include "llvm/Support/IRBuilder.h"
62 #include "llvm/Support/Dwarf.h"
63 #include "llvm/Support/TargetSelect.h"
66 // See use of UpgradeExceptionHandling(...) below
67 #include "llvm/AutoUpgrade.h"
70 // FIXME: Although all systems tested with (Linux, OS X), do not need this
71 // header file included. A user on ubuntu reported, undefined symbols
72 // for stderr, and fprintf, and the addition of this include fixed the
73 // issue for them. Given that LLVM's best practices include the goal
74 // of reducing the number of redundant header files included, the
75 // correct solution would be to find out why these symbols are not
76 // defined for the system in question, and fix the issue by finding out
77 // which LLVM header file, if any, would include these symbols.
84 #ifndef USE_GLOBAL_STR_CONSTS
85 #define USE_GLOBAL_STR_CONSTS true
88 // System C++ ABI unwind types from:
89 // http://refspecs.freestandards.org/abi-eh-1.21.html
95 _URC_FOREIGN_EXCEPTION_CAUGHT = 1,
96 _URC_FATAL_PHASE2_ERROR = 2,
97 _URC_FATAL_PHASE1_ERROR = 3,
99 _URC_END_OF_STACK = 5,
100 _URC_HANDLER_FOUND = 6,
101 _URC_INSTALL_CONTEXT = 7,
102 _URC_CONTINUE_UNWIND = 8
103 } _Unwind_Reason_Code;
106 _UA_SEARCH_PHASE = 1,
107 _UA_CLEANUP_PHASE = 2,
108 _UA_HANDLER_FRAME = 4,
109 _UA_FORCE_UNWIND = 8,
110 _UA_END_OF_STACK = 16
113 struct _Unwind_Exception;
115 typedef void (*_Unwind_Exception_Cleanup_Fn) (_Unwind_Reason_Code,
116 struct _Unwind_Exception *);
118 struct _Unwind_Exception {
119 uint64_t exception_class;
120 _Unwind_Exception_Cleanup_Fn exception_cleanup;
125 // @@@ The IA-64 ABI says that this structure must be double-word aligned.
126 // Taking that literally does not make much sense generically. Instead
127 // we provide the maximum alignment required by any type for the machine.
128 } __attribute__((__aligned__));
130 struct _Unwind_Context;
131 typedef struct _Unwind_Context *_Unwind_Context_t;
133 extern const uint8_t *_Unwind_GetLanguageSpecificData (_Unwind_Context_t c);
134 extern uintptr_t _Unwind_GetGR (_Unwind_Context_t c, int i);
135 extern void _Unwind_SetGR (_Unwind_Context_t c, int i, uintptr_t n);
136 extern void _Unwind_SetIP (_Unwind_Context_t, uintptr_t new_value);
137 extern uintptr_t _Unwind_GetIP (_Unwind_Context_t context);
138 extern uintptr_t _Unwind_GetRegionStart (_Unwind_Context_t context);
146 /// This is our simplistic type info
147 struct OurExceptionType_t {
153 /// This is our Exception class which relies on a negative offset to calculate
154 /// pointers to its instances from pointers to its unwindException member.
156 /// Note: The above unwind.h defines struct _Unwind_Exception to be aligned
157 /// on a double word boundary. This is necessary to match the standard:
158 /// http://refspecs.freestandards.org/abi-eh-1.21.html
159 struct OurBaseException_t {
160 struct OurExceptionType_t type;
162 // Note: This is properly aligned in unwind.h
163 struct _Unwind_Exception unwindException;
167 // Note: Not needed since we are C++
168 typedef struct OurBaseException_t OurException;
169 typedef struct _Unwind_Exception OurUnwindException;
172 // Various globals used to support typeinfo and generatted exceptions in
176 static std::map<std::string, llvm::Value*> namedValues;
178 int64_t ourBaseFromUnwindOffset;
180 const unsigned char ourBaseExcpClassChars[] =
181 {'o', 'b', 'j', '\0', 'b', 'a', 's', '\0'};
184 static uint64_t ourBaseExceptionClass = 0;
186 static std::vector<std::string> ourTypeInfoNames;
187 static std::map<int, std::string> ourTypeInfoNamesIndex;
189 static llvm::StructType *ourTypeInfoType;
190 #ifndef OLD_EXC_SYSTEM
191 static llvm::StructType *ourCaughtResultType;
193 static llvm::StructType *ourExceptionType;
194 static llvm::StructType *ourUnwindExceptionType;
196 static llvm::ConstantInt *ourExceptionNotThrownState;
197 static llvm::ConstantInt *ourExceptionThrownState;
198 static llvm::ConstantInt *ourExceptionCaughtState;
200 typedef std::vector<std::string> ArgNames;
201 typedef std::vector<llvm::Type*> ArgTypes;
204 // Code Generation Utilities
207 /// Utility used to create a function, both declarations and definitions
208 /// @param module for module instance
209 /// @param retType function return type
210 /// @param theArgTypes function's ordered argument types
211 /// @param theArgNames function's ordered arguments needed if use of this
212 /// function corresponds to a function definition. Use empty
213 /// aggregate for function declarations.
214 /// @param functName function name
215 /// @param linkage function linkage
216 /// @param declarationOnly for function declarations
217 /// @param isVarArg function uses vararg arguments
218 /// @returns function instance
219 llvm::Function *createFunction(llvm::Module &module,
221 const ArgTypes &theArgTypes,
222 const ArgNames &theArgNames,
223 const std::string &functName,
224 llvm::GlobalValue::LinkageTypes linkage,
225 bool declarationOnly,
227 llvm::FunctionType *functType =
228 llvm::FunctionType::get(retType, theArgTypes, isVarArg);
229 llvm::Function *ret =
230 llvm::Function::Create(functType, linkage, functName, &module);
231 if (!ret || declarationOnly)
236 for (llvm::Function::arg_iterator argIndex = ret->arg_begin();
237 i != theArgNames.size();
240 argIndex->setName(theArgNames[i]);
241 namedValues[theArgNames[i]] = argIndex;
248 /// Create an alloca instruction in the entry block of
249 /// the parent function. This is used for mutable variables etc.
250 /// @param function parent instance
251 /// @param varName stack variable name
252 /// @param type stack variable type
253 /// @param initWith optional constant initialization value
254 /// @returns AllocaInst instance
255 static llvm::AllocaInst *createEntryBlockAlloca(llvm::Function &function,
256 const std::string &varName,
258 llvm::Constant *initWith = 0) {
259 llvm::BasicBlock &block = function.getEntryBlock();
260 llvm::IRBuilder<> tmp(&block, block.begin());
261 llvm::AllocaInst *ret = tmp.CreateAlloca(type, 0, varName.c_str());
264 tmp.CreateStore(initWith, ret);
271 // Code Generation Utilities End
275 // Runtime C Library functions
278 // Note: using an extern "C" block so that static functions can be used
281 // Note: Better ways to decide on bit width
283 /// Prints a 32 bit number, according to the format, to stderr.
284 /// @param intToPrint integer to print
285 /// @param format printf like format to use when printing
286 void print32Int(int intToPrint, const char *format) {
288 // Note: No NULL check
289 fprintf(stderr, format, intToPrint);
292 // Note: No NULL check
293 fprintf(stderr, "::print32Int(...):NULL arg.\n");
298 // Note: Better ways to decide on bit width
300 /// Prints a 64 bit number, according to the format, to stderr.
301 /// @param intToPrint integer to print
302 /// @param format printf like format to use when printing
303 void print64Int(long int intToPrint, const char *format) {
305 // Note: No NULL check
306 fprintf(stderr, format, intToPrint);
309 // Note: No NULL check
310 fprintf(stderr, "::print64Int(...):NULL arg.\n");
315 /// Prints a C string to stderr
316 /// @param toPrint string to print
317 void printStr(char *toPrint) {
319 fprintf(stderr, "%s", toPrint);
322 fprintf(stderr, "::printStr(...):NULL arg.\n");
327 /// Deletes the true previosly allocated exception whose address
328 /// is calculated from the supplied OurBaseException_t::unwindException
329 /// member address. Handles (ignores), NULL pointers.
330 /// @param expToDelete exception to delete
331 void deleteOurException(OurUnwindException *expToDelete) {
334 "deleteOurException(...).\n");
338 (expToDelete->exception_class == ourBaseExceptionClass)) {
340 free(((char*) expToDelete) + ourBaseFromUnwindOffset);
345 /// This function is the struct _Unwind_Exception API mandated delete function
346 /// used by foreign exception handlers when deleting our exception
347 /// (OurException), instances.
348 /// @param reason @link http://refspecs.freestandards.org/abi-eh-1.21.html
350 /// @param expToDelete exception instance to delete
351 void deleteFromUnwindOurException(_Unwind_Reason_Code reason,
352 OurUnwindException *expToDelete) {
355 "deleteFromUnwindOurException(...).\n");
358 deleteOurException(expToDelete);
362 /// Creates (allocates on the heap), an exception (OurException instance),
363 /// of the supplied type info type.
364 /// @param type type info type
365 OurUnwindException *createOurException(int type) {
366 size_t size = sizeof(OurException);
367 OurException *ret = (OurException*) memset(malloc(size), 0, size);
368 (ret->type).type = type;
369 (ret->unwindException).exception_class = ourBaseExceptionClass;
370 (ret->unwindException).exception_cleanup = deleteFromUnwindOurException;
372 return(&(ret->unwindException));
376 /// Read a uleb128 encoded value and advance pointer
377 /// See Variable Length Data in:
378 /// @link http://dwarfstd.org/Dwarf3.pdf @unlink
379 /// @param data reference variable holding memory pointer to decode from
380 /// @returns decoded value
381 static uintptr_t readULEB128(const uint8_t **data) {
382 uintptr_t result = 0;
385 const uint8_t *p = *data;
389 result |= (byte & 0x7f) << shift;
400 /// Read a sleb128 encoded value and advance pointer
401 /// See Variable Length Data in:
402 /// @link http://dwarfstd.org/Dwarf3.pdf @unlink
403 /// @param data reference variable holding memory pointer to decode from
404 /// @returns decoded value
405 static uintptr_t readSLEB128(const uint8_t **data) {
406 uintptr_t result = 0;
409 const uint8_t *p = *data;
413 result |= (byte & 0x7f) << shift;
420 if ((byte & 0x40) && (shift < (sizeof(result) << 3))) {
421 result |= (~0 << shift);
428 /// Read a pointer encoded value and advance pointer
429 /// See Variable Length Data in:
430 /// @link http://dwarfstd.org/Dwarf3.pdf @unlink
431 /// @param data reference variable holding memory pointer to decode from
432 /// @param encoding dwarf encoding type
433 /// @returns decoded value
434 static uintptr_t readEncodedPointer(const uint8_t **data, uint8_t encoding) {
435 uintptr_t result = 0;
436 const uint8_t *p = *data;
438 if (encoding == llvm::dwarf::DW_EH_PE_omit)
442 switch (encoding & 0x0F) {
443 case llvm::dwarf::DW_EH_PE_absptr:
444 result = *((uintptr_t*)p);
445 p += sizeof(uintptr_t);
447 case llvm::dwarf::DW_EH_PE_uleb128:
448 result = readULEB128(&p);
450 // Note: This case has not been tested
451 case llvm::dwarf::DW_EH_PE_sleb128:
452 result = readSLEB128(&p);
454 case llvm::dwarf::DW_EH_PE_udata2:
455 result = *((uint16_t*)p);
456 p += sizeof(uint16_t);
458 case llvm::dwarf::DW_EH_PE_udata4:
459 result = *((uint32_t*)p);
460 p += sizeof(uint32_t);
462 case llvm::dwarf::DW_EH_PE_udata8:
463 result = *((uint64_t*)p);
464 p += sizeof(uint64_t);
466 case llvm::dwarf::DW_EH_PE_sdata2:
467 result = *((int16_t*)p);
468 p += sizeof(int16_t);
470 case llvm::dwarf::DW_EH_PE_sdata4:
471 result = *((int32_t*)p);
472 p += sizeof(int32_t);
474 case llvm::dwarf::DW_EH_PE_sdata8:
475 result = *((int64_t*)p);
476 p += sizeof(int64_t);
484 // then add relative offset
485 switch (encoding & 0x70) {
486 case llvm::dwarf::DW_EH_PE_absptr:
489 case llvm::dwarf::DW_EH_PE_pcrel:
490 result += (uintptr_t)(*data);
492 case llvm::dwarf::DW_EH_PE_textrel:
493 case llvm::dwarf::DW_EH_PE_datarel:
494 case llvm::dwarf::DW_EH_PE_funcrel:
495 case llvm::dwarf::DW_EH_PE_aligned:
502 // then apply indirection
503 if (encoding & llvm::dwarf::DW_EH_PE_indirect) {
504 result = *((uintptr_t*)result);
513 /// Deals with Dwarf actions matching our type infos
514 /// (OurExceptionType_t instances). Returns whether or not a dwarf emitted
515 /// action matches the supplied exception type. If such a match succeeds,
516 /// the resultAction argument will be set with > 0 index value. Only
517 /// corresponding llvm.eh.selector type info arguments, cleanup arguments
518 /// are supported. Filters are not supported.
519 /// See Variable Length Data in:
520 /// @link http://dwarfstd.org/Dwarf3.pdf @unlink
521 /// Also see @link http://refspecs.freestandards.org/abi-eh-1.21.html @unlink
522 /// @param resultAction reference variable which will be set with result
523 /// @param classInfo our array of type info pointers (to globals)
524 /// @param actionEntry index into above type info array or 0 (clean up).
525 /// We do not support filters.
526 /// @param exceptionClass exception class (_Unwind_Exception::exception_class)
527 /// of thrown exception.
528 /// @param exceptionObject thrown _Unwind_Exception instance.
529 /// @returns whether or not a type info was found. False is returned if only
530 /// a cleanup was found
531 static bool handleActionValue(int64_t *resultAction,
532 struct OurExceptionType_t **classInfo,
533 uintptr_t actionEntry,
534 uint64_t exceptionClass,
535 struct _Unwind_Exception *exceptionObject) {
540 (exceptionClass != ourBaseExceptionClass))
543 struct OurBaseException_t *excp = (struct OurBaseException_t*)
544 (((char*) exceptionObject) + ourBaseFromUnwindOffset);
545 struct OurExceptionType_t *excpType = &(excp->type);
546 int type = excpType->type;
550 "handleActionValue(...): exceptionObject = <%p>, "
556 const uint8_t *actionPos = (uint8_t*) actionEntry,
558 int64_t typeOffset = 0,
561 for (int i = 0; true; ++i) {
562 // Each emitted dwarf action corresponds to a 2 tuple of
563 // type info address offset, and action offset to the next
565 typeOffset = readSLEB128(&actionPos);
566 tempActionPos = actionPos;
567 actionOffset = readSLEB128(&tempActionPos);
571 "handleActionValue(...):typeOffset: <%lld>, "
572 "actionOffset: <%lld>.\n",
576 assert((typeOffset >= 0) &&
577 "handleActionValue(...):filters are not supported.");
579 // Note: A typeOffset == 0 implies that a cleanup llvm.eh.selector
580 // argument has been matched.
581 if ((typeOffset > 0) &&
582 (type == (classInfo[-typeOffset])->type)) {
585 "handleActionValue(...):actionValue <%d> found.\n",
588 *resultAction = i + 1;
595 "handleActionValue(...):actionValue not found.\n");
600 actionPos += actionOffset;
607 /// Deals with the Language specific data portion of the emitted dwarf code.
608 /// See @link http://refspecs.freestandards.org/abi-eh-1.21.html @unlink
609 /// @param version unsupported (ignored), unwind version
610 /// @param lsda language specific data area
611 /// @param _Unwind_Action actions minimally supported unwind stage
612 /// (forced specifically not supported)
613 /// @param exceptionClass exception class (_Unwind_Exception::exception_class)
614 /// of thrown exception.
615 /// @param exceptionObject thrown _Unwind_Exception instance.
616 /// @param context unwind system context
617 /// @returns minimally supported unwinding control indicator
618 static _Unwind_Reason_Code handleLsda(int version,
620 _Unwind_Action actions,
621 uint64_t exceptionClass,
622 struct _Unwind_Exception *exceptionObject,
623 _Unwind_Context_t context) {
624 _Unwind_Reason_Code ret = _URC_CONTINUE_UNWIND;
631 "handleLsda(...):lsda is non-zero.\n");
634 // Get the current instruction pointer and offset it before next
635 // instruction in the current frame which threw the exception.
636 uintptr_t pc = _Unwind_GetIP(context)-1;
638 // Get beginning current frame's code (as defined by the
639 // emitted dwarf code)
640 uintptr_t funcStart = _Unwind_GetRegionStart(context);
641 uintptr_t pcOffset = pc - funcStart;
642 struct OurExceptionType_t **classInfo = NULL;
644 // Note: See JITDwarfEmitter::EmitExceptionTable(...) for corresponding
647 // Parse LSDA header.
648 uint8_t lpStartEncoding = *lsda++;
650 if (lpStartEncoding != llvm::dwarf::DW_EH_PE_omit) {
651 readEncodedPointer(&lsda, lpStartEncoding);
654 uint8_t ttypeEncoding = *lsda++;
655 uintptr_t classInfoOffset;
657 if (ttypeEncoding != llvm::dwarf::DW_EH_PE_omit) {
658 // Calculate type info locations in emitted dwarf code which
659 // were flagged by type info arguments to llvm.eh.selector
661 classInfoOffset = readULEB128(&lsda);
662 classInfo = (struct OurExceptionType_t**) (lsda + classInfoOffset);
665 // Walk call-site table looking for range that
666 // includes current PC.
668 uint8_t callSiteEncoding = *lsda++;
669 uint32_t callSiteTableLength = readULEB128(&lsda);
670 const uint8_t *callSiteTableStart = lsda;
671 const uint8_t *callSiteTableEnd = callSiteTableStart +
673 const uint8_t *actionTableStart = callSiteTableEnd;
674 const uint8_t *callSitePtr = callSiteTableStart;
676 bool foreignException = false;
678 while (callSitePtr < callSiteTableEnd) {
679 uintptr_t start = readEncodedPointer(&callSitePtr,
681 uintptr_t length = readEncodedPointer(&callSitePtr,
683 uintptr_t landingPad = readEncodedPointer(&callSitePtr,
686 // Note: Action value
687 uintptr_t actionEntry = readULEB128(&callSitePtr);
689 if (exceptionClass != ourBaseExceptionClass) {
690 // We have been notified of a foreign exception being thrown,
691 // and we therefore need to execute cleanup landing pads
693 foreignException = true;
696 if (landingPad == 0) {
699 "handleLsda(...): No landing pad found.\n");
702 continue; // no landing pad for this entry
706 actionEntry += ((uintptr_t) actionTableStart) - 1;
711 "handleLsda(...):No action table found.\n");
715 bool exceptionMatched = false;
717 if ((start <= pcOffset) && (pcOffset < (start + length))) {
720 "handleLsda(...): Landing pad found.\n");
722 int64_t actionValue = 0;
725 exceptionMatched = handleActionValue(&actionValue,
732 if (!(actions & _UA_SEARCH_PHASE)) {
735 "handleLsda(...): installed landing pad "
739 // Found landing pad for the PC.
740 // Set Instruction Pointer to so we re-enter function
741 // at landing pad. The landing pad is created by the
742 // compiler to take two parameters in registers.
743 _Unwind_SetGR(context,
744 __builtin_eh_return_data_regno(0),
745 (uintptr_t)exceptionObject);
747 // Note: this virtual register directly corresponds
748 // to the return of the llvm.eh.selector intrinsic
749 if (!actionEntry || !exceptionMatched) {
750 // We indicate cleanup only
751 _Unwind_SetGR(context,
752 __builtin_eh_return_data_regno(1),
756 // Matched type info index of llvm.eh.selector intrinsic
758 _Unwind_SetGR(context,
759 __builtin_eh_return_data_regno(1),
763 // To execute landing pad set here
764 _Unwind_SetIP(context, funcStart + landingPad);
765 ret = _URC_INSTALL_CONTEXT;
767 else if (exceptionMatched) {
770 "handleLsda(...): setting handler found.\n");
772 ret = _URC_HANDLER_FOUND;
775 // Note: Only non-clean up handlers are marked as
776 // found. Otherwise the clean up handlers will be
777 // re-found and executed during the clean up
781 "handleLsda(...): cleanup handler found.\n");
793 /// This is the personality function which is embedded (dwarf emitted), in the
794 /// dwarf unwind info block. Again see: JITDwarfEmitter.cpp.
795 /// See @link http://refspecs.freestandards.org/abi-eh-1.21.html @unlink
796 /// @param version unsupported (ignored), unwind version
797 /// @param _Unwind_Action actions minimally supported unwind stage
798 /// (forced specifically not supported)
799 /// @param exceptionClass exception class (_Unwind_Exception::exception_class)
800 /// of thrown exception.
801 /// @param exceptionObject thrown _Unwind_Exception instance.
802 /// @param context unwind system context
803 /// @returns minimally supported unwinding control indicator
804 _Unwind_Reason_Code ourPersonality(int version,
805 _Unwind_Action actions,
806 uint64_t exceptionClass,
807 struct _Unwind_Exception *exceptionObject,
808 _Unwind_Context_t context) {
811 "We are in ourPersonality(...):actions is <%d>.\n",
814 if (actions & _UA_SEARCH_PHASE) {
815 fprintf(stderr, "ourPersonality(...):In search phase.\n");
818 fprintf(stderr, "ourPersonality(...):In non-search phase.\n");
822 const uint8_t *lsda = _Unwind_GetLanguageSpecificData(context);
826 "ourPersonality(...):lsda = <%p>.\n",
830 // The real work of the personality function is captured here
831 return(handleLsda(version,
840 /// Generates our _Unwind_Exception class from a given character array.
841 /// thereby handling arbitrary lengths (not in standard), and handling
843 /// See @link http://refspecs.freestandards.org/abi-eh-1.21.html @unlink
844 /// @param classChars char array to encode. NULL values not checkedf
845 /// @param classCharsSize number of chars in classChars. Value is not checked.
846 /// @returns class value
847 uint64_t genClass(const unsigned char classChars[], size_t classCharsSize)
849 uint64_t ret = classChars[0];
851 for (unsigned i = 1; i < classCharsSize; ++i) {
853 ret += classChars[i];
862 // Runtime C Library functions End
866 // Code generation functions
869 /// Generates code to print given constant string
870 /// @param context llvm context
871 /// @param module code for module instance
872 /// @param builder builder instance
873 /// @param toPrint string to print
874 /// @param useGlobal A value of true (default) indicates a GlobalValue is
875 /// generated, and is used to hold the constant string. A value of
876 /// false indicates that the constant string will be stored on the
878 void generateStringPrint(llvm::LLVMContext &context,
879 llvm::Module &module,
880 llvm::IRBuilder<> &builder,
882 bool useGlobal = true) {
883 llvm::Function *printFunct = module.getFunction("printStr");
885 llvm::Value *stringVar;
886 llvm::Constant *stringConstant =
887 llvm::ConstantArray::get(context, toPrint);
890 // Note: Does not work without allocation
892 new llvm::GlobalVariable(module,
893 stringConstant->getType(),
895 llvm::GlobalValue::LinkerPrivateLinkage,
900 stringVar = builder.CreateAlloca(stringConstant->getType());
901 builder.CreateStore(stringConstant, stringVar);
904 llvm::Value *cast = builder.CreatePointerCast(stringVar,
905 builder.getInt8PtrTy());
906 builder.CreateCall(printFunct, cast);
910 /// Generates code to print given runtime integer according to constant
911 /// string format, and a given print function.
912 /// @param context llvm context
913 /// @param module code for module instance
914 /// @param builder builder instance
915 /// @param printFunct function used to "print" integer
916 /// @param toPrint string to print
917 /// @param format printf like formating string for print
918 /// @param useGlobal A value of true (default) indicates a GlobalValue is
919 /// generated, and is used to hold the constant string. A value of
920 /// false indicates that the constant string will be stored on the
922 void generateIntegerPrint(llvm::LLVMContext &context,
923 llvm::Module &module,
924 llvm::IRBuilder<> &builder,
925 llvm::Function &printFunct,
926 llvm::Value &toPrint,
928 bool useGlobal = true) {
929 llvm::Constant *stringConstant = llvm::ConstantArray::get(context, format);
930 llvm::Value *stringVar;
933 // Note: Does not seem to work without allocation
935 new llvm::GlobalVariable(module,
936 stringConstant->getType(),
938 llvm::GlobalValue::LinkerPrivateLinkage,
943 stringVar = builder.CreateAlloca(stringConstant->getType());
944 builder.CreateStore(stringConstant, stringVar);
947 llvm::Value *cast = builder.CreateBitCast(stringVar,
948 builder.getInt8PtrTy());
949 builder.CreateCall2(&printFunct, &toPrint, cast);
953 /// Generates code to handle finally block type semantics: always runs
954 /// regardless of whether a thrown exception is passing through or the
955 /// parent function is simply exiting. In addition to printing some state
956 /// to stderr, this code will resume the exception handling--runs the
957 /// unwind resume block, if the exception has not been previously caught
958 /// by a catch clause, and will otherwise execute the end block (terminator
959 /// block). In addition this function creates the corresponding function's
960 /// stack storage for the exception pointer and catch flag status.
961 /// @param context llvm context
962 /// @param module code for module instance
963 /// @param builder builder instance
964 /// @param toAddTo parent function to add block to
965 /// @param blockName block name of new "finally" block.
966 /// @param functionId output id used for printing
967 /// @param terminatorBlock terminator "end" block
968 /// @param unwindResumeBlock unwind resume block
969 /// @param exceptionCaughtFlag reference exception caught/thrown status storage
970 /// @param exceptionStorage reference to exception pointer storage
971 #ifndef OLD_EXC_SYSTEM
972 /// @param caughtResultStorage reference to landingpad result storage
974 /// @returns newly created block
975 static llvm::BasicBlock *createFinallyBlock(llvm::LLVMContext &context,
976 llvm::Module &module,
977 llvm::IRBuilder<> &builder,
978 llvm::Function &toAddTo,
979 std::string &blockName,
980 std::string &functionId,
981 llvm::BasicBlock &terminatorBlock,
982 llvm::BasicBlock &unwindResumeBlock,
983 llvm::Value **exceptionCaughtFlag,
984 llvm::Value **exceptionStorage
985 #ifndef OLD_EXC_SYSTEM
986 ,llvm::Value **caughtResultStorage
989 assert(exceptionCaughtFlag &&
990 "ExceptionDemo::createFinallyBlock(...):exceptionCaughtFlag "
992 assert(exceptionStorage &&
993 "ExceptionDemo::createFinallyBlock(...):exceptionStorage "
996 #ifndef OLD_EXC_SYSTEM
997 assert(caughtResultStorage &&
998 "ExceptionDemo::createFinallyBlock(...):caughtResultStorage "
1002 *exceptionCaughtFlag = createEntryBlockAlloca(toAddTo,
1004 ourExceptionNotThrownState->getType(),
1005 ourExceptionNotThrownState);
1007 llvm::PointerType *exceptionStorageType = builder.getInt8PtrTy();
1008 *exceptionStorage = createEntryBlockAlloca(toAddTo,
1010 exceptionStorageType,
1011 llvm::ConstantPointerNull::get(
1012 exceptionStorageType));
1013 #ifndef OLD_EXC_SYSTEM
1014 *caughtResultStorage = createEntryBlockAlloca(toAddTo,
1015 "caughtResultStorage",
1016 ourCaughtResultType,
1017 llvm::ConstantAggregateZero::get(
1018 ourCaughtResultType));
1021 llvm::BasicBlock *ret = llvm::BasicBlock::Create(context,
1025 builder.SetInsertPoint(ret);
1027 std::ostringstream bufferToPrint;
1028 bufferToPrint << "Gen: Executing finally block "
1029 << blockName << " in " << functionId << "\n";
1030 generateStringPrint(context,
1033 bufferToPrint.str(),
1034 USE_GLOBAL_STR_CONSTS);
1036 llvm::SwitchInst *theSwitch = builder.CreateSwitch(builder.CreateLoad(
1037 *exceptionCaughtFlag),
1040 theSwitch->addCase(ourExceptionCaughtState, &terminatorBlock);
1041 theSwitch->addCase(ourExceptionThrownState, &unwindResumeBlock);
1047 /// Generates catch block semantics which print a string to indicate type of
1048 /// catch executed, sets an exception caught flag, and executes passed in
1049 /// end block (terminator block).
1050 /// @param context llvm context
1051 /// @param module code for module instance
1052 /// @param builder builder instance
1053 /// @param toAddTo parent function to add block to
1054 /// @param blockName block name of new "catch" block.
1055 /// @param functionId output id used for printing
1056 /// @param terminatorBlock terminator "end" block
1057 /// @param exceptionCaughtFlag exception caught/thrown status
1058 /// @returns newly created block
1059 static llvm::BasicBlock *createCatchBlock(llvm::LLVMContext &context,
1060 llvm::Module &module,
1061 llvm::IRBuilder<> &builder,
1062 llvm::Function &toAddTo,
1063 std::string &blockName,
1064 std::string &functionId,
1065 llvm::BasicBlock &terminatorBlock,
1066 llvm::Value &exceptionCaughtFlag) {
1068 llvm::BasicBlock *ret = llvm::BasicBlock::Create(context,
1072 builder.SetInsertPoint(ret);
1074 std::ostringstream bufferToPrint;
1075 bufferToPrint << "Gen: Executing catch block "
1080 generateStringPrint(context,
1083 bufferToPrint.str(),
1084 USE_GLOBAL_STR_CONSTS);
1085 builder.CreateStore(ourExceptionCaughtState, &exceptionCaughtFlag);
1086 builder.CreateBr(&terminatorBlock);
1092 /// Generates a function which invokes a function (toInvoke) and, whose
1093 /// unwind block will "catch" the type info types correspondingly held in the
1094 /// exceptionTypesToCatch argument. If the toInvoke function throws an
1095 /// exception which does not match any type info types contained in
1096 /// exceptionTypesToCatch, the generated code will call _Unwind_Resume
1097 /// with the raised exception. On the other hand the generated code will
1098 /// normally exit if the toInvoke function does not throw an exception.
1099 /// The generated "finally" block is always run regardless of the cause of
1100 /// the generated function exit.
1101 /// The generated function is returned after being verified.
1102 /// @param module code for module instance
1103 /// @param builder builder instance
1104 /// @param fpm a function pass manager holding optional IR to IR
1106 /// @param toInvoke inner function to invoke
1107 /// @param ourId id used to printing purposes
1108 /// @param numExceptionsToCatch length of exceptionTypesToCatch array
1109 /// @param exceptionTypesToCatch array of type info types to "catch"
1110 /// @returns generated function
1112 llvm::Function *createCatchWrappedInvokeFunction(llvm::Module &module,
1113 llvm::IRBuilder<> &builder,
1114 llvm::FunctionPassManager &fpm,
1115 llvm::Function &toInvoke,
1117 unsigned numExceptionsToCatch,
1118 unsigned exceptionTypesToCatch[]) {
1120 llvm::LLVMContext &context = module.getContext();
1121 llvm::Function *toPrint32Int = module.getFunction("print32Int");
1124 argTypes.push_back(builder.getInt32Ty());
1127 argNames.push_back("exceptTypeToThrow");
1129 llvm::Function *ret = createFunction(module,
1130 builder.getVoidTy(),
1134 llvm::Function::ExternalLinkage,
1138 // Block which calls invoke
1139 llvm::BasicBlock *entryBlock = llvm::BasicBlock::Create(context,
1142 // Normal block for invoke
1143 llvm::BasicBlock *normalBlock = llvm::BasicBlock::Create(context,
1146 // Unwind block for invoke
1147 llvm::BasicBlock *exceptionBlock = llvm::BasicBlock::Create(context,
1151 // Block which routes exception to correct catch handler block
1152 llvm::BasicBlock *exceptionRouteBlock = llvm::BasicBlock::Create(context,
1156 // Foreign exception handler
1157 llvm::BasicBlock *externalExceptionBlock = llvm::BasicBlock::Create(context,
1158 "externalException",
1161 // Block which calls _Unwind_Resume
1162 llvm::BasicBlock *unwindResumeBlock = llvm::BasicBlock::Create(context,
1166 // Clean up block which delete exception if needed
1167 llvm::BasicBlock *endBlock = llvm::BasicBlock::Create(context, "end", ret);
1169 std::string nextName;
1170 std::vector<llvm::BasicBlock*> catchBlocks(numExceptionsToCatch);
1171 llvm::Value *exceptionCaughtFlag = NULL;
1172 llvm::Value *exceptionStorage = NULL;
1173 #ifndef OLD_EXC_SYSTEM
1174 llvm::Value *caughtResultStorage = NULL;
1177 // Finally block which will branch to unwindResumeBlock if
1178 // exception is not caught. Initializes/allocates stack locations.
1179 llvm::BasicBlock *finallyBlock = createFinallyBlock(context,
1183 nextName = "finally",
1187 &exceptionCaughtFlag,
1189 #ifndef OLD_EXC_SYSTEM
1190 ,&caughtResultStorage
1194 for (unsigned i = 0; i < numExceptionsToCatch; ++i) {
1195 nextName = ourTypeInfoNames[exceptionTypesToCatch[i]];
1197 // One catch block per type info to be caught
1198 catchBlocks[i] = createCatchBlock(context,
1205 *exceptionCaughtFlag);
1210 builder.SetInsertPoint(entryBlock);
1212 std::vector<llvm::Value*> args;
1213 args.push_back(namedValues["exceptTypeToThrow"]);
1214 builder.CreateInvoke(&toInvoke,
1221 builder.SetInsertPoint(endBlock);
1223 generateStringPrint(context,
1226 "Gen: In end block: exiting in " + ourId + ".\n",
1227 USE_GLOBAL_STR_CONSTS);
1228 llvm::Function *deleteOurException = module.getFunction("deleteOurException");
1230 // Note: function handles NULL exceptions
1231 builder.CreateCall(deleteOurException,
1232 builder.CreateLoad(exceptionStorage));
1233 builder.CreateRetVoid();
1237 builder.SetInsertPoint(normalBlock);
1239 generateStringPrint(context,
1242 "Gen: No exception in " + ourId + "!\n",
1243 USE_GLOBAL_STR_CONSTS);
1245 // Finally block is always called
1246 builder.CreateBr(finallyBlock);
1248 // Unwind Resume Block
1250 builder.SetInsertPoint(unwindResumeBlock);
1253 #ifndef OLD_EXC_SYSTEM
1254 builder.CreateResume(builder.CreateLoad(caughtResultStorage));
1256 llvm::Function *resumeOurException = module.getFunction("_Unwind_Resume");
1257 builder.CreateCall(resumeOurException,
1258 builder.CreateLoad(exceptionStorage));
1259 builder.CreateUnreachable();
1264 builder.SetInsertPoint(exceptionBlock);
1266 llvm::Function *personality = module.getFunction("ourPersonality");
1268 #ifndef OLD_EXC_SYSTEM
1269 llvm::LandingPadInst *caughtResult =
1270 builder.CreateLandingPad(ourCaughtResultType,
1272 numExceptionsToCatch,
1275 caughtResult->setCleanup(true);
1277 for (unsigned i = 0; i < numExceptionsToCatch; ++i) {
1278 // Set up type infos to be caught
1279 caughtResult->addClause(module.getGlobalVariable(
1280 ourTypeInfoNames[exceptionTypesToCatch[i]]));
1283 llvm::Value *unwindException = builder.CreateExtractValue(caughtResult, 0);
1284 llvm::Value *retTypeInfoIndex = builder.CreateExtractValue(caughtResult, 1);
1286 // FIXME: Redundant storage which, beyond utilizing value of
1287 // caughtResultStore for unwindException storage, may be alleviated
1288 // alltogether with a block rearrangement
1289 builder.CreateStore(caughtResult, caughtResultStorage);
1290 builder.CreateStore(unwindException, exceptionStorage);
1291 builder.CreateStore(ourExceptionThrownState, exceptionCaughtFlag);
1293 llvm::Function *ehException = module.getFunction("llvm.eh.exception");
1295 // Retrieve thrown exception
1296 llvm::Value *unwindException = builder.CreateCall(ehException);
1298 // Store exception and flag
1299 builder.CreateStore(unwindException, exceptionStorage);
1300 builder.CreateStore(ourExceptionThrownState, exceptionCaughtFlag);
1301 llvm::Value *functPtr = builder.CreatePointerCast(personality,
1302 builder.getInt8PtrTy());
1305 args.push_back(unwindException);
1306 args.push_back(functPtr);
1308 // Note: Skipping index 0
1309 for (unsigned i = 0; i < numExceptionsToCatch; ++i) {
1310 // Set up type infos to be caught
1311 args.push_back(module.getGlobalVariable(
1312 ourTypeInfoNames[exceptionTypesToCatch[i]]));
1315 args.push_back(llvm::ConstantInt::get(builder.getInt32Ty(), 0));
1317 llvm::Function *ehSelector = module.getFunction("llvm.eh.selector");
1319 // Set up this exeption block as the landing pad which will handle
1320 // given type infos. See case Intrinsic::eh_selector in
1321 // SelectionDAGBuilder::visitIntrinsicCall(...) and AddCatchInfo(...)
1322 // implemented in FunctionLoweringInfo.cpp to see how the implementation
1323 // handles this call. This landing pad (this exception block), will be
1324 // called either because it nees to cleanup (call finally) or a type
1325 // info was found which matched the thrown exception.
1326 llvm::Value *retTypeInfoIndex = builder.CreateCall(ehSelector, args);
1329 // Retrieve exception_class member from thrown exception
1330 // (_Unwind_Exception instance). This member tells us whether or not
1331 // the exception is foreign.
1332 llvm::Value *unwindExceptionClass =
1333 builder.CreateLoad(builder.CreateStructGEP(
1334 builder.CreatePointerCast(unwindException,
1335 ourUnwindExceptionType->getPointerTo()),
1338 // Branch to the externalExceptionBlock if the exception is foreign or
1339 // to a catch router if not. Either way the finally block will be run.
1340 builder.CreateCondBr(builder.CreateICmpEQ(unwindExceptionClass,
1341 llvm::ConstantInt::get(builder.getInt64Ty(),
1342 ourBaseExceptionClass)),
1343 exceptionRouteBlock,
1344 externalExceptionBlock);
1346 // External Exception Block
1348 builder.SetInsertPoint(externalExceptionBlock);
1350 generateStringPrint(context,
1353 "Gen: Foreign exception received.\n",
1354 USE_GLOBAL_STR_CONSTS);
1356 // Branch to the finally block
1357 builder.CreateBr(finallyBlock);
1359 // Exception Route Block
1361 builder.SetInsertPoint(exceptionRouteBlock);
1363 // Casts exception pointer (_Unwind_Exception instance) to parent
1364 // (OurException instance).
1366 // Note: ourBaseFromUnwindOffset is usually negative
1367 llvm::Value *typeInfoThrown = builder.CreatePointerCast(
1368 builder.CreateConstGEP1_64(unwindException,
1369 ourBaseFromUnwindOffset),
1370 ourExceptionType->getPointerTo());
1372 // Retrieve thrown exception type info type
1374 // Note: Index is not relative to pointer but instead to structure
1375 // unlike a true getelementptr (GEP) instruction
1376 typeInfoThrown = builder.CreateStructGEP(typeInfoThrown, 0);
1378 llvm::Value *typeInfoThrownType =
1379 builder.CreateStructGEP(typeInfoThrown, 0);
1381 generateIntegerPrint(context,
1385 *(builder.CreateLoad(typeInfoThrownType)),
1386 "Gen: Exception type <%d> received (stack unwound) "
1390 USE_GLOBAL_STR_CONSTS);
1392 // Route to matched type info catch block or run cleanup finally block
1393 llvm::SwitchInst *switchToCatchBlock = builder.CreateSwitch(retTypeInfoIndex,
1395 numExceptionsToCatch);
1397 unsigned nextTypeToCatch;
1399 for (unsigned i = 1; i <= numExceptionsToCatch; ++i) {
1400 nextTypeToCatch = i - 1;
1401 switchToCatchBlock->addCase(llvm::ConstantInt::get(
1402 llvm::Type::getInt32Ty(context), i),
1403 catchBlocks[nextTypeToCatch]);
1406 #ifdef OLD_EXC_SYSTEM
1407 // Must be run before verifier
1408 UpgradeExceptionHandling(&module);
1412 llvm::verifyFunction(*ret);
1419 /// Generates function which throws either an exception matched to a runtime
1420 /// determined type info type (argument to generated function), or if this
1421 /// runtime value matches nativeThrowType, throws a foreign exception by
1422 /// calling nativeThrowFunct.
1423 /// @param module code for module instance
1424 /// @param builder builder instance
1425 /// @param fpm a function pass manager holding optional IR to IR
1427 /// @param ourId id used to printing purposes
1428 /// @param nativeThrowType a runtime argument of this value results in
1429 /// nativeThrowFunct being called to generate/throw exception.
1430 /// @param nativeThrowFunct function which will throw a foreign exception
1431 /// if the above nativeThrowType matches generated function's arg.
1432 /// @returns generated function
1434 llvm::Function *createThrowExceptionFunction(llvm::Module &module,
1435 llvm::IRBuilder<> &builder,
1436 llvm::FunctionPassManager &fpm,
1438 int32_t nativeThrowType,
1439 llvm::Function &nativeThrowFunct) {
1440 llvm::LLVMContext &context = module.getContext();
1441 namedValues.clear();
1442 ArgTypes unwindArgTypes;
1443 unwindArgTypes.push_back(builder.getInt32Ty());
1444 ArgNames unwindArgNames;
1445 unwindArgNames.push_back("exceptTypeToThrow");
1447 llvm::Function *ret = createFunction(module,
1448 builder.getVoidTy(),
1452 llvm::Function::ExternalLinkage,
1456 // Throws either one of our exception or a native C++ exception depending
1457 // on a runtime argument value containing a type info type.
1458 llvm::BasicBlock *entryBlock = llvm::BasicBlock::Create(context,
1461 // Throws a foreign exception
1462 llvm::BasicBlock *nativeThrowBlock = llvm::BasicBlock::Create(context,
1465 // Throws one of our Exceptions
1466 llvm::BasicBlock *generatedThrowBlock = llvm::BasicBlock::Create(context,
1469 // Retrieved runtime type info type to throw
1470 llvm::Value *exceptionType = namedValues["exceptTypeToThrow"];
1472 // nativeThrowBlock block
1474 builder.SetInsertPoint(nativeThrowBlock);
1476 // Throws foreign exception
1477 builder.CreateCall(&nativeThrowFunct, exceptionType);
1478 builder.CreateUnreachable();
1482 builder.SetInsertPoint(entryBlock);
1484 llvm::Function *toPrint32Int = module.getFunction("print32Int");
1485 generateIntegerPrint(context,
1490 "\nGen: About to throw exception type <%d> in " +
1493 USE_GLOBAL_STR_CONSTS);
1495 // Switches on runtime type info type value to determine whether or not
1496 // a foreign exception is thrown. Defaults to throwing one of our
1497 // generated exceptions.
1498 llvm::SwitchInst *theSwitch = builder.CreateSwitch(exceptionType,
1499 generatedThrowBlock,
1502 theSwitch->addCase(llvm::ConstantInt::get(llvm::Type::getInt32Ty(context),
1506 // generatedThrow block
1508 builder.SetInsertPoint(generatedThrowBlock);
1510 llvm::Function *createOurException = module.getFunction("createOurException");
1511 llvm::Function *raiseOurException = module.getFunction(
1512 "_Unwind_RaiseException");
1514 // Creates exception to throw with runtime type info type.
1515 llvm::Value *exception = builder.CreateCall(createOurException,
1516 namedValues["exceptTypeToThrow"]);
1518 // Throw generated Exception
1519 builder.CreateCall(raiseOurException, exception);
1520 builder.CreateUnreachable();
1522 llvm::verifyFunction(*ret);
1528 static void createStandardUtilityFunctions(unsigned numTypeInfos,
1529 llvm::Module &module,
1530 llvm::IRBuilder<> &builder);
1532 /// Creates test code by generating and organizing these functions into the
1533 /// test case. The test case consists of an outer function setup to invoke
1534 /// an inner function within an environment having multiple catch and single
1535 /// finally blocks. This inner function is also setup to invoke a throw
1536 /// function within an evironment similar in nature to the outer function's
1537 /// catch and finally blocks. Each of these two functions catch mutually
1538 /// exclusive subsets (even or odd) of the type info types configured
1539 /// for this this. All generated functions have a runtime argument which
1540 /// holds a type info type to throw that each function takes and passes it
1541 /// to the inner one if such a inner function exists. This type info type is
1542 /// looked at by the generated throw function to see whether or not it should
1543 /// throw a generated exception with the same type info type, or instead call
1544 /// a supplied a function which in turn will throw a foreign exception.
1545 /// @param module code for module instance
1546 /// @param builder builder instance
1547 /// @param fpm a function pass manager holding optional IR to IR
1549 /// @param nativeThrowFunctName name of external function which will throw
1550 /// a foreign exception
1551 /// @returns outermost generated test function.
1552 llvm::Function *createUnwindExceptionTest(llvm::Module &module,
1553 llvm::IRBuilder<> &builder,
1554 llvm::FunctionPassManager &fpm,
1555 std::string nativeThrowFunctName) {
1556 // Number of type infos to generate
1557 unsigned numTypeInfos = 6;
1559 // Initialze intrisics and external functions to use along with exception
1560 // and type info globals.
1561 createStandardUtilityFunctions(numTypeInfos,
1564 llvm::Function *nativeThrowFunct = module.getFunction(nativeThrowFunctName);
1566 // Create exception throw function using the value ~0 to cause
1567 // foreign exceptions to be thrown.
1568 llvm::Function *throwFunct = createThrowExceptionFunction(module,
1574 // Inner function will catch even type infos
1575 unsigned innerExceptionTypesToCatch[] = {6, 2, 4};
1576 size_t numExceptionTypesToCatch = sizeof(innerExceptionTypesToCatch) /
1579 // Generate inner function.
1580 llvm::Function *innerCatchFunct = createCatchWrappedInvokeFunction(module,
1585 numExceptionTypesToCatch,
1586 innerExceptionTypesToCatch);
1588 // Outer function will catch odd type infos
1589 unsigned outerExceptionTypesToCatch[] = {3, 1, 5};
1590 numExceptionTypesToCatch = sizeof(outerExceptionTypesToCatch) /
1593 // Generate outer function
1594 llvm::Function *outerCatchFunct = createCatchWrappedInvokeFunction(module,
1599 numExceptionTypesToCatch,
1600 outerExceptionTypesToCatch);
1602 // Return outer function to run
1603 return(outerCatchFunct);
1607 /// Represents our foreign exceptions
1608 class OurCppRunException : public std::runtime_error {
1610 OurCppRunException(const std::string reason) :
1611 std::runtime_error(reason) {}
1613 OurCppRunException (const OurCppRunException &toCopy) :
1614 std::runtime_error(toCopy) {}
1616 OurCppRunException &operator = (const OurCppRunException &toCopy) {
1617 return(reinterpret_cast<OurCppRunException&>(
1618 std::runtime_error::operator=(toCopy)));
1621 ~OurCppRunException (void) throw () {}
1625 /// Throws foreign C++ exception.
1626 /// @param ignoreIt unused parameter that allows function to match implied
1627 /// generated function contract.
1629 void throwCppException (int32_t ignoreIt) {
1630 throw(OurCppRunException("thrown by throwCppException(...)"));
1633 typedef void (*OurExceptionThrowFunctType) (int32_t typeToThrow);
1635 /// This is a test harness which runs test by executing generated
1636 /// function with a type info type to throw. Harness wraps the execution
1637 /// of generated function in a C++ try catch clause.
1638 /// @param engine execution engine to use for executing generated function.
1639 /// This demo program expects this to be a JIT instance for demo
1641 /// @param function generated test function to run
1642 /// @param typeToThrow type info type of generated exception to throw, or
1643 /// indicator to cause foreign exception to be thrown.
1645 void runExceptionThrow(llvm::ExecutionEngine *engine,
1646 llvm::Function *function,
1647 int32_t typeToThrow) {
1649 // Find test's function pointer
1650 OurExceptionThrowFunctType functPtr =
1651 reinterpret_cast<OurExceptionThrowFunctType>(
1652 reinterpret_cast<intptr_t>(engine->getPointerToFunction(function)));
1656 (*functPtr)(typeToThrow);
1658 catch (OurCppRunException exc) {
1659 // Catch foreign C++ exception
1661 "\nrunExceptionThrow(...):In C++ catch OurCppRunException "
1662 "with reason: %s.\n",
1666 // Catch all exceptions including our generated ones. I'm not sure
1667 // why this latter functionality should work, as it seems that
1668 // our exceptions should be foreign to C++ (the _Unwind_Exception::
1669 // exception_class should be different from the one used by C++), and
1670 // therefore C++ should ignore the generated exceptions.
1673 "\nrunExceptionThrow(...):In C++ catch all.\n");
1678 // End test functions
1681 typedef llvm::ArrayRef<llvm::Type*> TypeArray;
1683 /// This initialization routine creates type info globals and
1684 /// adds external function declarations to module.
1685 /// @param numTypeInfos number of linear type info associated type info types
1686 /// to create as GlobalVariable instances, starting with the value 1.
1687 /// @param module code for module instance
1688 /// @param builder builder instance
1689 static void createStandardUtilityFunctions(unsigned numTypeInfos,
1690 llvm::Module &module,
1691 llvm::IRBuilder<> &builder) {
1693 llvm::LLVMContext &context = module.getContext();
1695 // Exception initializations
1697 // Setup exception catch state
1698 ourExceptionNotThrownState =
1699 llvm::ConstantInt::get(llvm::Type::getInt8Ty(context), 0),
1700 ourExceptionThrownState =
1701 llvm::ConstantInt::get(llvm::Type::getInt8Ty(context), 1),
1702 ourExceptionCaughtState =
1703 llvm::ConstantInt::get(llvm::Type::getInt8Ty(context), 2),
1707 // Create our type info type
1708 ourTypeInfoType = llvm::StructType::get(context,
1709 TypeArray(builder.getInt32Ty()));
1711 #ifndef OLD_EXC_SYSTEM
1713 llvm::Type *caughtResultFieldTypes[] = {
1714 builder.getInt8PtrTy(),
1715 builder.getInt32Ty()
1718 // Create our landingpad result type
1719 ourCaughtResultType = llvm::StructType::get(context,
1720 TypeArray(caughtResultFieldTypes));
1724 // Create OurException type
1725 ourExceptionType = llvm::StructType::get(context,
1726 TypeArray(ourTypeInfoType));
1728 // Create portion of _Unwind_Exception type
1730 // Note: Declaring only a portion of the _Unwind_Exception struct.
1731 // Does this cause problems?
1732 ourUnwindExceptionType =
1733 llvm::StructType::get(context,
1734 TypeArray(builder.getInt64Ty()));
1736 struct OurBaseException_t dummyException;
1738 // Calculate offset of OurException::unwindException member.
1739 ourBaseFromUnwindOffset = ((uintptr_t) &dummyException) -
1740 ((uintptr_t) &(dummyException.unwindException));
1744 "createStandardUtilityFunctions(...):ourBaseFromUnwindOffset "
1745 "= %lld, sizeof(struct OurBaseException_t) - "
1746 "sizeof(struct _Unwind_Exception) = %lu.\n",
1747 ourBaseFromUnwindOffset,
1748 sizeof(struct OurBaseException_t) -
1749 sizeof(struct _Unwind_Exception));
1752 size_t numChars = sizeof(ourBaseExcpClassChars) / sizeof(char);
1754 // Create our _Unwind_Exception::exception_class value
1755 ourBaseExceptionClass = genClass(ourBaseExcpClassChars, numChars);
1759 std::string baseStr = "typeInfo", typeInfoName;
1760 std::ostringstream typeInfoNameBuilder;
1761 std::vector<llvm::Constant*> structVals;
1763 llvm::Constant *nextStruct;
1764 llvm::GlobalVariable *nextGlobal = NULL;
1766 // Generate each type info
1768 // Note: First type info is not used.
1769 for (unsigned i = 0; i <= numTypeInfos; ++i) {
1771 structVals.push_back(llvm::ConstantInt::get(builder.getInt32Ty(), i));
1772 nextStruct = llvm::ConstantStruct::get(ourTypeInfoType, structVals);
1774 typeInfoNameBuilder.str("");
1775 typeInfoNameBuilder << baseStr << i;
1776 typeInfoName = typeInfoNameBuilder.str();
1778 // Note: Does not seem to work without allocation
1780 new llvm::GlobalVariable(module,
1783 llvm::GlobalValue::ExternalLinkage,
1787 ourTypeInfoNames.push_back(typeInfoName);
1788 ourTypeInfoNamesIndex[i] = typeInfoName;
1793 llvm::Function *funct = NULL;
1797 llvm::Type *retType = builder.getVoidTy();
1800 argTypes.push_back(builder.getInt32Ty());
1801 argTypes.push_back(builder.getInt8PtrTy());
1805 createFunction(module,
1810 llvm::Function::ExternalLinkage,
1816 retType = builder.getVoidTy();
1819 argTypes.push_back(builder.getInt64Ty());
1820 argTypes.push_back(builder.getInt8PtrTy());
1824 createFunction(module,
1829 llvm::Function::ExternalLinkage,
1835 retType = builder.getVoidTy();
1838 argTypes.push_back(builder.getInt8PtrTy());
1842 createFunction(module,
1847 llvm::Function::ExternalLinkage,
1851 // throwCppException
1853 retType = builder.getVoidTy();
1856 argTypes.push_back(builder.getInt32Ty());
1860 createFunction(module,
1864 "throwCppException",
1865 llvm::Function::ExternalLinkage,
1869 // deleteOurException
1871 retType = builder.getVoidTy();
1874 argTypes.push_back(builder.getInt8PtrTy());
1878 createFunction(module,
1882 "deleteOurException",
1883 llvm::Function::ExternalLinkage,
1887 // createOurException
1889 retType = builder.getInt8PtrTy();
1892 argTypes.push_back(builder.getInt32Ty());
1896 createFunction(module,
1900 "createOurException",
1901 llvm::Function::ExternalLinkage,
1905 // _Unwind_RaiseException
1907 retType = builder.getInt32Ty();
1910 argTypes.push_back(builder.getInt8PtrTy());
1914 funct = createFunction(module,
1918 "_Unwind_RaiseException",
1919 llvm::Function::ExternalLinkage,
1923 funct->addFnAttr(llvm::Attribute::NoReturn);
1927 retType = builder.getInt32Ty();
1930 argTypes.push_back(builder.getInt8PtrTy());
1934 funct = createFunction(module,
1939 llvm::Function::ExternalLinkage,
1943 funct->addFnAttr(llvm::Attribute::NoReturn);
1947 retType = builder.getInt32Ty();
1950 argTypes.push_back(builder.getInt32Ty());
1951 argTypes.push_back(builder.getInt32Ty());
1952 argTypes.push_back(builder.getInt64Ty());
1953 argTypes.push_back(builder.getInt8PtrTy());
1954 argTypes.push_back(builder.getInt8PtrTy());
1958 createFunction(module,
1963 llvm::Function::ExternalLinkage,
1967 // llvm.eh.selector intrinsic
1969 getDeclaration(&module, llvm::Intrinsic::eh_selector);
1971 // llvm.eh.exception intrinsic
1973 getDeclaration(&module, llvm::Intrinsic::eh_exception);
1975 // llvm.eh.typeid.for intrinsic
1977 getDeclaration(&module, llvm::Intrinsic::eh_typeid_for);
1981 //===----------------------------------------------------------------------===//
1982 // Main test driver code.
1983 //===----------------------------------------------------------------------===//
1985 /// Demo main routine which takes the type info types to throw. A test will
1986 /// be run for each given type info type. While type info types with the value
1987 /// of -1 will trigger a foreign C++ exception to be thrown; type info types
1988 /// <= 6 and >= 1 will be caught by test functions; and type info types > 6
1989 /// will result in exceptions which pass through to the test harness. All other
1990 /// type info types are not supported and could cause a crash.
1991 int main(int argc, char *argv[]) {
1994 "\nUsage: ExceptionDemo <exception type to throw> "
1995 "[<type 2>...<type n>].\n"
1996 " Each type must have the value of 1 - 6 for "
1997 "generated exceptions to be caught;\n"
1998 " the value -1 for foreign C++ exceptions to be "
1999 "generated and thrown;\n"
2000 " or the values > 6 for exceptions to be ignored.\n"
2001 "\nTry: ExceptionDemo 2 3 7 -1\n"
2002 " for a full test.\n\n");
2006 // If not set, exception handling will not be turned on
2007 llvm::JITExceptionHandling = true;
2009 llvm::InitializeNativeTarget();
2010 llvm::LLVMContext &context = llvm::getGlobalContext();
2011 llvm::IRBuilder<> theBuilder(context);
2013 // Make the module, which holds all the code.
2014 llvm::Module *module = new llvm::Module("my cool jit", context);
2016 // Build engine with JIT
2017 llvm::EngineBuilder factory(module);
2018 factory.setEngineKind(llvm::EngineKind::JIT);
2019 factory.setAllocateGVsWithCode(false);
2020 llvm::ExecutionEngine *executionEngine = factory.create();
2023 llvm::FunctionPassManager fpm(module);
2025 // Set up the optimizer pipeline.
2026 // Start with registering info about how the
2027 // target lays out data structures.
2028 fpm.add(new llvm::TargetData(*executionEngine->getTargetData()));
2030 // Optimizations turned on
2031 #ifdef ADD_OPT_PASSES
2033 // Basic AliasAnslysis support for GVN.
2034 fpm.add(llvm::createBasicAliasAnalysisPass());
2036 // Promote allocas to registers.
2037 fpm.add(llvm::createPromoteMemoryToRegisterPass());
2039 // Do simple "peephole" optimizations and bit-twiddling optzns.
2040 fpm.add(llvm::createInstructionCombiningPass());
2042 // Reassociate expressions.
2043 fpm.add(llvm::createReassociatePass());
2045 // Eliminate Common SubExpressions.
2046 fpm.add(llvm::createGVNPass());
2048 // Simplify the control flow graph (deleting unreachable
2050 fpm.add(llvm::createCFGSimplificationPass());
2051 #endif // ADD_OPT_PASSES
2053 fpm.doInitialization();
2055 // Generate test code using function throwCppException(...) as
2056 // the function which throws foreign exceptions.
2057 llvm::Function *toRun =
2058 createUnwindExceptionTest(*module,
2061 "throwCppException");
2063 fprintf(stderr, "\nBegin module dump:\n\n");
2067 fprintf(stderr, "\nEnd module dump:\n");
2069 fprintf(stderr, "\n\nBegin Test:\n");
2071 for (int i = 1; i < argc; ++i) {
2072 // Run test for each argument whose value is the exception
2074 runExceptionThrow(executionEngine,
2076 (unsigned) strtoul(argv[i], NULL, 10));
2079 fprintf(stderr, "\nEnd Test:\n\n");
2082 delete executionEngine;