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