Converted Exception demo over to using new 3.0 landingpad instruction. This
[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 questionable.
44 //
45 // This code uses code from the llvm compiler-rt project and the llvm 
46 // Kaleidoscope project.
47 //
48 //===----------------------------------------------------------------------===//
49
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"
64
65 #ifdef OLD_EXC_SYSTEM
66 // See use of UpgradeExceptionHandling(...) below                        
67 #include "llvm/AutoUpgrade.h"
68 #endif
69
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.
78 #include <cstdio>
79
80 #include <sstream>
81 #include <stdexcept>
82
83
84 #ifndef USE_GLOBAL_STR_CONSTS
85 #define USE_GLOBAL_STR_CONSTS true
86 #endif
87
88 // System C++ ABI unwind types from: 
89 //     http://refspecs.freestandards.org/abi-eh-1.21.html
90
91 extern "C" {
92   
93   typedef enum {
94     _URC_NO_REASON = 0,
95     _URC_FOREIGN_EXCEPTION_CAUGHT = 1,
96     _URC_FATAL_PHASE2_ERROR = 2,
97     _URC_FATAL_PHASE1_ERROR = 3,
98     _URC_NORMAL_STOP = 4,
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;
104   
105   typedef enum {
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
111   } _Unwind_Action;
112   
113   struct _Unwind_Exception;
114   
115   typedef void (*_Unwind_Exception_Cleanup_Fn) (_Unwind_Reason_Code,
116                                                 struct _Unwind_Exception *);
117   
118   struct _Unwind_Exception {
119     uint64_t exception_class;
120     _Unwind_Exception_Cleanup_Fn exception_cleanup;
121     
122     uintptr_t private_1;    
123     uintptr_t private_2;    
124     
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__));
129   
130   struct _Unwind_Context;
131   typedef struct _Unwind_Context *_Unwind_Context_t;
132   
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);
139   
140 } // extern "C"
141
142 //
143 // Example types
144 //
145
146 /// This is our simplistic type info
147 struct OurExceptionType_t {
148   /// type info type
149   int type;
150 };
151
152
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.
155 /// 
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;
161   
162   // Note: This is properly aligned in unwind.h
163   struct _Unwind_Exception unwindException;
164 };
165
166
167 // Note: Not needed since we are C++
168 typedef struct OurBaseException_t OurException;
169 typedef struct _Unwind_Exception OurUnwindException;
170
171 //
172 // Various globals used to support typeinfo and generatted exceptions in 
173 // general
174 //
175
176 static std::map<std::string, llvm::Value*> namedValues;
177
178 int64_t ourBaseFromUnwindOffset;
179
180 const unsigned char ourBaseExcpClassChars[] = 
181 {'o', 'b', 'j', '\0', 'b', 'a', 's', '\0'};
182
183
184 static uint64_t ourBaseExceptionClass = 0;
185
186 static std::vector<std::string> ourTypeInfoNames;
187 static std::map<int, std::string> ourTypeInfoNamesIndex;
188
189 static llvm::StructType *ourTypeInfoType;
190 #ifndef OLD_EXC_SYSTEM
191 static llvm::StructType *ourCaughtResultType;
192 #endif
193 static llvm::StructType *ourExceptionType;
194 static llvm::StructType *ourUnwindExceptionType;
195
196 static llvm::ConstantInt *ourExceptionNotThrownState;
197 static llvm::ConstantInt *ourExceptionThrownState;
198 static llvm::ConstantInt *ourExceptionCaughtState;
199
200 typedef std::vector<std::string> ArgNames;
201 typedef std::vector<llvm::Type*> ArgTypes;
202
203 //
204 // Code Generation Utilities
205 //
206
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,
220                                llvm::Type *retType,
221                                const ArgTypes &theArgTypes,
222                                const ArgNames &theArgNames,
223                                const std::string &functName,
224                                llvm::GlobalValue::LinkageTypes linkage,
225                                bool declarationOnly,
226                                bool isVarArg) {
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)
232     return(ret);
233   
234   namedValues.clear();
235   unsigned i = 0; 
236   for (llvm::Function::arg_iterator argIndex = ret->arg_begin();
237        i != theArgNames.size();
238        ++argIndex, ++i) {
239     
240     argIndex->setName(theArgNames[i]);
241     namedValues[theArgNames[i]] = argIndex;
242   }
243   
244   return(ret);
245 }
246
247
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,
257                                                 llvm::Type *type,
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());
262   
263   if (initWith) 
264     tmp.CreateStore(initWith, ret);
265   
266   return(ret);
267 }
268
269
270 //
271 // Code Generation Utilities End
272 //
273
274 //
275 // Runtime C Library functions 
276 //
277
278 // Note: using an extern "C" block so that static functions can be used
279 extern "C" {
280
281 // Note: Better ways to decide on bit width
282 //
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) {
287   if (format) {
288     // Note: No NULL check
289     fprintf(stderr, format, intToPrint);
290   }
291   else {
292     // Note: No NULL check
293     fprintf(stderr, "::print32Int(...):NULL arg.\n");
294   }
295 }
296
297
298 // Note: Better ways to decide on bit width
299 //
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) {
304   if (format) {
305     // Note: No NULL check
306     fprintf(stderr, format, intToPrint);
307   }
308   else {
309     // Note: No NULL check
310     fprintf(stderr, "::print64Int(...):NULL arg.\n");
311   }
312 }
313
314
315 /// Prints a C string to stderr
316 /// @param toPrint string to print
317 void printStr(char *toPrint) {
318   if (toPrint) {
319     fprintf(stderr, "%s", toPrint);
320   }
321   else {
322     fprintf(stderr, "::printStr(...):NULL arg.\n");
323   }
324 }
325
326
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) {
332 #ifdef DEBUG
333   fprintf(stderr,
334           "deleteOurException(...).\n");
335 #endif
336   
337   if (expToDelete &&
338       (expToDelete->exception_class == ourBaseExceptionClass)) {
339     
340     free(((char*) expToDelete) + ourBaseFromUnwindOffset);
341   }
342 }
343
344
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 
349 /// @unlink
350 /// @param expToDelete exception instance to delete
351 void deleteFromUnwindOurException(_Unwind_Reason_Code reason,
352                                   OurUnwindException *expToDelete) {
353 #ifdef DEBUG
354   fprintf(stderr,
355           "deleteFromUnwindOurException(...).\n");
356 #endif
357   
358   deleteOurException(expToDelete);
359 }
360
361
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;
371   
372   return(&(ret->unwindException));
373 }
374
375
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;
383   uintptr_t shift = 0;
384   unsigned char byte;
385   const uint8_t *p = *data;
386   
387   do {
388     byte = *p++;
389     result |= (byte & 0x7f) << shift;
390     shift += 7;
391   } 
392   while (byte & 0x80);
393   
394   *data = p;
395   
396   return result;
397 }
398
399
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;
407   uintptr_t shift = 0;
408   unsigned char byte;
409   const uint8_t *p = *data;
410   
411   do {
412     byte = *p++;
413     result |= (byte & 0x7f) << shift;
414     shift += 7;
415   } 
416   while (byte & 0x80);
417   
418   *data = p;
419   
420   if ((byte & 0x40) && (shift < (sizeof(result) << 3))) {
421     result |= (~0 << shift);
422   }
423   
424   return result;
425 }
426
427
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;
437   
438   if (encoding == llvm::dwarf::DW_EH_PE_omit) 
439     return(result);
440   
441   // first get value 
442   switch (encoding & 0x0F) {
443     case llvm::dwarf::DW_EH_PE_absptr:
444       result = *((uintptr_t*)p);
445       p += sizeof(uintptr_t);
446       break;
447     case llvm::dwarf::DW_EH_PE_uleb128:
448       result = readULEB128(&p);
449       break;
450       // Note: This case has not been tested
451     case llvm::dwarf::DW_EH_PE_sleb128:
452       result = readSLEB128(&p);
453       break;
454     case llvm::dwarf::DW_EH_PE_udata2:
455       result = *((uint16_t*)p);
456       p += sizeof(uint16_t);
457       break;
458     case llvm::dwarf::DW_EH_PE_udata4:
459       result = *((uint32_t*)p);
460       p += sizeof(uint32_t);
461       break;
462     case llvm::dwarf::DW_EH_PE_udata8:
463       result = *((uint64_t*)p);
464       p += sizeof(uint64_t);
465       break;
466     case llvm::dwarf::DW_EH_PE_sdata2:
467       result = *((int16_t*)p);
468       p += sizeof(int16_t);
469       break;
470     case llvm::dwarf::DW_EH_PE_sdata4:
471       result = *((int32_t*)p);
472       p += sizeof(int32_t);
473       break;
474     case llvm::dwarf::DW_EH_PE_sdata8:
475       result = *((int64_t*)p);
476       p += sizeof(int64_t);
477       break;
478     default:
479       // not supported 
480       abort();
481       break;
482   }
483   
484   // then add relative offset 
485   switch (encoding & 0x70) {
486     case llvm::dwarf::DW_EH_PE_absptr:
487       // do nothing 
488       break;
489     case llvm::dwarf::DW_EH_PE_pcrel:
490       result += (uintptr_t)(*data);
491       break;
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:
496     default:
497       // not supported 
498       abort();
499       break;
500   }
501   
502   // then apply indirection 
503   if (encoding & llvm::dwarf::DW_EH_PE_indirect) {
504     result = *((uintptr_t*)result);
505   }
506   
507   *data = p;
508   
509   return result;
510 }
511
512
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) {
536   bool ret = false;
537   
538   if (!resultAction || 
539       !exceptionObject || 
540       (exceptionClass != ourBaseExceptionClass))
541     return(ret);
542   
543   struct OurBaseException_t *excp = (struct OurBaseException_t*)
544   (((char*) exceptionObject) + ourBaseFromUnwindOffset);
545   struct OurExceptionType_t *excpType = &(excp->type);
546   int type = excpType->type;
547   
548 #ifdef DEBUG
549   fprintf(stderr,
550           "handleActionValue(...): exceptionObject = <%p>, "
551           "excp = <%p>.\n",
552           exceptionObject,
553           excp);
554 #endif
555   
556   const uint8_t *actionPos = (uint8_t*) actionEntry,
557   *tempActionPos;
558   int64_t typeOffset = 0,
559   actionOffset;
560   
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
564     // emitted action.
565     typeOffset = readSLEB128(&actionPos);
566     tempActionPos = actionPos;
567     actionOffset = readSLEB128(&tempActionPos);
568     
569 #ifdef DEBUG
570     fprintf(stderr,
571             "handleActionValue(...):typeOffset: <%lld>, "
572             "actionOffset: <%lld>.\n",
573             typeOffset,
574             actionOffset);
575 #endif
576     assert((typeOffset >= 0) && 
577            "handleActionValue(...):filters are not supported.");
578     
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)) {
583 #ifdef DEBUG
584       fprintf(stderr,
585               "handleActionValue(...):actionValue <%d> found.\n",
586               i);
587 #endif
588       *resultAction = i + 1;
589       ret = true;
590       break;
591     }
592     
593 #ifdef DEBUG
594     fprintf(stderr,
595             "handleActionValue(...):actionValue not found.\n");
596 #endif
597     if (!actionOffset)
598       break;
599     
600     actionPos += actionOffset;
601   }
602   
603   return(ret);
604 }
605
606
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, 
619                                       const uint8_t *lsda,
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;
625   
626   if (!lsda)
627     return(ret);
628   
629 #ifdef DEBUG
630   fprintf(stderr, 
631           "handleLsda(...):lsda is non-zero.\n");
632 #endif
633   
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;
637   
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;
643   
644   // Note: See JITDwarfEmitter::EmitExceptionTable(...) for corresponding
645   //       dwarf emission
646   
647   // Parse LSDA header.
648   uint8_t lpStartEncoding = *lsda++;
649   
650   if (lpStartEncoding != llvm::dwarf::DW_EH_PE_omit) {
651     readEncodedPointer(&lsda, lpStartEncoding); 
652   }
653   
654   uint8_t ttypeEncoding = *lsda++;
655   uintptr_t classInfoOffset;
656   
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
660     // intrinsic
661     classInfoOffset = readULEB128(&lsda);
662     classInfo = (struct OurExceptionType_t**) (lsda + classInfoOffset);
663   }
664   
665   // Walk call-site table looking for range that 
666   // includes current PC. 
667   
668   uint8_t         callSiteEncoding = *lsda++;
669   uint32_t        callSiteTableLength = readULEB128(&lsda);
670   const uint8_t   *callSiteTableStart = lsda;
671   const uint8_t   *callSiteTableEnd = callSiteTableStart + 
672   callSiteTableLength;
673   const uint8_t   *actionTableStart = callSiteTableEnd;
674   const uint8_t   *callSitePtr = callSiteTableStart;
675   
676   bool foreignException = false;
677   
678   while (callSitePtr < callSiteTableEnd) {
679     uintptr_t start = readEncodedPointer(&callSitePtr, 
680                                          callSiteEncoding);
681     uintptr_t length = readEncodedPointer(&callSitePtr, 
682                                           callSiteEncoding);
683     uintptr_t landingPad = readEncodedPointer(&callSitePtr, 
684                                               callSiteEncoding);
685     
686     // Note: Action value
687     uintptr_t actionEntry = readULEB128(&callSitePtr);
688     
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
692       actionEntry = 0;
693       foreignException = true;
694     }
695     
696     if (landingPad == 0) {
697 #ifdef DEBUG
698       fprintf(stderr,
699               "handleLsda(...): No landing pad found.\n");
700 #endif
701       
702       continue; // no landing pad for this entry
703     }
704     
705     if (actionEntry) {
706       actionEntry += ((uintptr_t) actionTableStart) - 1;
707     }
708     else {
709 #ifdef DEBUG
710       fprintf(stderr,
711               "handleLsda(...):No action table found.\n");
712 #endif
713     }
714     
715     bool exceptionMatched = false;
716     
717     if ((start <= pcOffset) && (pcOffset < (start + length))) {
718 #ifdef DEBUG
719       fprintf(stderr,
720               "handleLsda(...): Landing pad found.\n");
721 #endif
722       int64_t actionValue = 0;
723       
724       if (actionEntry) {
725         exceptionMatched = handleActionValue(&actionValue,
726                                              classInfo, 
727                                              actionEntry, 
728                                              exceptionClass, 
729                                              exceptionObject);
730       }
731       
732       if (!(actions & _UA_SEARCH_PHASE)) {
733 #ifdef DEBUG
734         fprintf(stderr,
735                 "handleLsda(...): installed landing pad "
736                 "context.\n");
737 #endif
738         
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);
746         
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), 
753                         0);
754         }
755         else {
756           // Matched type info index of llvm.eh.selector intrinsic
757           // passed here.
758           _Unwind_SetGR(context, 
759                         __builtin_eh_return_data_regno(1), 
760                         actionValue);
761         }
762         
763         // To execute landing pad set here
764         _Unwind_SetIP(context, funcStart + landingPad);
765         ret = _URC_INSTALL_CONTEXT;
766       }
767       else if (exceptionMatched) {
768 #ifdef DEBUG
769         fprintf(stderr,
770                 "handleLsda(...): setting handler found.\n");
771 #endif
772         ret = _URC_HANDLER_FOUND;
773       }
774       else {
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 
778         //       phase.
779 #ifdef DEBUG
780         fprintf(stderr,
781                 "handleLsda(...): cleanup handler found.\n");
782 #endif
783       }
784       
785       break;
786     }
787   }
788   
789   return(ret);
790 }
791
792
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) {
809 #ifdef DEBUG
810   fprintf(stderr, 
811           "We are in ourPersonality(...):actions is <%d>.\n",
812           actions);
813   
814   if (actions & _UA_SEARCH_PHASE) {
815     fprintf(stderr, "ourPersonality(...):In search phase.\n");
816   }
817   else {
818     fprintf(stderr, "ourPersonality(...):In non-search phase.\n");
819   }
820 #endif
821   
822   const uint8_t *lsda = _Unwind_GetLanguageSpecificData(context);
823   
824 #ifdef DEBUG
825   fprintf(stderr, 
826           "ourPersonality(...):lsda = <%p>.\n",
827           lsda);
828 #endif
829   
830   // The real work of the personality function is captured here
831   return(handleLsda(version,
832                     lsda,
833                     actions,
834                     exceptionClass,
835                     exceptionObject,
836                     context));
837 }
838
839
840 /// Generates our _Unwind_Exception class from a given character array.
841 /// thereby handling arbitrary lengths (not in standard), and handling
842 /// embedded \0s.
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)
848 {
849   uint64_t ret = classChars[0];
850   
851   for (unsigned i = 1; i < classCharsSize; ++i) {
852     ret <<= 8;
853     ret += classChars[i];
854   }
855   
856   return(ret);
857 }
858
859 } // extern "C"
860
861 //
862 // Runtime C Library functions End
863 //
864
865 //
866 // Code generation functions
867 //
868
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 
877 ///        stack.
878 void generateStringPrint(llvm::LLVMContext &context, 
879                          llvm::Module &module,
880                          llvm::IRBuilder<> &builder, 
881                          std::string toPrint,
882                          bool useGlobal = true) {
883   llvm::Function *printFunct = module.getFunction("printStr");
884   
885   llvm::Value *stringVar;
886   llvm::Constant *stringConstant = 
887   llvm::ConstantArray::get(context, toPrint);
888   
889   if (useGlobal) {
890     // Note: Does not work without allocation
891     stringVar = 
892     new llvm::GlobalVariable(module, 
893                              stringConstant->getType(),
894                              true, 
895                              llvm::GlobalValue::LinkerPrivateLinkage, 
896                              stringConstant, 
897                              "");
898   }
899   else {
900     stringVar = builder.CreateAlloca(stringConstant->getType());
901     builder.CreateStore(stringConstant, stringVar);
902   }
903   
904   llvm::Value *cast = 
905   builder.CreatePointerCast(stringVar, 
906                             builder.getInt8PtrTy());
907   builder.CreateCall(printFunct, cast);
908 }
909
910
911 /// Generates code to print given runtime integer according to constant
912 /// string format, and a given print function.
913 /// @param context llvm context
914 /// @param module code for module instance
915 /// @param builder builder instance
916 /// @param printFunct function used to "print" integer
917 /// @param toPrint string to print
918 /// @param format printf like formating string for print
919 /// @param useGlobal A value of true (default) indicates a GlobalValue is 
920 ///        generated, and is used to hold the constant string. A value of 
921 ///        false indicates that the constant string will be stored on the 
922 ///        stack.
923 void generateIntegerPrint(llvm::LLVMContext &context, 
924                           llvm::Module &module,
925                           llvm::IRBuilder<> &builder, 
926                           llvm::Function &printFunct,
927                           llvm::Value &toPrint,
928                           std::string format, 
929                           bool useGlobal = true) {
930   llvm::Constant *stringConstant = llvm::ConstantArray::get(context, format);
931   llvm::Value *stringVar;
932   
933   if (useGlobal) {
934     // Note: Does not seem to work without allocation
935     stringVar = 
936     new llvm::GlobalVariable(module, 
937                              stringConstant->getType(),
938                              true, 
939                              llvm::GlobalValue::LinkerPrivateLinkage, 
940                              stringConstant, 
941                              "");
942   }
943   else {
944     stringVar = builder.CreateAlloca(stringConstant->getType());
945     builder.CreateStore(stringConstant, stringVar);
946   }
947   
948   llvm::Value *cast = 
949   builder.CreateBitCast(stringVar, 
950                         builder.getInt8PtrTy());
951   builder.CreateCall2(&printFunct, &toPrint, cast);
952 }
953
954
955 /// Generates code to handle finally block type semantics: always runs 
956 /// regardless of whether a thrown exception is passing through or the 
957 /// parent function is simply exiting. In addition to printing some state 
958 /// to stderr, this code will resume the exception handling--runs the 
959 /// unwind resume block, if the exception has not been previously caught 
960 /// by a catch clause, and will otherwise execute the end block (terminator 
961 /// block). In addition this function creates the corresponding function's 
962 /// stack storage for the exception pointer and catch flag status.
963 /// @param context llvm context
964 /// @param module code for module instance
965 /// @param builder builder instance
966 /// @param toAddTo parent function to add block to
967 /// @param blockName block name of new "finally" block.
968 /// @param functionId output id used for printing
969 /// @param terminatorBlock terminator "end" block
970 /// @param unwindResumeBlock unwind resume block
971 /// @param exceptionCaughtFlag reference exception caught/thrown status storage
972 /// @param exceptionStorage reference to exception pointer storage
973 /// @returns newly created block
974 static llvm::BasicBlock *createFinallyBlock(llvm::LLVMContext &context, 
975                                             llvm::Module &module, 
976                                             llvm::IRBuilder<> &builder, 
977                                             llvm::Function &toAddTo,
978                                             std::string &blockName,
979                                             std::string &functionId,
980                                             llvm::BasicBlock &terminatorBlock,
981                                             llvm::BasicBlock &unwindResumeBlock,
982                                             llvm::Value **exceptionCaughtFlag,
983                                             llvm::Value **exceptionStorage) {
984   assert(exceptionCaughtFlag && 
985          "ExceptionDemo::createFinallyBlock(...):exceptionCaughtFlag "
986          "is NULL");
987   assert(exceptionStorage && 
988          "ExceptionDemo::createFinallyBlock(...):exceptionStorage "
989          "is NULL");
990   
991   *exceptionCaughtFlag = 
992   createEntryBlockAlloca(toAddTo,
993                          "exceptionCaught",
994                          ourExceptionNotThrownState->getType(),
995                          ourExceptionNotThrownState);
996   
997   llvm::PointerType *exceptionStorageType = builder.getInt8PtrTy();
998   *exceptionStorage = 
999   createEntryBlockAlloca(toAddTo,
1000                          "exceptionStorage",
1001                          exceptionStorageType,
1002                          llvm::ConstantPointerNull::get(
1003                                                         exceptionStorageType));
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 = 
1021   builder.CreateSwitch(builder.CreateLoad(*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 = 
1132   llvm::BasicBlock::Create(context, "exception", ret);
1133   
1134   // Block which routes exception to correct catch handler block
1135   llvm::BasicBlock *exceptionRouteBlock = 
1136   llvm::BasicBlock::Create(context, "exceptionRoute", ret);
1137   
1138   // Foreign exception handler
1139   llvm::BasicBlock *externalExceptionBlock = 
1140   llvm::BasicBlock::Create(context, "externalException", ret);
1141   
1142   // Block which calls _Unwind_Resume
1143   llvm::BasicBlock *unwindResumeBlock = 
1144   llvm::BasicBlock::Create(context, "unwindResume", ret);
1145   
1146   // Clean up block which delete exception if needed
1147   llvm::BasicBlock *endBlock = 
1148   llvm::BasicBlock::Create(context, "end", ret);
1149   
1150   std::string nextName;
1151   std::vector<llvm::BasicBlock*> catchBlocks(numExceptionsToCatch);
1152   llvm::Value *exceptionCaughtFlag = NULL;
1153   llvm::Value *exceptionStorage = NULL;
1154   
1155   // Finally block which will branch to unwindResumeBlock if 
1156   // exception is not caught. Initializes/allocates stack locations.
1157   llvm::BasicBlock *finallyBlock = createFinallyBlock(context, 
1158                                                       module, 
1159                                                       builder, 
1160                                                       *ret, 
1161                                                       nextName = "finally", 
1162                                                       ourId,
1163                                                       *endBlock,
1164                                                       *unwindResumeBlock,
1165                                                       &exceptionCaughtFlag,
1166                                                       &exceptionStorage);
1167   
1168   for (unsigned i = 0; i < numExceptionsToCatch; ++i) {
1169     nextName = ourTypeInfoNames[exceptionTypesToCatch[i]];
1170     
1171     // One catch block per type info to be caught
1172     catchBlocks[i] = createCatchBlock(context, 
1173                                       module, 
1174                                       builder, 
1175                                       *ret,
1176                                       nextName, 
1177                                       ourId,
1178                                       *finallyBlock,
1179                                       *exceptionCaughtFlag);
1180   }
1181   
1182   // Entry Block
1183   
1184   builder.SetInsertPoint(entryBlock);
1185   
1186   std::vector<llvm::Value*> args;
1187   args.push_back(namedValues["exceptTypeToThrow"]);
1188   builder.CreateInvoke(&toInvoke, 
1189                        normalBlock, 
1190                        exceptionBlock, 
1191                        args);
1192   
1193   // End Block
1194   
1195   builder.SetInsertPoint(endBlock);
1196   
1197   generateStringPrint(context, 
1198                       module,
1199                       builder, 
1200                       "Gen: In end block: exiting in " + ourId + ".\n",
1201                       USE_GLOBAL_STR_CONSTS);
1202   llvm::Function *deleteOurException = 
1203   module.getFunction("deleteOurException");
1204   
1205   // Note: function handles NULL exceptions
1206   builder.CreateCall(deleteOurException, 
1207                      builder.CreateLoad(exceptionStorage));
1208   builder.CreateRetVoid();
1209   
1210   // Normal Block
1211   
1212   builder.SetInsertPoint(normalBlock);
1213   
1214   generateStringPrint(context, 
1215                       module,
1216                       builder, 
1217                       "Gen: No exception in " + ourId + "!\n",
1218                       USE_GLOBAL_STR_CONSTS);
1219   
1220   // Finally block is always called
1221   builder.CreateBr(finallyBlock);
1222   
1223   // Unwind Resume Block
1224   
1225   builder.SetInsertPoint(unwindResumeBlock);
1226   
1227   llvm::Function *resumeOurException = module.getFunction("_Unwind_Resume");
1228   builder.CreateCall(resumeOurException, 
1229                      builder.CreateLoad(exceptionStorage));
1230   builder.CreateUnreachable();
1231   
1232   // Exception Block
1233   
1234   builder.SetInsertPoint(exceptionBlock);
1235   
1236   llvm::Function *personality = module.getFunction("ourPersonality");
1237   
1238 #ifndef OLD_EXC_SYSTEM
1239   llvm::LandingPadInst *caughtResult = 
1240     builder.CreateLandingPad(ourCaughtResultType,
1241                              personality,
1242                              numExceptionsToCatch,
1243                              "landingPad");
1244
1245   caughtResult->setCleanup(true);
1246
1247   for (unsigned i = 0; i < numExceptionsToCatch; ++i) {
1248     // Set up type infos to be caught
1249     caughtResult->addClause(module.getGlobalVariable(
1250                              ourTypeInfoNames[exceptionTypesToCatch[i]]));
1251   }
1252
1253   llvm::Value *unwindException = builder.CreateExtractValue(caughtResult, 0);
1254   llvm::Value *retTypeInfoIndex = 
1255     builder.CreateExtractValue(caughtResult, 1);
1256
1257   builder.CreateStore(unwindException, exceptionStorage);
1258   builder.CreateStore(ourExceptionThrownState, exceptionCaughtFlag);
1259
1260 #else
1261   llvm::Function *ehException = module.getFunction("llvm.eh.exception");
1262
1263   // Retrieve thrown exception
1264   llvm::Value *unwindException = builder.CreateCall(ehException);
1265   
1266   // Store exception and flag
1267   builder.CreateStore(unwindException, exceptionStorage);
1268   builder.CreateStore(ourExceptionThrownState, exceptionCaughtFlag);
1269   llvm::Value *functPtr = 
1270     builder.CreatePointerCast(personality, builder.getInt8PtrTy());
1271   
1272   args.clear();
1273   args.push_back(unwindException);
1274   args.push_back(functPtr);
1275   
1276   // Note: Skipping index 0
1277   for (unsigned i = 0; i < numExceptionsToCatch; ++i) {
1278     // Set up type infos to be caught
1279     args.push_back(module.getGlobalVariable(
1280                                   ourTypeInfoNames[exceptionTypesToCatch[i]]));
1281   }
1282   
1283   args.push_back(llvm::ConstantInt::get(builder.getInt32Ty(), 0));
1284   
1285   llvm::Function *ehSelector = module.getFunction("llvm.eh.selector");
1286   
1287   // Set up this exeption block as the landing pad which will handle
1288   // given type infos. See case Intrinsic::eh_selector in 
1289   // SelectionDAGBuilder::visitIntrinsicCall(...) and AddCatchInfo(...)
1290   // implemented in FunctionLoweringInfo.cpp to see how the implementation
1291   // handles this call. This landing pad (this exception block), will be 
1292   // called either because it nees to cleanup (call finally) or a type 
1293   // info was found which matched the thrown exception.
1294   llvm::Value *retTypeInfoIndex = builder.CreateCall(ehSelector, args);
1295 #endif
1296   
1297   // Retrieve exception_class member from thrown exception 
1298   // (_Unwind_Exception instance). This member tells us whether or not
1299   // the exception is foreign.
1300   llvm::Value *unwindExceptionClass = 
1301     builder.CreateLoad(builder.CreateStructGEP(
1302              builder.CreatePointerCast(unwindException, 
1303                                        ourUnwindExceptionType->getPointerTo()), 
1304                                                0));
1305   
1306   // Branch to the externalExceptionBlock if the exception is foreign or
1307   // to a catch router if not. Either way the finally block will be run.
1308   builder.CreateCondBr(builder.CreateICmpEQ(unwindExceptionClass,
1309                             llvm::ConstantInt::get(builder.getInt64Ty(), 
1310                                                    ourBaseExceptionClass)),
1311                        exceptionRouteBlock,
1312                        externalExceptionBlock);
1313   
1314   // External Exception Block
1315   
1316   builder.SetInsertPoint(externalExceptionBlock);
1317   
1318   generateStringPrint(context, 
1319                       module,
1320                       builder, 
1321                       "Gen: Foreign exception received.\n",
1322                       USE_GLOBAL_STR_CONSTS);
1323   
1324   // Branch to the finally block
1325   builder.CreateBr(finallyBlock);
1326   
1327   // Exception Route Block
1328   
1329   builder.SetInsertPoint(exceptionRouteBlock);
1330   
1331   // Casts exception pointer (_Unwind_Exception instance) to parent 
1332   // (OurException instance).
1333   //
1334   // Note: ourBaseFromUnwindOffset is usually negative
1335   llvm::Value *typeInfoThrown = 
1336   builder.CreatePointerCast(builder.CreateConstGEP1_64(unwindException,
1337                                                        ourBaseFromUnwindOffset),
1338                             ourExceptionType->getPointerTo());
1339   
1340   // Retrieve thrown exception type info type
1341   //
1342   // Note: Index is not relative to pointer but instead to structure
1343   //       unlike a true getelementptr (GEP) instruction
1344   typeInfoThrown = builder.CreateStructGEP(typeInfoThrown, 0);
1345   
1346   llvm::Value *typeInfoThrownType = 
1347   builder.CreateStructGEP(typeInfoThrown, 0);
1348   
1349   generateIntegerPrint(context, 
1350                        module,
1351                        builder, 
1352                        *toPrint32Int, 
1353                        *(builder.CreateLoad(typeInfoThrownType)),
1354                        "Gen: Exception type <%d> received (stack unwound) " 
1355                        " in " + 
1356                        ourId + 
1357                        ".\n",
1358                        USE_GLOBAL_STR_CONSTS);
1359   
1360   // Route to matched type info catch block or run cleanup finally block
1361   llvm::SwitchInst *switchToCatchBlock = 
1362   builder.CreateSwitch(retTypeInfoIndex, 
1363                        finallyBlock, 
1364                        numExceptionsToCatch);
1365   
1366   unsigned nextTypeToCatch;
1367   
1368   for (unsigned i = 1; i <= numExceptionsToCatch; ++i) {
1369     nextTypeToCatch = i - 1;
1370     switchToCatchBlock->addCase(llvm::ConstantInt::get(
1371                                    llvm::Type::getInt32Ty(context), i),
1372                                 catchBlocks[nextTypeToCatch]);
1373   }
1374
1375 #ifdef OLD_EXC_SYSTEM
1376   // Must be run before verifier                                                
1377   UpgradeExceptionHandling(&module);
1378 #endif
1379
1380   
1381   llvm::verifyFunction(*ret);
1382   fpm.run(*ret);
1383   
1384   return(ret);
1385 }
1386
1387
1388 /// Generates function which throws either an exception matched to a runtime
1389 /// determined type info type (argument to generated function), or if this 
1390 /// runtime value matches nativeThrowType, throws a foreign exception by 
1391 /// calling nativeThrowFunct.
1392 /// @param module code for module instance
1393 /// @param builder builder instance
1394 /// @param fpm a function pass manager holding optional IR to IR 
1395 ///        transformations
1396 /// @param ourId id used to printing purposes
1397 /// @param nativeThrowType a runtime argument of this value results in
1398 ///        nativeThrowFunct being called to generate/throw exception.
1399 /// @param nativeThrowFunct function which will throw a foreign exception
1400 ///        if the above nativeThrowType matches generated function's arg.
1401 /// @returns generated function
1402 static
1403 llvm::Function *createThrowExceptionFunction(llvm::Module &module, 
1404                                              llvm::IRBuilder<> &builder, 
1405                                              llvm::FunctionPassManager &fpm,
1406                                              std::string ourId,
1407                                              int32_t nativeThrowType,
1408                                              llvm::Function &nativeThrowFunct) {
1409   llvm::LLVMContext &context = module.getContext();
1410   namedValues.clear();
1411   ArgTypes unwindArgTypes;
1412   unwindArgTypes.push_back(builder.getInt32Ty());
1413   ArgNames unwindArgNames;
1414   unwindArgNames.push_back("exceptTypeToThrow");
1415   
1416   llvm::Function *ret = createFunction(module,
1417                                        builder.getVoidTy(),
1418                                        unwindArgTypes,
1419                                        unwindArgNames,
1420                                        ourId,
1421                                        llvm::Function::ExternalLinkage,
1422                                        false,
1423                                        false);
1424   
1425   // Throws either one of our exception or a native C++ exception depending
1426   // on a runtime argument value containing a type info type.
1427   llvm::BasicBlock *entryBlock = llvm::BasicBlock::Create(context,
1428                                                           "entry", 
1429                                                           ret);
1430   // Throws a foreign exception
1431   llvm::BasicBlock *nativeThrowBlock = 
1432   llvm::BasicBlock::Create(context,
1433                            "nativeThrow", 
1434                            ret);
1435   // Throws one of our Exceptions
1436   llvm::BasicBlock *generatedThrowBlock = 
1437   llvm::BasicBlock::Create(context,
1438                            "generatedThrow", 
1439                            ret);
1440   // Retrieved runtime type info type to throw
1441   llvm::Value *exceptionType = namedValues["exceptTypeToThrow"];
1442   
1443   // nativeThrowBlock block
1444   
1445   builder.SetInsertPoint(nativeThrowBlock);
1446   
1447   // Throws foreign exception
1448   builder.CreateCall(&nativeThrowFunct, exceptionType);
1449   builder.CreateUnreachable();
1450   
1451   // entry block
1452   
1453   builder.SetInsertPoint(entryBlock);
1454   
1455   llvm::Function *toPrint32Int = module.getFunction("print32Int");
1456   generateIntegerPrint(context, 
1457                        module,
1458                        builder, 
1459                        *toPrint32Int, 
1460                        *exceptionType, 
1461                        "\nGen: About to throw exception type <%d> in " + 
1462                        ourId + 
1463                        ".\n",
1464                        USE_GLOBAL_STR_CONSTS);
1465   
1466   // Switches on runtime type info type value to determine whether or not
1467   // a foreign exception is thrown. Defaults to throwing one of our 
1468   // generated exceptions.
1469   llvm::SwitchInst *theSwitch = builder.CreateSwitch(exceptionType,
1470                                                      generatedThrowBlock,
1471                                                      1);
1472   
1473   theSwitch->addCase(llvm::ConstantInt::get(llvm::Type::getInt32Ty(context), 
1474                                             nativeThrowType),
1475                      nativeThrowBlock);
1476   
1477   // generatedThrow block
1478   
1479   builder.SetInsertPoint(generatedThrowBlock);
1480   
1481   llvm::Function *createOurException = 
1482   module.getFunction("createOurException");
1483   llvm::Function *raiseOurException = 
1484   module.getFunction("_Unwind_RaiseException");
1485   
1486   // Creates exception to throw with runtime type info type.
1487   llvm::Value *exception = 
1488   builder.CreateCall(createOurException, 
1489                      namedValues["exceptTypeToThrow"]);
1490   
1491   // Throw generated Exception
1492   builder.CreateCall(raiseOurException, exception);
1493   builder.CreateUnreachable();
1494   
1495   llvm::verifyFunction(*ret);
1496   fpm.run(*ret);
1497   
1498   return(ret);
1499 }
1500
1501 static void createStandardUtilityFunctions(unsigned numTypeInfos,
1502                                            llvm::Module &module, 
1503                                            llvm::IRBuilder<> &builder);
1504
1505 /// Creates test code by generating and organizing these functions into the 
1506 /// test case. The test case consists of an outer function setup to invoke
1507 /// an inner function within an environment having multiple catch and single 
1508 /// finally blocks. This inner function is also setup to invoke a throw
1509 /// function within an evironment similar in nature to the outer function's 
1510 /// catch and finally blocks. Each of these two functions catch mutually
1511 /// exclusive subsets (even or odd) of the type info types configured
1512 /// for this this. All generated functions have a runtime argument which
1513 /// holds a type info type to throw that each function takes and passes it
1514 /// to the inner one if such a inner function exists. This type info type is
1515 /// looked at by the generated throw function to see whether or not it should
1516 /// throw a generated exception with the same type info type, or instead call
1517 /// a supplied a function which in turn will throw a foreign exception.
1518 /// @param module code for module instance
1519 /// @param builder builder instance
1520 /// @param fpm a function pass manager holding optional IR to IR 
1521 ///        transformations
1522 /// @param nativeThrowFunctName name of external function which will throw
1523 ///        a foreign exception
1524 /// @returns outermost generated test function.
1525 llvm::Function *createUnwindExceptionTest(llvm::Module &module, 
1526                                           llvm::IRBuilder<> &builder, 
1527                                           llvm::FunctionPassManager &fpm,
1528                                           std::string nativeThrowFunctName) {
1529   // Number of type infos to generate
1530   unsigned numTypeInfos = 6;
1531   
1532   // Initialze intrisics and external functions to use along with exception
1533   // and type info globals.
1534   createStandardUtilityFunctions(numTypeInfos,
1535                                  module,
1536                                  builder);
1537   llvm::Function *nativeThrowFunct = 
1538   module.getFunction(nativeThrowFunctName);
1539   
1540   // Create exception throw function using the value ~0 to cause 
1541   // foreign exceptions to be thrown.
1542   llvm::Function *throwFunct = 
1543   createThrowExceptionFunction(module,
1544                                builder,
1545                                fpm,
1546                                "throwFunct",
1547                                ~0,
1548                                *nativeThrowFunct);
1549   // Inner function will catch even type infos
1550   unsigned innerExceptionTypesToCatch[] = {6, 2, 4};
1551   size_t numExceptionTypesToCatch = sizeof(innerExceptionTypesToCatch) / 
1552   sizeof(unsigned);
1553   
1554   // Generate inner function.
1555   llvm::Function *innerCatchFunct = 
1556   createCatchWrappedInvokeFunction(module,
1557                                    builder,
1558                                    fpm,
1559                                    *throwFunct,
1560                                    "innerCatchFunct",
1561                                    numExceptionTypesToCatch,
1562                                    innerExceptionTypesToCatch);
1563   
1564   // Outer function will catch odd type infos
1565   unsigned outerExceptionTypesToCatch[] = {3, 1, 5};
1566   numExceptionTypesToCatch = sizeof(outerExceptionTypesToCatch) / 
1567   sizeof(unsigned);
1568   
1569   // Generate outer function
1570   llvm::Function *outerCatchFunct = 
1571   createCatchWrappedInvokeFunction(module,
1572                                    builder,
1573                                    fpm,
1574                                    *innerCatchFunct,
1575                                    "outerCatchFunct",
1576                                    numExceptionTypesToCatch,
1577                                    outerExceptionTypesToCatch);
1578   
1579   // Return outer function to run
1580   return(outerCatchFunct);
1581 }
1582
1583
1584 /// Represents our foreign exceptions
1585 class OurCppRunException : public std::runtime_error {
1586 public:
1587   OurCppRunException(const std::string reason) :
1588   std::runtime_error(reason) {}
1589   
1590   OurCppRunException (const OurCppRunException &toCopy) :
1591   std::runtime_error(toCopy) {}
1592   
1593   OurCppRunException &operator = (const OurCppRunException &toCopy) {
1594     return(reinterpret_cast<OurCppRunException&>(
1595                                  std::runtime_error::operator=(toCopy)));
1596   }
1597   
1598   ~OurCppRunException (void) throw () {}
1599 };
1600
1601
1602 /// Throws foreign C++ exception.
1603 /// @param ignoreIt unused parameter that allows function to match implied
1604 ///        generated function contract.
1605 extern "C"
1606 void throwCppException (int32_t ignoreIt) {
1607   throw(OurCppRunException("thrown by throwCppException(...)"));
1608 }
1609
1610 typedef void (*OurExceptionThrowFunctType) (int32_t typeToThrow);
1611
1612 /// This is a test harness which runs test by executing generated 
1613 /// function with a type info type to throw. Harness wraps the execution
1614 /// of generated function in a C++ try catch clause.
1615 /// @param engine execution engine to use for executing generated function.
1616 ///        This demo program expects this to be a JIT instance for demo
1617 ///        purposes.
1618 /// @param function generated test function to run
1619 /// @param typeToThrow type info type of generated exception to throw, or
1620 ///        indicator to cause foreign exception to be thrown.
1621 static
1622 void runExceptionThrow(llvm::ExecutionEngine *engine, 
1623                        llvm::Function *function, 
1624                        int32_t typeToThrow) {
1625   
1626   // Find test's function pointer
1627   OurExceptionThrowFunctType functPtr = 
1628     reinterpret_cast<OurExceptionThrowFunctType>(
1629        reinterpret_cast<intptr_t>(engine->getPointerToFunction(function)));
1630   
1631   try {
1632     // Run test
1633     (*functPtr)(typeToThrow);
1634   }
1635   catch (OurCppRunException exc) {
1636     // Catch foreign C++ exception
1637     fprintf(stderr,
1638             "\nrunExceptionThrow(...):In C++ catch OurCppRunException "
1639             "with reason: %s.\n", 
1640             exc.what());
1641   }
1642   catch (...) {
1643     // Catch all exceptions including our generated ones. I'm not sure
1644     // why this latter functionality should work, as it seems that
1645     // our exceptions should be foreign to C++ (the _Unwind_Exception::
1646     // exception_class should be different from the one used by C++), and
1647     // therefore C++ should ignore the generated exceptions. 
1648     
1649     fprintf(stderr,
1650             "\nrunExceptionThrow(...):In C++ catch all.\n");
1651   }
1652 }
1653
1654 //
1655 // End test functions
1656 //
1657
1658 typedef llvm::ArrayRef<llvm::Type*> TypeArray;
1659
1660 /// This initialization routine creates type info globals and 
1661 /// adds external function declarations to module.
1662 /// @param numTypeInfos number of linear type info associated type info types
1663 ///        to create as GlobalVariable instances, starting with the value 1.
1664 /// @param module code for module instance
1665 /// @param builder builder instance
1666 static void createStandardUtilityFunctions(unsigned numTypeInfos,
1667                                            llvm::Module &module, 
1668                                            llvm::IRBuilder<> &builder) {
1669   
1670   llvm::LLVMContext &context = module.getContext();
1671   
1672   // Exception initializations
1673   
1674   // Setup exception catch state
1675   ourExceptionNotThrownState = 
1676   llvm::ConstantInt::get(llvm::Type::getInt8Ty(context), 0),
1677   ourExceptionThrownState = 
1678   llvm::ConstantInt::get(llvm::Type::getInt8Ty(context), 1),
1679   ourExceptionCaughtState = 
1680   llvm::ConstantInt::get(llvm::Type::getInt8Ty(context), 2),
1681   
1682   
1683   
1684   // Create our type info type
1685   ourTypeInfoType = llvm::StructType::get(context, 
1686                       TypeArray(builder.getInt32Ty()));
1687
1688 #ifndef OLD_EXC_SYSTEM
1689
1690   llvm::Type *caughtResultFieldTypes[] = {
1691     builder.getInt8PtrTy(),
1692     builder.getInt32Ty()
1693   };
1694
1695   // Create our landingpad result type
1696   ourCaughtResultType = llvm::StructType::get(context,
1697                                             TypeArray(caughtResultFieldTypes));
1698
1699 #endif
1700
1701   // Create OurException type
1702   ourExceptionType = llvm::StructType::get(context, 
1703                                            TypeArray(ourTypeInfoType));
1704   
1705   // Create portion of _Unwind_Exception type
1706   //
1707   // Note: Declaring only a portion of the _Unwind_Exception struct.
1708   //       Does this cause problems?
1709   ourUnwindExceptionType =
1710     llvm::StructType::get(context, 
1711                     TypeArray(builder.getInt64Ty()));
1712
1713   struct OurBaseException_t dummyException;
1714   
1715   // Calculate offset of OurException::unwindException member.
1716   ourBaseFromUnwindOffset = ((uintptr_t) &dummyException) - 
1717     ((uintptr_t) &(dummyException.unwindException));
1718   
1719 #ifdef DEBUG
1720   fprintf(stderr,
1721           "createStandardUtilityFunctions(...):ourBaseFromUnwindOffset "
1722           "= %lld, sizeof(struct OurBaseException_t) - "
1723           "sizeof(struct _Unwind_Exception) = %lu.\n",
1724           ourBaseFromUnwindOffset,
1725           sizeof(struct OurBaseException_t) - 
1726           sizeof(struct _Unwind_Exception));
1727 #endif
1728   
1729   size_t numChars = sizeof(ourBaseExcpClassChars) / sizeof(char);
1730   
1731   // Create our _Unwind_Exception::exception_class value
1732   ourBaseExceptionClass = genClass(ourBaseExcpClassChars, numChars);
1733   
1734   // Type infos
1735   
1736   std::string baseStr = "typeInfo", typeInfoName;
1737   std::ostringstream typeInfoNameBuilder;
1738   std::vector<llvm::Constant*> structVals;
1739   
1740   llvm::Constant *nextStruct;
1741   llvm::GlobalVariable *nextGlobal = NULL;
1742   
1743   // Generate each type info
1744   //
1745   // Note: First type info is not used.
1746   for (unsigned i = 0; i <= numTypeInfos; ++i) {
1747     structVals.clear();
1748     structVals.push_back(llvm::ConstantInt::get(builder.getInt32Ty(), i));
1749     nextStruct = llvm::ConstantStruct::get(ourTypeInfoType, structVals);
1750     
1751     typeInfoNameBuilder.str("");
1752     typeInfoNameBuilder << baseStr << i;
1753     typeInfoName = typeInfoNameBuilder.str();
1754     
1755     // Note: Does not seem to work without allocation
1756     nextGlobal = 
1757     new llvm::GlobalVariable(module, 
1758                              ourTypeInfoType, 
1759                              true, 
1760                              llvm::GlobalValue::ExternalLinkage, 
1761                              nextStruct, 
1762                              typeInfoName);
1763     
1764     ourTypeInfoNames.push_back(typeInfoName);
1765     ourTypeInfoNamesIndex[i] = typeInfoName;
1766   }
1767   
1768   ArgNames argNames;
1769   ArgTypes argTypes;
1770   llvm::Function *funct = NULL;
1771   
1772   // print32Int
1773   
1774   llvm::Type *retType = builder.getVoidTy();
1775   
1776   argTypes.clear();
1777   argTypes.push_back(builder.getInt32Ty());
1778   argTypes.push_back(builder.getInt8PtrTy());
1779   
1780   argNames.clear();
1781   
1782   createFunction(module, 
1783                  retType, 
1784                  argTypes, 
1785                  argNames, 
1786                  "print32Int", 
1787                  llvm::Function::ExternalLinkage, 
1788                  true, 
1789                  false);
1790   
1791   // print64Int
1792   
1793   retType = builder.getVoidTy();
1794   
1795   argTypes.clear();
1796   argTypes.push_back(builder.getInt64Ty());
1797   argTypes.push_back(builder.getInt8PtrTy());
1798   
1799   argNames.clear();
1800   
1801   createFunction(module, 
1802                  retType, 
1803                  argTypes, 
1804                  argNames, 
1805                  "print64Int", 
1806                  llvm::Function::ExternalLinkage, 
1807                  true, 
1808                  false);
1809   
1810   // printStr
1811   
1812   retType = builder.getVoidTy();
1813   
1814   argTypes.clear();
1815   argTypes.push_back(builder.getInt8PtrTy());
1816   
1817   argNames.clear();
1818   
1819   createFunction(module, 
1820                  retType, 
1821                  argTypes, 
1822                  argNames, 
1823                  "printStr", 
1824                  llvm::Function::ExternalLinkage, 
1825                  true, 
1826                  false);
1827   
1828   // throwCppException
1829   
1830   retType = builder.getVoidTy();
1831   
1832   argTypes.clear();
1833   argTypes.push_back(builder.getInt32Ty());
1834   
1835   argNames.clear();
1836   
1837   createFunction(module, 
1838                  retType, 
1839                  argTypes, 
1840                  argNames, 
1841                  "throwCppException", 
1842                  llvm::Function::ExternalLinkage, 
1843                  true, 
1844                  false);
1845   
1846   // deleteOurException
1847   
1848   retType = builder.getVoidTy();
1849   
1850   argTypes.clear();
1851   argTypes.push_back(builder.getInt8PtrTy());
1852   
1853   argNames.clear();
1854   
1855   createFunction(module, 
1856                  retType, 
1857                  argTypes, 
1858                  argNames, 
1859                  "deleteOurException", 
1860                  llvm::Function::ExternalLinkage, 
1861                  true, 
1862                  false);
1863   
1864   // createOurException
1865   
1866   retType = builder.getInt8PtrTy();
1867   
1868   argTypes.clear();
1869   argTypes.push_back(builder.getInt32Ty());
1870   
1871   argNames.clear();
1872   
1873   createFunction(module, 
1874                  retType, 
1875                  argTypes, 
1876                  argNames, 
1877                  "createOurException", 
1878                  llvm::Function::ExternalLinkage, 
1879                  true, 
1880                  false);
1881   
1882   // _Unwind_RaiseException
1883   
1884   retType = builder.getInt32Ty();
1885   
1886   argTypes.clear();
1887   argTypes.push_back(builder.getInt8PtrTy());
1888   
1889   argNames.clear();
1890   
1891   funct = createFunction(module, 
1892                          retType, 
1893                          argTypes, 
1894                          argNames, 
1895                          "_Unwind_RaiseException", 
1896                          llvm::Function::ExternalLinkage, 
1897                          true, 
1898                          false);
1899   
1900   funct->addFnAttr(llvm::Attribute::NoReturn);
1901   
1902   // _Unwind_Resume
1903   
1904   retType = builder.getInt32Ty();
1905   
1906   argTypes.clear();
1907   argTypes.push_back(builder.getInt8PtrTy());
1908   
1909   argNames.clear();
1910   
1911   funct = createFunction(module, 
1912                          retType, 
1913                          argTypes, 
1914                          argNames, 
1915                          "_Unwind_Resume", 
1916                          llvm::Function::ExternalLinkage, 
1917                          true, 
1918                          false);
1919   
1920   funct->addFnAttr(llvm::Attribute::NoReturn);
1921   
1922   // ourPersonality
1923   
1924   retType = builder.getInt32Ty();
1925   
1926   argTypes.clear();
1927   argTypes.push_back(builder.getInt32Ty());
1928   argTypes.push_back(builder.getInt32Ty());
1929   argTypes.push_back(builder.getInt64Ty());
1930   argTypes.push_back(builder.getInt8PtrTy());
1931   argTypes.push_back(builder.getInt8PtrTy());
1932   
1933   argNames.clear();
1934   
1935   createFunction(module, 
1936                  retType, 
1937                  argTypes, 
1938                  argNames, 
1939                  "ourPersonality", 
1940                  llvm::Function::ExternalLinkage, 
1941                  true, 
1942                  false);
1943   
1944   // llvm.eh.selector intrinsic
1945   
1946   getDeclaration(&module, llvm::Intrinsic::eh_selector);
1947   
1948   // llvm.eh.exception intrinsic
1949   
1950   getDeclaration(&module, llvm::Intrinsic::eh_exception);
1951   
1952   // llvm.eh.typeid.for intrinsic
1953   
1954   getDeclaration(&module, llvm::Intrinsic::eh_typeid_for);
1955 }
1956
1957
1958 //===----------------------------------------------------------------------===//
1959 // Main test driver code.
1960 //===----------------------------------------------------------------------===//
1961
1962 /// Demo main routine which takes the type info types to throw. A test will
1963 /// be run for each given type info type. While type info types with the value 
1964 /// of -1 will trigger a foreign C++ exception to be thrown; type info types
1965 /// <= 6 and >= 1 will be caught by test functions; and type info types > 6
1966 /// will result in exceptions which pass through to the test harness. All other
1967 /// type info types are not supported and could cause a crash.
1968 int main(int argc, char *argv[]) {
1969   if (argc == 1) {
1970     fprintf(stderr,
1971             "\nUsage: ExceptionDemo <exception type to throw> "
1972             "[<type 2>...<type n>].\n"
1973             "   Each type must have the value of 1 - 6 for "
1974             "generated exceptions to be caught;\n"
1975             "   the value -1 for foreign C++ exceptions to be "
1976             "generated and thrown;\n"
1977             "   or the values > 6 for exceptions to be ignored.\n"
1978             "\nTry: ExceptionDemo 2 3 7 -1\n"
1979             "   for a full test.\n\n");
1980     return(0);
1981   }
1982   
1983   // If not set, exception handling will not be turned on
1984   llvm::JITExceptionHandling = true;
1985   
1986   llvm::InitializeNativeTarget();
1987   llvm::LLVMContext &context = llvm::getGlobalContext();
1988   llvm::IRBuilder<> theBuilder(context);
1989   
1990   // Make the module, which holds all the code.
1991   llvm::Module *module = new llvm::Module("my cool jit", context);
1992   
1993   // Build engine with JIT
1994   llvm::EngineBuilder factory(module);
1995   factory.setEngineKind(llvm::EngineKind::JIT);
1996   factory.setAllocateGVsWithCode(false);
1997   llvm::ExecutionEngine *executionEngine = factory.create();
1998   
1999   {
2000     llvm::FunctionPassManager fpm(module);
2001     
2002     // Set up the optimizer pipeline.  
2003     // Start with registering info about how the
2004     // target lays out data structures.
2005     fpm.add(new llvm::TargetData(*executionEngine->getTargetData()));
2006     
2007     // Optimizations turned on
2008 #ifdef ADD_OPT_PASSES
2009     
2010     // Basic AliasAnslysis support for GVN.
2011     fpm.add(llvm::createBasicAliasAnalysisPass());
2012     
2013     // Promote allocas to registers.
2014     fpm.add(llvm::createPromoteMemoryToRegisterPass());
2015     
2016     // Do simple "peephole" optimizations and bit-twiddling optzns.
2017     fpm.add(llvm::createInstructionCombiningPass());
2018     
2019     // Reassociate expressions.
2020     fpm.add(llvm::createReassociatePass());
2021     
2022     // Eliminate Common SubExpressions.
2023     fpm.add(llvm::createGVNPass());
2024     
2025     // Simplify the control flow graph (deleting unreachable 
2026     // blocks, etc).
2027     fpm.add(llvm::createCFGSimplificationPass());
2028 #endif  // ADD_OPT_PASSES
2029     
2030     fpm.doInitialization();
2031     
2032     // Generate test code using function throwCppException(...) as
2033     // the function which throws foreign exceptions.
2034     llvm::Function *toRun = 
2035     createUnwindExceptionTest(*module, 
2036                               theBuilder, 
2037                               fpm,
2038                               "throwCppException");
2039     
2040     fprintf(stderr, "\nBegin module dump:\n\n");
2041     
2042     module->dump();
2043     
2044     fprintf(stderr, "\nEnd module dump:\n");
2045     
2046     fprintf(stderr, "\n\nBegin Test:\n");
2047     
2048     for (int i = 1; i < argc; ++i) {
2049       // Run test for each argument whose value is the exception
2050       // type to throw.
2051       runExceptionThrow(executionEngine, 
2052                         toRun, 
2053                         (unsigned) strtoul(argv[i], NULL, 10));
2054     }
2055     
2056     fprintf(stderr, "\nEnd Test:\n\n");
2057   } 
2058   
2059   delete executionEngine;
2060   
2061   return 0;
2062 }
2063