Update to the new EH system...remove OLD EH code.
[oota-llvm.git] / examples / ExceptionDemo / ExceptionDemo.cpp
1 //===-- ExceptionDemo.cpp - An example using llvm Exceptions --------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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
21 // thrown exception.
22 //
23 // examples:
24 //
25 // ExceptionDemo
26 //
27 //     causes a usage to be printed to stderr
28 // 
29 // ExceptionDemo 2 3 7 -1
30 //
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
40 //
41 //     Cases -1 and 7 are caught by a C++ test harness where the validity of
42 //         of a C++ catch(...) clause catching a generated exception with a 
43 //         type info type of 7 is explained by: example in rules 1.6.4 in 
44 //         http://sourcery.mentor.com/public/cxx-abi/abi-eh.html (v1.22)
45 //
46 // This code uses code from the llvm compiler-rt project and the llvm 
47 // Kaleidoscope project.
48 //
49 //===----------------------------------------------------------------------===//
50
51 #include "llvm/LLVMContext.h"
52 #include "llvm/DerivedTypes.h"
53 #include "llvm/ExecutionEngine/ExecutionEngine.h"
54 #include "llvm/ExecutionEngine/JIT.h"
55 #include "llvm/Module.h"
56 #include "llvm/PassManager.h"
57 #include "llvm/Intrinsics.h"
58 #include "llvm/Analysis/Verifier.h"
59 #include "llvm/Target/TargetData.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"
64 #include "llvm/Support/TargetSelect.h"
65
66 // FIXME: Although all systems tested with (Linux, OS X), do not need this 
67 //        header file included. A user on ubuntu reported, undefined symbols 
68 //        for stderr, and fprintf, and the addition of this include fixed the
69 //        issue for them. Given that LLVM's best practices include the goal 
70 //        of reducing the number of redundant header files included, the 
71 //        correct solution would be to find out why these symbols are not 
72 //        defined for the system in question, and fix the issue by finding out
73 //        which LLVM header file, if any, would include these symbols.
74 #include <cstdio>
75
76 #include <sstream>
77 #include <stdexcept>
78
79
80 #ifndef USE_GLOBAL_STR_CONSTS
81 #define USE_GLOBAL_STR_CONSTS true
82 #endif
83
84 // System C++ ABI unwind types from: 
85 //     http://sourcery.mentor.com/public/cxx-abi/abi-eh.html (v1.22)
86
87 extern "C" {
88   
89   typedef enum {
90     _URC_NO_REASON = 0,
91     _URC_FOREIGN_EXCEPTION_CAUGHT = 1,
92     _URC_FATAL_PHASE2_ERROR = 2,
93     _URC_FATAL_PHASE1_ERROR = 3,
94     _URC_NORMAL_STOP = 4,
95     _URC_END_OF_STACK = 5,
96     _URC_HANDLER_FOUND = 6,
97     _URC_INSTALL_CONTEXT = 7,
98     _URC_CONTINUE_UNWIND = 8
99   } _Unwind_Reason_Code;
100   
101   typedef enum {
102     _UA_SEARCH_PHASE = 1,
103     _UA_CLEANUP_PHASE = 2,
104     _UA_HANDLER_FRAME = 4,
105     _UA_FORCE_UNWIND = 8,
106     _UA_END_OF_STACK = 16
107   } _Unwind_Action;
108   
109   struct _Unwind_Exception;
110   
111   typedef void (*_Unwind_Exception_Cleanup_Fn) (_Unwind_Reason_Code,
112                                                 struct _Unwind_Exception *);
113   
114   struct _Unwind_Exception {
115     uint64_t exception_class;
116     _Unwind_Exception_Cleanup_Fn exception_cleanup;
117     
118     uintptr_t private_1;    
119     uintptr_t private_2;    
120     
121     // @@@ The IA-64 ABI says that this structure must be double-word aligned.
122     //  Taking that literally does not make much sense generically.  Instead 
123     //  we provide the maximum alignment required by any type for the machine.
124   } __attribute__((__aligned__));
125   
126   struct _Unwind_Context;
127   typedef struct _Unwind_Context *_Unwind_Context_t;
128   
129   extern const uint8_t *_Unwind_GetLanguageSpecificData (_Unwind_Context_t c);
130   extern uintptr_t _Unwind_GetGR (_Unwind_Context_t c, int i);
131   extern void _Unwind_SetGR (_Unwind_Context_t c, int i, uintptr_t n);
132   extern void _Unwind_SetIP (_Unwind_Context_t, uintptr_t new_value);
133   extern uintptr_t _Unwind_GetIP (_Unwind_Context_t context);
134   extern uintptr_t _Unwind_GetRegionStart (_Unwind_Context_t context);
135   
136 } // extern "C"
137
138 //
139 // Example types
140 //
141
142 /// This is our simplistic type info
143 struct OurExceptionType_t {
144   /// type info type
145   int type;
146 };
147
148
149 /// This is our Exception class which relies on a negative offset to calculate
150 /// pointers to its instances from pointers to its unwindException member.
151 /// 
152 /// Note: The above unwind.h defines struct _Unwind_Exception to be aligned
153 ///       on a double word boundary. This is necessary to match the standard:
154 ///       http://refspecs.freestandards.org/abi-eh-1.21.html
155 struct OurBaseException_t {
156   struct OurExceptionType_t type;
157   
158   // Note: This is properly aligned in unwind.h
159   struct _Unwind_Exception unwindException;
160 };
161
162
163 // Note: Not needed since we are C++
164 typedef struct OurBaseException_t OurException;
165 typedef struct _Unwind_Exception OurUnwindException;
166
167 //
168 // Various globals used to support typeinfo and generatted exceptions in 
169 // general
170 //
171
172 static std::map<std::string, llvm::Value*> namedValues;
173
174 int64_t ourBaseFromUnwindOffset;
175
176 const unsigned char ourBaseExcpClassChars[] = 
177 {'o', 'b', 'j', '\0', 'b', 'a', 's', '\0'};
178
179
180 static uint64_t ourBaseExceptionClass = 0;
181
182 static std::vector<std::string> ourTypeInfoNames;
183 static std::map<int, std::string> ourTypeInfoNamesIndex;
184
185 static llvm::StructType *ourTypeInfoType;
186 static llvm::StructType *ourCaughtResultType;
187 static llvm::StructType *ourExceptionType;
188 static llvm::StructType *ourUnwindExceptionType;
189
190 static llvm::ConstantInt *ourExceptionNotThrownState;
191 static llvm::ConstantInt *ourExceptionThrownState;
192 static llvm::ConstantInt *ourExceptionCaughtState;
193
194 typedef std::vector<std::string> ArgNames;
195 typedef std::vector<llvm::Type*> ArgTypes;
196
197 //
198 // Code Generation Utilities
199 //
200
201 /// Utility used to create a function, both declarations and definitions
202 /// @param module for module instance
203 /// @param retType function return type
204 /// @param theArgTypes function's ordered argument types
205 /// @param theArgNames function's ordered arguments needed if use of this
206 ///        function corresponds to a function definition. Use empty 
207 ///        aggregate for function declarations.
208 /// @param functName function name
209 /// @param linkage function linkage
210 /// @param declarationOnly for function declarations
211 /// @param isVarArg function uses vararg arguments
212 /// @returns function instance
213 llvm::Function *createFunction(llvm::Module &module,
214                                llvm::Type *retType,
215                                const ArgTypes &theArgTypes,
216                                const ArgNames &theArgNames,
217                                const std::string &functName,
218                                llvm::GlobalValue::LinkageTypes linkage,
219                                bool declarationOnly,
220                                bool isVarArg) {
221   llvm::FunctionType *functType =
222     llvm::FunctionType::get(retType, theArgTypes, isVarArg);
223   llvm::Function *ret =
224     llvm::Function::Create(functType, linkage, functName, &module);
225   if (!ret || declarationOnly)
226     return(ret);
227   
228   namedValues.clear();
229   unsigned i = 0; 
230   for (llvm::Function::arg_iterator argIndex = ret->arg_begin();
231        i != theArgNames.size();
232        ++argIndex, ++i) {
233     
234     argIndex->setName(theArgNames[i]);
235     namedValues[theArgNames[i]] = argIndex;
236   }
237   
238   return(ret);
239 }
240
241
242 /// Create an alloca instruction in the entry block of
243 /// the parent function.  This is used for mutable variables etc.
244 /// @param function parent instance
245 /// @param varName stack variable name
246 /// @param type stack variable type
247 /// @param initWith optional constant initialization value
248 /// @returns AllocaInst instance
249 static llvm::AllocaInst *createEntryBlockAlloca(llvm::Function &function,
250                                                 const std::string &varName,
251                                                 llvm::Type *type,
252                                                 llvm::Constant *initWith = 0) {
253   llvm::BasicBlock &block = function.getEntryBlock(); 
254   llvm::IRBuilder<> tmp(&block, block.begin());
255   llvm::AllocaInst *ret = tmp.CreateAlloca(type, 0, varName.c_str());
256   
257   if (initWith) 
258     tmp.CreateStore(initWith, ret);
259   
260   return(ret);
261 }
262
263
264 //
265 // Code Generation Utilities End
266 //
267
268 //
269 // Runtime C Library functions 
270 //
271
272 // Note: using an extern "C" block so that static functions can be used
273 extern "C" {
274
275 // Note: Better ways to decide on bit width
276 //
277 /// Prints a 32 bit number, according to the format, to stderr.
278 /// @param intToPrint integer to print 
279 /// @param format printf like format to use when printing
280 void print32Int(int intToPrint, const char *format) {
281   if (format) {
282     // Note: No NULL check
283     fprintf(stderr, format, intToPrint);
284   }
285   else {
286     // Note: No NULL check
287     fprintf(stderr, "::print32Int(...):NULL arg.\n");
288   }
289 }
290
291
292 // Note: Better ways to decide on bit width
293 //
294 /// Prints a 64 bit number, according to the format, to stderr.
295 /// @param intToPrint integer to print 
296 /// @param format printf like format to use when printing
297 void print64Int(long int intToPrint, const char *format) {
298   if (format) {
299     // Note: No NULL check
300     fprintf(stderr, format, intToPrint);
301   }
302   else {
303     // Note: No NULL check
304     fprintf(stderr, "::print64Int(...):NULL arg.\n");
305   }
306 }
307
308
309 /// Prints a C string to stderr
310 /// @param toPrint string to print
311 void printStr(char *toPrint) {
312   if (toPrint) {
313     fprintf(stderr, "%s", toPrint);
314   }
315   else {
316     fprintf(stderr, "::printStr(...):NULL arg.\n");
317   }
318 }
319
320
321 /// Deletes the true previosly allocated exception whose address
322 /// is calculated from the supplied OurBaseException_t::unwindException
323 /// member address. Handles (ignores), NULL pointers.
324 /// @param expToDelete exception to delete
325 void deleteOurException(OurUnwindException *expToDelete) {
326 #ifdef DEBUG
327   fprintf(stderr,
328           "deleteOurException(...).\n");
329 #endif
330   
331   if (expToDelete &&
332       (expToDelete->exception_class == ourBaseExceptionClass)) {
333     
334     free(((char*) expToDelete) + ourBaseFromUnwindOffset);
335   }
336 }
337
338
339 /// This function is the struct _Unwind_Exception API mandated delete function 
340 /// used by foreign exception handlers when deleting our exception 
341 /// (OurException), instances.
342 /// @param reason @link http://refspecs.freestandards.org/abi-eh-1.21.html 
343 /// @unlink
344 /// @param expToDelete exception instance to delete
345 void deleteFromUnwindOurException(_Unwind_Reason_Code reason,
346                                   OurUnwindException *expToDelete) {
347 #ifdef DEBUG
348   fprintf(stderr,
349           "deleteFromUnwindOurException(...).\n");
350 #endif
351   
352   deleteOurException(expToDelete);
353 }
354
355
356 /// Creates (allocates on the heap), an exception (OurException instance),
357 /// of the supplied type info type.
358 /// @param type type info type
359 OurUnwindException *createOurException(int type) {
360   size_t size = sizeof(OurException);
361   OurException *ret = (OurException*) memset(malloc(size), 0, size);
362   (ret->type).type = type;
363   (ret->unwindException).exception_class = ourBaseExceptionClass;
364   (ret->unwindException).exception_cleanup = deleteFromUnwindOurException;
365   
366   return(&(ret->unwindException));
367 }
368
369
370 /// Read a uleb128 encoded value and advance pointer 
371 /// See Variable Length Data in: 
372 /// @link http://dwarfstd.org/Dwarf3.pdf @unlink
373 /// @param data reference variable holding memory pointer to decode from
374 /// @returns decoded value
375 static uintptr_t readULEB128(const uint8_t **data) {
376   uintptr_t result = 0;
377   uintptr_t shift = 0;
378   unsigned char byte;
379   const uint8_t *p = *data;
380   
381   do {
382     byte = *p++;
383     result |= (byte & 0x7f) << shift;
384     shift += 7;
385   } 
386   while (byte & 0x80);
387   
388   *data = p;
389   
390   return result;
391 }
392
393
394 /// Read a sleb128 encoded value and advance pointer 
395 /// See Variable Length Data in: 
396 /// @link http://dwarfstd.org/Dwarf3.pdf @unlink
397 /// @param data reference variable holding memory pointer to decode from
398 /// @returns decoded value
399 static uintptr_t readSLEB128(const uint8_t **data) {
400   uintptr_t result = 0;
401   uintptr_t shift = 0;
402   unsigned char byte;
403   const uint8_t *p = *data;
404   
405   do {
406     byte = *p++;
407     result |= (byte & 0x7f) << shift;
408     shift += 7;
409   } 
410   while (byte & 0x80);
411   
412   *data = p;
413   
414   if ((byte & 0x40) && (shift < (sizeof(result) << 3))) {
415     result |= (~0 << shift);
416   }
417   
418   return result;
419 }
420
421
422 /// Read a pointer encoded value and advance pointer 
423 /// See Variable Length Data in: 
424 /// @link http://dwarfstd.org/Dwarf3.pdf @unlink
425 /// @param data reference variable holding memory pointer to decode from
426 /// @param encoding dwarf encoding type
427 /// @returns decoded value
428 static uintptr_t readEncodedPointer(const uint8_t **data, uint8_t encoding) {
429   uintptr_t result = 0;
430   const uint8_t *p = *data;
431   
432   if (encoding == llvm::dwarf::DW_EH_PE_omit) 
433     return(result);
434   
435   // first get value 
436   switch (encoding & 0x0F) {
437     case llvm::dwarf::DW_EH_PE_absptr:
438       result = *((uintptr_t*)p);
439       p += sizeof(uintptr_t);
440       break;
441     case llvm::dwarf::DW_EH_PE_uleb128:
442       result = readULEB128(&p);
443       break;
444       // Note: This case has not been tested
445     case llvm::dwarf::DW_EH_PE_sleb128:
446       result = readSLEB128(&p);
447       break;
448     case llvm::dwarf::DW_EH_PE_udata2:
449       result = *((uint16_t*)p);
450       p += sizeof(uint16_t);
451       break;
452     case llvm::dwarf::DW_EH_PE_udata4:
453       result = *((uint32_t*)p);
454       p += sizeof(uint32_t);
455       break;
456     case llvm::dwarf::DW_EH_PE_udata8:
457       result = *((uint64_t*)p);
458       p += sizeof(uint64_t);
459       break;
460     case llvm::dwarf::DW_EH_PE_sdata2:
461       result = *((int16_t*)p);
462       p += sizeof(int16_t);
463       break;
464     case llvm::dwarf::DW_EH_PE_sdata4:
465       result = *((int32_t*)p);
466       p += sizeof(int32_t);
467       break;
468     case llvm::dwarf::DW_EH_PE_sdata8:
469       result = *((int64_t*)p);
470       p += sizeof(int64_t);
471       break;
472     default:
473       // not supported 
474       abort();
475       break;
476   }
477   
478   // then add relative offset 
479   switch (encoding & 0x70) {
480     case llvm::dwarf::DW_EH_PE_absptr:
481       // do nothing 
482       break;
483     case llvm::dwarf::DW_EH_PE_pcrel:
484       result += (uintptr_t)(*data);
485       break;
486     case llvm::dwarf::DW_EH_PE_textrel:
487     case llvm::dwarf::DW_EH_PE_datarel:
488     case llvm::dwarf::DW_EH_PE_funcrel:
489     case llvm::dwarf::DW_EH_PE_aligned:
490     default:
491       // not supported 
492       abort();
493       break;
494   }
495   
496   // then apply indirection 
497   if (encoding & llvm::dwarf::DW_EH_PE_indirect) {
498     result = *((uintptr_t*)result);
499   }
500   
501   *data = p;
502   
503   return result;
504 }
505
506
507 /// Deals with Dwarf actions matching our type infos 
508 /// (OurExceptionType_t instances). Returns whether or not a dwarf emitted 
509 /// action matches the supplied exception type. If such a match succeeds, 
510 /// the resultAction argument will be set with > 0 index value. Only 
511 /// corresponding llvm.eh.selector type info arguments, cleanup arguments 
512 /// are supported. Filters are not supported.
513 /// See Variable Length Data in: 
514 /// @link http://dwarfstd.org/Dwarf3.pdf @unlink
515 /// Also see @link http://refspecs.freestandards.org/abi-eh-1.21.html @unlink
516 /// @param resultAction reference variable which will be set with result
517 /// @param classInfo our array of type info pointers (to globals)
518 /// @param actionEntry index into above type info array or 0 (clean up). 
519 ///        We do not support filters.
520 /// @param exceptionClass exception class (_Unwind_Exception::exception_class)
521 ///        of thrown exception.
522 /// @param exceptionObject thrown _Unwind_Exception instance.
523 /// @returns whether or not a type info was found. False is returned if only
524 ///          a cleanup was found
525 static bool handleActionValue(int64_t *resultAction,
526                               struct OurExceptionType_t **classInfo, 
527                               uintptr_t actionEntry, 
528                               uint64_t exceptionClass, 
529                               struct _Unwind_Exception *exceptionObject) {
530   bool ret = false;
531   
532   if (!resultAction || 
533       !exceptionObject || 
534       (exceptionClass != ourBaseExceptionClass))
535     return(ret);
536   
537   struct OurBaseException_t *excp = (struct OurBaseException_t*)
538   (((char*) exceptionObject) + ourBaseFromUnwindOffset);
539   struct OurExceptionType_t *excpType = &(excp->type);
540   int type = excpType->type;
541   
542 #ifdef DEBUG
543   fprintf(stderr,
544           "handleActionValue(...): exceptionObject = <%p>, "
545           "excp = <%p>.\n",
546           exceptionObject,
547           excp);
548 #endif
549   
550   const uint8_t *actionPos = (uint8_t*) actionEntry,
551   *tempActionPos;
552   int64_t typeOffset = 0,
553   actionOffset;
554   
555   for (int i = 0; true; ++i) {
556     // Each emitted dwarf action corresponds to a 2 tuple of
557     // type info address offset, and action offset to the next
558     // emitted action.
559     typeOffset = readSLEB128(&actionPos);
560     tempActionPos = actionPos;
561     actionOffset = readSLEB128(&tempActionPos);
562     
563 #ifdef DEBUG
564     fprintf(stderr,
565             "handleActionValue(...):typeOffset: <%lld>, "
566             "actionOffset: <%lld>.\n",
567             typeOffset,
568             actionOffset);
569 #endif
570     assert((typeOffset >= 0) && 
571            "handleActionValue(...):filters are not supported.");
572     
573     // Note: A typeOffset == 0 implies that a cleanup llvm.eh.selector
574     //       argument has been matched.
575     if ((typeOffset > 0) &&
576         (type == (classInfo[-typeOffset])->type)) {
577 #ifdef DEBUG
578       fprintf(stderr,
579               "handleActionValue(...):actionValue <%d> found.\n",
580               i);
581 #endif
582       *resultAction = i + 1;
583       ret = true;
584       break;
585     }
586     
587 #ifdef DEBUG
588     fprintf(stderr,
589             "handleActionValue(...):actionValue not found.\n");
590 #endif
591     if (!actionOffset)
592       break;
593     
594     actionPos += actionOffset;
595   }
596   
597   return(ret);
598 }
599
600
601 /// Deals with the Language specific data portion of the emitted dwarf code.
602 /// See @link http://refspecs.freestandards.org/abi-eh-1.21.html @unlink
603 /// @param version unsupported (ignored), unwind version
604 /// @param lsda language specific data area
605 /// @param _Unwind_Action actions minimally supported unwind stage 
606 ///        (forced specifically not supported)
607 /// @param exceptionClass exception class (_Unwind_Exception::exception_class)
608 ///        of thrown exception.
609 /// @param exceptionObject thrown _Unwind_Exception instance.
610 /// @param context unwind system context
611 /// @returns minimally supported unwinding control indicator 
612 static _Unwind_Reason_Code handleLsda(int version, 
613                                       const uint8_t *lsda,
614                                       _Unwind_Action actions,
615                                       uint64_t exceptionClass, 
616                                     struct _Unwind_Exception *exceptionObject,
617                                       _Unwind_Context_t context) {
618   _Unwind_Reason_Code ret = _URC_CONTINUE_UNWIND;
619   
620   if (!lsda)
621     return(ret);
622   
623 #ifdef DEBUG
624   fprintf(stderr, 
625           "handleLsda(...):lsda is non-zero.\n");
626 #endif
627   
628   // Get the current instruction pointer and offset it before next
629   // instruction in the current frame which threw the exception.
630   uintptr_t pc = _Unwind_GetIP(context)-1;
631   
632   // Get beginning current frame's code (as defined by the 
633   // emitted dwarf code)
634   uintptr_t funcStart = _Unwind_GetRegionStart(context);
635   uintptr_t pcOffset = pc - funcStart;
636   struct OurExceptionType_t **classInfo = NULL;
637   
638   // Note: See JITDwarfEmitter::EmitExceptionTable(...) for corresponding
639   //       dwarf emission
640   
641   // Parse LSDA header.
642   uint8_t lpStartEncoding = *lsda++;
643   
644   if (lpStartEncoding != llvm::dwarf::DW_EH_PE_omit) {
645     readEncodedPointer(&lsda, lpStartEncoding); 
646   }
647   
648   uint8_t ttypeEncoding = *lsda++;
649   uintptr_t classInfoOffset;
650   
651   if (ttypeEncoding != llvm::dwarf::DW_EH_PE_omit) {
652     // Calculate type info locations in emitted dwarf code which
653     // were flagged by type info arguments to llvm.eh.selector
654     // intrinsic
655     classInfoOffset = readULEB128(&lsda);
656     classInfo = (struct OurExceptionType_t**) (lsda + classInfoOffset);
657   }
658   
659   // Walk call-site table looking for range that 
660   // includes current PC. 
661   
662   uint8_t         callSiteEncoding = *lsda++;
663   uint32_t        callSiteTableLength = readULEB128(&lsda);
664   const uint8_t   *callSiteTableStart = lsda;
665   const uint8_t   *callSiteTableEnd = callSiteTableStart + 
666   callSiteTableLength;
667   const uint8_t   *actionTableStart = callSiteTableEnd;
668   const uint8_t   *callSitePtr = callSiteTableStart;
669   
670   bool foreignException = false;
671   
672   while (callSitePtr < callSiteTableEnd) {
673     uintptr_t start = readEncodedPointer(&callSitePtr, 
674                                          callSiteEncoding);
675     uintptr_t length = readEncodedPointer(&callSitePtr, 
676                                           callSiteEncoding);
677     uintptr_t landingPad = readEncodedPointer(&callSitePtr, 
678                                               callSiteEncoding);
679     
680     // Note: Action value
681     uintptr_t actionEntry = readULEB128(&callSitePtr);
682     
683     if (exceptionClass != ourBaseExceptionClass) {
684       // We have been notified of a foreign exception being thrown,
685       // and we therefore need to execute cleanup landing pads
686       actionEntry = 0;
687       foreignException = true;
688     }
689     
690     if (landingPad == 0) {
691 #ifdef DEBUG
692       fprintf(stderr,
693               "handleLsda(...): No landing pad found.\n");
694 #endif
695       
696       continue; // no landing pad for this entry
697     }
698     
699     if (actionEntry) {
700       actionEntry += ((uintptr_t) actionTableStart) - 1;
701     }
702     else {
703 #ifdef DEBUG
704       fprintf(stderr,
705               "handleLsda(...):No action table found.\n");
706 #endif
707     }
708     
709     bool exceptionMatched = false;
710     
711     if ((start <= pcOffset) && (pcOffset < (start + length))) {
712 #ifdef DEBUG
713       fprintf(stderr,
714               "handleLsda(...): Landing pad found.\n");
715 #endif
716       int64_t actionValue = 0;
717       
718       if (actionEntry) {
719         exceptionMatched = handleActionValue(&actionValue,
720                                              classInfo, 
721                                              actionEntry, 
722                                              exceptionClass, 
723                                              exceptionObject);
724       }
725       
726       if (!(actions & _UA_SEARCH_PHASE)) {
727 #ifdef DEBUG
728         fprintf(stderr,
729                 "handleLsda(...): installed landing pad "
730                 "context.\n");
731 #endif
732         
733         // Found landing pad for the PC.
734         // Set Instruction Pointer to so we re-enter function 
735         // at landing pad. The landing pad is created by the 
736         // compiler to take two parameters in registers.
737         _Unwind_SetGR(context, 
738                       __builtin_eh_return_data_regno(0), 
739                       (uintptr_t)exceptionObject);
740         
741         // Note: this virtual register directly corresponds
742         //       to the return of the llvm.eh.selector intrinsic
743         if (!actionEntry || !exceptionMatched) {
744           // We indicate cleanup only
745           _Unwind_SetGR(context, 
746                         __builtin_eh_return_data_regno(1), 
747                         0);
748         }
749         else {
750           // Matched type info index of llvm.eh.selector intrinsic
751           // passed here.
752           _Unwind_SetGR(context, 
753                         __builtin_eh_return_data_regno(1), 
754                         actionValue);
755         }
756         
757         // To execute landing pad set here
758         _Unwind_SetIP(context, funcStart + landingPad);
759         ret = _URC_INSTALL_CONTEXT;
760       }
761       else if (exceptionMatched) {
762 #ifdef DEBUG
763         fprintf(stderr,
764                 "handleLsda(...): setting handler found.\n");
765 #endif
766         ret = _URC_HANDLER_FOUND;
767       }
768       else {
769         // Note: Only non-clean up handlers are marked as
770         //       found. Otherwise the clean up handlers will be 
771         //       re-found and executed during the clean up 
772         //       phase.
773 #ifdef DEBUG
774         fprintf(stderr,
775                 "handleLsda(...): cleanup handler found.\n");
776 #endif
777       }
778       
779       break;
780     }
781   }
782   
783   return(ret);
784 }
785
786
787 /// This is the personality function which is embedded (dwarf emitted), in the
788 /// dwarf unwind info block. Again see: JITDwarfEmitter.cpp.
789 /// See @link http://refspecs.freestandards.org/abi-eh-1.21.html @unlink
790 /// @param version unsupported (ignored), unwind version
791 /// @param _Unwind_Action actions minimally supported unwind stage 
792 ///        (forced specifically not supported)
793 /// @param exceptionClass exception class (_Unwind_Exception::exception_class)
794 ///        of thrown exception.
795 /// @param exceptionObject thrown _Unwind_Exception instance.
796 /// @param context unwind system context
797 /// @returns minimally supported unwinding control indicator 
798 _Unwind_Reason_Code ourPersonality(int version, 
799                                    _Unwind_Action actions,
800                                    uint64_t exceptionClass, 
801                                    struct _Unwind_Exception *exceptionObject,
802                                    _Unwind_Context_t context) {
803 #ifdef DEBUG
804   fprintf(stderr, 
805           "We are in ourPersonality(...):actions is <%d>.\n",
806           actions);
807   
808   if (actions & _UA_SEARCH_PHASE) {
809     fprintf(stderr, "ourPersonality(...):In search phase.\n");
810   }
811   else {
812     fprintf(stderr, "ourPersonality(...):In non-search phase.\n");
813   }
814 #endif
815   
816   const uint8_t *lsda = _Unwind_GetLanguageSpecificData(context);
817   
818 #ifdef DEBUG
819   fprintf(stderr, 
820           "ourPersonality(...):lsda = <%p>.\n",
821           lsda);
822 #endif
823   
824   // The real work of the personality function is captured here
825   return(handleLsda(version,
826                     lsda,
827                     actions,
828                     exceptionClass,
829                     exceptionObject,
830                     context));
831 }
832
833
834 /// Generates our _Unwind_Exception class from a given character array.
835 /// thereby handling arbitrary lengths (not in standard), and handling
836 /// embedded \0s.
837 /// See @link http://refspecs.freestandards.org/abi-eh-1.21.html @unlink
838 /// @param classChars char array to encode. NULL values not checkedf
839 /// @param classCharsSize number of chars in classChars. Value is not checked.
840 /// @returns class value
841 uint64_t genClass(const unsigned char classChars[], size_t classCharsSize)
842 {
843   uint64_t ret = classChars[0];
844   
845   for (unsigned i = 1; i < classCharsSize; ++i) {
846     ret <<= 8;
847     ret += classChars[i];
848   }
849   
850   return(ret);
851 }
852
853 } // extern "C"
854
855 //
856 // Runtime C Library functions End
857 //
858
859 //
860 // Code generation functions
861 //
862
863 /// Generates code to print given constant string
864 /// @param context llvm context
865 /// @param module code for module instance
866 /// @param builder builder instance
867 /// @param toPrint string to print
868 /// @param useGlobal A value of true (default) indicates a GlobalValue is 
869 ///        generated, and is used to hold the constant string. A value of 
870 ///        false indicates that the constant string will be stored on the 
871 ///        stack.
872 void generateStringPrint(llvm::LLVMContext &context, 
873                          llvm::Module &module,
874                          llvm::IRBuilder<> &builder, 
875                          std::string toPrint,
876                          bool useGlobal = true) {
877   llvm::Function *printFunct = module.getFunction("printStr");
878   
879   llvm::Value *stringVar;
880   llvm::Constant *stringConstant = 
881   llvm::ConstantArray::get(context, toPrint);
882   
883   if (useGlobal) {
884     // Note: Does not work without allocation
885     stringVar = 
886     new llvm::GlobalVariable(module, 
887                              stringConstant->getType(),
888                              true, 
889                              llvm::GlobalValue::LinkerPrivateLinkage, 
890                              stringConstant, 
891                              "");
892   }
893   else {
894     stringVar = builder.CreateAlloca(stringConstant->getType());
895     builder.CreateStore(stringConstant, stringVar);
896   }
897   
898   llvm::Value *cast = builder.CreatePointerCast(stringVar, 
899                                                 builder.getInt8PtrTy());
900   builder.CreateCall(printFunct, cast);
901 }
902
903
904 /// Generates code to print given runtime integer according to constant
905 /// string format, and a given print function.
906 /// @param context llvm context
907 /// @param module code for module instance
908 /// @param builder builder instance
909 /// @param printFunct function used to "print" integer
910 /// @param toPrint string to print
911 /// @param format printf like formating string for print
912 /// @param useGlobal A value of true (default) indicates a GlobalValue is 
913 ///        generated, and is used to hold the constant string. A value of 
914 ///        false indicates that the constant string will be stored on the 
915 ///        stack.
916 void generateIntegerPrint(llvm::LLVMContext &context, 
917                           llvm::Module &module,
918                           llvm::IRBuilder<> &builder, 
919                           llvm::Function &printFunct,
920                           llvm::Value &toPrint,
921                           std::string format, 
922                           bool useGlobal = true) {
923   llvm::Constant *stringConstant = llvm::ConstantArray::get(context, format);
924   llvm::Value *stringVar;
925   
926   if (useGlobal) {
927     // Note: Does not seem to work without allocation
928     stringVar = 
929     new llvm::GlobalVariable(module, 
930                              stringConstant->getType(),
931                              true, 
932                              llvm::GlobalValue::LinkerPrivateLinkage, 
933                              stringConstant, 
934                              "");
935   }
936   else {
937     stringVar = builder.CreateAlloca(stringConstant->getType());
938     builder.CreateStore(stringConstant, stringVar);
939   }
940   
941   llvm::Value *cast = builder.CreateBitCast(stringVar, 
942                                             builder.getInt8PtrTy());
943   builder.CreateCall2(&printFunct, &toPrint, cast);
944 }
945
946
947 /// Generates code to handle finally block type semantics: always runs 
948 /// regardless of whether a thrown exception is passing through or the 
949 /// parent function is simply exiting. In addition to printing some state 
950 /// to stderr, this code will resume the exception handling--runs the 
951 /// unwind resume block, if the exception has not been previously caught 
952 /// by a catch clause, and will otherwise execute the end block (terminator 
953 /// block). In addition this function creates the corresponding function's 
954 /// stack storage for the exception pointer and catch flag status.
955 /// @param context llvm context
956 /// @param module code for module instance
957 /// @param builder builder instance
958 /// @param toAddTo parent function to add block to
959 /// @param blockName block name of new "finally" block.
960 /// @param functionId output id used for printing
961 /// @param terminatorBlock terminator "end" block
962 /// @param unwindResumeBlock unwind resume block
963 /// @param exceptionCaughtFlag reference exception caught/thrown status storage
964 /// @param exceptionStorage reference to exception pointer storage
965 /// @param caughtResultStorage reference to landingpad result storage
966 /// @returns newly created block
967 static llvm::BasicBlock *createFinallyBlock(llvm::LLVMContext &context, 
968                                             llvm::Module &module, 
969                                             llvm::IRBuilder<> &builder, 
970                                             llvm::Function &toAddTo,
971                                             std::string &blockName,
972                                             std::string &functionId,
973                                             llvm::BasicBlock &terminatorBlock,
974                                             llvm::BasicBlock &unwindResumeBlock,
975                                             llvm::Value **exceptionCaughtFlag,
976                                             llvm::Value **exceptionStorage,
977                                             llvm::Value **caughtResultStorage) {
978   assert(exceptionCaughtFlag && 
979          "ExceptionDemo::createFinallyBlock(...):exceptionCaughtFlag "
980          "is NULL");
981   assert(exceptionStorage && 
982          "ExceptionDemo::createFinallyBlock(...):exceptionStorage "
983          "is NULL");
984   assert(caughtResultStorage && 
985          "ExceptionDemo::createFinallyBlock(...):caughtResultStorage "
986          "is NULL");
987   
988   *exceptionCaughtFlag = createEntryBlockAlloca(toAddTo,
989                                          "exceptionCaught",
990                                          ourExceptionNotThrownState->getType(),
991                                          ourExceptionNotThrownState);
992   
993   llvm::PointerType *exceptionStorageType = builder.getInt8PtrTy();
994   *exceptionStorage = createEntryBlockAlloca(toAddTo,
995                                              "exceptionStorage",
996                                              exceptionStorageType,
997                                              llvm::ConstantPointerNull::get(
998                                                exceptionStorageType));
999   *caughtResultStorage = createEntryBlockAlloca(toAddTo,
1000                                               "caughtResultStorage",
1001                                               ourCaughtResultType,
1002                                               llvm::ConstantAggregateZero::get(
1003                                                 ourCaughtResultType));
1004   
1005   llvm::BasicBlock *ret = llvm::BasicBlock::Create(context,
1006                                                    blockName,
1007                                                    &toAddTo);
1008   
1009   builder.SetInsertPoint(ret);
1010   
1011   std::ostringstream bufferToPrint;
1012   bufferToPrint << "Gen: Executing finally block "
1013     << blockName << " in " << functionId << "\n";
1014   generateStringPrint(context, 
1015                       module, 
1016                       builder, 
1017                       bufferToPrint.str(),
1018                       USE_GLOBAL_STR_CONSTS);
1019   
1020   llvm::SwitchInst *theSwitch = builder.CreateSwitch(builder.CreateLoad(
1021                                                        *exceptionCaughtFlag), 
1022                                                      &terminatorBlock,
1023                                                      2);
1024   theSwitch->addCase(ourExceptionCaughtState, &terminatorBlock);
1025   theSwitch->addCase(ourExceptionThrownState, &unwindResumeBlock);
1026   
1027   return(ret);
1028 }
1029
1030
1031 /// Generates catch block semantics which print a string to indicate type of
1032 /// catch executed, sets an exception caught flag, and executes passed in 
1033 /// end block (terminator block).
1034 /// @param context llvm context
1035 /// @param module code for module instance
1036 /// @param builder builder instance
1037 /// @param toAddTo parent function to add block to
1038 /// @param blockName block name of new "catch" block.
1039 /// @param functionId output id used for printing
1040 /// @param terminatorBlock terminator "end" block
1041 /// @param exceptionCaughtFlag exception caught/thrown status
1042 /// @returns newly created block
1043 static llvm::BasicBlock *createCatchBlock(llvm::LLVMContext &context, 
1044                                           llvm::Module &module, 
1045                                           llvm::IRBuilder<> &builder, 
1046                                           llvm::Function &toAddTo,
1047                                           std::string &blockName,
1048                                           std::string &functionId,
1049                                           llvm::BasicBlock &terminatorBlock,
1050                                           llvm::Value &exceptionCaughtFlag) {
1051   
1052   llvm::BasicBlock *ret = llvm::BasicBlock::Create(context,
1053                                                    blockName,
1054                                                    &toAddTo);
1055   
1056   builder.SetInsertPoint(ret);
1057   
1058   std::ostringstream bufferToPrint;
1059   bufferToPrint << "Gen: Executing catch block "
1060   << blockName
1061   << " in "
1062   << functionId
1063   << std::endl;
1064   generateStringPrint(context, 
1065                       module, 
1066                       builder, 
1067                       bufferToPrint.str(),
1068                       USE_GLOBAL_STR_CONSTS);
1069   builder.CreateStore(ourExceptionCaughtState, &exceptionCaughtFlag);
1070   builder.CreateBr(&terminatorBlock);
1071   
1072   return(ret);
1073 }
1074
1075
1076 /// Generates a function which invokes a function (toInvoke) and, whose 
1077 /// unwind block will "catch" the type info types correspondingly held in the 
1078 /// exceptionTypesToCatch argument. If the toInvoke function throws an 
1079 /// exception which does not match any type info types contained in 
1080 /// exceptionTypesToCatch, the generated code will call _Unwind_Resume 
1081 /// with the raised exception. On the other hand the generated code will 
1082 /// normally exit if the toInvoke function does not throw an exception.
1083 /// The generated "finally" block is always run regardless of the cause of 
1084 /// the generated function exit.
1085 /// The generated function is returned after being verified.
1086 /// @param module code for module instance
1087 /// @param builder builder instance
1088 /// @param fpm a function pass manager holding optional IR to IR 
1089 ///        transformations
1090 /// @param toInvoke inner function to invoke
1091 /// @param ourId id used to printing purposes
1092 /// @param numExceptionsToCatch length of exceptionTypesToCatch array
1093 /// @param exceptionTypesToCatch array of type info types to "catch"
1094 /// @returns generated function
1095 static
1096 llvm::Function *createCatchWrappedInvokeFunction(llvm::Module &module, 
1097                                              llvm::IRBuilder<> &builder, 
1098                                              llvm::FunctionPassManager &fpm,
1099                                              llvm::Function &toInvoke,
1100                                              std::string ourId,
1101                                              unsigned numExceptionsToCatch,
1102                                              unsigned exceptionTypesToCatch[]) {
1103   
1104   llvm::LLVMContext &context = module.getContext();
1105   llvm::Function *toPrint32Int = module.getFunction("print32Int");
1106   
1107   ArgTypes argTypes;
1108   argTypes.push_back(builder.getInt32Ty());
1109   
1110   ArgNames argNames;
1111   argNames.push_back("exceptTypeToThrow");
1112   
1113   llvm::Function *ret = createFunction(module, 
1114                                        builder.getVoidTy(),
1115                                        argTypes, 
1116                                        argNames, 
1117                                        ourId,
1118                                        llvm::Function::ExternalLinkage, 
1119                                        false, 
1120                                        false);
1121   
1122   // Block which calls invoke
1123   llvm::BasicBlock *entryBlock = llvm::BasicBlock::Create(context,
1124                                                           "entry", 
1125                                                           ret);
1126   // Normal block for invoke
1127   llvm::BasicBlock *normalBlock = llvm::BasicBlock::Create(context, 
1128                                                            "normal", 
1129                                                            ret);
1130   // Unwind block for invoke
1131   llvm::BasicBlock *exceptionBlock = llvm::BasicBlock::Create(context, 
1132                                                               "exception", 
1133                                                               ret);
1134   
1135   // Block which routes exception to correct catch handler block
1136   llvm::BasicBlock *exceptionRouteBlock = llvm::BasicBlock::Create(context, 
1137                                                              "exceptionRoute", 
1138                                                              ret);
1139   
1140   // Foreign exception handler
1141   llvm::BasicBlock *externalExceptionBlock = llvm::BasicBlock::Create(context, 
1142                                                           "externalException", 
1143                                                           ret);
1144   
1145   // Block which calls _Unwind_Resume
1146   llvm::BasicBlock *unwindResumeBlock = llvm::BasicBlock::Create(context, 
1147                                                                "unwindResume", 
1148                                                                ret);
1149   
1150   // Clean up block which delete exception if needed
1151   llvm::BasicBlock *endBlock = llvm::BasicBlock::Create(context, "end", ret);
1152   
1153   std::string nextName;
1154   std::vector<llvm::BasicBlock*> catchBlocks(numExceptionsToCatch);
1155   llvm::Value *exceptionCaughtFlag = NULL;
1156   llvm::Value *exceptionStorage = NULL;
1157   llvm::Value *caughtResultStorage = NULL;
1158   
1159   // Finally block which will branch to unwindResumeBlock if 
1160   // exception is not caught. Initializes/allocates stack locations.
1161   llvm::BasicBlock *finallyBlock = createFinallyBlock(context, 
1162                                                       module, 
1163                                                       builder, 
1164                                                       *ret, 
1165                                                       nextName = "finally", 
1166                                                       ourId,
1167                                                       *endBlock,
1168                                                       *unwindResumeBlock,
1169                                                       &exceptionCaughtFlag,
1170                                                       &exceptionStorage,
1171                                                       &caughtResultStorage
1172                                                       );
1173   
1174   for (unsigned i = 0; i < numExceptionsToCatch; ++i) {
1175     nextName = ourTypeInfoNames[exceptionTypesToCatch[i]];
1176     
1177     // One catch block per type info to be caught
1178     catchBlocks[i] = createCatchBlock(context, 
1179                                       module, 
1180                                       builder, 
1181                                       *ret,
1182                                       nextName, 
1183                                       ourId,
1184                                       *finallyBlock,
1185                                       *exceptionCaughtFlag);
1186   }
1187   
1188   // Entry Block
1189   
1190   builder.SetInsertPoint(entryBlock);
1191   
1192   std::vector<llvm::Value*> args;
1193   args.push_back(namedValues["exceptTypeToThrow"]);
1194   builder.CreateInvoke(&toInvoke, 
1195                        normalBlock, 
1196                        exceptionBlock, 
1197                        args);
1198   
1199   // End Block
1200   
1201   builder.SetInsertPoint(endBlock);
1202   
1203   generateStringPrint(context, 
1204                       module,
1205                       builder, 
1206                       "Gen: In end block: exiting in " + ourId + ".\n",
1207                       USE_GLOBAL_STR_CONSTS);
1208   llvm::Function *deleteOurException = module.getFunction("deleteOurException");
1209   
1210   // Note: function handles NULL exceptions
1211   builder.CreateCall(deleteOurException, 
1212                      builder.CreateLoad(exceptionStorage));
1213   builder.CreateRetVoid();
1214   
1215   // Normal Block
1216   
1217   builder.SetInsertPoint(normalBlock);
1218   
1219   generateStringPrint(context, 
1220                       module,
1221                       builder, 
1222                       "Gen: No exception in " + ourId + "!\n",
1223                       USE_GLOBAL_STR_CONSTS);
1224   
1225   // Finally block is always called
1226   builder.CreateBr(finallyBlock);
1227   
1228   // Unwind Resume Block
1229   
1230   builder.SetInsertPoint(unwindResumeBlock);
1231   
1232   builder.CreateResume(builder.CreateLoad(caughtResultStorage));
1233   
1234   // Exception Block
1235   
1236   builder.SetInsertPoint(exceptionBlock);
1237   
1238   llvm::Function *personality = module.getFunction("ourPersonality");
1239   
1240   llvm::LandingPadInst *caughtResult = 
1241     builder.CreateLandingPad(ourCaughtResultType,
1242                              personality,
1243                              numExceptionsToCatch,
1244                              "landingPad");
1245
1246   caughtResult->setCleanup(true);
1247
1248   for (unsigned i = 0; i < numExceptionsToCatch; ++i) {
1249     // Set up type infos to be caught
1250     caughtResult->addClause(module.getGlobalVariable(
1251                              ourTypeInfoNames[exceptionTypesToCatch[i]]));
1252   }
1253
1254   llvm::Value *unwindException = builder.CreateExtractValue(caughtResult, 0);
1255   llvm::Value *retTypeInfoIndex = builder.CreateExtractValue(caughtResult, 1);
1256
1257   // FIXME: Redundant storage which, beyond utilizing value of 
1258   //        caughtResultStore for unwindException storage, may be alleviated 
1259   //        alltogether with a block rearrangement
1260   builder.CreateStore(caughtResult, caughtResultStorage);
1261   builder.CreateStore(unwindException, exceptionStorage);
1262   builder.CreateStore(ourExceptionThrownState, exceptionCaughtFlag);
1263   
1264   // Retrieve exception_class member from thrown exception 
1265   // (_Unwind_Exception instance). This member tells us whether or not
1266   // the exception is foreign.
1267   llvm::Value *unwindExceptionClass = 
1268     builder.CreateLoad(builder.CreateStructGEP(
1269              builder.CreatePointerCast(unwindException, 
1270                                        ourUnwindExceptionType->getPointerTo()), 
1271                                                0));
1272   
1273   // Branch to the externalExceptionBlock if the exception is foreign or
1274   // to a catch router if not. Either way the finally block will be run.
1275   builder.CreateCondBr(builder.CreateICmpEQ(unwindExceptionClass,
1276                             llvm::ConstantInt::get(builder.getInt64Ty(), 
1277                                                    ourBaseExceptionClass)),
1278                        exceptionRouteBlock,
1279                        externalExceptionBlock);
1280   
1281   // External Exception Block
1282   
1283   builder.SetInsertPoint(externalExceptionBlock);
1284   
1285   generateStringPrint(context, 
1286                       module,
1287                       builder, 
1288                       "Gen: Foreign exception received.\n",
1289                       USE_GLOBAL_STR_CONSTS);
1290   
1291   // Branch to the finally block
1292   builder.CreateBr(finallyBlock);
1293   
1294   // Exception Route Block
1295   
1296   builder.SetInsertPoint(exceptionRouteBlock);
1297   
1298   // Casts exception pointer (_Unwind_Exception instance) to parent 
1299   // (OurException instance).
1300   //
1301   // Note: ourBaseFromUnwindOffset is usually negative
1302   llvm::Value *typeInfoThrown = builder.CreatePointerCast(
1303                                   builder.CreateConstGEP1_64(unwindException,
1304                                                        ourBaseFromUnwindOffset),
1305                                   ourExceptionType->getPointerTo());
1306   
1307   // Retrieve thrown exception type info type
1308   //
1309   // Note: Index is not relative to pointer but instead to structure
1310   //       unlike a true getelementptr (GEP) instruction
1311   typeInfoThrown = builder.CreateStructGEP(typeInfoThrown, 0);
1312   
1313   llvm::Value *typeInfoThrownType = 
1314   builder.CreateStructGEP(typeInfoThrown, 0);
1315   
1316   generateIntegerPrint(context, 
1317                        module,
1318                        builder, 
1319                        *toPrint32Int, 
1320                        *(builder.CreateLoad(typeInfoThrownType)),
1321                        "Gen: Exception type <%d> received (stack unwound) " 
1322                        " in " + 
1323                        ourId + 
1324                        ".\n",
1325                        USE_GLOBAL_STR_CONSTS);
1326   
1327   // Route to matched type info catch block or run cleanup finally block
1328   llvm::SwitchInst *switchToCatchBlock = builder.CreateSwitch(retTypeInfoIndex, 
1329                                                           finallyBlock, 
1330                                                           numExceptionsToCatch);
1331   
1332   unsigned nextTypeToCatch;
1333   
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]);
1339   }
1340
1341   llvm::verifyFunction(*ret);
1342   fpm.run(*ret);
1343   
1344   return(ret);
1345 }
1346
1347
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 
1355 ///        transformations
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
1362 static
1363 llvm::Function *createThrowExceptionFunction(llvm::Module &module, 
1364                                              llvm::IRBuilder<> &builder, 
1365                                              llvm::FunctionPassManager &fpm,
1366                                              std::string ourId,
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");
1375   
1376   llvm::Function *ret = createFunction(module,
1377                                        builder.getVoidTy(),
1378                                        unwindArgTypes,
1379                                        unwindArgNames,
1380                                        ourId,
1381                                        llvm::Function::ExternalLinkage,
1382                                        false,
1383                                        false);
1384   
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,
1388                                                           "entry", 
1389                                                           ret);
1390   // Throws a foreign exception
1391   llvm::BasicBlock *nativeThrowBlock = llvm::BasicBlock::Create(context,
1392                                                                 "nativeThrow", 
1393                                                                 ret);
1394   // Throws one of our Exceptions
1395   llvm::BasicBlock *generatedThrowBlock = llvm::BasicBlock::Create(context,
1396                                                              "generatedThrow", 
1397                                                              ret);
1398   // Retrieved runtime type info type to throw
1399   llvm::Value *exceptionType = namedValues["exceptTypeToThrow"];
1400   
1401   // nativeThrowBlock block
1402   
1403   builder.SetInsertPoint(nativeThrowBlock);
1404   
1405   // Throws foreign exception
1406   builder.CreateCall(&nativeThrowFunct, exceptionType);
1407   builder.CreateUnreachable();
1408   
1409   // entry block
1410   
1411   builder.SetInsertPoint(entryBlock);
1412   
1413   llvm::Function *toPrint32Int = module.getFunction("print32Int");
1414   generateIntegerPrint(context, 
1415                        module,
1416                        builder, 
1417                        *toPrint32Int, 
1418                        *exceptionType, 
1419                        "\nGen: About to throw exception type <%d> in " + 
1420                        ourId + 
1421                        ".\n",
1422                        USE_GLOBAL_STR_CONSTS);
1423   
1424   // Switches on runtime type info type value to determine whether or not
1425   // a foreign exception is thrown. Defaults to throwing one of our 
1426   // generated exceptions.
1427   llvm::SwitchInst *theSwitch = builder.CreateSwitch(exceptionType,
1428                                                      generatedThrowBlock,
1429                                                      1);
1430   
1431   theSwitch->addCase(llvm::ConstantInt::get(llvm::Type::getInt32Ty(context), 
1432                                             nativeThrowType),
1433                      nativeThrowBlock);
1434   
1435   // generatedThrow block
1436   
1437   builder.SetInsertPoint(generatedThrowBlock);
1438   
1439   llvm::Function *createOurException = module.getFunction("createOurException");
1440   llvm::Function *raiseOurException = module.getFunction(
1441                                         "_Unwind_RaiseException");
1442   
1443   // Creates exception to throw with runtime type info type.
1444   llvm::Value *exception = builder.CreateCall(createOurException, 
1445                                               namedValues["exceptTypeToThrow"]);
1446   
1447   // Throw generated Exception
1448   builder.CreateCall(raiseOurException, exception);
1449   builder.CreateUnreachable();
1450   
1451   llvm::verifyFunction(*ret);
1452   fpm.run(*ret);
1453   
1454   return(ret);
1455 }
1456
1457 static void createStandardUtilityFunctions(unsigned numTypeInfos,
1458                                            llvm::Module &module, 
1459                                            llvm::IRBuilder<> &builder);
1460
1461 /// Creates test code by generating and organizing these functions into the 
1462 /// test case. The test case consists of an outer function setup to invoke
1463 /// an inner function within an environment having multiple catch and single 
1464 /// finally blocks. This inner function is also setup to invoke a throw
1465 /// function within an evironment similar in nature to the outer function's 
1466 /// catch and finally blocks. Each of these two functions catch mutually
1467 /// exclusive subsets (even or odd) of the type info types configured
1468 /// for this this. All generated functions have a runtime argument which
1469 /// holds a type info type to throw that each function takes and passes it
1470 /// to the inner one if such a inner function exists. This type info type is
1471 /// looked at by the generated throw function to see whether or not it should
1472 /// throw a generated exception with the same type info type, or instead call
1473 /// a supplied a function which in turn will throw a foreign exception.
1474 /// @param module code for module instance
1475 /// @param builder builder instance
1476 /// @param fpm a function pass manager holding optional IR to IR 
1477 ///        transformations
1478 /// @param nativeThrowFunctName name of external function which will throw
1479 ///        a foreign exception
1480 /// @returns outermost generated test function.
1481 llvm::Function *createUnwindExceptionTest(llvm::Module &module, 
1482                                           llvm::IRBuilder<> &builder, 
1483                                           llvm::FunctionPassManager &fpm,
1484                                           std::string nativeThrowFunctName) {
1485   // Number of type infos to generate
1486   unsigned numTypeInfos = 6;
1487   
1488   // Initialze intrisics and external functions to use along with exception
1489   // and type info globals.
1490   createStandardUtilityFunctions(numTypeInfos,
1491                                  module,
1492                                  builder);
1493   llvm::Function *nativeThrowFunct = module.getFunction(nativeThrowFunctName);
1494   
1495   // Create exception throw function using the value ~0 to cause 
1496   // foreign exceptions to be thrown.
1497   llvm::Function *throwFunct = createThrowExceptionFunction(module,
1498                                                             builder,
1499                                                             fpm,
1500                                                             "throwFunct",
1501                                                             ~0,
1502                                                             *nativeThrowFunct);
1503   // Inner function will catch even type infos
1504   unsigned innerExceptionTypesToCatch[] = {6, 2, 4};
1505   size_t numExceptionTypesToCatch = sizeof(innerExceptionTypesToCatch) / 
1506                                     sizeof(unsigned);
1507   
1508   // Generate inner function.
1509   llvm::Function *innerCatchFunct = createCatchWrappedInvokeFunction(module,
1510                                                     builder,
1511                                                     fpm,
1512                                                     *throwFunct,
1513                                                     "innerCatchFunct",
1514                                                     numExceptionTypesToCatch,
1515                                                     innerExceptionTypesToCatch);
1516   
1517   // Outer function will catch odd type infos
1518   unsigned outerExceptionTypesToCatch[] = {3, 1, 5};
1519   numExceptionTypesToCatch = sizeof(outerExceptionTypesToCatch) / 
1520   sizeof(unsigned);
1521   
1522   // Generate outer function
1523   llvm::Function *outerCatchFunct = createCatchWrappedInvokeFunction(module,
1524                                                     builder,
1525                                                     fpm,
1526                                                     *innerCatchFunct,
1527                                                     "outerCatchFunct",
1528                                                     numExceptionTypesToCatch,
1529                                                     outerExceptionTypesToCatch);
1530   
1531   // Return outer function to run
1532   return(outerCatchFunct);
1533 }
1534
1535
1536 /// Represents our foreign exceptions
1537 class OurCppRunException : public std::runtime_error {
1538 public:
1539   OurCppRunException(const std::string reason) :
1540   std::runtime_error(reason) {}
1541   
1542   OurCppRunException (const OurCppRunException &toCopy) :
1543   std::runtime_error(toCopy) {}
1544   
1545   OurCppRunException &operator = (const OurCppRunException &toCopy) {
1546     return(reinterpret_cast<OurCppRunException&>(
1547                                  std::runtime_error::operator=(toCopy)));
1548   }
1549   
1550   ~OurCppRunException (void) throw () {}
1551 };
1552
1553
1554 /// Throws foreign C++ exception.
1555 /// @param ignoreIt unused parameter that allows function to match implied
1556 ///        generated function contract.
1557 extern "C"
1558 void throwCppException (int32_t ignoreIt) {
1559   throw(OurCppRunException("thrown by throwCppException(...)"));
1560 }
1561
1562 typedef void (*OurExceptionThrowFunctType) (int32_t typeToThrow);
1563
1564 /// This is a test harness which runs test by executing generated 
1565 /// function with a type info type to throw. Harness wraps the execution
1566 /// of generated function in a C++ try catch clause.
1567 /// @param engine execution engine to use for executing generated function.
1568 ///        This demo program expects this to be a JIT instance for demo
1569 ///        purposes.
1570 /// @param function generated test function to run
1571 /// @param typeToThrow type info type of generated exception to throw, or
1572 ///        indicator to cause foreign exception to be thrown.
1573 static
1574 void runExceptionThrow(llvm::ExecutionEngine *engine, 
1575                        llvm::Function *function, 
1576                        int32_t typeToThrow) {
1577   
1578   // Find test's function pointer
1579   OurExceptionThrowFunctType functPtr = 
1580     reinterpret_cast<OurExceptionThrowFunctType>(
1581        reinterpret_cast<intptr_t>(engine->getPointerToFunction(function)));
1582   
1583   try {
1584     // Run test
1585     (*functPtr)(typeToThrow);
1586   }
1587   catch (OurCppRunException exc) {
1588     // Catch foreign C++ exception
1589     fprintf(stderr,
1590             "\nrunExceptionThrow(...):In C++ catch OurCppRunException "
1591             "with reason: %s.\n", 
1592             exc.what());
1593   }
1594   catch (...) {
1595     // Catch all exceptions including our generated ones. This latter 
1596     // functionality works according to the example in rules 1.6.4 of
1597     // http://sourcery.mentor.com/public/cxx-abi/abi-eh.html (v1.22), 
1598     // given that these will be exceptions foreign to C++ 
1599     // (the _Unwind_Exception::exception_class should be different from 
1600     // the one used by C++).
1601     fprintf(stderr,
1602             "\nrunExceptionThrow(...):In C++ catch all.\n");
1603   }
1604 }
1605
1606 //
1607 // End test functions
1608 //
1609
1610 typedef llvm::ArrayRef<llvm::Type*> TypeArray;
1611
1612 /// This initialization routine creates type info globals and 
1613 /// adds external function declarations to module.
1614 /// @param numTypeInfos number of linear type info associated type info types
1615 ///        to create as GlobalVariable instances, starting with the value 1.
1616 /// @param module code for module instance
1617 /// @param builder builder instance
1618 static void createStandardUtilityFunctions(unsigned numTypeInfos,
1619                                            llvm::Module &module, 
1620                                            llvm::IRBuilder<> &builder) {
1621   
1622   llvm::LLVMContext &context = module.getContext();
1623   
1624   // Exception initializations
1625   
1626   // Setup exception catch state
1627   ourExceptionNotThrownState = 
1628     llvm::ConstantInt::get(llvm::Type::getInt8Ty(context), 0),
1629   ourExceptionThrownState = 
1630     llvm::ConstantInt::get(llvm::Type::getInt8Ty(context), 1),
1631   ourExceptionCaughtState = 
1632     llvm::ConstantInt::get(llvm::Type::getInt8Ty(context), 2),
1633   
1634   
1635   
1636   // Create our type info type
1637   ourTypeInfoType = llvm::StructType::get(context, 
1638                                           TypeArray(builder.getInt32Ty()));
1639
1640   llvm::Type *caughtResultFieldTypes[] = {
1641     builder.getInt8PtrTy(),
1642     builder.getInt32Ty()
1643   };
1644
1645   // Create our landingpad result type
1646   ourCaughtResultType = llvm::StructType::get(context,
1647                                             TypeArray(caughtResultFieldTypes));
1648
1649   // Create OurException type
1650   ourExceptionType = llvm::StructType::get(context, 
1651                                            TypeArray(ourTypeInfoType));
1652   
1653   // Create portion of _Unwind_Exception type
1654   //
1655   // Note: Declaring only a portion of the _Unwind_Exception struct.
1656   //       Does this cause problems?
1657   ourUnwindExceptionType =
1658     llvm::StructType::get(context, 
1659                     TypeArray(builder.getInt64Ty()));
1660
1661   struct OurBaseException_t dummyException;
1662   
1663   // Calculate offset of OurException::unwindException member.
1664   ourBaseFromUnwindOffset = ((uintptr_t) &dummyException) - 
1665                             ((uintptr_t) &(dummyException.unwindException));
1666   
1667 #ifdef DEBUG
1668   fprintf(stderr,
1669           "createStandardUtilityFunctions(...):ourBaseFromUnwindOffset "
1670           "= %lld, sizeof(struct OurBaseException_t) - "
1671           "sizeof(struct _Unwind_Exception) = %lu.\n",
1672           ourBaseFromUnwindOffset,
1673           sizeof(struct OurBaseException_t) - 
1674           sizeof(struct _Unwind_Exception));
1675 #endif
1676   
1677   size_t numChars = sizeof(ourBaseExcpClassChars) / sizeof(char);
1678   
1679   // Create our _Unwind_Exception::exception_class value
1680   ourBaseExceptionClass = genClass(ourBaseExcpClassChars, numChars);
1681   
1682   // Type infos
1683   
1684   std::string baseStr = "typeInfo", typeInfoName;
1685   std::ostringstream typeInfoNameBuilder;
1686   std::vector<llvm::Constant*> structVals;
1687   
1688   llvm::Constant *nextStruct;
1689   llvm::GlobalVariable *nextGlobal = NULL;
1690   
1691   // Generate each type info
1692   //
1693   // Note: First type info is not used.
1694   for (unsigned i = 0; i <= numTypeInfos; ++i) {
1695     structVals.clear();
1696     structVals.push_back(llvm::ConstantInt::get(builder.getInt32Ty(), i));
1697     nextStruct = llvm::ConstantStruct::get(ourTypeInfoType, structVals);
1698     
1699     typeInfoNameBuilder.str("");
1700     typeInfoNameBuilder << baseStr << i;
1701     typeInfoName = typeInfoNameBuilder.str();
1702     
1703     // Note: Does not seem to work without allocation
1704     nextGlobal = 
1705     new llvm::GlobalVariable(module, 
1706                              ourTypeInfoType, 
1707                              true, 
1708                              llvm::GlobalValue::ExternalLinkage, 
1709                              nextStruct, 
1710                              typeInfoName);
1711     
1712     ourTypeInfoNames.push_back(typeInfoName);
1713     ourTypeInfoNamesIndex[i] = typeInfoName;
1714   }
1715   
1716   ArgNames argNames;
1717   ArgTypes argTypes;
1718   llvm::Function *funct = NULL;
1719   
1720   // print32Int
1721   
1722   llvm::Type *retType = builder.getVoidTy();
1723   
1724   argTypes.clear();
1725   argTypes.push_back(builder.getInt32Ty());
1726   argTypes.push_back(builder.getInt8PtrTy());
1727   
1728   argNames.clear();
1729   
1730   createFunction(module, 
1731                  retType, 
1732                  argTypes, 
1733                  argNames, 
1734                  "print32Int", 
1735                  llvm::Function::ExternalLinkage, 
1736                  true, 
1737                  false);
1738   
1739   // print64Int
1740   
1741   retType = builder.getVoidTy();
1742   
1743   argTypes.clear();
1744   argTypes.push_back(builder.getInt64Ty());
1745   argTypes.push_back(builder.getInt8PtrTy());
1746   
1747   argNames.clear();
1748   
1749   createFunction(module, 
1750                  retType, 
1751                  argTypes, 
1752                  argNames, 
1753                  "print64Int", 
1754                  llvm::Function::ExternalLinkage, 
1755                  true, 
1756                  false);
1757   
1758   // printStr
1759   
1760   retType = builder.getVoidTy();
1761   
1762   argTypes.clear();
1763   argTypes.push_back(builder.getInt8PtrTy());
1764   
1765   argNames.clear();
1766   
1767   createFunction(module, 
1768                  retType, 
1769                  argTypes, 
1770                  argNames, 
1771                  "printStr", 
1772                  llvm::Function::ExternalLinkage, 
1773                  true, 
1774                  false);
1775   
1776   // throwCppException
1777   
1778   retType = builder.getVoidTy();
1779   
1780   argTypes.clear();
1781   argTypes.push_back(builder.getInt32Ty());
1782   
1783   argNames.clear();
1784   
1785   createFunction(module, 
1786                  retType, 
1787                  argTypes, 
1788                  argNames, 
1789                  "throwCppException", 
1790                  llvm::Function::ExternalLinkage, 
1791                  true, 
1792                  false);
1793   
1794   // deleteOurException
1795   
1796   retType = builder.getVoidTy();
1797   
1798   argTypes.clear();
1799   argTypes.push_back(builder.getInt8PtrTy());
1800   
1801   argNames.clear();
1802   
1803   createFunction(module, 
1804                  retType, 
1805                  argTypes, 
1806                  argNames, 
1807                  "deleteOurException", 
1808                  llvm::Function::ExternalLinkage, 
1809                  true, 
1810                  false);
1811   
1812   // createOurException
1813   
1814   retType = builder.getInt8PtrTy();
1815   
1816   argTypes.clear();
1817   argTypes.push_back(builder.getInt32Ty());
1818   
1819   argNames.clear();
1820   
1821   createFunction(module, 
1822                  retType, 
1823                  argTypes, 
1824                  argNames, 
1825                  "createOurException", 
1826                  llvm::Function::ExternalLinkage, 
1827                  true, 
1828                  false);
1829   
1830   // _Unwind_RaiseException
1831   
1832   retType = builder.getInt32Ty();
1833   
1834   argTypes.clear();
1835   argTypes.push_back(builder.getInt8PtrTy());
1836   
1837   argNames.clear();
1838   
1839   funct = createFunction(module, 
1840                          retType, 
1841                          argTypes, 
1842                          argNames, 
1843                          "_Unwind_RaiseException", 
1844                          llvm::Function::ExternalLinkage, 
1845                          true, 
1846                          false);
1847   
1848   funct->addFnAttr(llvm::Attribute::NoReturn);
1849   
1850   // _Unwind_Resume
1851   
1852   retType = builder.getInt32Ty();
1853   
1854   argTypes.clear();
1855   argTypes.push_back(builder.getInt8PtrTy());
1856   
1857   argNames.clear();
1858   
1859   funct = createFunction(module, 
1860                          retType, 
1861                          argTypes, 
1862                          argNames, 
1863                          "_Unwind_Resume", 
1864                          llvm::Function::ExternalLinkage, 
1865                          true, 
1866                          false);
1867   
1868   funct->addFnAttr(llvm::Attribute::NoReturn);
1869   
1870   // ourPersonality
1871   
1872   retType = builder.getInt32Ty();
1873   
1874   argTypes.clear();
1875   argTypes.push_back(builder.getInt32Ty());
1876   argTypes.push_back(builder.getInt32Ty());
1877   argTypes.push_back(builder.getInt64Ty());
1878   argTypes.push_back(builder.getInt8PtrTy());
1879   argTypes.push_back(builder.getInt8PtrTy());
1880   
1881   argNames.clear();
1882   
1883   createFunction(module, 
1884                  retType, 
1885                  argTypes, 
1886                  argNames, 
1887                  "ourPersonality", 
1888                  llvm::Function::ExternalLinkage, 
1889                  true, 
1890                  false);
1891   
1892   // llvm.eh.typeid.for intrinsic
1893   
1894   getDeclaration(&module, llvm::Intrinsic::eh_typeid_for);
1895 }
1896
1897
1898 //===----------------------------------------------------------------------===//
1899 // Main test driver code.
1900 //===----------------------------------------------------------------------===//
1901
1902 /// Demo main routine which takes the type info types to throw. A test will
1903 /// be run for each given type info type. While type info types with the value 
1904 /// of -1 will trigger a foreign C++ exception to be thrown; type info types
1905 /// <= 6 and >= 1 will be caught by test functions; and type info types > 6
1906 /// will result in exceptions which pass through to the test harness. All other
1907 /// type info types are not supported and could cause a crash.
1908 int main(int argc, char *argv[]) {
1909   if (argc == 1) {
1910     fprintf(stderr,
1911             "\nUsage: ExceptionDemo <exception type to throw> "
1912             "[<type 2>...<type n>].\n"
1913             "   Each type must have the value of 1 - 6 for "
1914             "generated exceptions to be caught;\n"
1915             "   the value -1 for foreign C++ exceptions to be "
1916             "generated and thrown;\n"
1917             "   or the values > 6 for exceptions to be ignored.\n"
1918             "\nTry: ExceptionDemo 2 3 7 -1\n"
1919             "   for a full test.\n\n");
1920     return(0);
1921   }
1922   
1923   // If not set, exception handling will not be turned on
1924   llvm::TargetOptions Opts;
1925   Opts.JITExceptionHandling = true;
1926   
1927   llvm::InitializeNativeTarget();
1928   llvm::LLVMContext &context = llvm::getGlobalContext();
1929   llvm::IRBuilder<> theBuilder(context);
1930   
1931   // Make the module, which holds all the code.
1932   llvm::Module *module = new llvm::Module("my cool jit", context);
1933   
1934   // Build engine with JIT
1935   llvm::EngineBuilder factory(module);
1936   factory.setEngineKind(llvm::EngineKind::JIT);
1937   factory.setAllocateGVsWithCode(false);
1938   factory.setTargetOptions(Opts);
1939   llvm::ExecutionEngine *executionEngine = factory.create();
1940   
1941   {
1942     llvm::FunctionPassManager fpm(module);
1943     
1944     // Set up the optimizer pipeline.  
1945     // Start with registering info about how the
1946     // target lays out data structures.
1947     fpm.add(new llvm::TargetData(*executionEngine->getTargetData()));
1948     
1949     // Optimizations turned on
1950 #ifdef ADD_OPT_PASSES
1951     
1952     // Basic AliasAnslysis support for GVN.
1953     fpm.add(llvm::createBasicAliasAnalysisPass());
1954     
1955     // Promote allocas to registers.
1956     fpm.add(llvm::createPromoteMemoryToRegisterPass());
1957     
1958     // Do simple "peephole" optimizations and bit-twiddling optzns.
1959     fpm.add(llvm::createInstructionCombiningPass());
1960     
1961     // Reassociate expressions.
1962     fpm.add(llvm::createReassociatePass());
1963     
1964     // Eliminate Common SubExpressions.
1965     fpm.add(llvm::createGVNPass());
1966     
1967     // Simplify the control flow graph (deleting unreachable 
1968     // blocks, etc).
1969     fpm.add(llvm::createCFGSimplificationPass());
1970 #endif  // ADD_OPT_PASSES
1971     
1972     fpm.doInitialization();
1973     
1974     // Generate test code using function throwCppException(...) as
1975     // the function which throws foreign exceptions.
1976     llvm::Function *toRun = 
1977     createUnwindExceptionTest(*module, 
1978                               theBuilder, 
1979                               fpm,
1980                               "throwCppException");
1981     
1982     fprintf(stderr, "\nBegin module dump:\n\n");
1983     
1984     module->dump();
1985     
1986     fprintf(stderr, "\nEnd module dump:\n");
1987     
1988     fprintf(stderr, "\n\nBegin Test:\n");
1989     
1990     for (int i = 1; i < argc; ++i) {
1991       // Run test for each argument whose value is the exception
1992       // type to throw.
1993       runExceptionThrow(executionEngine, 
1994                         toRun, 
1995                         (unsigned) strtoul(argv[i], NULL, 10));
1996     }
1997     
1998     fprintf(stderr, "\nEnd Test:\n\n");
1999   } 
2000   
2001   delete executionEngine;
2002   
2003   return 0;
2004 }
2005