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